Release branch for 4.0.0.
This commit is contained in:
jubnl
2026-08-27 13:22:39 +02:00
committed by GitHub
parent e60427f813
commit 77dddd5e8a
3355 changed files with 403744 additions and 67215 deletions
@@ -0,0 +1,82 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { getAppUrl, getMcpSafeUrl } from '../../../src/app-config/app-url';
// These tests PIN the exact behavior moved verbatim from
// services/notifications.ts (2026-07-28): the APP_URL → ALLOWED_ORIGINS →
// localhost fallback chain, the strip-ALL-trailing-slashes quirk, the
// invalid-URL silent fallthrough, and getMcpSafeUrl's HTTPS/localhost issuer
// sanitization. If one fails after an edit, the edit changed runtime
// behavior — fix the edit, not the test (parity is law).
const KEYS = ['APP_URL', 'ALLOWED_ORIGINS', 'PORT'] as const;
const saved: Record<string, string | undefined> = {};
beforeEach(() => {
for (const k of KEYS) {
saved[k] = process.env[k];
delete process.env[k];
}
});
afterEach(() => {
for (const k of KEYS) {
if (saved[k] === undefined) delete process.env[k];
else process.env[k] = saved[k];
}
});
describe('getAppUrl', () => {
it('returns APP_URL with ALL trailing slashes stripped', () => {
process.env.APP_URL = 'https://trek.example.com///';
expect(getAppUrl()).toBe('https://trek.example.com');
});
it('falls through an invalid APP_URL to the first ALLOWED_ORIGINS entry', () => {
process.env.APP_URL = 'not a url';
process.env.ALLOWED_ORIGINS = 'https://a.example/, https://b.example';
expect(getAppUrl()).toBe('https://a.example');
});
it('uses the first ALLOWED_ORIGINS entry (trimmed, slashes stripped) when APP_URL is unset', () => {
process.env.ALLOWED_ORIGINS = ' https://origin.example// ,https://other.example';
expect(getAppUrl()).toBe('https://origin.example');
});
it('falls back to http://localhost:{PORT} when neither is usable', () => {
process.env.ALLOWED_ORIGINS = 'not-a-url';
process.env.PORT = '4123';
expect(getAppUrl()).toBe('http://localhost:4123');
});
it('defaults to port 3001 with no env at all', () => {
expect(getAppUrl()).toBe('http://localhost:3001');
});
it('reads the env live — no caching across calls', () => {
process.env.APP_URL = 'https://first.example';
expect(getAppUrl()).toBe('https://first.example');
process.env.APP_URL = 'https://second.example';
expect(getAppUrl()).toBe('https://second.example');
});
});
describe('getMcpSafeUrl', () => {
it('passes through HTTPS URLs', () => {
process.env.APP_URL = 'https://trek.example.com';
expect(getMcpSafeUrl()).toBe('https://trek.example.com');
});
it('passes through http://localhost and http://127.0.0.1', () => {
process.env.APP_URL = 'http://localhost:8080';
expect(getMcpSafeUrl()).toBe('http://localhost:8080');
process.env.APP_URL = 'http://127.0.0.1:8080';
expect(getMcpSafeUrl()).toBe('http://127.0.0.1:8080');
});
it('sanitizes non-HTTPS, non-localhost URLs to http://localhost:{PORT}', () => {
process.env.APP_URL = 'http://trek.internal.lan';
process.env.PORT = '3005';
expect(getMcpSafeUrl()).toBe('http://localhost:3005');
});
});
+254
View File
@@ -0,0 +1,254 @@
import { describe, it, expect } from 'vitest';
import {
deriveApp,
deriveHttp,
deriveSession,
deriveDemo,
deriveOidc,
deriveSmtp,
deriveMcp,
derivePlugins,
deriveIntegrations,
deriveBackup,
deriveNet,
derivePaths,
deriveAll,
} from '../../../src/app-config/derive';
// These tests PIN the exact legacy coercions each derived field replaced.
// If one fails after an edit, the edit changed runtime behavior — fix the
// edit, not the test (parity is law).
describe('deriveApp', () => {
it('NODE_ENV: loose helpers lowercase, isTest stays case-sensitive (db/database.ts)', () => {
expect(deriveApp({ NODE_ENV: 'PRODUCTION' }).isProduction).toBe(true);
expect(deriveApp({ NODE_ENV: 'Development' }).isDevelopment).toBe(true);
expect(deriveApp({ NODE_ENV: 'test' }).isTest).toBe(true);
expect(deriveApp({ NODE_ENV: 'TEST' }).isTest).toBe(false); // strict on purpose
expect(deriveApp({}).isProduction).toBe(false);
});
it('PORT: Number(x) || 3001 (index.ts)', () => {
expect(deriveApp({ PORT: '8080' }).port).toBe(8080);
expect(deriveApp({ PORT: 'abc' }).port).toBe(3001);
expect(deriveApp({}).port).toBe(3001);
});
it('APP_VERSION / APP_URL stay raw — per-site fallbacks live at the call sites', () => {
expect(deriveApp({}).appVersion).toBeUndefined();
expect(deriveApp({ APP_URL: 'https://x.example/' }).appUrl).toBe('https://x.example/');
});
it('DEFAULT_LANGUAGE resolves: case-insensitive, canonical code, en fallback', () => {
expect(deriveApp({ DEFAULT_LANGUAGE: 'EN' }).defaultLanguage).toBe('en');
expect(deriveApp({ DEFAULT_LANGUAGE: 'de' }).defaultLanguage).toBe('de');
expect(deriveApp({ DEFAULT_LANGUAGE: 'klingon' }).defaultLanguage).toBe('en');
expect(deriveApp({}).defaultLanguage).toBe('en');
// Mixed-case canonical codes resolve to their canonical form (legacy could
// never match zh-TW and silently served English).
expect(deriveApp({ DEFAULT_LANGUAGE: 'zh-TW' }).defaultLanguage).toBe('zh-TW');
expect(deriveApp({ DEFAULT_LANGUAGE: 'zh-tw' }).defaultLanguage).toBe('zh-TW');
});
});
describe('deriveHttp', () => {
it('ALLOWED_ORIGINS: CORS variant filters empties, websocket variant keeps them', () => {
const env = { ALLOWED_ORIGINS: ' https://a.example ,, https://b.example ' };
expect(deriveHttp(env).corsOrigins).toEqual(['https://a.example', 'https://b.example']);
expect(deriveHttp(env).wsOrigins).toEqual(['https://a.example', '', 'https://b.example']);
expect(deriveHttp({}).corsOrigins).toBeNull();
expect(deriveHttp({}).wsOrigins).toBeNull();
});
it('TRUST_PROXY: numeric hop count wins, 1 only as fallback (globalMiddleware)', () => {
expect(deriveHttp({ TRUST_PROXY: '2' }).trustProxy).toBe(2);
// 0 is a valid hop count ("trust no proxy"), not a missing value.
expect(deriveHttp({ TRUST_PROXY: '0' }).trustProxy).toBe(0);
expect(deriveHttp({ TRUST_PROXY: 'abc' }).trustProxy).toBe(1);
expect(deriveHttp({}).trustProxy).toBe(1);
});
it('boolean switches accept the whole boolean-like family (unified semantics)', () => {
expect(deriveHttp({ FORCE_HTTPS: 'TRUE' }).forceHttps).toBe(true);
expect(deriveHttp({ FORCE_HTTPS: 'on' }).forceHttps).toBe(true);
expect(deriveHttp({ HSTS_INCLUDE_SUBDOMAINS: 'TRUE' }).hstsIncludeSubdomains).toBe(true);
expect(deriveHttp({ HSTS_INCLUDE_SUBDOMAINS: '1' }).hstsIncludeSubdomains).toBe(true);
expect(deriveHttp({ HSTS_INCLUDE_SUBDOMAINS: 'off' }).hstsIncludeSubdomains).toBe(false);
});
it('COOKIE_SECURE is tri-state: explicit falsy disables, anything else auto-detects', () => {
expect(deriveHttp({ COOKIE_SECURE: 'false' }).cookieSecureDisabled).toBe(true);
expect(deriveHttp({ COOKIE_SECURE: 'off' }).cookieSecureDisabled).toBe(true);
expect(deriveHttp({ COOKIE_SECURE: 'true' }).cookieSecureDisabled).toBe(false);
expect(deriveHttp({}).cookieSecureDisabled).toBe(false);
});
it('TREK_API_DOCS_ENABLED: trimmed, boolean-like (api-docs.kill-switch)', () => {
expect(deriveHttp({ TREK_API_DOCS_ENABLED: ' TRUE ' }).apiDocsEnabled).toBe(true);
expect(deriveHttp({ TREK_API_DOCS_ENABLED: '1' }).apiDocsEnabled).toBe(true);
expect(deriveHttp({ TREK_API_DOCS_ENABLED: 'false' }).apiDocsEnabled).toBe(false);
expect(deriveHttp({}).apiDocsEnabled).toBe(false);
});
});
describe('deriveSession', () => {
it('parses durations and falls back on invalid input (src/config.ts semantics)', () => {
const ok = deriveSession({ SESSION_DURATION: '12h', SESSION_DURATION_REMEMBER: '90d' });
expect(ok.duration).toBe('12h');
expect(ok.durationMs).toBe(12 * 3_600_000);
expect(ok.durationSeconds).toBe(12 * 3600);
expect(ok.durationRememberMs).toBe(90 * 86_400_000);
const bad = deriveSession({ SESSION_DURATION: 'bogus' });
expect(bad.duration).toBe('24h');
expect(bad.durationMs).toBe(24 * 3_600_000);
expect(deriveSession({}).durationRemember).toBe('30d');
});
it('IDEMPOTENCY_TTL_SECONDS: positive number or 30 days (scheduler.ts)', () => {
expect(deriveSession({ IDEMPOTENCY_TTL_SECONDS: '60' }).idempotencyTtlSeconds).toBe(60);
expect(deriveSession({ IDEMPOTENCY_TTL_SECONDS: '0' }).idempotencyTtlSeconds).toBe(30 * 24 * 60 * 60);
expect(deriveSession({}).idempotencyTtlSeconds).toBe(30 * 24 * 60 * 60);
});
});
describe('deriveDemo', () => {
it('DEMO_MODE coerces the whole boolean-like family to one bool', () => {
expect(deriveDemo({ DEMO_MODE: 'TRUE' }).enabled).toBe(true);
expect(deriveDemo({ DEMO_MODE: 'yes' }).enabled).toBe(true);
expect(deriveDemo({ DEMO_MODE: 'off' }).enabled).toBe(false);
expect(deriveDemo({ DEMO_MODE: 'maybe' }).enabled).toBe(false); // out-of-family → default (validation rejects it at boot)
expect(deriveDemo({}).enabled).toBe(false);
});
it('DEMO_ADMIN_EMAIL stays raw — demo-seed and demo-reset apply different defaults', () => {
expect(deriveDemo({}).adminEmailRaw).toBeUndefined();
expect(deriveDemo({}).adminUser).toBe('admin');
expect(deriveDemo({}).adminPass).toBe('admin12345');
});
it('DEMO_ADMIN_PASS: adminPassSet tells the default apart from an explicit value', () => {
expect(deriveDemo({}).adminPassSet).toBe(false);
expect(deriveDemo({ DEMO_ADMIN_PASS: '' }).adminPassSet).toBe(false);
expect(deriveDemo({ DEMO_ADMIN_PASS: 'hunter22' }).adminPassSet).toBe(true);
});
});
describe('deriveOidc', () => {
it('scope and adminClaim carry their single-site defaults', () => {
expect(deriveOidc({}).scope).toBe('openid email profile');
expect(deriveOidc({}).adminClaim).toBe('groups');
expect(deriveOidc({ OIDC_ADMIN_CLAIM: 'roles' }).adminClaim).toBe('roles');
});
it('OIDC_ONLY coerces the boolean-like family', () => {
expect(deriveOidc({ OIDC_ONLY: 'True' }).only).toBe(true);
expect(deriveOidc({ OIDC_ONLY: '1' }).only).toBe(true);
expect(deriveOidc({ OIDC_ONLY: 'no' }).only).toBe(false);
});
});
describe('deriveSmtp', () => {
it('SMTP_SKIP_TLS_VERIFY coerces the boolean-like family', () => {
expect(deriveSmtp({ SMTP_SKIP_TLS_VERIFY: 'true' }).skipTlsVerify).toBe(true);
expect(deriveSmtp({ SMTP_SKIP_TLS_VERIFY: 'TRUE' }).skipTlsVerify).toBe(true);
expect(deriveSmtp({ SMTP_SKIP_TLS_VERIFY: 'off' }).skipTlsVerify).toBe(false);
expect(deriveSmtp({}).skipTlsVerify).toBe(false);
});
});
describe('deriveMcp', () => {
it('pins the mcp/index.ts module-const parsing', () => {
expect(deriveMcp({}).sessionTtlMs).toBe(3_600_000);
expect(deriveMcp({ MCP_MAX_SESSION_PER_USER: '5' }).maxSessionsPerUser).toBe(5);
expect(deriveMcp({ MCP_MAX_SESSION_PER_USER: '0' }).maxSessionsPerUser).toBe(20);
expect(deriveMcp({ MCP_SSE_KEEPALIVE: '0' }).sseKeepaliveMs).toBe(0);
expect(deriveMcp({ MCP_RATE_LIMIT: '100' }).rateLimitMax).toBe(100);
expect(deriveMcp({}).rateLimitMax).toBe(300);
});
});
describe('derivePlugins', () => {
it('kill-switch is default-on; only an explicit falsy value disables', () => {
expect(derivePlugins({}).enabled).toBe(true);
expect(derivePlugins({ TREK_PLUGINS_ENABLED: 'anything' }).enabled).toBe(true); // out-of-family → default-on
for (const v of ['false', '0', 'off', 'no', ' OFF ']) {
expect(derivePlugins({ TREK_PLUGINS_ENABLED: v }).enabled).toBe(false);
}
});
it('devLink and permissions jail coerce the boolean-like family; jail is default-on', () => {
expect(derivePlugins({ TREK_PLUGINS_DEV_LINK: '1' }).devLink).toBe(true);
expect(derivePlugins({ TREK_PLUGINS_DEV_LINK: 'true' }).devLink).toBe(true);
expect(derivePlugins({ TREK_PLUGINS_DEV_LINK: 'off' }).devLink).toBe(false);
expect(derivePlugins({ TREK_PLUGIN_PERMISSIONS: 'OFF' }).permissionsOff).toBe(true);
expect(derivePlugins({ TREK_PLUGIN_PERMISSIONS: 'false' }).permissionsOff).toBe(true);
expect(derivePlugins({ TREK_PLUGIN_PERMISSIONS: 'on' }).permissionsOff).toBe(false);
expect(derivePlugins({}).permissionsOff).toBe(false);
});
it('allowPrivateEgress is a bool (supervisor normalizes it to the literal "on" for the child)', () => {
expect(derivePlugins({ TREK_PLUGIN_ALLOW_PRIVATE_EGRESS: 'on' }).allowPrivateEgress).toBe(true);
expect(derivePlugins({ TREK_PLUGIN_ALLOW_PRIVATE_EGRESS: 'true' }).allowPrivateEgress).toBe(true);
expect(derivePlugins({ TREK_PLUGIN_ALLOW_PRIVATE_EGRESS: 'off' }).allowPrivateEgress).toBe(false);
expect(derivePlugins({}).allowPrivateEgress).toBe(false);
});
it('rate limits use Number(x) || default (rate-limit.ts / supervisor)', () => {
expect(derivePlugins({}).rpcBurst).toBe(60);
expect(derivePlugins({ TREK_PLUGIN_RPC_PER_SEC: '5' }).rpcPerSec).toBe(5);
expect(derivePlugins({ TREK_PLUGIN_MAX_RSS_MB: 'abc' }).maxRssMb).toBe(300);
});
});
describe('deriveIntegrations', () => {
it('pins unsplash trim, transit base strip + default, overpass timeout', () => {
expect(deriveIntegrations({ UNSPLASH_ACCESS_KEY: ' key ' }).unsplashAccessKey).toBe('key');
expect(deriveIntegrations({}).transitApiBase).toBe('https://api.transitous.org');
expect(deriveIntegrations({ TRANSIT_API_URL: 'https://t.example//' }).transitApiBase).toBe('https://t.example');
expect(deriveIntegrations({}).overpassTimeoutMs).toBe(12000);
expect(deriveIntegrations({ OVERPASS_TIMEOUT_MS: '-1' }).overpassTimeoutMs).toBe(12000);
});
});
describe('deriveBackup', () => {
it('pins the backupService limit parsing (positive number or default)', () => {
expect(deriveBackup({}).uploadLimitMb).toBe(500);
expect(deriveBackup({ BACKUP_UPLOAD_LIMIT_MB: ' 750 ' }).uploadLimitMb).toBe(750);
expect(deriveBackup({ BACKUP_UPLOAD_LIMIT_MB: '-1' }).uploadLimitMb).toBe(500);
expect(deriveBackup({}).maxDecompressedMb).toBe(5 * 1024);
expect(deriveBackup({ ENCRYPTION_KEY: 'x' }).encryptionKeyFromEnv).toBe(true);
});
});
describe('deriveNet', () => {
it('ALLOW_INTERNAL_NETWORK coerces the boolean-like family (ssrfGuard)', () => {
expect(deriveNet({ ALLOW_INTERNAL_NETWORK: 'True' }).allowInternalNetwork).toBe(true);
expect(deriveNet({ ALLOW_INTERNAL_NETWORK: '1' }).allowInternalNetwork).toBe(true);
expect(deriveNet({}).allowInternalNetwork).toBe(false);
});
});
describe('derivePaths', () => {
it('passes the path vars through raw — defaulting stays at the consumer', () => {
expect(derivePaths({ TREK_WIKI_DIR: '/w' }).wikiDir).toBe('/w');
expect(derivePaths({ TREK_PLACE_PHOTO_DIR: '/p' }).placePhotoDir).toBe('/p');
expect(derivePaths({}).wikiDir).toBeUndefined();
expect(derivePaths({}).placePhotoDir).toBeUndefined();
});
});
describe('deriveAll', () => {
it('assembles every namespace', () => {
const env = deriveAll({ PORT: '4000', DEMO_MODE: 'true' });
expect(env.app.port).toBe(4000);
expect(env.demo.enabled).toBe(true);
for (const ns of [
'app', 'http', 'session', 'demo', 'adminBootstrap', 'oidc', 'smtp', 'mcp',
'plugins', 'webauthn', 'integrations', 'backup', 'db', 'paths', 'net',
] as const) {
expect(env[ns]).toBeDefined();
}
});
});
@@ -0,0 +1,157 @@
import { describe, it, expect } from 'vitest';
import {
csvList,
csvListFiltered,
nonNegativeIntOr,
numberOr,
parseBool,
parseDurationMs,
positiveIntOr,
positiveNumberOr,
resolveKeepaliveMs,
resolveSessionTtlMs,
stripTrailingSlashes,
} from '../../../src/app-config/parsers';
describe('parseBool', () => {
it('accepts the whole truthy family, any casing, padded', () => {
for (const v of ['true', 'TRUE', 'True', '1', 'on', 'ON', 'yes', 'Yes', ' true ']) {
expect(parseBool(v)).toBe(true);
}
});
it('accepts the whole falsy family', () => {
for (const v of ['false', 'FALSE', '0', 'off', 'OFF', 'no', 'No', ' off ']) {
expect(parseBool(v)).toBe(false);
}
});
it('returns undefined for unset, blank and out-of-family values (default applies)', () => {
expect(parseBool(undefined)).toBeUndefined();
expect(parseBool('')).toBeUndefined();
expect(parseBool(' ')).toBeUndefined();
expect(parseBool('maybe')).toBeUndefined();
expect(parseBool('enabled')).toBeUndefined();
});
});
describe('numberOr', () => {
it('parses plain numbers', () => {
expect(numberOr('8080', 3001)).toBe(8080);
});
// Pins the legacy `Number(x) || d` quirk: "0" is treated as unset.
it('falls back on NaN, empty and "0"', () => {
expect(numberOr('abc', 3001)).toBe(3001);
expect(numberOr('', 3001)).toBe(3001);
expect(numberOr(undefined, 3001)).toBe(3001);
expect(numberOr('0', 3001)).toBe(3001);
});
it('keeps negative values (legacy quirk: -5 || d === -5)', () => {
expect(numberOr('-5', 3001)).toBe(-5);
});
});
describe('positiveNumberOr', () => {
it('accepts positive numbers including fractions', () => {
expect(positiveNumberOr('12.5', 500)).toBe(12.5);
});
it('falls back on zero, negatives, NaN and unset', () => {
expect(positiveNumberOr('0', 500)).toBe(500);
expect(positiveNumberOr('-3', 500)).toBe(500);
expect(positiveNumberOr('abc', 500)).toBe(500);
expect(positiveNumberOr(undefined, 500)).toBe(500);
});
});
describe('positiveIntOr', () => {
it('parses leading integers the way parseInt does (pins "5x" → 5)', () => {
expect(positiveIntOr('5', 20)).toBe(5);
expect(positiveIntOr('5x', 20)).toBe(5);
});
it('falls back on zero, negatives and garbage', () => {
expect(positiveIntOr('0', 20)).toBe(20);
expect(positiveIntOr('-1', 20)).toBe(20);
expect(positiveIntOr('abc', 20)).toBe(20);
expect(positiveIntOr(undefined, 20)).toBe(20);
});
});
describe('nonNegativeIntOr', () => {
it('accepts zero (0 disables retries) and positive integers', () => {
expect(nonNegativeIntOr('0', 1)).toBe(0);
expect(nonNegativeIntOr('3', 1)).toBe(3);
});
it('falls back on unset, blank, negative, and non-numeric', () => {
expect(nonNegativeIntOr(undefined, 1)).toBe(1);
expect(nonNegativeIntOr(' ', 1)).toBe(1);
expect(nonNegativeIntOr('-1', 1)).toBe(1);
expect(nonNegativeIntOr('nope', 1)).toBe(1);
});
});
describe('csvList / csvListFiltered', () => {
it('returns null when unset or empty', () => {
expect(csvList(undefined)).toBeNull();
expect(csvList('')).toBeNull();
expect(csvListFiltered(undefined)).toBeNull();
});
it('trims entries', () => {
expect(csvList(' a.example , b.example ')).toEqual(['a.example', 'b.example']);
});
// The two ALLOWED_ORIGINS call sites differ: websocket keeps empty entries,
// the CORS middleware drops them. Both behaviors are pinned.
it('csvList keeps empty entries, csvListFiltered drops them', () => {
expect(csvList('a,,b')).toEqual(['a', '', 'b']);
expect(csvListFiltered('a,,b')).toEqual(['a', 'b']);
});
});
describe('stripTrailingSlashes', () => {
it('strips all trailing slashes', () => {
expect(stripTrailingSlashes('https://x.example///')).toBe('https://x.example');
expect(stripTrailingSlashes('https://x.example')).toBe('https://x.example');
});
});
describe('parseDurationMs', () => {
it('parses the ms-style units used by SESSION_DURATION', () => {
expect(parseDurationMs('1h')).toBe(3_600_000);
expect(parseDurationMs('7d')).toBe(7 * 86_400_000);
expect(parseDurationMs('500')).toBe(500); // unitless = ms
expect(parseDurationMs(' 12H ')).toBe(12 * 3_600_000); // trims + case-insensitive
expect(parseDurationMs('1.5h')).toBe(1.5 * 3_600_000);
});
it('rejects zero, negatives and garbage', () => {
expect(parseDurationMs('0h')).toBeNull();
expect(parseDurationMs('bogus')).toBeNull();
expect(parseDurationMs('-1d')).toBeNull();
expect(parseDurationMs('1 fortnight')).toBeNull();
});
});
describe('resolveSessionTtlMs', () => {
it('defaults to 1h and clamps to 24h', () => {
expect(resolveSessionTtlMs(undefined)).toBe(3_600_000);
expect(resolveSessionTtlMs('120')).toBe(120_000);
expect(resolveSessionTtlMs(String(48 * 60 * 60))).toBe(24 * 60 * 60 * 1000);
expect(resolveSessionTtlMs('0')).toBe(3_600_000);
expect(resolveSessionTtlMs('abc')).toBe(3_600_000);
});
});
describe('resolveKeepaliveMs', () => {
it('defaults to 25s and allows 0 to disable', () => {
expect(resolveKeepaliveMs(undefined)).toBe(25_000);
expect(resolveKeepaliveMs('10')).toBe(10_000);
expect(resolveKeepaliveMs('0')).toBe(0);
expect(resolveKeepaliveMs('abc')).toBe(25_000);
});
});
@@ -0,0 +1,174 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { validateEnvAtBoot, readEnv } from '../../../src/app-config/env';
describe('validateEnvAtBoot', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('passes with a completely empty environment (all defaults)', () => {
expect(() => validateEnvAtBoot({})).not.toThrow();
});
it('passes with a representative valid environment', () => {
expect(() =>
validateEnvAtBoot({
PORT: '3001',
NODE_ENV: 'production',
DEMO_MODE: 'false',
SESSION_DURATION: '12h',
SESSION_DURATION_REMEMBER: '90d',
DEFAULT_LANGUAGE: 'en',
APP_URL: 'https://trek.example.com',
ALLOWED_ORIGINS: 'https://trek.example.com',
LOG_LEVEL: 'debug',
TRUST_PROXY: '2',
OIDC_ISSUER: 'https://auth.example.com/realms/trek',
SMTP_PORT: '587',
MCP_RATE_LIMIT: '100',
BACKUP_UPLOAD_LIMIT_MB: '750',
TREK_PLUGINS_ENABLED: 'off',
TREK_PLUGIN_PERMISSIONS: 'on',
}),
).not.toThrow();
});
it('treats blank values as unset (defaults apply, no error)', () => {
expect(() => validateEnvAtBoot({ DEMO_MODE: '', PORT: ' ', TZ: '' })).not.toThrow();
});
it('ignores unknown environment variables', () => {
expect(() => validateEnvAtBoot({ SOME_OTHER_TOOLS_VAR: '!!not-a-trek-var!!' })).not.toThrow();
});
it('does not validate NODE_ENV (non-standard values must keep booting)', () => {
expect(() => validateEnvAtBoot({ NODE_ENV: 'staging' })).not.toThrow();
});
it('throws on present-but-malformed values with an aggregated report', () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() =>
validateEnvAtBoot({
PORT: 'not-a-port',
SESSION_DURATION: 'bogus',
DEMO_MODE: 'maybe',
APP_URL: 'not a url',
}),
).toThrow(/Invalid environment configuration \(4 problems\)/);
const report = error.mock.calls.map((c) => c.join(' ')).join('\n');
expect(report).toContain('PORT="not-a-port"');
expect(report).toContain('SESSION_DURATION="bogus"');
expect(report).toContain('DEMO_MODE="maybe"');
expect(report).toContain('APP_URL="not a url"');
});
it.each([
['PORT', '70000'],
['TRUST_PROXY', '1.5'],
['DEFAULT_LANGUAGE', 'klingon'],
['LOG_LEVEL', 'verbose'],
['SESSION_DURATION_REMEMBER', '-1d'],
['OIDC_ISSUER', 'auth.example.com'],
['SMTP_PORT', 'smtp'],
['MCP_SSE_KEEPALIVE', '-1'],
['IDEMPOTENCY_TTL_SECONDS', '0'],
['BACKUP_UPLOAD_LIMIT_MB', '0'],
['HSTS_INCLUDE_SUBDOMAINS', 'enabled'],
['TREK_PLUGINS_ENABLED', 'maybe'],
['TREK_PLUGINS_DEV_LINK', 'always'],
['TREK_PLUGIN_PERMISSIONS', 'disabled'],
['TREK_PLUGIN_MAX_RSS_MB', '-100'],
])('rejects malformed %s=%s', (key, value) => {
vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() => validateEnvAtBoot({ [key]: value })).toThrow(/Invalid environment configuration/);
});
it.each([
['DEMO_MODE', 'TRUE'],
['TREK_API_DOCS_ENABLED', ' TRUE '],
['TREK_PLUGINS_ENABLED', ' OFF '],
['DEFAULT_LANGUAGE', 'EN'],
['DEFAULT_LANGUAGE', 'zh-TW'],
['LOG_LEVEL', 'ERROR'],
['SESSION_DURATION', ' 12H '],
])('accepts differently-cased/padded valid %s=%s', (key, value) => {
expect(() => validateEnvAtBoot({ [key]: value })).not.toThrow();
});
// Booleans accept the whole boolean-like family (true/false, 1/0, on/off,
// yes/no) and derive to real booleans via parseBool — DEMO_MODE=yes enables
// demo mode, TREK_PLUGINS_DEV_LINK=true activates dev-link (see derive.test).
it.each([
['DEMO_MODE', 'yes'],
['HSTS_INCLUDE_SUBDOMAINS', '1'],
['TREK_PLUGINS_DEV_LINK', 'true'],
['TREK_PLUGIN_PERMISSIONS', 'off'],
['TREK_PLUGIN_ALLOW_PRIVATE_EGRESS', 'on'],
['FORCE_HTTPS', 'On'],
])('accepts boolean-like %s=%s', (key, value) => {
expect(() => validateEnvAtBoot({ [key]: value })).not.toThrow();
});
});
describe('validateEnvAtBoot — centrally administered preconditions', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('MANAGED-BOOT-001: refuses TREK_MANAGED without ENCRYPTION_KEY', () => {
// The combination boots fine and is wrong: the at-rest key falls back to a
// file in the data volume, and backupService puts that file in every archive
// an instance admin can download.
vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() => validateEnvAtBoot({ TREK_MANAGED: '1' })).toThrow(/1 problem/);
});
it('MANAGED-BOOT-002: names the variable, so the fix does not need the source', () => {
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() => validateEnvAtBoot({ TREK_MANAGED: 'true' })).toThrow();
expect(err.mock.calls[0][0]).toMatch(/ENCRYPTION_KEY/);
});
it('MANAGED-BOOT-003: passes once the key is supplied', () => {
expect(() =>
validateEnvAtBoot({ TREK_MANAGED: '1', ENCRYPTION_KEY: 'a'.repeat(64) }),
).not.toThrow();
});
it('MANAGED-BOOT-004: inert without the switch — a self-hoster keeps the file-based key', () => {
// The whole point of the check is that it cannot reach anyone who did not
// ask to be centrally administered.
expect(() => validateEnvAtBoot({})).not.toThrow();
expect(() => validateEnvAtBoot({ TREK_MANAGED: 'off' })).not.toThrow();
expect(() => validateEnvAtBoot({ TREK_MANAGED: 'false' })).not.toThrow();
});
it('MANAGED-BOOT-005: reports alongside schema problems rather than instead of them', () => {
// Both kinds land in one report: fixing the env should take one pass, not a
// restart per problem.
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() => validateEnvAtBoot({ TREK_MANAGED: '1', PORT: 'not-a-port' })).toThrow(
/2 problems/,
);
expect(err.mock.calls[0][0]).toMatch(/PORT/);
expect(err.mock.calls[0][0]).toMatch(/ENCRYPTION_KEY/);
});
});
describe('readEnv', () => {
it('reads process.env live — a runtime mutation is visible on the next call', () => {
const before = process.env.DEMO_MODE;
try {
process.env.DEMO_MODE = 'true';
expect(readEnv().demo.enabled).toBe(true);
process.env.DEMO_MODE = 'false';
expect(readEnv().demo.enabled).toBe(false);
delete process.env.DEMO_MODE;
expect(readEnv().demo.enabled).toBe(false);
} finally {
if (before === undefined) delete process.env.DEMO_MODE;
else process.env.DEMO_MODE = before;
}
});
});
+371
View File
@@ -0,0 +1,371 @@
/**
* Scheduled backup run (AutoBackupJob).
*
* The auto-backup used to archive the live travel.db: the archiver reads its
* entries while streaming, so a WAL auto-checkpoint writing pages back mid-run
* left a torn copy in the zip — without the -wal that would make it recoverable.
* It also shipped without .encryption_key, so the archive could not be decrypted
* on another install. The run now goes through backupService.createBackup(),
* which snapshots the DB with VACUUM INTO and bundles the key.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import type { PathLike } from 'node:fs';
const fsMock = vi.hoisted(() => ({
// The parameter is declared so the double carries fs's real signature: the
// cases below replace this default with a path-dependent implementation.
existsSync: vi.fn((_p: PathLike) => false),
mkdirSync: vi.fn(),
readFileSync: vi.fn(() => '{}'),
writeFileSync: vi.fn(),
readdirSync: vi.fn(() => [] as unknown as string[]),
statSync: vi.fn(() => ({ size: 0, birthtime: new Date(0), mtimeMs: 0 })),
unlinkSync: vi.fn(),
createWriteStream: vi.fn(),
createReadStream: vi.fn(),
rmSync: vi.fn(),
copyFileSync: vi.fn(),
renameSync: vi.fn(),
cpSync: vi.fn(),
realpathSync: vi.fn((p: string) => p),
}));
const archiveMock = vi.hoisted(() => ({
pipe: vi.fn(),
file: vi.fn(),
directory: vi.fn(),
glob: vi.fn(),
finalize: vi.fn(),
on: vi.fn(),
}));
const archiverMock = vi.hoisted(() => vi.fn());
const dbMock = vi.hoisted(() => ({
db: { exec: vi.fn(), prepare: vi.fn() },
closeDb: vi.fn(),
reinitialize: vi.fn(),
}));
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn() }));
vi.mock('fs', () => ({ default: fsMock, ...fsMock }));
vi.mock('node:fs', () => ({ default: fsMock, ...fsMock }));
vi.mock('archiver', () => ({ default: archiverMock }));
vi.mock('unzipper', () => ({ default: { Extract: vi.fn(), Open: { file: vi.fn() } } }));
vi.mock('../../src/db/database', () => dbMock);
vi.mock('../../src/nest/audit/audit-log.logger', () => logMock);
vi.mock('../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a'.repeat(64),
updateJwtSecret: () => {},
}));
import path from 'node:path';
import { AutoBackupJob } from '../../src/nest/backup/auto-backup.job';
import { createBackup } from '../../src/nest/backup/backup.impl';
import type { BackupService } from '../../src/nest/backup/backup.service';
import type { StorageService } from '../../src/nest/storage/storage.service';
import type { CronRegistrarService } from '../../src/nest/scheduling/cron-registrar.service';
const liveDb = path.join(__dirname, '../../data', 'travel.db');
// createBackup receives StorageService as a parameter (BackupService injects
// it). fs is mocked wholesale here, so a plain stub stands in for the backups
// backend: staging under /stub/spool, empty category listings, put/stat succeed.
const storageStub = vi.hoisted(() => ({}) as Record<string, unknown>);
function resetStorageStub() {
Object.assign(storageStub, {
spoolDirFor: vi.fn(() => '/stub/spool'),
tempDir: vi.fn(() => '/stub/tmp'),
list: vi.fn(async function* () {}),
withLocalFile: vi.fn(async (_c: string, _k: string, fn: (p: string) => Promise<unknown>) => fn('/stub/local/path')),
put: vi.fn(async () => {}),
stat: vi.fn(async (_c: string, key: string) => ({ key, size: 4096, mtimeMs: Date.parse('2026-04-27T02:00:00Z') })),
exists: vi.fn(async () => true),
delete: vi.fn(async () => {}),
});
}
resetStorageStub();
interface Registered {
name: string;
expr: string;
onTick: () => Promise<void> | void;
}
/** An AutoBackupJob wired to the real createBackup and a capturing registrar double. */
function makeJob() {
const registered: Registered[] = [];
const registrar = {
isEnabled: vi.fn(() => true),
register: vi.fn((name: string, expr: string, onTick: Registered['onTick']) => {
registered.push({ name, expr, onTick });
return true;
}),
unregister: vi.fn(),
};
const job = new AutoBackupJob(
// The same wiring the container does, with the real service function behind
// it — the run below is still the production code path. The forward mirrors
// BackupService: inject the storage stub as the first argument.
{ createBackup: (prefix?: 'backup' | 'auto-backup') => createBackup(storageStub as unknown as StorageService, prefix) } as unknown as BackupService,
registrar as unknown as CronRegistrarService,
storageStub as unknown as StorageService,
);
return { job, registered, registrar };
}
/** Wires up the archiver so finalize() resolves the run, and returns its events. */
function stubArchiver(): Record<string, (arg?: unknown) => void> {
const outputEvents: Record<string, (arg?: unknown) => void> = {};
const archiveEvents: Record<string, (arg?: unknown) => void> = {};
fsMock.createWriteStream.mockReturnValue({
on: vi.fn((event: string, cb: () => void) => { outputEvents[event] = cb; }),
} as never);
archiveMock.on.mockImplementation((event: string, cb: (arg?: unknown) => void) => { archiveEvents[event] = cb; });
archiveMock.finalize.mockImplementation(() => { outputEvents['close']?.(); });
archiverMock.mockReturnValue(archiveMock);
return archiveEvents;
}
/** Arms the job with auto-backup enabled and hands back the cron tick. */
function scheduledRun(): () => Promise<void> {
fsMock.readFileSync.mockReturnValue(JSON.stringify({ enabled: true, interval: 'daily', keep_days: 7 }));
const { job, registered } = makeJob();
job.start();
return registered.at(-1)?.onTick as () => Promise<void>;
}
describe('auto-backup run', () => {
const envKey = process.env.ENCRYPTION_KEY;
beforeEach(() => {
vi.clearAllMocks();
resetStorageStub();
// No ENCRYPTION_KEY in the env means the key file is the source of truth and
// has to travel with the backup.
delete process.env.ENCRYPTION_KEY;
fsMock.statSync.mockReturnValue({ size: 4096, birthtime: new Date('2026-04-27T02:00:00Z'), mtimeMs: Date.now() } as never);
});
afterEach(() => {
process.env.ENCRYPTION_KEY = envKey;
});
it('archives a VACUUM INTO snapshot, never the live travel.db', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('travel.db') || String(p).endsWith('backup-settings.json'));
stubArchiver();
await scheduledRun()();
expect(dbMock.db.exec).toHaveBeenCalledWith(expect.stringContaining('VACUUM INTO'));
const dbEntry = archiveMock.file.mock.calls.find(([, opts]) => opts?.name === 'travel.db');
expect(dbEntry).toBeDefined();
expect(dbEntry?.[0]).toContain('/stub/spool/travel-snap-auto-backup-');
expect(dbEntry?.[0]).not.toBe(liveDb);
});
it('bundles the at-rest encryption key', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('.encryption_key') || String(p).endsWith('backup-settings.json'));
stubArchiver();
await scheduledRun()();
expect(archiveMock.file).toHaveBeenCalledWith(
expect.stringContaining('.encryption_key'),
{ name: '.encryption_key' },
);
});
it('keeps the auto-backup-*.zip naming so retention still prunes it', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('backup-settings.json'));
// An expired scheduled archive sits in the backups category (retention
// lists through storage now); the category enumeration stays empty.
storageStub.list = vi.fn((category: string) =>
(async function* () {
if (category === 'backups') yield { key: 'auto-backup-2020-01-01T02-00-00.zip', size: 0, mtimeMs: 0 };
})(),
);
stubArchiver();
await scheduledRun()();
expect(logMock.logInfo).toHaveBeenCalledWith(expect.stringMatching(/^Auto-Backup created: auto-backup-[\dT-]+\.zip$/));
// cleanupOldBackups(storage, keep_days) still runs after the archive and
// only prunes objects it can match by prefix — through storage.delete
expect(storageStub.delete).toHaveBeenCalledWith('backups', 'auto-backup-2020-01-01T02-00-00.zip');
});
it('logs the failure, drops the partial zip and skips retention', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('.zip') || String(p).endsWith('backup-settings.json'));
const archiveEvents = stubArchiver();
archiveMock.finalize.mockImplementation(() => { archiveEvents['error']?.(new Error('disk full')); });
await scheduledRun()();
expect(logMock.logError).toHaveBeenCalledWith('Auto-Backup: disk full');
expect(logMock.logInfo).not.toHaveBeenCalledWith(expect.stringContaining('Auto-Backup created'));
// nothing was committed (put commits by rename only on success); the
// half-built zip spool and snapshot scratch are cleaned up, and retention
// never runs
expect(storageStub.put).not.toHaveBeenCalled();
expect(fsMock.rmSync).toHaveBeenCalledWith(expect.stringContaining('zip-build-auto-backup-'), { force: true });
expect(fsMock.rmSync).toHaveBeenCalledWith(expect.stringContaining('travel-snap-auto-backup-'), { force: true });
expect(storageStub.list).not.toHaveBeenCalledWith('backups');
expect(storageStub.delete).not.toHaveBeenCalled();
});
});
describe('auto-backup scheduling (AutoBackupJob.start)', () => {
beforeEach(() => {
vi.clearAllMocks();
resetStorageStub();
fsMock.existsSync.mockImplementation(() => false);
fsMock.readFileSync.mockReturnValue('{}');
});
it('disabled settings unregister the job and log Auto-Backup disabled', () => {
const { job, registrar } = makeJob();
job.start();
expect(registrar.unregister).toHaveBeenCalledWith('auto-backup');
expect(registrar.register).not.toHaveBeenCalled();
expect(logMock.logInfo).toHaveBeenCalledWith('Auto-Backup disabled');
});
it('enabled settings register the built expression under the auto-backup name and log the banner', () => {
fsMock.existsSync.mockImplementation((p: PathLike) => String(p).endsWith('backup-settings.json'));
fsMock.readFileSync.mockReturnValue(JSON.stringify({ enabled: true, interval: 'daily', keep_days: 7, hour: 2 }));
const { job, registered } = makeJob();
job.start();
expect(registered.at(-1)?.name).toBe('auto-backup');
expect(registered.at(-1)?.expr).toBe('0 2 * * *');
expect(logMock.logInfo).toHaveBeenCalledWith(
expect.stringMatching(/^Auto-Backup scheduled: daily \(0 2 \* \* \*\), tz: .+, retention: 7 days$/),
);
});
it('skips the banner when the registrar refuses to arm (test gate)', () => {
fsMock.existsSync.mockImplementation((p: PathLike) => String(p).endsWith('backup-settings.json'));
fsMock.readFileSync.mockReturnValue(JSON.stringify({ enabled: true, interval: 'daily', keep_days: 7 }));
const { job, registrar } = makeJob();
registrar.register.mockImplementation(() => false);
job.start();
expect(logMock.logInfo).not.toHaveBeenCalledWith(expect.stringContaining('Auto-Backup scheduled'));
});
it('onApplicationBootstrap does nothing when the registrar is disabled', () => {
const { job, registrar } = makeJob();
registrar.isEnabled.mockReturnValue(false);
job.onApplicationBootstrap();
expect(registrar.register).not.toHaveBeenCalled();
expect(registrar.unregister).not.toHaveBeenCalled();
expect(logMock.logInfo).not.toHaveBeenCalled();
});
it('onApplicationBootstrap arms the cron when the registrar is enabled', () => {
fsMock.existsSync.mockImplementation((p: PathLike) => String(p).endsWith('backup-settings.json'));
fsMock.readFileSync.mockReturnValue(JSON.stringify({ enabled: true, interval: 'hourly' }));
const { job, registered } = makeJob();
job.onApplicationBootstrap();
expect(registered.at(-1)?.name).toBe('auto-backup');
expect(registered.at(-1)?.expr).toBe('0 * * * *');
});
it('keep_days 0 banners "retention: forever" and skips retention after a run', async () => {
fsMock.existsSync.mockImplementation((p: PathLike) => String(p).endsWith('backup-settings.json'));
fsMock.readFileSync.mockReturnValue(JSON.stringify({ enabled: true, interval: 'daily', keep_days: 0 }));
stubArchiver();
const { job, registered } = makeJob();
job.start();
expect(logMock.logInfo).toHaveBeenCalledWith(expect.stringContaining('retention: forever'));
await (registered.at(-1)?.onTick as () => Promise<void>)();
expect(logMock.logInfo).toHaveBeenCalledWith(expect.stringContaining('Auto-Backup created'));
expect(storageStub.list).not.toHaveBeenCalledWith('backups'); // cleanupOldBackups never ran
expect(storageStub.delete).not.toHaveBeenCalled();
});
it('a non-Error rejection from createBackup is stringified into the failure log', async () => {
const broken = { createBackup: vi.fn().mockRejectedValue('plain string') } as unknown as BackupService;
const registrar = { isEnabled: vi.fn(() => true), register: vi.fn(() => true), unregister: vi.fn() };
const job = new AutoBackupJob(broken, registrar as unknown as CronRegistrarService, storageStub as unknown as StorageService);
await job.runBackup();
expect(logMock.logError).toHaveBeenCalledWith('Auto-Backup: plain string');
});
it('getAutoSettings returns the loaded settings with a resolved timezone', () => {
const prevTz = process.env.TZ;
try {
process.env.TZ = 'Europe/Zurich';
const { job } = makeJob();
expect(job.getAutoSettings()).toEqual({
settings: { enabled: false, interval: 'daily', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 },
timezone: 'Europe/Zurich',
});
delete process.env.TZ;
// Falls back to the host zone (or UTC when the host reports none).
expect(typeof job.getAutoSettings().timezone).toBe('string');
expect(job.getAutoSettings().timezone.length).toBeGreaterThan(0);
} finally {
if (prevTz === undefined) delete process.env.TZ;
else process.env.TZ = prevTz;
}
});
});
// Moved from backup.impl.test.ts when updateAutoSettings moved onto the job
// (the impl used to call scheduler.saveSettings + scheduler.start()).
describe('BACKUP-047 updateAutoSettings', () => {
beforeEach(() => {
vi.clearAllMocks();
resetStorageStub();
fsMock.existsSync.mockImplementation(() => false);
fsMock.readFileSync.mockReturnValue('{}');
});
it('BACKUP-047a — persists the parsed settings to backup-settings.json', () => {
const { job } = makeJob();
job.updateAutoSettings({ enabled: true, interval: 'weekly', hour: 6 });
expect(fsMock.writeFileSync).toHaveBeenCalledOnce();
const [file, payload] = fsMock.writeFileSync.mock.calls[0] as [string, string];
expect(file).toContain('backup-settings.json');
expect(JSON.parse(payload)).toMatchObject({ enabled: true, interval: 'weekly', hour: 6 });
});
it('BACKUP-047b — re-arms the job only after saving', () => {
const order: string[] = [];
fsMock.writeFileSync.mockImplementation(() => { order.push('save'); });
const { job, registrar } = makeJob();
// Saving {enabled:false} sends start() down the disabled path — unregister
// is its scheduling action, so it stands in for the old scheduler.start().
registrar.unregister.mockImplementation(() => { order.push('start'); });
job.updateAutoSettings({ enabled: false });
expect(order).toEqual(['save', 'start']);
});
it('BACKUP-047c — returns the parsed settings object', () => {
const { job } = makeJob();
const result = job.updateAutoSettings({
enabled: true,
interval: 'monthly',
keep_days: 30,
hour: 3,
day_of_week: 2,
day_of_month: 15,
});
expect(result).toEqual({
enabled: true,
interval: 'monthly',
keep_days: 30,
hour: 3,
day_of_week: 2,
day_of_month: 15,
});
});
});
+151
View File
@@ -0,0 +1,151 @@
/**
* The cost plugin surface after it moved onto @PluginMethod. This is the first
* addon-gated domain, and the addon check sits in a different place in each of the
* two reads: inside the membership callback for costs.getByTrip, before everything
* for costs.listMine. Both orderings are asserted, because swapping them changes
* which refusal a caller sees.
*/
import { describe, it, expect, vi } from 'vitest';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
import { CostsRpc } from '../../../src/nest/budget/costs.rpc';
import { BudgetModule } from '../../../src/nest/budget/budget.module';
import type { BudgetService } from '../../../src/nest/budget/budget.service';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import type { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
import { makeDeps } from '../../helpers/rpc-host-deps';
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
/** Trip 1 belongs to user 42, cost 5 sits on it, and the addon is on unless said otherwise. */
function build(opts: { addonOn?: boolean; canEdit?: boolean; missing?: boolean } = {}) {
const budget = {
listBudgetItems: vi.fn((tripId: number) => [{ id: 5, trip_id: tripId }]),
create: vi.fn(async (tripId: string, i: Record<string, unknown>) => ({ id: 9, trip_id: tripId, ...i })),
update: vi.fn(async () => (opts.missing ? null : { id: 5, name: 'Hotel' })),
remove: vi.fn(() => !opts.missing),
} as unknown as BudgetService & Record<string, ReturnType<typeof vi.fn>>;
const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };
const db = {
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)),
prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })),
} as unknown as DatabaseService;
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,
);
// The leaf membership read replaced the deleted trips.bridge for listMine.
const membership = { listAccessibleTripIds: vi.fn(() => [1, 2]) } as unknown as TripMembershipService;
const rpc = new CostsRpc(budget, db, realtime, guards, membership);
const host = (...grants: string[]) =>
new PluginRpcHost('p', new Set(grants.length ? grants : ['db:read:costs', 'db:write:costs']), makeDeps(), createTestPluginRegistry([rpc]));
return { budget, realtime, host };
}
describe('CostsRpc reads', () => {
it('COSTS-RPC-001 getByTrip is membership-checked and addon-gated', async () => {
const f = build();
expect((await f.host().dispatch(req('costs.getByTrip', { tripId: 1 }), 42)).ok).toBe(true);
expect(((await f.host().dispatch(req('costs.getByTrip', { tripId: 2 }), 42)) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
});
it('COSTS-RPC-002 getByTrip reports the TRIP first when both would fail', async () => {
// The addon check runs inside the membership callback, so a caller without trip
// access never learns whether the addon is on. Reversing the two would leak that.
const f = build({ addonOn: false });
const res = (await f.host().dispatch(req('costs.getByTrip', { tripId: 2 }), 42)) as RpcError;
expect(res.error.message).toBe('no access to trip 2');
});
it('COSTS-RPC-003 getByTrip reports the addon once the trip checks out', async () => {
const f = build({ addonOn: false });
const res = (await f.host().dispatch(req('costs.getByTrip', { tripId: 1 }), 42)) as RpcError;
expect(res.error.message).toBe('the costs addon is disabled');
expect(f.budget.listBudgetItems).not.toHaveBeenCalled();
});
it('COSTS-RPC-004 listMine checks the user first, then the addon', async () => {
const f = build({ addonOn: false });
// No trip to check here, so the userless refusal comes first and the addon second.
expect(((await f.host().dispatch(req('costs.listMine'), undefined)) as RpcError).error.message)
.toBe('cost reads require an authenticated user context');
expect(((await f.host().dispatch(req('costs.listMine'), 42)) as RpcError).error.message)
.toBe('the costs addon is disabled');
});
it('COSTS-RPC-005 listMine aggregates across every accessible trip', async () => {
const f = build();
const res = await f.host().dispatch(req('costs.listMine'), 42);
expect(res.ok).toBe(true);
expect(f.budget.listBudgetItems).toHaveBeenCalledTimes(2);
});
});
describe('CostsRpc writes', () => {
it('COSTS-RPC-006 every write needs the addon, trip access and budget_edit', async () => {
const f = build();
expect((await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel', price: 10 } }), 42)).ok).toBe(true);
const off = build({ addonOn: false });
expect(((await off.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError).error.message)
.toBe('the costs addon is disabled');
const noEdit = build({ canEdit: false });
expect(((await noEdit.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError).error.message)
.toBe('no permission to edit costs on trip 1');
});
it('COSTS-RPC-007 the refusal says "costs on trip", not the generic trip message', async () => {
// requireTripEdit would say "no permission to edit trip 1"; shipped plugins read
// these strings, so the cost-specific wording is kept.
const f = build({ canEdit: false });
for (const [method, params] of [
['costs.create', { tripId: 1, input: { name: 'x', price: 1 } }],
['costs.update', { tripId: 1, itemId: 5, input: { name: 'x' } }],
['costs.delete', { tripId: 1, itemId: 5 }],
] as const) {
expect(((await f.host().dispatch(req(method, params), 42)) as RpcError).error.message)
.toBe('no permission to edit costs on trip 1');
}
});
it('COSTS-RPC-008 a userless write says "cost writes"', async () => {
const f = build();
expect(((await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), undefined)) as RpcError).error.message)
.toBe('cost writes require an authenticated user context');
});
it('COSTS-RPC-009 db:read:costs does not unlock a write', async () => {
const f = build();
expect(((await f.host('db:read:costs').dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError).error.code)
.toBe('PERMISSION_DENIED');
});
it('COSTS-RPC-010 a missing item is RESOURCE_FORBIDDEN, naming it', async () => {
const f = build({ missing: true });
expect(((await f.host().dispatch(req('costs.update', { tripId: 1, itemId: 404, input: { name: 'x' } }), 42)) as RpcError).error.message)
.toBe('no cost 404 on trip 1');
expect(((await f.host().dispatch(req('costs.delete', { tripId: 1, itemId: 404 }), 42)) as RpcError).error.message)
.toBe('no cost 404 on trip 1');
});
it('COSTS-RPC-011 each write broadcasts its event, a refused one broadcasts nothing', async () => {
const f = build();
await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel', price: 10 } }), 42);
await f.host().dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { name: 'x' } }), 42);
await f.host().dispatch(req('costs.delete', { tripId: 1, itemId: 5 }), 42);
expect(f.realtime.broadcast.mock.calls.map((c) => c[1])).toEqual(['budget:created', 'budget:updated', 'budget:deleted']);
const off = build({ addonOn: false });
await off.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42);
expect(off.realtime.broadcast).not.toHaveBeenCalled();
});
it('COSTS-RPC-012 the class is listed in its module providers', () => {
expectRegisteredProvider(BudgetModule, CostsRpc);
});
});
+109
View File
@@ -0,0 +1,109 @@
import fs from 'node:fs';
import path from 'node:path';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// config.ts resolves its key material at import time, so every case here has to
// reset the module registry and re-import it with the file system stubbed out.
const ENC_KEY_FILE = path.resolve(__dirname, '../../data/.encryption_key');
const JWT_SECRET_FILE = path.resolve(__dirname, '../../data/.jwt_secret');
const enoent = (): NodeJS.ErrnoException => {
const err = new Error('ENOENT: no such file or directory') as NodeJS.ErrnoException;
err.code = 'ENOENT';
return err;
};
describe('config — encryption key resolution', () => {
const realEnvKey = process.env.ENCRYPTION_KEY;
const realRead = fs.readFileSync;
beforeEach(() => {
// The env var short-circuits the whole file-resolution chain under test.
delete process.env.ENCRYPTION_KEY;
vi.resetModules();
});
afterEach(() => {
vi.restoreAllMocks();
vi.resetModules();
process.env.ENCRYPTION_KEY = realEnvKey;
});
// Only the key file itself is faked; everything else keeps reading from disk,
// because app-config and its dependants load in the same import.
const stubKeyFileRead = (impl: () => string) => {
vi.spyOn(fs, 'readFileSync').mockImplementation(((file: fs.PathOrFileDescriptor, ...rest: unknown[]) => {
if (String(file) === ENC_KEY_FILE) return impl();
if (String(file) === JWT_SECRET_FILE) throw enoent();
return (realRead as (...args: unknown[]) => unknown)(file, ...rest);
}) as typeof fs.readFileSync);
};
it('CFGKEY-001: aborts boot when the key file cannot be read for a reason other than ENOENT', async () => {
const exit = vi.spyOn(process, 'exit').mockImplementation((() => {
throw new Error('process.exit called');
}) as never);
const write = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
vi.spyOn(console, 'error').mockImplementation(() => undefined);
stubKeyFileRead(() => {
const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;
err.code = 'EACCES';
throw err;
});
await expect(import('../../src/config')).rejects.toThrow('process.exit called');
expect(exit).toHaveBeenCalledWith(1);
expect(write).not.toHaveBeenCalledWith(ENC_KEY_FILE, expect.anything(), expect.anything());
});
it('CFGKEY-001b: names the errno, and the bind-mount case behind EISDIR', async () => {
vi.spyOn(process, 'exit').mockImplementation((() => {
throw new Error('process.exit called');
}) as never);
vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);
stubKeyFileRead(() => {
const err = new Error('EISDIR: illegal operation on a directory, read') as NodeJS.ErrnoException;
err.code = 'EISDIR';
throw err;
});
await expect(import('../../src/config')).rejects.toThrow('process.exit called');
// Without the code the operator sees a message and no way to tell a
// permission problem from a directory in the file's place.
const lines = error.mock.calls.map((c) => c.join(' '));
expect(lines.some((l) => l.startsWith('FATAL:') && l.includes('EISDIR'))).toBe(true);
expect(lines.some((l) => l.includes('bind mount'))).toBe(true);
});
it('CFGKEY-002: refuses to regenerate over an existing but empty key file', async () => {
const exit = vi.spyOn(process, 'exit').mockImplementation((() => {
throw new Error('process.exit called');
}) as never);
const write = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
vi.spyOn(console, 'error').mockImplementation(() => undefined);
vi.spyOn(fs, 'existsSync').mockImplementation(((file: fs.PathLike) => String(file) === ENC_KEY_FILE) as typeof fs.existsSync);
stubKeyFileRead(() => ' \n');
await expect(import('../../src/config')).rejects.toThrow('process.exit called');
expect(exit).toHaveBeenCalledWith(1);
expect(write).not.toHaveBeenCalledWith(ENC_KEY_FILE, expect.anything(), expect.anything());
});
it('CFGKEY-003: still auto-generates a key when nothing is on disk yet', async () => {
const exit = vi.spyOn(process, 'exit').mockImplementation((() => {
throw new Error('process.exit called');
}) as never);
vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
vi.spyOn(console, 'log').mockImplementation(() => undefined);
// The key file is genuinely absent, so the empty-file guard must not fire.
vi.spyOn(fs, 'existsSync').mockImplementation(((file: fs.PathLike) => String(file) !== ENC_KEY_FILE) as typeof fs.existsSync);
stubKeyFileRead(() => {
throw enoent();
});
const config = await import('../../src/config');
expect(exit).not.toHaveBeenCalled();
expect(config.ENCRYPTION_KEY).toMatch(/^[0-9a-f]{64}$/);
});
});
@@ -0,0 +1,120 @@
/**
* The day-note plugin surface after it moved onto @PluginMethod. The dispatch-level
* cases come from rpc-host.test.ts unchanged except for the construction line and
* the stub identity; the rest cover the per-handler paths the router-level test had
* no room for.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
import { DayNotesRpc } from '../../../src/nest/day-notes/day-notes.rpc';
import { DayNotesModule } from '../../../src/nest/day-notes/day-notes.module';
import type { DayNotesService } from '../../../src/nest/day-notes/day-notes.service';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
import { makeDeps } from '../../helpers/rpc-host-deps';
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
/** Trip 1 belongs to user 42; day 5 and note 50 sit on it. Nothing else does. */
function build(canEdit = true) {
const notes = {
list: vi.fn((dayId: number, tripId: number) => [{ id: 50, day_id: dayId, trip_id: tripId, text: 'note' }]),
dayExists: vi.fn((dayId: number, tripId: number) => dayId === 5 && tripId === 1),
getNote: vi.fn((id: number, dayId: number, tripId: number) =>
id === 50 && dayId === 5 && tripId === 1 ? { id: 50, text: 'note' } : undefined,
),
create: vi.fn((dayId: number, tripId: number, text: string) => ({ id: 51, day_id: dayId, trip_id: tripId, text })),
update: vi.fn((id: number) => ({ id, text: 'updated' })),
remove: vi.fn(),
} as unknown as DayNotesService & Record<string, ReturnType<typeof vi.fn>>;
const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };
const db = {
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)),
prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })),
} as unknown as DatabaseService;
const guards = new PluginGuards(
db,
{ checkPermission: vi.fn(() => canEdit) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
);
const rpc = new DayNotesRpc(notes, realtime, guards);
const host = (...grants: string[]) =>
new PluginRpcHost('p', new Set(grants), makeDeps(), createTestPluginRegistry([rpc]));
return { notes, realtime, rpc, host };
}
describe('DayNotesRpc through the router', () => {
let f: ReturnType<typeof build>;
beforeEach(() => {
f = build();
});
it('DAYNOTES-RPC-001 daynotes.list is membership-checked (trip-scoped)', async () => {
const host = f.host('db:read:daynotes');
expect((await host.dispatch(req('daynotes.list', { tripId: 1, dayId: 5 }), 42)).ok).toBe(true);
expect(f.notes.list).toHaveBeenCalledWith(5, 1);
const forbidden = await host.dispatch(req('daynotes.list', { tripId: 999, dayId: 5 }), 42);
expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
});
it('DAYNOTES-RPC-002 create needs db:write:daynotes + day_edit, membership-checked, text required', async () => {
const host = f.host('db:write:daynotes');
expect((await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'Pack sunscreen' } }), 42)).ok).toBe(true);
expect(f.notes.create).toHaveBeenCalledWith(5, 1, 'Pack sunscreen', undefined, undefined, undefined);
const bad = await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: ' ' } }), 42);
expect((bad as RpcError).error.code).toBe('BAD_PARAMS');
const forbidden = await host.dispatch(req('daynotes.create', { tripId: 2, dayId: 5, input: { text: 'x' } }), 42);
expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
});
it('DAYNOTES-RPC-003 delete is gated the same way (edit + membership + bound user)', async () => {
const host = f.host('db:write:daynotes');
expect((await host.dispatch(req('daynotes.delete', { tripId: 1, dayId: 5, noteId: 50 }), 42)).ok).toBe(true);
expect(f.notes.remove).toHaveBeenCalledWith(50);
const noUser = await host.dispatch(req('daynotes.delete', { tripId: 1, dayId: 5, noteId: 50 }), undefined);
expect((noUser as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
});
it('DAYNOTES-RPC-004 the read grant does not unlock a write', async () => {
const host = f.host('db:read:daynotes');
const res = (await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'x' } }), 42)) as RpcError;
expect(res.error.code).toBe('PERMISSION_DENIED');
});
it('DAYNOTES-RPC-005 update broadcasts and returns the updated note', async () => {
const host = f.host('db:write:daynotes');
expect((await host.dispatch(req('daynotes.update', { tripId: 1, dayId: 5, noteId: 50, input: { text: 'new' } }), 42)).ok).toBe(true);
expect(f.realtime.broadcast).toHaveBeenCalledWith(1, 'dayNote:updated', expect.objectContaining({ dayId: 5 }), undefined);
});
it('DAYNOTES-RPC-006 a note on another day is refused, naming it', async () => {
const host = f.host('db:write:daynotes');
const res = (await host.dispatch(req('daynotes.update', { tripId: 1, dayId: 5, noteId: 404, input: {} }), 42)) as RpcError;
expect(res.error.code).toBe('RESOURCE_FORBIDDEN');
expect(res.error.message).toBe('no note 404 on day 5');
});
it('DAYNOTES-RPC-007 without the edit permission the write is refused before it touches the service', async () => {
const noEdit = build(false);
const host = noEdit.host('db:write:daynotes');
const res = (await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'x' } }), 42)) as RpcError;
expect(res.error.message).toBe('no permission to edit trip 1');
expect(noEdit.notes.create).not.toHaveBeenCalled();
});
it('DAYNOTES-RPC-008 a day outside the trip is refused, naming it', async () => {
const host = f.host('db:write:daynotes');
const res = (await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 99, input: { text: 'x' } }), 42)) as RpcError;
expect(res.error.message).toBe('no day 99 on trip 1');
});
it('DAYNOTES-RPC-009 the class is listed in its module providers', () => {
expectRegisteredProvider(DayNotesModule, DayNotesRpc);
});
});
@@ -0,0 +1,146 @@
/**
* The day and itinerary plugin surfaces after they moved onto @PluginMethod.
*
* They are tested together because they share the gate: assigning a place to a day
* counts as a DAY edit in the app, so itinerary.* runs under day_edit rather than a
* permission of its own, and both halves scope their rows to the trip before writing.
*/
import { describe, it, expect, vi } from 'vitest';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
import { DaysRpc } from '../../../src/nest/days/days.rpc';
import { DaysModule } from '../../../src/nest/days/days.module';
import { ItineraryRpc } from '../../../src/nest/assignments/itinerary.rpc';
import { AssignmentsModule } from '../../../src/nest/assignments/assignments.module';
import type { DaysService } from '../../../src/nest/days/days.service';
import type { AssignmentsService } from '../../../src/nest/assignments/assignments.service';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
import { makeDeps } from '../../helpers/rpc-host-deps';
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
/** Trip 1 belongs to user 42; day 3, place 7 and assignment 30 sit on it. */
function build(opts: { canEdit?: boolean } = {}) {
const days = {
create: vi.fn((tripId: number, date?: string) => ({ id: 20, trip_id: tripId, date })),
getDay: vi.fn((dayId: number, tripId: number) => (dayId === 3 && tripId === 1 ? { id: 3 } : undefined)),
update: vi.fn((id: number) => ({ id })),
remove: vi.fn(),
} as unknown as DaysService & Record<string, ReturnType<typeof vi.fn>>;
const assignments = {
dayExists: vi.fn((dayId: number, tripId: number) => dayId === 3 && tripId === 1),
placeExists: vi.fn((placeId: number, tripId: number) => placeId === 7 && tripId === 1),
createAssignment: vi.fn(() => ({ id: 30, day_id: 3, place_id: 7 })),
getAssignmentForTrip: vi.fn((id: number, tripId: number) => (id === 30 && tripId === 1 ? { id: 30, day_id: 3 } : undefined)),
deleteAssignment: vi.fn(),
reconcile: vi.fn(),
} as unknown as AssignmentsService & Record<string, ReturnType<typeof vi.fn>>;
const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };
const guards = new PluginGuards(
{
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)),
prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })),
} as unknown as DatabaseService,
{ checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
);
const registry = createTestPluginRegistry([new DaysRpc(days, realtime, guards), new ItineraryRpc(assignments, realtime, guards)]);
const host = (...grants: string[]) => new PluginRpcHost('p', new Set(grants), makeDeps(), registry);
return { days, assignments, realtime, host };
}
describe('DaysRpc', () => {
it('DAYS-RPC-001 writes need the grant, the edit right and a bound user', async () => {
const f = build();
const host = f.host('db:write:days');
expect((await host.dispatch(req('days.create', { tripId: 1, input: { date: '2027-01-01' } }), 42)).ok).toBe(true);
expect(((await host.dispatch(req('days.create', { tripId: 2, input: {} }), 42)) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
const noUser = (await host.dispatch(req('days.create', { tripId: 1, input: {} }), undefined)) as RpcError;
expect(noUser.error.message).toBe('day writes require an authenticated user context');
});
it('DAYS-RPC-002 a day on another trip is refused for update and delete alike', async () => {
const f = build();
const host = f.host('db:write:days');
expect(((await host.dispatch(req('days.update', { tripId: 1, dayId: 404, input: {} }), 42)) as RpcError).error.message)
.toBe('no day 404 on trip 1');
expect(((await host.dispatch(req('days.delete', { tripId: 1, dayId: 404 }), 42)) as RpcError).error.message)
.toBe('no day 404 on trip 1');
expect(f.days.remove).not.toHaveBeenCalled();
});
it('DAYS-RPC-003 every write broadcasts its event', async () => {
const f = build();
const host = f.host('db:write:days');
await host.dispatch(req('days.create', { tripId: 1, input: {} }), 42);
await host.dispatch(req('days.update', { tripId: 1, dayId: 3, input: { notes: 'x' } }), 42);
await host.dispatch(req('days.delete', { tripId: 1, dayId: 3 }), 42);
expect(f.realtime.broadcast.mock.calls.map((c) => c[1])).toEqual(['day:created', 'day:updated', 'day:deleted']);
});
it('DAYS-RPC-004 the class is listed in its module providers', () => {
expectRegisteredProvider(DaysModule, DaysRpc);
});
});
describe('ItineraryRpc', () => {
it('ITIN-RPC-001 assign links a day and a place that both belong to the trip', async () => {
const f = build();
const res = await f.host('db:write:itinerary').dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 7 }), 42);
expect(res.ok).toBe(true);
expect(f.assignments.createAssignment).toHaveBeenCalledWith(3, 7, null);
});
it('ITIN-RPC-002 a day or place from another trip is refused, so nothing cross-links', async () => {
const f = build();
const host = f.host('db:write:itinerary');
expect(((await host.dispatch(req('itinerary.assign', { tripId: 1, dayId: 404, placeId: 7 }), 42)) as RpcError).error.message)
.toBe('no day 404 on trip 1');
expect(((await host.dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 404 }), 42)) as RpcError).error.message)
.toBe('no place 404 on trip 1');
expect(f.assignments.createAssignment).not.toHaveBeenCalled();
});
it('ITIN-RPC-003 it runs under day_edit, not an itinerary permission of its own', async () => {
const f = build({ canEdit: false });
const res = (await f.host('db:write:itinerary').dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 7 }), 42)) as RpcError;
expect(res.error.message).toBe('no permission to edit trip 1');
});
it('ITIN-RPC-004 notes are optional and pass through as null when absent', async () => {
const f = build();
await f.host('db:write:itinerary').dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 7, notes: 'lunch' }), 42);
expect(f.assignments.createAssignment).toHaveBeenCalledWith(3, 7, 'lunch');
});
it('ITIN-RPC-005 unassign carries the dayId, which the client keys its eviction on', async () => {
const f = build();
await f.host('db:write:itinerary').dispatch(req('itinerary.unassign', { tripId: 1, assignmentId: 30 }), 42);
expect(f.realtime.broadcast).toHaveBeenCalledWith(1, 'assignment:deleted', { assignmentId: 30, dayId: 3 });
});
it('ITIN-RPC-006 both writes re-mirror the journey skeletons afterwards', async () => {
const f = build();
const host = f.host('db:write:itinerary');
await host.dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 7 }), 42);
await host.dispatch(req('itinerary.unassign', { tripId: 1, assignmentId: 30 }), 42);
expect(f.assignments.reconcile).toHaveBeenCalledTimes(2);
});
it('ITIN-RPC-007 an assignment on another trip is refused and nothing is deleted', async () => {
const f = build();
const res = (await f.host('db:write:itinerary').dispatch(req('itinerary.unassign', { tripId: 1, assignmentId: 404 }), 42)) as RpcError;
expect(res.error.message).toBe('no assignment 404 on trip 1');
expect(f.assignments.deleteAssignment).not.toHaveBeenCalled();
});
it('ITIN-RPC-008 the class is listed in its module providers', () => {
expectRegisteredProvider(AssignmentsModule, ItineraryRpc);
});
});
@@ -0,0 +1,127 @@
/**
* Boot migration: move the itemized receipt out of budget_items.note (#1658).
*
* The costs UI stored the receipt as a `TICKETJSON:` prefix on the note, so the
* migration lifts it into its own column and clears the note. The match has to
* be case-SENSITIVE: LIKE is not, which would swallow a hand-written note that
* happens to start with the same word.
*
* The second half covers the databases that ran the LIKE version before it was
* repaired — a fixed step never replays, so the damage is undone by a migration
* of its own at the end of the array.
*/
import { describe, it, expect } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
function makeDbWithNotes(): Database.Database {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA busy_timeout = 5000');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
// Minimal FK chain: user -> trip -> budget_items rows.
db.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')").run();
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run();
db.prepare(
'INSERT INTO budget_items (id, trip_id, name, note) VALUES (1, 1, ?, ?), (2, 1, ?, ?)',
).run('Dinner', 'TICKETJSON:{"items":[]}', 'Museum', 'ticketjson: buy at the door');
return db;
}
describe('budget_items ticket_json migration', () => {
it('moves a real receipt into ticket_json and clears the note', () => {
const db = makeDbWithNotes();
try {
runMigrations(db);
const row = db.prepare('SELECT note, ticket_json FROM budget_items WHERE id = 1').get() as {
note: string | null;
ticket_json: string | null;
};
expect(row).toEqual({ note: null, ticket_json: '{"items":[]}' });
} finally {
db.close();
}
});
it('leaves a lowercase note alone (LIKE would have eaten it)', () => {
const db = makeDbWithNotes();
try {
runMigrations(db);
const row = db.prepare('SELECT note, ticket_json FROM budget_items WHERE id = 2').get() as {
note: string | null;
ticket_json: string | null;
};
expect(row).toEqual({ note: 'ticketjson: buy at the door', ticket_json: null });
} finally {
db.close();
}
});
});
describe('recovering what the case-insensitive match destroyed', () => {
/**
* A database that already ran the buggy step: migrated to the tip, then wound
* back to just before the recovery step so it runs again — which is exactly
* what an existing install does on the next boot. The wind-back target is the
* recovery step's ABSOLUTE version (the array is append-only and
* index-addressed, so it never moves); anything appended after it replays too,
* which every later migration must tolerate anyway.
*/
function makeDamagedDb(): Database.Database {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA busy_timeout = 5000');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
runMigrations(db);
db.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')").run();
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run();
// Row 1: what the LIKE match left behind for "ticketjson: buy at the door".
// Row 2: an actual receipt. Row 3: a receipt on a row whose owner has since
// written a note.
db.prepare('INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)')
.run(1, 1, 'Museum', null, ' buy at the door');
db.prepare('INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)')
.run(2, 1, 'Dinner', null, '{"items":[{"name":"Beer","price":"4.50","parts":[1]}]}');
db.prepare('INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)')
.run(3, 1, 'Taxi', 'split at the hotel', '{"items":[]}');
// 196 = the version just before the recovery step (migration #197).
db.prepare('UPDATE schema_version SET version = ?').run(196);
return db;
}
const read = (db: Database.Database, id: number) =>
db.prepare('SELECT note, ticket_json FROM budget_items WHERE id = ?').get(id) as {
note: string | null;
ticket_json: string | null;
};
it('puts a chopped note back where it came from', () => {
const db = makeDamagedDb();
try {
runMigrations(db);
expect(read(db, 1)).toEqual({ note: ' buy at the door', ticket_json: null });
} finally {
db.close();
}
});
it('leaves a genuine receipt alone', () => {
const db = makeDamagedDb();
try {
runMigrations(db);
expect(read(db, 2)).toEqual({
note: null,
ticket_json: '{"items":[{"name":"Beer","price":"4.50","parts":[1]}]}',
});
// A note written since the damage means the row was not chopped, so it is
// not a candidate at all.
expect(read(db, 3)).toEqual({ note: 'split at the hotel', ticket_json: '{"items":[]}' });
} finally {
db.close();
}
});
});
+241
View File
@@ -0,0 +1,241 @@
import { execFileSync } from 'child_process';
import fs from 'fs';
import os from 'os';
import path from 'path';
import Database from 'better-sqlite3';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { resolveDurability } from '../../../src/app-config/parsers';
import { applyDurabilityPragmas } from '../../../src/db/durability';
// journal_mode is written into the database file header, so it outlives the
// connection that set it. Anything asserting a mode here therefore reopens the
// file: that is the property operators on SMB/NFS volumes actually depend on.
const SERVER_ROOT = path.resolve(__dirname, '../../..');
let tmpDir: string;
let dbPath: string;
function readModes(file: string): { journalMode: string; synchronous: number } {
const db = new Database(file);
try {
return {
journalMode: String(db.pragma('journal_mode', { simple: true })).toUpperCase(),
synchronous: Number(db.pragma('synchronous', { simple: true })),
};
} finally {
db.close();
}
}
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-durability-'));
dbPath = path.join(tmpDir, 'travel.db');
delete process.env.TREK_DB_JOURNAL_MODE;
delete process.env.TREK_DB_SYNCHRONOUS;
});
afterEach(() => {
delete process.env.TREK_DB_JOURNAL_MODE;
delete process.env.TREK_DB_SYNCHRONOUS;
vi.restoreAllMocks();
fs.rmSync(tmpDir, { recursive: true, force: true });
});
describe('resolveDurability', () => {
it('defaults to WAL with the synchronous level a WAL database already runs at', () => {
expect(resolveDurability(undefined, undefined)).toEqual({
journalMode: 'WAL',
synchronous: 'NORMAL',
warnings: [],
});
expect(resolveDurability('', '')).toEqual({ journalMode: 'WAL', synchronous: 'NORMAL', warnings: [] });
});
it('accepts every SQLite journal mode, case- and padding-insensitively', () => {
expect(resolveDurability('delete', undefined).journalMode).toBe('DELETE');
expect(resolveDurability(' Truncate ', undefined).journalMode).toBe('TRUNCATE');
expect(resolveDurability('PERSIST', undefined).journalMode).toBe('PERSIST');
expect(resolveDurability('memory', undefined).journalMode).toBe('MEMORY');
expect(resolveDurability('off', undefined).journalMode).toBe('OFF');
});
it('raises the default to FULL once a rollback journal is in play', () => {
// NORMAL is only safe under WAL; on DELETE/TRUNCATE it lets a power cut eat
// committed transactions, which would defeat the point of leaving WAL.
expect(resolveDurability('DELETE', undefined).synchronous).toBe('FULL');
expect(resolveDurability('TRUNCATE', undefined).synchronous).toBe('FULL');
expect(resolveDurability('WAL', undefined).synchronous).toBe('NORMAL');
});
it('lets synchronous be set independently of the journal mode', () => {
expect(resolveDurability('WAL', 'full').synchronous).toBe('FULL');
expect(resolveDurability('DELETE', 'normal').synchronous).toBe('NORMAL');
expect(resolveDurability(undefined, 'EXTRA').synchronous).toBe('EXTRA');
expect(resolveDurability(undefined, 'off').synchronous).toBe('OFF');
});
it('falls back and reports instead of rejecting an unusable value', () => {
const result = resolveDurability('WALL', 'sort-of');
expect(result.journalMode).toBe('WAL');
expect(result.synchronous).toBe('NORMAL');
expect(result.warnings).toHaveLength(2);
expect(result.warnings[0]).toContain('TREK_DB_JOURNAL_MODE="WALL"');
expect(result.warnings[1]).toContain('TREK_DB_SYNCHRONOUS="sort-of"');
});
it('keeps the per-mode synchronous default when only that value is bogus', () => {
const result = resolveDurability('DELETE', 'maybe');
expect(result.journalMode).toBe('DELETE');
expect(result.synchronous).toBe('FULL');
expect(result.warnings).toHaveLength(1);
});
});
describe('applyDurabilityPragmas', () => {
it('leaves an unconfigured install on WAL', () => {
const db = new Database(dbPath);
const active = applyDurabilityPragmas(db);
db.exec('CREATE TABLE t (a)');
db.close();
expect(active).toEqual({ journalMode: 'WAL', synchronous: 'NORMAL' });
expect(readModes(dbPath).journalMode).toBe('WAL');
});
it('switches the file to the configured mode and persists it', () => {
process.env.TREK_DB_JOURNAL_MODE = 'DELETE';
const wal = new Database(dbPath);
wal.exec('PRAGMA journal_mode = WAL');
wal.exec('CREATE TABLE t (a)');
wal.close();
expect(readModes(dbPath).journalMode).toBe('WAL');
const db = new Database(dbPath);
const active = applyDurabilityPragmas(db);
db.close();
expect(active.journalMode).toBe('DELETE');
// FULL (2) — a rollback journal without it is no safer than the WAL setup
// the operator moved away from.
expect(active.synchronous).toBe('FULL');
expect(readModes(dbPath)).toEqual({ journalMode: 'DELETE', synchronous: 2 });
});
it('applies an explicit synchronous level on top of the journal mode', () => {
process.env.TREK_DB_SYNCHRONOUS = 'FULL';
const db = new Database(dbPath);
const active = applyDurabilityPragmas(db);
expect(active).toEqual({ journalMode: 'WAL', synchronous: 'FULL' });
expect(Number(db.pragma('synchronous', { simple: true }))).toBe(2);
db.close();
});
it('warns and stays on the default when the mode is misspelled', () => {
process.env.TREK_DB_JOURNAL_MODE = 'DELET';
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const db = new Database(dbPath);
const active = applyDurabilityPragmas(db);
db.close();
expect(active.journalMode).toBe('WAL');
expect(warn).toHaveBeenCalledTimes(1);
expect(String(warn.mock.calls[0][0])).toContain('TREK_DB_JOURNAL_MODE="DELET"');
});
it('warns and keeps the mode default when synchronous is misspelled', () => {
process.env.TREK_DB_SYNCHRONOUS = 'VERY';
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const db = new Database(dbPath);
const active = applyDurabilityPragmas(db);
db.close();
expect(active.synchronous).toBe('NORMAL');
expect(warn).toHaveBeenCalledTimes(1);
expect(String(warn.mock.calls[0][0])).toContain('TREK_DB_SYNCHRONOUS="VERY"');
});
it('reports what the engine settled on, not what was asked for', () => {
process.env.TREK_DB_JOURNAL_MODE = 'WAL';
const db = new Database(':memory:');
expect(applyDurabilityPragmas(db).journalMode).toBe('MEMORY');
db.close();
});
});
// The other two processes that open travel.db read-write. They cannot import
// the module above (standalone scripts, and src/ is not in the container
// image), so they are exercised as processes — a copy of the resolution that
// drifts flips the header back and silently un-does the operator's choice.
describe('standalone scripts honour the same configuration', () => {
function seedWalDb(): void {
const db = new Database(dbPath);
db.exec('PRAGMA journal_mode = WAL');
db.exec(`
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
email TEXT UNIQUE,
password_hash TEXT,
role TEXT,
must_change_password INTEGER DEFAULT 0,
mfa_secret TEXT,
maps_api_key TEXT,
openweather_api_key TEXT,
immich_api_key TEXT,
synology_password TEXT,
synology_sid TEXT,
synology_did TEXT
);
CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE settings (user_id INTEGER, key TEXT, value TEXT);
CREATE TABLE trip_album_links (id INTEGER PRIMARY KEY, passphrase TEXT);
CREATE TABLE trek_photos (id INTEGER PRIMARY KEY, passphrase TEXT);
`);
db.close();
expect(readModes(dbPath).journalMode).toBe('WAL');
}
it('reset-admin.js applies TREK_DB_JOURNAL_MODE instead of leaving WAL behind', () => {
seedWalDb();
execFileSync(process.execPath, ['reset-admin.js'], {
cwd: SERVER_ROOT,
env: {
...process.env,
TREK_DB_FILE: dbPath,
TREK_DB_JOURNAL_MODE: 'DELETE',
RESET_ADMIN_EMAIL: 'locked-out@example.com',
RESET_ADMIN_PASSWORD: 'Recovery12345!',
},
stdio: 'pipe',
});
expect(readModes(dbPath)).toEqual({ journalMode: 'DELETE', synchronous: 2 });
const db = new Database(dbPath);
const admin = db.prepare('SELECT role FROM users WHERE email = ?').get('locked-out@example.com') as
| { role: string }
| undefined;
db.close();
expect(admin?.role).toBe('admin');
}, 60000);
it('migrate-encryption.ts no longer forces the database back to WAL', () => {
seedWalDb();
execFileSync(process.execPath, ['--import', 'tsx', 'scripts/migrate-encryption.ts'], {
cwd: SERVER_ROOT,
env: { ...process.env, DB_PATH: dbPath, TREK_DB_JOURNAL_MODE: 'DELETE' },
input: 'old-key\nnew-key\nyes\n',
stdio: 'pipe',
});
expect(readModes(dbPath)).toEqual({ journalMode: 'DELETE', synchronous: 2 });
}, 120000);
});
@@ -0,0 +1,141 @@
/**
* Unit test for the instance API-key backfill migration (#1939).
*
* The Places/Unsplash credential moved from "whichever admin row the resolver
* happened to find" to an instance-wide app_settings row. An install that
* upgrades must keep searching with the key it already had, so the migration
* copies the value the old resolver would have handed out — the lowest-id admin
* who has one — and leaves the users columns alone. It only does so where that
* value was the whole install's key: as soon as a second row holds one, the
* promotion is skipped, because the instance row outranks everybody's own
* column and nobody may be moved onto a stranger's key by an upgrade.
*
* Seeded before runMigrations rather than by rewinding schema_version
* afterwards: createTables already brings users.role and both key columns, so
* the backfill fires on its normal pass and finds the rows. That keeps this
* file independent of where the entry sits in the append-only array, so
* appending the next migration does not drag it along. The one guard that does
* have to track the tail is tests/integration/leg-mode-incoming.test.ts, which
* says so in place.
*/
import { describe, it, expect } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
function freshDb() {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
return db;
}
function seedUser(
db: Database.Database,
id: number,
role: 'admin' | 'user',
keys: { maps?: string; unsplash?: string } = {},
) {
db.prepare(
`INSERT INTO users (id, username, email, password_hash, role, maps_api_key, unsplash_api_key)
VALUES (?, ?, ?, 'x', ?, ?, ?)`
).run(id, `u${id}`, `u${id}@test.local`, role, keys.maps ?? null, keys.unsplash ?? null);
}
const setting = (db: Database.Database, key: string) =>
(db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value;
describe('instance API-key backfill migration', () => {
it('KEYFILL-001: copies the one key the install was searching with and keeps the column', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'the-admin-google', unsplash: 'the-admin-unsplash' });
seedUser(db, 2, 'user');
runMigrations(db);
expect(setting(db, 'maps_api_key')).toBe('the-admin-google');
expect(setting(db, 'unsplash_api_key')).toBe('the-admin-unsplash');
// Nothing is taken away: the columns are still the per-user fallback.
const row = db.prepare('SELECT maps_api_key FROM users WHERE id = 1').get() as { maps_api_key: string };
expect(row.maps_api_key).toBe('the-admin-google');
db.close();
});
it('KEYFILL-002: skips an admin whose column is empty and takes the next one', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: '' });
seedUser(db, 2, 'admin', { maps: 'the-only-real-key' });
runMigrations(db);
expect(setting(db, 'maps_api_key')).toBe('the-only-real-key');
db.close();
});
it('KEYFILL-003: never overwrites a value the admin has already saved instance-wide', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'old-column-key' });
db.prepare("INSERT INTO app_settings (key, value) VALUES ('maps_api_key', 'already-instance-wide')").run();
runMigrations(db);
expect(setting(db, 'maps_api_key')).toBe('already-instance-wide');
db.close();
});
it('KEYFILL-004: ignores a non-admin key and writes no row at all', () => {
const db = freshDb();
seedUser(db, 1, 'user', { maps: 'members-own-key' });
runMigrations(db);
// A member's key stays theirs — the resolver still finds it for them, and
// promoting it would hand their billing to the whole instance.
expect(setting(db, 'maps_api_key')).toBeUndefined();
db.close();
});
it('KEYFILL-005: writes nothing on an install that never had a key', () => {
const db = freshDb();
seedUser(db, 1, 'admin');
runMigrations(db);
expect(setting(db, 'maps_api_key')).toBeUndefined();
expect(setting(db, 'unsplash_api_key')).toBeUndefined();
db.close();
});
it('KEYFILL-006: leaves a column alone once a member holds a key of their own', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'admins-own-google', unsplash: 'admins-own-unsplash' });
seedUser(db, 7, 'user', { maps: 'members-own-google' });
runMigrations(db);
// Member 7 pays for their own Google key. Promoting the admin's would put
// every one of their searches on his key and his bill, because the instance
// row is resolved before their own column.
expect(setting(db, 'maps_api_key')).toBeUndefined();
// Decided per column: nobody else has an Unsplash key, so that one really
// was the whole install's and stays it.
expect(setting(db, 'unsplash_api_key')).toBe('admins-own-unsplash');
const row = db.prepare('SELECT maps_api_key FROM users WHERE id = 7').get() as { maps_api_key: string };
expect(row.maps_api_key).toBe('members-own-google');
db.close();
});
it('KEYFILL-007: two admins with their own keys both keep them', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'first-admin-google' });
seedUser(db, 2, 'admin', { maps: 'second-admin-google' });
runMigrations(db);
expect(setting(db, 'maps_api_key')).toBeUndefined();
const rows = db.prepare('SELECT maps_api_key FROM users ORDER BY id').all() as { maps_api_key: string }[];
expect(rows.map((r) => r.maps_api_key)).toEqual(['first-admin-google', 'second-admin-google']);
db.close();
});
});
@@ -0,0 +1,313 @@
/**
* Parity guard for scripts/migrate-encryption.ts.
*
* The rotation script re-encrypts at-rest secrets from one ENCRYPTION_KEY to the
* next, and it walks a hardcoded list of app_settings keys. It cannot import the
* canonical list from src/, because it deliberately runs without config.ts and
* without the Nest container, so the list is a copy.
*
* A missing name does not fail loudly: the value stays encrypted under the old
* key, decrypt_api_key returns null on the next read, and the instance quietly
* behaves as if no key were configured. This pins the copy instead.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { execFileSync } from 'node:child_process';
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
import { INSTANCE_API_KEY_NAMES } from '../../../src/nest/settings/instance-api-keys';
import { storageSecretFields } from '@trek/shared';
const SERVER_ROOT = path.join(__dirname, '..', '..', '..');
const script = fs.readFileSync(
path.join(__dirname, '..', '..', '..', 'scripts', 'migrate-encryption.ts'),
'utf8',
);
// The app_settings loop only, so a name that happens to appear elsewhere in the
// script (a users column of the same name, a comment) cannot satisfy the test.
const appSettingsLoop = (() => {
const start = script.indexOf("'oidc_client_secret'");
expect(start).toBeGreaterThan(-1);
const end = script.indexOf('--- users:', start);
expect(end).toBeGreaterThan(start);
return script.slice(start, end);
})();
// The storage.backends section only — bounded by its own marker and the next
// one (`--- settings:`), so a field name appearing elsewhere in the script
// cannot satisfy the test.
const storageBackendsSection = (() => {
const start = script.indexOf('--- app_settings: storage.backends ---');
expect(start).toBeGreaterThan(-1);
const end = script.indexOf('--- settings:', start);
expect(end).toBeGreaterThan(start);
return script.slice(start, end);
})();
// The users loop only, bounded by its own marker and the next section.
const usersSection = (() => {
const start = script.indexOf('--- users:');
expect(start).toBeGreaterThan(-1);
const end = script.indexOf('--- app_settings: storage.backends ---', start);
expect(end).toBeGreaterThan(start);
return script.slice(start, end);
})();
// The per-user settings loop only.
const settingsSection = (() => {
const start = script.indexOf('--- settings:');
expect(start).toBeGreaterThan(-1);
const end = script.indexOf('--- plugins:', start);
expect(end).toBeGreaterThan(start);
return script.slice(start, end);
})();
// ENCRYPTED_SETTING_KEYS is module-private in settings.service.ts, so the
// canonical list is read off the source rather than imported.
const canonicalSettingKeys = (() => {
const source = fs.readFileSync(path.join(SERVER_ROOT, 'src', 'nest', 'settings', 'settings.service.ts'), 'utf8');
const marker = 'const ENCRYPTED_SETTING_KEYS = new Set([';
const start = source.indexOf(marker);
expect(start).toBeGreaterThan(-1);
const end = source.indexOf(']', start + marker.length);
return source
.slice(start + marker.length, end)
.split(',')
.map((part) => part.trim())
.filter(Boolean)
.map((quoted) => quoted.slice(1, -1));
})();
describe('migrate-encryption.ts app_settings parity', () => {
it('ROTPAR-001: rotates every instance-wide API key', () => {
for (const name of INSTANCE_API_KEY_NAMES) {
expect(appSettingsLoop).toContain(`'${name}'`);
}
});
it('ROTPAR-002: still rotates the app_settings secrets that predate them', () => {
for (const name of ['oidc_client_secret', 'smtp_pass', 'admin_webhook_url', 'admin_ntfy_token']) {
expect(appSettingsLoop).toContain(`'${name}'`);
}
});
it('ROTPAR-003: the canonical list is not empty, so ROTPAR-001 cannot pass vacuously', () => {
expect(INSTANCE_API_KEY_NAMES.length).toBeGreaterThan(0);
});
it('ROTPAR-004: rotates every storage.backends secret field for s3', () => {
const fields = storageSecretFields('s3');
expect(fields.length).toBeGreaterThan(0);
for (const field of fields) {
expect(storageBackendsSection).toContain(`'${field}'`);
}
});
// airtrail.service.ts stores the key with maybe_encrypt_api_key, i.e. the same
// enc:v1: scheme; missed by a rotation the integration reads back as unset.
it('ROTPAR-006: rotates the per-user AirTrail key', () => {
const airtrail = fs.readFileSync(
path.join(SERVER_ROOT, 'src', 'nest', 'integrations', 'airtrail.service.ts'),
'utf8',
);
expect(airtrail).toContain('maybe_encrypt_api_key');
expect(airtrail).toContain('airtrail_api_key');
expect(usersSection).toContain("'airtrail_api_key'");
});
it('ROTPAR-007: rotates every encrypted per-user setting key', () => {
expect(canonicalSettingKeys.length).toBeGreaterThan(0);
for (const key of canonicalSettingKeys) {
expect(settingsSection).toContain(`'${key}'`);
}
});
// Both plugin secret stores use the same scheme: OAuth tokens encrypted by
// plugin-oauth.service, and the config fields a manifest marked secret.
it('ROTPAR-008: rotates the plugin OAuth tokens and both config stores', () => {
expect(script).toContain('plugin_oauth_tokens');
expect(script).toContain('access_token');
expect(script).toContain('refresh_token');
expect(script).toContain('plugin_settings_fields');
expect(script).toContain("UPDATE plugins SET config = ?");
expect(script).toContain('plugin_user_config');
});
});
describe('migrate-encryption.ts storage.backends: malformed shape', () => {
let tmpDir: string;
let dbPath: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-migrate-encryption-'));
dbPath = path.join(tmpDir, 'travel.db');
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('ROTPAR-005: reports an error instead of silently skipping a non-array storage.backends value', () => {
const seed = new Database(dbPath);
seed.exec(`
CREATE TABLE users (
id INTEGER PRIMARY KEY,
maps_api_key TEXT, unsplash_api_key TEXT, openweather_api_key TEXT,
immich_api_key TEXT, synology_password TEXT, synology_sid TEXT,
synology_did TEXT, mfa_secret TEXT
);
CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE settings (user_id INTEGER, key TEXT, value TEXT);
CREATE TABLE trip_album_links (id INTEGER PRIMARY KEY, passphrase TEXT);
CREATE TABLE trek_photos (id INTEGER PRIMARY KEY, passphrase TEXT);
`);
// Valid JSON, but not an array — the malformed shape the fix must not
// silently skip.
seed.prepare('INSERT INTO app_settings (key, value) VALUES (?, ?)').run(
'storage.backends',
JSON.stringify({ not: 'an array' }),
);
seed.close();
let output: string;
let threw = false;
try {
const stdout = execFileSync(process.execPath, ['--import', 'tsx', 'scripts/migrate-encryption.ts'], {
cwd: SERVER_ROOT,
env: { ...process.env, DB_PATH: dbPath },
input: 'old-key\nnew-key\nyes\n',
stdio: 'pipe',
encoding: 'utf8',
});
output = stdout;
} catch (err) {
// A non-empty result.errors makes the script exit(1) — the SUT's
// documented posture for "some secrets could not be migrated". The
// error itself is written via console.warn (stderr), not stdout.
threw = true;
const e = err as { stdout?: string; stderr?: string };
output = `${e.stdout ?? ''}${e.stderr ?? ''}`;
}
expect(threw).toBe(true);
expect(output).toContain('app_settings.storage.backends: not an array — skipping');
}, 30000);
});
// The same enc:v1: scheme the app and the script share, so a fixture can be
// written under the OLD key and read back under the NEW one.
const ENCRYPTED_PREFIX = 'enc:v1:';
const apiKeyFor = (key: string) => crypto.createHash('sha256').update(`${key}:api_keys:v1`).digest();
function encryptWith(key: string, plain: string): string {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', apiKeyFor(key), iv);
const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
return `${ENCRYPTED_PREFIX}${Buffer.concat([iv, cipher.getAuthTag(), enc]).toString('base64')}`;
}
function decryptWith(key: string, value: string): string | null {
if (!value.startsWith(ENCRYPTED_PREFIX)) return null;
try {
const buf = Buffer.from(value.slice(ENCRYPTED_PREFIX.length), 'base64');
const decipher = crypto.createDecipheriv('aes-256-gcm', apiKeyFor(key), buf.subarray(0, 12));
decipher.setAuthTag(buf.subarray(12, 28));
return Buffer.concat([decipher.update(buf.subarray(28)), decipher.final()]).toString('utf8');
} catch {
return null;
}
}
const BASE_SCHEMA = `
CREATE TABLE users (
id INTEGER PRIMARY KEY,
maps_api_key TEXT, unsplash_api_key TEXT, openweather_api_key TEXT,
immich_api_key TEXT, synology_password TEXT, synology_sid TEXT,
synology_did TEXT, airtrail_api_key TEXT, mfa_secret TEXT
);
CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE settings (user_id INTEGER, key TEXT, value TEXT);
CREATE TABLE trip_album_links (id INTEGER PRIMARY KEY, passphrase TEXT);
CREATE TABLE trek_photos (id INTEGER PRIMARY KEY, passphrase TEXT);
CREATE TABLE plugins (id TEXT PRIMARY KEY, config TEXT);
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER);
CREATE TABLE plugin_oauth_tokens (
plugin_id TEXT, user_id INTEGER, access_token TEXT, refresh_token TEXT,
PRIMARY KEY (plugin_id, user_id)
);
CREATE TABLE plugin_user_config (plugin_id TEXT, user_id INTEGER, config TEXT);
`;
describe('migrate-encryption.ts rotates the stores the app writes', () => {
let tmpDir: string;
let dbPath: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-migrate-encryption-plugins-'));
dbPath = path.join(tmpDir, 'travel.db');
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('ROTPAR-009: re-encrypts AirTrail, llm_api_key, plugin OAuth tokens and plugin configs', () => {
const seed = new Database(dbPath);
seed.exec(BASE_SCHEMA);
seed.prepare('INSERT INTO users (id, airtrail_api_key) VALUES (1, ?)').run(encryptWith('old-key', 'at-token'));
seed.prepare('INSERT INTO settings (user_id, key, value) VALUES (1, ?, ?)').run('llm_api_key', encryptWith('old-key', 'sk-llm'));
seed.prepare('INSERT INTO plugins (id, config) VALUES (?, ?)').run(
'koffi',
JSON.stringify({ api_key: encryptWith('old-key', 'plugin-secret'), server: 'https://h' }),
);
seed.prepare('INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES (?, ?, ?, ?)').run('koffi', 'api_key', 'instance', 1);
seed.prepare('INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES (?, ?, ?, ?)').run('koffi', 'token', 'user', 1);
seed.prepare('INSERT INTO plugin_user_config (plugin_id, user_id, config) VALUES (?, ?, ?)').run(
'koffi',
1,
JSON.stringify({ token: encryptWith('old-key', 'user-secret') }),
);
seed.prepare('INSERT INTO plugin_oauth_tokens (plugin_id, user_id, access_token, refresh_token) VALUES (?, ?, ?, ?)').run(
'koffi',
1,
encryptWith('old-key', 'access'),
encryptWith('old-key', 'refresh'),
);
seed.close();
execFileSync(process.execPath, ['--import', 'tsx', 'scripts/migrate-encryption.ts'], {
cwd: SERVER_ROOT,
env: { ...process.env, DB_PATH: dbPath },
input: ['old-key', 'new-key', 'yes', ''].join(String.fromCharCode(10)),
stdio: 'pipe',
encoding: 'utf8',
});
const after = new Database(dbPath, { readonly: true });
const airtrail = (after.prepare('SELECT airtrail_api_key AS v FROM users WHERE id = 1').get() as { v: string }).v;
expect(decryptWith('new-key', airtrail)).toBe('at-token');
const llm = (after.prepare("SELECT value AS v FROM settings WHERE key = 'llm_api_key'").get() as { v: string }).v;
expect(decryptWith('new-key', llm)).toBe('sk-llm');
const tokens = after.prepare('SELECT access_token, refresh_token FROM plugin_oauth_tokens').get() as {
access_token: string;
refresh_token: string;
};
expect(decryptWith('new-key', tokens.access_token)).toBe('access');
expect(decryptWith('new-key', tokens.refresh_token)).toBe('refresh');
const pluginConfig = JSON.parse((after.prepare("SELECT config AS v FROM plugins WHERE id = 'koffi'").get() as { v: string }).v);
expect(decryptWith('new-key', pluginConfig.api_key)).toBe('plugin-secret');
// A non-secret field is left exactly as it was.
expect(pluginConfig.server).toBe('https://h');
const userConfig = JSON.parse((after.prepare('SELECT config AS v FROM plugin_user_config').get() as { v: string }).v);
expect(decryptWith('new-key', userConfig.token)).toBe('user-secret');
after.close();
}, 30000);
});
@@ -17,12 +17,10 @@
*/
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import { resolve } from 'node:path';
import { createTestDb } from '../../helpers/test-db';
const here = dirname(fileURLToPath(import.meta.url));
const MIGRATIONS_PATH = resolve(here, '../../../src/db/migrations.ts');
const MIGRATIONS_PATH = resolve(__dirname, '../../../src/db/migrations.ts');
const migrationsSource = readFileSync(MIGRATIONS_PATH, 'utf8');
/**
@@ -137,6 +135,8 @@ const ALLOWED_DESTRUCTIVE: Record<string, string> = {
'Atlas enclave fix: DELETE ... WHERE place_id IN (places inside specific enclave boxes) — invalidate stale region cache; re-resolved on next request.',
'DELETE FROM visited_regions':
'Atlas geoBoundaries swap (#1119): DELETE ... WHERE id = ? — after UPDATE OR IGNORE re-codes a manually-marked region to its current code, drop only the single leftover row whose UNIQUE(user_id, region_code) collision caused the update to be skipped (a duplicate of a region the user already has).',
'DELETE FROM reservation_day_positions':
'DELETE ... WHERE the row joins a reservation and a day sitting on different trips. The table has no trip_id and its two foreign keys only require the ids to exist, so a pair that never belonged together was storable; the writer scopes to the trip now and this clears what earlier builds allowed. Bounded by the join — a row whose reservation and day agree on their trip is untouched.',
};
describe('migration hygiene — destructive operation guard', () => {
@@ -0,0 +1,55 @@
/**
* The schema_version bump must commit with the migration that earned it.
*
* If it lands in a statement of its own, a crash between the two leaves the
* schema advanced and the version stale, and the next boot replays a step that
* is not idempotent (an INSERT INTO app_settings, say) and exits 1 forever.
*/
import { describe, it, expect, vi } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
function migratedDb(): Database.Database {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA busy_timeout = 5000');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
runMigrations(db);
return db;
}
describe('migration version bump atomicity', () => {
it('MIGRATE-ATOMIC-001: writes schema_version inside the migration transaction', () => {
const db = migratedDb();
try {
const { version } = db.prepare('SELECT version FROM schema_version LIMIT 1').get() as { version: number };
// Rewind one slot so exactly the last migration replays.
db.prepare('UPDATE schema_version SET version = ?').run(version - 1);
const realPrepare = db.prepare.bind(db);
const inTransaction: boolean[] = [];
vi.spyOn(db, 'prepare').mockImplementation(((sql: string) => {
const stmt = realPrepare(sql);
if (sql.includes('UPDATE schema_version SET version')) {
const realRun = stmt.run.bind(stmt);
stmt.run = ((...args: unknown[]) => {
inTransaction.push(db.inTransaction);
return realRun(...(args as never[]));
}) as typeof stmt.run;
}
return stmt;
}) as typeof db.prepare);
runMigrations(db);
expect(inTransaction).toEqual([true]);
const after = db.prepare('SELECT version FROM schema_version LIMIT 1').get() as { version: number };
expect(after.version).toBe(version);
} finally {
vi.restoreAllMocks();
db.close();
}
});
});
+32
View File
@@ -7,6 +7,7 @@
*/
import { describe, it, expect, beforeEach } from 'vitest';
import { db, canAccessTrip } from '../../../src/db/database';
import { CAN_ACCESS_TRIP_SQL, buildDbMock, createTestDb } from '../../helpers/test-db';
function seedUser(username: string): number {
return Number(
@@ -52,3 +53,34 @@ describe('canAccessTrip', () => {
expect(canAccessTrip(tripId, stranger)).toBeUndefined();
});
});
/**
* The mock every domain test runs against had the pre-#1543 SELECT, so the very
* regression the block above pins was invisible to the suites that mock the db.
*/
describe('the buildDbMock stand-in for canAccessTrip', () => {
it('hands back the trip currency, like the real one', () => {
const testDb = createTestDb();
try {
const owner = Number(
testDb.prepare("INSERT INTO users (username, email, password_hash, role) VALUES ('m', 'm@example.test', 'x', 'user')")
.run().lastInsertRowid,
);
const tripId = Number(
testDb.prepare("INSERT INTO trips (user_id, title, currency) VALUES (?, 'Trip', 'ISK')")
.run(owner).lastInsertRowid,
);
expect(buildDbMock(testDb).canAccessTrip(tripId, owner)).toMatchObject({ id: tripId, currency: 'ISK' });
} finally {
testDb.close();
}
});
it('selects the same columns the production statement does', () => {
const columns = (sql: string) => sql.replace(/\s+/g, ' ').trim();
expect(columns(CAN_ACCESS_TRIP_SQL)).toBe(
'SELECT t.id, t.user_id, t.currency FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)',
);
});
});
@@ -0,0 +1,43 @@
/**
* Boot migration: strip the legacy 'files/' prefix from trip_files.filename.
*
* Collab note attachments historically stored 'files/<name>' while the file
* manager stored bare names in the same column; the storage layer addresses
* objects as category + bare name, so existing prefixed rows are normalized
* once at boot (storage slice 2).
*/
import { describe, it, expect } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
function makeDbWithRows(): Database.Database {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA busy_timeout = 5000');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
// Minimal FK chain: user → trip → trip_files rows.
db.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')").run();
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run();
db.prepare(
"INSERT INTO trip_files (trip_id, filename, original_name) VALUES (1, 'files/aaa.pdf', 'a.pdf'), (1, 'bbb.pdf', 'b.pdf')",
).run();
return db;
}
describe('trip_files files/-prefix migration', () => {
it('strips the files/ prefix from legacy collab rows and leaves bare rows alone', () => {
const db = makeDbWithRows();
try {
runMigrations(db);
const names = db
.prepare('SELECT filename FROM trip_files ORDER BY id')
.all()
.map((r) => (r as { filename: string }).filename);
expect(names).toEqual(['aaa.pdf', 'bbb.pdf']);
} finally {
db.close();
}
});
});
@@ -0,0 +1,86 @@
/**
* demo-reset's DB path.
*
* demo-reset closes the live connection, copies the baseline over the database
* file and reopens. It used to compute that file itself as data/travel.db, which
* is wrong the moment TREK_DB_FILE moves the database elsewhere: the baseline
* lands on an unrelated file and the real database is never reset. The path has
* to come from the connection that database.ts actually opened, so what these
* cases assert is which file each copy names.
*
* demo-reset resolves ../db/database through a runtime require() — the module is
* a boot-time singleton — and vitest's mock registry never sees that call: it
* goes to Node's own resolver, which cannot load a .ts file and throws
* "Cannot find module '../db/database'". Hence the loader below, which is the
* seam that lets the module run at all. The file system is spied rather than
* written to, because the baseline path is fixed at data/travel-baseline.db and
* a developer running a demo instance has a real one sitting there.
*/
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
// eslint-disable-next-line @typescript-eslint/no-require-imports
const Module = require('node:module');
const BASELINE = path.resolve(__dirname, '..', '..', '..', 'data', 'travel-baseline.db');
const LIVE_DB = path.join(path.sep, 'srv', 'trek', 'custom-name.db');
const dbStub = {
name: LIVE_DB,
exec: vi.fn(),
prepare: vi.fn(() => ({ get: () => undefined, all: () => [], run: () => undefined })),
};
const databaseModule = { db: dbStub, closeDb: vi.fn(), reinitialize: vi.fn() };
// Teach Node's require how to answer the one runtime require demo-reset makes.
const previousLoader = Module._extensions['.ts'];
Module._extensions['.ts'] = (mod: { exports: unknown }, filename: string) => {
if (filename.endsWith(path.join('src', 'db', 'database.ts'))) {
mod.exports = databaseModule;
return;
}
throw new Error(`unexpected runtime require of ${filename}`);
};
afterAll(() => {
if (previousLoader) Module._extensions['.ts'] = previousLoader;
else delete Module._extensions['.ts'];
});
import { resetDemoUser, saveBaseline } from '../../../src/demo/demo-reset';
describe('demo-reset DB path', () => {
let copyFileSync: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
dbStub.name = LIVE_DB;
vi.spyOn(console, 'log').mockImplementation(() => undefined);
copyFileSync = vi.spyOn(fs, 'copyFileSync').mockImplementation(() => undefined);
vi.spyOn(fs, 'unlinkSync').mockImplementation(() => undefined);
vi.spyOn(fs, 'existsSync').mockImplementation(((p: fs.PathLike) => String(p) === BASELINE) as typeof fs.existsSync);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('DEMORESET-001: saves the baseline from the file the connection has open', () => {
saveBaseline();
expect(copyFileSync).toHaveBeenCalledWith(LIVE_DB, BASELINE);
});
it('DEMORESET-002: restores the baseline onto that same file, not data/travel.db', () => {
resetDemoUser();
expect(copyFileSync).toHaveBeenCalledWith(BASELINE, LIVE_DB);
// Closed before the copy and reopened after it — copying over an open
// SQLite file is how a database ends up half of each.
expect(databaseModule.closeDb).toHaveBeenCalled();
expect(databaseModule.reinitialize).toHaveBeenCalled();
});
it('DEMORESET-003: an in-memory database is left alone rather than copied around', () => {
dbStub.name = ':memory:';
saveBaseline();
resetDemoUser();
expect(copyFileSync).not.toHaveBeenCalled();
});
});
+64
View File
@@ -0,0 +1,64 @@
/**
* Demo mode boot seeding.
*
* DEMO_MODE=true creates a role=admin account on first boot. When
* DEMO_ADMIN_PASS is unset that account gets the password published in
* demo-seed itself, so the seeder has to say so out loud.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import type Database from 'better-sqlite3';
import { createTestDb } from '../../helpers/test-db';
// Baseline handling is demo-reset's job and touches the file system.
vi.mock('../../../src/demo/demo-reset', () => ({
saveBaseline: vi.fn(),
hasBaseline: vi.fn(() => true),
resetDemoUser: vi.fn(),
}));
import { seedDemoData } from '../../../src/demo/demo-seed';
describe('demo seeding', () => {
let db: Database.Database;
const realPass = process.env.DEMO_ADMIN_PASS;
beforeEach(() => {
db = createTestDb();
vi.spyOn(console, 'log').mockImplementation(() => undefined);
});
afterEach(() => {
vi.restoreAllMocks();
db.close();
if (realPass === undefined) delete process.env.DEMO_ADMIN_PASS;
else process.env.DEMO_ADMIN_PASS = realPass;
});
it('DEMOSEED-001: warns when the admin account is created with the default password', () => {
delete process.env.DEMO_ADMIN_PASS;
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
seedDemoData(db);
expect(warn).toHaveBeenCalledWith(expect.stringContaining('DEMO_ADMIN_PASS is not set'));
});
it('DEMOSEED-002: stays quiet when the operator set DEMO_ADMIN_PASS', () => {
process.env.DEMO_ADMIN_PASS = 'a-real-password';
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
seedDemoData(db);
expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('DEMO_ADMIN_PASS is not set'));
});
it('DEMOSEED-003: does not warn again once the admin account exists', () => {
delete process.env.DEMO_ADMIN_PASS;
seedDemoData(db);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
seedDemoData(db);
expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('DEMO_ADMIN_PASS is not set'));
});
});
+334
View File
@@ -0,0 +1,334 @@
/**
* The file plugin surface after it moved onto @PluginMethod.
*
* Files are the only plugin surface with three separate rights (one per write
* operation), and both its byte-paths — read and write — go through the storage
* layer rather than touching disk directly. The cases here lean on the upload
* path: the extension blocklist, the size cap, the demo-mode refusal, that each
* operation asks for its own permission rather than one shared domain action, and
* that a create pins the validate -> put -> insert -> broadcast order so a failed
* put can never leave a DB row pointing at missing bytes.
*/
import { describe, it, expect, vi } from 'vitest';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { Readable } from 'node:stream';
import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
import { FilesRpc } from '../../../src/nest/files/files.rpc';
import { FilesModule } from '../../../src/nest/files/files.module';
import type { FilesService } from '../../../src/nest/files/files.service';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import type { StorageService } from '../../../src/nest/storage/storage.service';
import { StorageNotFoundError, StorageInvalidKeyError } from '../../../src/nest/storage/storage.types';
import type { RpcRequest, RpcError, RpcResponse } from '../../../src/nest/plugins/protocol/envelope';
import { makeDeps } from '../../helpers/rpc-host-deps';
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
const b64 = (s: string) => Buffer.from(s).toString('base64');
/** File 2 sits on trip 1, which belongs to user 42. */
function build(opts: { file?: Record<string, unknown> | undefined; foreign?: string | null; allow?: (a: string) => boolean } = {}) {
const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };
const files = {
listFiles: vi.fn(() => [{ id: 2, filename: 'visa.pdf' }]),
getFileById: vi.fn((id: number) =>
id === 2 ? (opts.file ?? { filename: 'visa.pdf', original_name: 'visa.pdf', mime_type: 'application/pdf', file_size: 2, deleted_at: null }) : undefined,
),
findForeignLinkTarget: vi.fn(() => opts.foreign ?? null),
createFile: vi.fn((_t: number, meta: Record<string, unknown>) => ({ id: 130, ...meta })),
createFileLink: vi.fn(() => [{ file_id: 2 }]),
updateFile: vi.fn((id: number) => ({ id })),
softDeleteFile: vi.fn(),
} as unknown as FilesService & Record<string, ReturnType<typeof vi.fn>>;
const db = {
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)),
prepare: vi.fn(() => ({ get: () => ({ role: 'user', email: 'real@example.test' }) })),
} as unknown as DatabaseService;
const permissions = {
checkPermission: vi.fn((action: string) => (opts.allow ? opts.allow(action) : true)),
} as unknown as PermissionsService;
const guards = new PluginGuards(db, permissions, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService);
const storage = {
getStream: vi.fn(async () => ({
stream: Readable.from(Buffer.from('hi')),
stat: { key: 'visa.pdf', size: 2, mtimeMs: 0 },
})),
put: vi.fn(async () => undefined),
} as unknown as StorageService & Record<string, ReturnType<typeof vi.fn>>;
const rpc = new FilesRpc(files, realtime, db, guards, storage);
const host = (...grants: string[]) => new PluginRpcHost('p', new Set(grants), makeDeps(), createTestPluginRegistry([rpc]));
return { files, realtime, permissions, storage, host };
}
describe('FilesRpc reads', () => {
it('FILES-RPC-001 files.list is membership-checked and excludes the trash', async () => {
const f = build();
const host = f.host('db:read:files');
expect((await host.dispatch(req('files.list', { tripId: 1 }), 42)).ok).toBe(true);
expect(f.files.listFiles).toHaveBeenCalledWith(1, false);
expect(((await host.dispatch(req('files.list', { tripId: 2 }), 42)) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
});
it('FILES-RPC-002 reading BYTES is a separate grant from reading metadata', async () => {
const f = build();
// db:read:files alone must not unlock the content.
const denied = (await f.host('db:read:files').dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42)) as RpcError;
expect(denied.error.code).toBe('PERMISSION_DENIED');
const ok = (await f.host('db:read:files:content').dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42)) as RpcResponse;
expect(ok.ok).toBe(true);
expect(ok.result).toMatchObject({ name: 'visa.pdf', mimetype: 'application/pdf', content_base64: b64('hi') });
});
it('FILES-RPC-003 a trashed file is refused like the download path', async () => {
const f = build({ file: { filename: 'visa.pdf', original_name: 'visa.pdf', mime_type: null, file_size: 2, deleted_at: '2027-01-01' } });
const res = (await f.host('db:read:files:content').dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42)) as RpcError;
expect(res.error.message).toBe('no file 2 on trip 1');
});
it('FILES-RPC-004 the size is capped BEFORE the read, not after', async () => {
const f = build({ file: { filename: 'visa.pdf', original_name: 'visa.pdf', mime_type: null, file_size: 400 * 1024 * 1024, deleted_at: null } });
const res = (await f.host('db:read:files:content').dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42)) as RpcError;
expect(res.error.code).toBe('BAD_PARAMS');
// The storage layer is never even asked for an oversized file.
expect(f.storage.getStream).not.toHaveBeenCalled();
});
it('FILES-RPC-005 a missing storage object gets the accessibility envelope, not a raw error', async () => {
const f = build();
(f.storage.getStream as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new StorageNotFoundError('files/visa.pdf'));
const res = (await f.host('db:read:files:content').dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42)) as RpcError;
expect(res.error.message).toBe('file path is not accessible');
});
it('FILES-RPC-005d an invalid storage key gets the accessibility envelope, not a raw error', async () => {
const f = build();
(f.storage.getStream as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new StorageInvalidKeyError('..'));
const res = (await f.host('db:read:files:content').dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42)) as RpcError;
expect(res.error.message).toBe('file path is not accessible');
});
it('FILES-RPC-005b an object whose stat exceeds the cap is refused before buffering', async () => {
const f = build();
const stream = Readable.from(Buffer.from('hi'));
(f.storage.getStream as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
stream, stat: { key: 'visa.pdf', size: 11 * 1024 * 1024, mtimeMs: 0 },
});
const res = (await f.host('db:read:files:content').dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42)) as RpcError;
expect(res.error.code).toBe('BAD_PARAMS');
expect(res.error.message).toBe('file too large to read (>10485760 bytes); use the download UI');
expect(stream.destroyed).toBe(true);
});
it('FILES-RPC-005c a stream that outgrows its stat is aborted mid-read', async () => {
const f = build();
// stat claims 2 bytes; the stream actually yields 10MB+1 — a lying driver
// must not push an oversized payload through the IPC pipe.
const big = Readable.from([Buffer.alloc(6 * 1024 * 1024), Buffer.alloc(6 * 1024 * 1024)]);
(f.storage.getStream as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
stream: big, stat: { key: 'visa.pdf', size: 2, mtimeMs: 0 },
});
const res = (await f.host('db:read:files:content').dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42)) as RpcError;
expect(res.error.message).toBe('file too large to read');
expect(big.destroyed).toBe(true);
});
});
describe('FilesRpc writes', () => {
it('FILES-RPC-006 each operation asks for its own right', async () => {
const seen: string[] = [];
const f = build({ allow: (a) => { seen.push(a); return true; } });
const host = f.host('db:write:files');
await host.dispatch(req('files.create', { tripId: 1, input: { name: 'a.pdf', content_base64: b64('x') } }), 42);
await host.dispatch(req('files.update', { tripId: 1, fileId: 2, input: {} }), 42);
await host.dispatch(req('files.softDelete', { tripId: 1, fileId: 2 }), 42);
expect(seen).toEqual(['file_upload', 'file_edit', 'file_delete']);
});
it('FILES-RPC-007 a blocked extension never reaches disk', async () => {
const f = build();
const res = (await f.host('db:write:files').dispatch(req('files.create', { tripId: 1, input: { name: 'evil.exe', content_base64: b64('MZ') } }), 42)) as RpcError;
expect(res.error.code).toBe('BAD_PARAMS');
expect(res.error.message).toBe("file extension '.exe' is not allowed");
expect(f.files.createFile).not.toHaveBeenCalled();
});
it('FILES-RPC-008 a file with no extension at all is refused', async () => {
const f = build();
const res = (await f.host('db:write:files').dispatch(req('files.create', { tripId: 1, input: { name: 'README', content_base64: b64('x') } }), 42)) as RpcError;
expect(res.error.message).toBe("file extension '(none)' is not allowed");
});
it('FILES-RPC-009 name and content are required, and the name is length-capped', async () => {
const f = build();
const host = f.host('db:write:files');
const bad = async (input: Record<string, unknown>) => ((await host.dispatch(req('files.create', { tripId: 1, input }), 42)) as RpcError).error.message;
expect(await bad({ content_base64: b64('x') })).toBe('file name is required (max 255 chars)');
expect(await bad({ name: 'x'.repeat(256), content_base64: b64('x') })).toBe('file name is required (max 255 chars)');
expect(await bad({ name: 'a.pdf' })).toBe('content_base64 is required');
expect(await bad({ name: 'a.pdf', content_base64: '' })).toBe('content_base64 is required');
});
it('FILES-RPC-010 an oversized payload is rejected on its ENCODED length', async () => {
const f = build();
const res = (await f.host('db:write:files').dispatch(
req('files.create', { tripId: 1, input: { name: 'big.pdf', content_base64: 'A'.repeat(15 * 1024 * 1024) } }), 42,
)) as RpcError;
expect(res.error.message).toBe('file exceeds the 10MB plugin upload cap');
});
it('FILES-RPC-011 empty decoded content is refused', async () => {
const f = build();
const res = (await f.host('db:write:files').dispatch(req('files.create', { tripId: 1, input: { name: 'a.pdf', content_base64: '====' } }), 42)) as RpcError;
expect(res.error.message).toBe('file content is empty');
});
it('FILES-RPC-012 a link target on another trip is refused, for create and update alike', async () => {
const f = build({ foreign: 'reservation 9' });
const host = f.host('db:write:files');
const created = (await host.dispatch(req('files.create', { tripId: 1, input: { name: 'a.pdf', content_base64: b64('x'), reservation_id: 9 } }), 42)) as RpcError;
expect(created.error.message).toBe('reservation 9 does not belong to trip 1');
const updated = (await host.dispatch(req('files.update', { tripId: 1, fileId: 2, input: { reservation_id: 9 } }), 42)) as RpcError;
expect(updated.error.message).toBe('reservation 9 does not belong to trip 1');
});
it('FILES-RPC-013 update tells null from undefined, so a link can be cleared', async () => {
const f = build();
const host = f.host('db:write:files');
await host.dispatch(req('files.update', { tripId: 1, fileId: 2, input: { place_id: null } }), 42);
expect(f.files.updateFile).toHaveBeenLastCalledWith(2, expect.anything(), expect.objectContaining({ place_id: null }));
await host.dispatch(req('files.update', { tripId: 1, fileId: 2, input: { description: 'x' } }), 42);
expect(f.files.updateFile).toHaveBeenLastCalledWith(2, expect.anything(), expect.objectContaining({ place_id: undefined }));
});
it('FILES-RPC-014 a missing file is RESOURCE_FORBIDDEN across every write', async () => {
const f = build();
const host = f.host('db:write:files');
for (const [method, params] of [
['files.createLink', { tripId: 1, fileId: 404, opts: {} }],
['files.update', { tripId: 1, fileId: 404, input: {} }],
['files.softDelete', { tripId: 1, fileId: 404 }],
] as const) {
const res = (await host.dispatch(req(method, params), 42)) as RpcError;
expect(res.error.message).toBe('no file 404 on trip 1');
}
});
it('FILES-RPC-015 a userless write is refused before anything else happens', async () => {
const f = build();
const res = (await f.host('db:write:files').dispatch(req('files.create', { tripId: 1, input: { name: 'a.pdf', content_base64: b64('x') } }), undefined)) as RpcError;
expect(res.error.message).toBe('file writes require an authenticated user context');
expect(f.files.createFile).not.toHaveBeenCalled();
});
it('FILES-RPC-016 a successful write broadcasts, a refused one does not', async () => {
const f = build();
const host = f.host('db:write:files');
await host.dispatch(req('files.softDelete', { tripId: 1, fileId: 2 }), 42);
expect(f.realtime.broadcast).toHaveBeenCalledWith(1, 'file:deleted', { fileId: 2 }, undefined);
f.realtime.broadcast.mockClear();
await host.dispatch(req('files.softDelete', { tripId: 1, fileId: 404 }), 42);
expect(f.realtime.broadcast).not.toHaveBeenCalled();
});
it('FILES-RPC-016b a demo account cannot upload while demo mode is on, other members can', async () => {
const prev = process.env.DEMO_MODE;
process.env.DEMO_MODE = 'true';
try {
const f = build();
// The demo guard resolves the uploader's email; user 9 is the demo account.
const db = {
canAccessTrip: vi.fn(() => ({ id: 1, user_id: 42 })),
prepare: vi.fn(() => ({ get: (id: number) => (id === 9 ? { role: 'user', email: 'demo@trek.app' } : { role: 'user', email: 'real@example.test' }) })),
} as unknown as DatabaseService;
const guards = new PluginGuards(
db,
{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
);
const files = {
findForeignLinkTarget: vi.fn(() => null),
createFile: vi.fn(() => ({ id: 130 })),
} as unknown as FilesService;
const storage = { getStream: vi.fn(), put: vi.fn(async () => undefined) } as unknown as StorageService;
const rpc = new FilesRpc(files, { broadcast: vi.fn() } as unknown as RealtimeService, db, guards, storage);
const host = new PluginRpcHost('p', new Set(['db:write:files']), makeDeps(), createTestPluginRegistry([rpc]));
const input = { name: 'a.pdf', content_base64: b64('x') };
const denied = (await host.dispatch(req('files.create', { tripId: 1, input }), 9)) as RpcError;
expect(denied.error.message).toBe('Uploads are disabled in demo mode.');
expect((await host.dispatch(req('files.create', { tripId: 1, input }), 42)).ok).toBe(true);
} finally {
if (prev === undefined) delete process.env.DEMO_MODE;
else process.env.DEMO_MODE = prev;
}
});
it('FILES-RPC-016c link ids are stringified, and absent ones become null', async () => {
const f = build();
await f.host('db:write:files').dispatch(req('files.createLink', { tripId: 1, fileId: 2, opts: { reservation_id: 9, assignment_id: 3 } }), 42);
expect(f.files.createFileLink).toHaveBeenCalledWith(2, { reservation_id: '9', assignment_id: '3', place_id: null });
});
it('FILES-RPC-016d create stores its optional link ids as strings', async () => {
const f = build();
await f.host('db:write:files').dispatch(
req('files.create', { tripId: 1, input: { name: 'a.pdf', content_base64: b64('x'), place_id: 7, reservation_id: 9, description: 'd' } }), 42,
);
expect(f.files.createFile).toHaveBeenCalledWith(1, expect.anything(), 42, { place_id: '7', reservation_id: '9', description: 'd' });
});
it('FILES-RPC-018 create puts the bytes into the storage layer before the DB row', async () => {
const f = build();
const order: string[] = [];
(f.storage.put as ReturnType<typeof vi.fn>).mockImplementation(async () => { order.push('put'); });
(f.files.createFile as ReturnType<typeof vi.fn>).mockImplementation(() => { order.push('insert'); return { id: 130 }; });
const res = await f.host('db:write:files').dispatch(
req('files.create', { tripId: 1, input: { name: 'a.pdf', content_base64: b64('x'), mimetype: 'application/pdf' } }), 42,
);
expect(res.ok).toBe(true);
expect(order).toEqual(['put', 'insert']);
const [category, name, source, opts] = (f.storage.put as ReturnType<typeof vi.fn>).mock.calls[0];
expect(category).toBe('files');
expect(name).toMatch(/^[0-9a-f-]{36}\.pdf$/);
expect(source).toBeInstanceOf(Readable);
expect(opts).toEqual({ contentType: 'application/pdf' });
});
it('FILES-RPC-019 create defaults the stored contentType like the returned mimetype', async () => {
const f = build();
await f.host('db:write:files').dispatch(req('files.create', { tripId: 1, input: { name: 'a.pdf', content_base64: b64('x') } }), 42);
const [, , , opts] = (f.storage.put as ReturnType<typeof vi.fn>).mock.calls[0];
expect(opts).toEqual({ contentType: 'application/octet-stream' });
});
it('FILES-RPC-020 a failed put creates no DB row and broadcasts nothing', async () => {
const f = build();
(f.storage.put as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('backend down'));
const res = (await f.host('db:write:files').dispatch(
req('files.create', { tripId: 1, input: { name: 'a.pdf', content_base64: b64('x') } }), 42,
)) as RpcError;
expect(res.error).toBeDefined();
expect(f.files.createFile).not.toHaveBeenCalled();
expect(f.realtime.broadcast).not.toHaveBeenCalled();
});
it('FILES-RPC-021 a refused create never reaches the storage layer', async () => {
const f = build();
await f.host('db:write:files').dispatch(req('files.create', { tripId: 1, input: { name: 'evil.exe', content_base64: b64('MZ') } }), 42);
expect(f.storage.put).not.toHaveBeenCalled();
});
it('FILES-RPC-016e a file with no recorded size or mimetype still reads', async () => {
const f = build({ file: { filename: 'visa.pdf', original_name: 'visa.pdf', mime_type: null, file_size: null, deleted_at: null } });
const res = await f.host('db:read:files:content').dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42);
expect((res as { result: { mimetype: string } }).result.mimetype).toBe('application/octet-stream');
});
it('FILES-RPC-017 the class is listed in its module providers', () => {
expectRegisteredProvider(FilesModule, FilesRpc);
});
});
+64 -2
View File
@@ -6,9 +6,12 @@
* offline window — otherwise a key GC'd before the device returns lets the
* replay create a duplicate. The TTL was raised from 24h to 30d (overridable).
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { db } from '../../src/db/database';
import { purgeExpiredIdempotencyKeys } from '../../src/scheduler';
import { purgeExpiredIdempotencyKeys } from '../../src/nest/common/idempotency-cleanup';
import { IdempotencyCleanupJob } from '../../src/nest/common/idempotency-cleanup.job';
import { DatabaseService } from '../../src/nest/database/database.service';
import type { CronRegistrarService } from '../../src/nest/scheduling/cron-registrar.service';
const DAY = 24 * 60 * 60;
const NOW = 2_000_000_000_000; // fixed ms so the test is deterministic
@@ -56,3 +59,62 @@ describe('purgeExpiredIdempotencyKeys', () => {
expect(purgeExpiredIdempotencyKeys(NOW, undefined, db)).toBe(1);
});
});
describe('IdempotencyCleanupJob', () => {
function makeJob(enabled = true) {
const registrar = {
isEnabled: vi.fn(() => enabled),
// Spelled out rather than vi.fn(() => enabled), because the test below
// reads the third argument back off mock.calls: a no-parameter stub types
// every recorded call as [], and indexing it fails typecheck:tests.
register: vi.fn((_name: string, _expression: string, _onTick: () => void | Promise<void>) => enabled),
unregister: vi.fn(),
};
const job = new IdempotencyCleanupJob(new DatabaseService(db), registrar as unknown as CronRegistrarService);
return { job, registrar };
}
it('registers the nightly 3 AM cron, and stays out of the registry under the test gate', () => {
const on = makeJob();
on.job.onApplicationBootstrap();
expect(on.registrar.register).toHaveBeenCalledWith('idempotency-cleanup', '0 3 * * *', expect.any(Function));
// The registered callback IS the tick — drive it once over an empty table
// (nothing to purge → no log, no throw).
const onTick = on.registrar.register.mock.calls[0][2];
expect(() => onTick()).not.toThrow();
const off = makeJob(false);
off.job.onApplicationBootstrap();
expect(off.registrar.register).not.toHaveBeenCalled();
});
it('the tick purges through the injected DatabaseService', () => {
// The tick uses the live clock, so these fixtures age against Date.now()
// (the pure-function cases above pin their own fixed NOW instead).
const liveNowSec = Math.floor(Date.now() / 1000);
const liveInsert = (key: string, ageSeconds: number) =>
db.prepare(
`INSERT INTO idempotency_keys (key, user_id, method, path, status_code, response_body, created_at)
VALUES (?, 1, 'POST', '/x', 200, '{}', ?)`,
).run(key, liveNowSec - ageSeconds);
liveInsert('old', 31 * DAY);
liveInsert('fresh', 5 * DAY);
const { job } = makeJob();
job.tick();
const keys = db.prepare('SELECT key FROM idempotency_keys').all().map((r: { key: string }) => r.key);
expect(keys).toEqual(['fresh']);
});
it('a failing purge is contained to the Idempotency cleanup log line', () => {
const broken = { prepare: () => { throw new Error('db gone'); } } as unknown as DatabaseService;
const job = new IdempotencyCleanupJob(broken, { isEnabled: () => true } as unknown as CronRegistrarService);
expect(() => job.tick()).not.toThrow();
// Non-Error throws are stringified rather than crashing the catch itself.
const brokenString = { prepare: () => { throw 'db string'; } } as unknown as DatabaseService;
const job2 = new IdempotencyCleanupJob(brokenString, { isEnabled: () => true } as unknown as CronRegistrarService);
expect(() => job2.tick()).not.toThrow();
});
});
@@ -0,0 +1,81 @@
/**
* Unit tests for the TREK access-group boot gate in
* server/src/mcp/nest-mcp-policy.ts. Pure functions + a bare registry — no DB.
*
* The compile-time half of the group typing (McpAccessGroup === ScopeGroup)
* is asserted in src by MCP_ACCESS_GROUPS_MATCH_SCOPE_GROUPS, which
* `npm run typecheck` covers — tests are not typechecked, so the bad-group
* case below has to cast its way past the union on purpose.
*/
import { describe, it, expect } from 'vitest';
import { createTestRegistry, McpController, Tool, type McpDeclarativeAccess } from '../../../src/nest-mcp';
import {
MCP_ACCESS_GROUPS_MATCH_SCOPE_GROUPS,
trekMcpAccessPolicy,
trekMcpValidateAccess,
} from '../../../src/mcp/nest-mcp-policy';
import { ALL_SCOPES, type ScopeGroup } from '../../../src/mcp/scopes';
const listing = { kind: 'tool' as const, name: 'x', className: 'X', methodName: 'x' };
describe('trekMcpValidateAccess', () => {
it('accepts every {group, mode} combination that resolves to a real scope', () => {
const combos = ALL_SCOPES.filter((s) => s.endsWith(':read') || s.endsWith(':write')).map((s) => {
const [group, mode] = s.split(':');
return { group, mode } as McpDeclarativeAccess;
});
expect(combos.length).toBeGreaterThan(0);
for (const access of combos) {
expect(trekMcpValidateAccess(access, listing)).toBeNull();
}
});
it('rejects an unknown group', () => {
const access = { group: 'budgets', mode: 'write' } as unknown as McpDeclarativeAccess;
expect(trekMcpValidateAccess(access, listing)).toBe("no 'budgets:write' scope in SCOPES");
});
it('rejects write mode on the read-only geo and weather groups', () => {
expect(trekMcpValidateAccess({ group: 'geo', mode: 'write' }, listing)).toBe("no 'geo:write' scope in SCOPES");
expect(trekMcpValidateAccess({ group: 'weather', mode: 'write' }, listing)).toBe(
"no 'weather:write' scope in SCOPES",
);
expect(trekMcpValidateAccess({ group: 'geo', mode: 'read' }, listing)).toBeNull();
expect(trekMcpValidateAccess({ group: 'weather', mode: 'read' }, listing)).toBeNull();
});
it('fails createTestRegistry construction for a bad group, naming the entry', () => {
@McpController()
class BadGroupMcp {
@Tool({ name: 'bad_tool', access: { group: 'budgets' as ScopeGroup, mode: 'write' } })
bad() {}
}
expect(() =>
createTestRegistry([new BadGroupMcp()], {
accessPolicy: trekMcpAccessPolicy,
validateAccess: trekMcpValidateAccess,
}),
).toThrow(
/invalid access declarations: tool "bad_tool" \(BadGroupMcp\.bad\): no 'budgets:write' scope in SCOPES/,
);
});
it('has a compile-checked group union (runtime touchpoint)', () => {
expect(MCP_ACCESS_GROUPS_MATCH_SCOPE_GROUPS).toBe(true);
});
});
describe('trekMcpAccessPolicy', () => {
it('keeps the null-scopes (static token) full-access contract', () => {
const ctx = { userId: 1, scopes: null, isStaticToken: true };
expect(trekMcpAccessPolicy({ group: 'vacay', mode: 'write' }, ctx)).toBe(true);
expect(trekMcpAccessPolicy({ group: 'trips', mode: 'read' }, ctx)).toBe(true);
});
it('resolves scoped sessions with the scopes.ts semantics', () => {
const ctx = { userId: 1, scopes: ['budget:write'], isStaticToken: false };
expect(trekMcpAccessPolicy({ group: 'budget', mode: 'write' }, ctx)).toBe(true);
expect(trekMcpAccessPolicy({ group: 'budget', mode: 'read' }, ctx)).toBe(true);
expect(trekMcpAccessPolicy({ group: 'trips', mode: 'read' }, ctx)).toBe(false);
});
});
-489
View File
@@ -1,489 +0,0 @@
/**
* Unit tests for MCP resources (resources.ts).
* Tests all 14 resources via InMemoryTransport + Client.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: (placeId: number) => {
const place: any = db.prepare(`SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon FROM places p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?`).get(placeId);
if (!place) return null;
const tags = db.prepare(`SELECT t.* FROM tags t JOIN place_tags pt ON t.id = pt.tag_id WHERE pt.place_id = ?`).all(placeId);
return { ...place, category: place.category_id ? { id: place.category_id, name: place.category_name, color: place.category_color, icon: place.category_icon } : null, tags };
},
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
isOwner: (tripId: any, userId: number) =>
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
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 { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, addTripMember, createBudgetItem, createPackingItem, createReservation, createDayNote, createCollabNote, createBucketListItem, createVisitedCountry, createDayAssignment, createDayAccommodation } from '../../helpers/factories';
import { createMcpHarness, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
async function withHarness(userId: number, fn: (harness: McpHarness) => Promise<void>) {
const harness = await createMcpHarness({ userId, withTools: false, withResources: true });
try {
await fn(harness);
} finally {
await harness.cleanup();
}
}
describe('Resource: trek://trips', () => {
it('returns all trips the user owns or is a member of', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
createTrip(testDb, user.id, { title: 'My Trip' });
const sharedTrip = createTrip(testDb, other.id, { title: 'Shared Trip' });
addTripMember(testDb, sharedTrip.id, user.id);
// Trip from another user (not accessible)
createTrip(testDb, other.id, { title: 'Other Trip' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://trips' });
const trips = parseResourceResult(result) as any[];
expect(trips).toHaveLength(2);
const titles = trips.map((t) => t.title);
expect(titles).toContain('My Trip');
expect(titles).toContain('Shared Trip');
expect(titles).not.toContain('Other Trip');
});
});
it('excludes archived trips', async () => {
const { user } = createUser(testDb);
createTrip(testDb, user.id, { title: 'Active Trip' });
const archived = createTrip(testDb, user.id, { title: 'Archived Trip' });
testDb.prepare('UPDATE trips SET is_archived = 1 WHERE id = ?').run(archived.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://trips' });
const trips = parseResourceResult(result) as any[];
expect(trips).toHaveLength(1);
expect(trips[0].title).toBe('Active Trip');
});
});
it('returns empty array when user has no trips', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://trips' });
const trips = parseResourceResult(result) as any[];
expect(trips).toEqual([]);
});
});
});
describe('Resource: trek://trips/{tripId}', () => {
it('returns trip data for an accessible trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}` });
const data = parseResourceResult(result) as any;
expect(data.title).toBe('Paris Trip');
expect(data.id).toBe(trip.id);
});
});
it('returns access denied for inaccessible trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const otherTrip = createTrip(testDb, other.id, { title: 'Private' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${otherTrip.id}` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
it('returns access denied for non-existent ID', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://trips/99999' });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
describe('Resource: trek://trips/{tripId}/days', () => {
it('returns days with assignments in order', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day1 = createDay(testDb, trip.id, { day_number: 1 });
const day2 = createDay(testDb, trip.id, { day_number: 2 });
const place = createPlace(testDb, trip.id);
createDayAssignment(testDb, day1.id, place.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/days` });
const days = parseResourceResult(result) as any[];
expect(days).toHaveLength(2);
expect(days[0].day_number).toBe(1);
expect(days[0].assignments).toHaveLength(1);
expect(days[1].day_number).toBe(2);
expect(days[1].assignments).toHaveLength(0);
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/days` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
describe('Resource: trek://trips/{tripId}/places', () => {
it('returns all places for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
createPlace(testDb, trip.id, { name: 'Louvre' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/places` });
const places = parseResourceResult(result) as any[];
expect(places).toHaveLength(2);
const names = places.map((p) => p.name);
expect(names).toContain('Eiffel Tower');
expect(names).toContain('Louvre');
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/places` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
describe('Resource: trek://trips/{tripId}/budget', () => {
it('returns budget items for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createBudgetItem(testDb, trip.id, { name: 'Hotel', category: 'Accommodation', total_price: 200 });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/budget` });
const items = parseResourceResult(result) as any[];
expect(items).toHaveLength(1);
expect(items[0].name).toBe('Hotel');
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/budget` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
describe('Resource: trek://trips/{tripId}/packing', () => {
it('returns packing items for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPackingItem(testDb, trip.id, { name: 'Passport' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/packing` });
const items = parseResourceResult(result) as any[];
expect(items).toHaveLength(1);
expect(items[0].name).toBe('Passport');
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/packing` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
describe('Resource: trek://trips/{tripId}/reservations', () => {
it('returns reservations for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createReservation(testDb, trip.id, { title: 'Flight to Paris', type: 'flight' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/reservations` });
const items = parseResourceResult(result) as any[];
expect(items).toHaveLength(1);
expect(items[0].title).toBe('Flight to Paris');
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/reservations` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
describe('Resource: trek://trips/{tripId}/days/{dayId}/notes', () => {
it('returns notes for a specific day', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
createDayNote(testDb, day.id, trip.id, { text: 'Check in at noon' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/days/${day.id}/notes` });
const notes = parseResourceResult(result) as any[];
expect(notes).toHaveLength(1);
expect(notes[0].text).toBe('Check in at noon');
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
const day = createDay(testDb, trip.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/days/${day.id}/notes` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
it('returns access denied for invalid dayId', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/days/abc/notes` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
describe('Resource: trek://trips/{tripId}/accommodations', () => {
it('returns accommodations for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day1 = createDay(testDb, trip.id, { day_number: 1 });
const day2 = createDay(testDb, trip.id, { day_number: 2 });
const place = createPlace(testDb, trip.id, { name: 'Grand Hotel' });
createDayAccommodation(testDb, trip.id, place.id, day1.id, day2.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/accommodations` });
const items = parseResourceResult(result) as any[];
expect(items).toHaveLength(1);
expect(items[0].place_name).toBe('Grand Hotel');
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/accommodations` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
describe('Resource: trek://trips/{tripId}/members', () => {
it('returns owner and collaborators', async () => {
const { user } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, user.id);
addTripMember(testDb, trip.id, member.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/members` });
const data = parseResourceResult(result) as any;
expect(data.owner).toBeTruthy();
expect(data.owner.id).toBe(user.id);
expect(data.members).toHaveLength(1);
expect(data.members[0].id).toBe(member.id);
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/members` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
describe('Resource: trek://trips/{tripId}/collab-notes', () => {
it('returns collab notes with username', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createCollabNote(testDb, trip.id, user.id, { title: 'Ideas' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/collab-notes` });
const notes = parseResourceResult(result) as any[];
expect(notes).toHaveLength(1);
expect(notes[0].title).toBe('Ideas');
expect(notes[0].username).toBeTruthy();
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/collab-notes` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
describe('Resource: trek://categories', () => {
it('returns all categories', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://categories' });
const categories = parseResourceResult(result) as any[];
expect(categories.length).toBeGreaterThan(0);
expect(categories[0]).toHaveProperty('id');
expect(categories[0]).toHaveProperty('name');
expect(categories[0]).toHaveProperty('color');
expect(categories[0]).toHaveProperty('icon');
});
});
});
describe('Resource: trek://bucket-list', () => {
it('returns only the current user\'s bucket list items', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
createBucketListItem(testDb, user.id, { name: 'Tokyo' });
createBucketListItem(testDb, other.id, { name: 'Rome' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://bucket-list' });
const items = parseResourceResult(result) as any[];
expect(items).toHaveLength(1);
expect(items[0].name).toBe('Tokyo');
});
});
it('returns empty array for user with no items', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://bucket-list' });
const items = parseResourceResult(result) as any[];
expect(items).toEqual([]);
});
});
});
describe('Resource: trek://visited-countries', () => {
it('returns only the current user\'s visited countries', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
createVisitedCountry(testDb, user.id, 'FR');
createVisitedCountry(testDb, user.id, 'JP');
createVisitedCountry(testDb, other.id, 'DE');
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://visited-countries' });
const countries = parseResourceResult(result) as any[];
expect(countries).toHaveLength(2);
const codes = countries.map((c) => c.country_code);
expect(codes).toContain('FR');
expect(codes).toContain('JP');
expect(codes).not.toContain('DE');
});
});
it('returns empty array for user with no visited countries', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://visited-countries' });
const countries = parseResourceResult(result) as any[];
expect(countries).toEqual([]);
});
});
});
+31
View File
@@ -45,6 +45,37 @@ describe('ALL_SCOPES', () => {
expect(Array.isArray(ALL_SCOPES)).toBe(true);
expect(ALL_SCOPES.length).toBeGreaterThan(0);
});
it('derives exactly the 14 known scope groups (ScopeGroup lockstep)', () => {
// The runtime half of the ScopeGroup lockstep — the type half is
// MCP_ACCESS_GROUPS_MATCH_SCOPE_GROUPS in src/mcp/nest-mcp-policy.ts,
// covered by `npm run typecheck`. If this list changes, the MCP
// access-group union and boot gate change with it — update deliberately.
const groups = [...new Set(ALL_SCOPES.map((s) => s.split(':')[0]))].sort();
expect(groups).toEqual([
'atlas',
'budget',
'collab',
'collections',
'geo',
'journey',
'notifications',
'packing',
'places',
'reservations',
'todos',
'trips',
'vacay',
'weather',
]);
});
it('has no :write scope for the read-only geo and weather groups', () => {
expect(ALL_SCOPES).not.toContain('geo:write');
expect(ALL_SCOPES).not.toContain('weather:write');
expect(ALL_SCOPES).toContain('geo:read');
expect(ALL_SCOPES).toContain('weather:read');
});
});
// ---------------------------------------------------------------------------
@@ -14,6 +14,7 @@ function makeSession(overrides: Partial<McpSession> = {}): McpSession {
clientId: null,
isStaticToken: false,
lastActivity: Date.now(),
lastClientIp: null,
...overrides,
};
}
@@ -32,20 +32,14 @@ vi.mock('../../../src/config', () => ({
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
const { isAddonEnabledMock } = vi.hoisted(() => {
const isAddonEnabledMock = vi.fn().mockReturnValue(true);
return { isAddonEnabledMock };
});
vi.mock('../../../src/services/adminService', () => ({
isAddonEnabled: isAddonEnabledMock,
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { setAddonEnabled } from '../../helpers/test-db';
import { ADDON_IDS } from '../../../src/addons';
beforeAll(() => {
createTables(testDb);
@@ -55,7 +49,12 @@ beforeAll(() => {
beforeEach(() => {
resetTestDb(testDb);
broadcastMock.mockClear();
isAddonEnabledMock.mockReturnValue(true);
// The summary reads these three off the injected AddonsService, so the case
// that wants one off writes the row the admin panel writes. resetTestDb
// leaves the addons table alone, so each case restates what it needs.
for (const id of [ADDON_IDS.BUDGET, ADDON_IDS.PACKING, ADDON_IDS.COLLAB]) {
setAddonEnabled(testDb, id, true);
}
});
afterAll(() => {
@@ -95,7 +94,7 @@ describe('get_trip_summary — addon gating', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'No Budget Trip' });
isAddonEnabledMock.mockImplementation((id: string) => id !== 'budget');
setAddonEnabled(testDb, ADDON_IDS.BUDGET, false);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'get_trip_summary', arguments: { tripId: trip.id } });
@@ -112,7 +111,7 @@ describe('get_trip_summary — addon gating', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'No Packing Trip' });
isAddonEnabledMock.mockImplementation((id: string) => id !== 'packing');
setAddonEnabled(testDb, ADDON_IDS.PACKING, false);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'get_trip_summary', arguments: { tripId: trip.id } });
@@ -128,7 +127,7 @@ describe('get_trip_summary — addon gating', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'No Collab Trip' });
isAddonEnabledMock.mockImplementation((id: string) => id !== 'collab');
setAddonEnabled(testDb, ADDON_IDS.COLLAB, false);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'get_trip_summary', arguments: { tripId: trip.id } });
@@ -150,7 +149,7 @@ describe('Budget tools — addon gating', () => {
it('when budget addon disabled, create_budget_item is not registered', async () => {
const { user } = createUser(testDb);
isAddonEnabledMock.mockImplementation((id: string) => id !== 'budget');
setAddonEnabled(testDb, ADDON_IDS.BUDGET, false);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'create_budget_item', arguments: { tripId: 1, name: 'Test', total_price: 100 } });
@@ -167,7 +166,7 @@ describe('Packing tools — addon gating', () => {
it('when packing addon disabled, create_packing_item is not registered', async () => {
const { user } = createUser(testDb);
isAddonEnabledMock.mockImplementation((id: string) => id !== 'packing');
setAddonEnabled(testDb, ADDON_IDS.PACKING, false);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'create_packing_item', arguments: { tripId: 1, name: 'Sunscreen' } });
@@ -184,7 +183,7 @@ describe('Collab tools — addon gating', () => {
it('when collab addon disabled, create_collab_note is not registered', async () => {
const { user } = createUser(testDb);
isAddonEnabledMock.mockImplementation((id: string) => id !== 'collab');
setAddonEnabled(testDb, ADDON_IDS.COLLAB, false);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'create_collab_note', arguments: { tripId: 1, title: 'Test Note' } });
@@ -201,7 +200,7 @@ describe('Atlas tools — addon gating', () => {
it('when atlas addon disabled, mark_country_visited is not registered', async () => {
const { user } = createUser(testDb);
isAddonEnabledMock.mockImplementation((id: string) => id !== 'atlas');
setAddonEnabled(testDb, ADDON_IDS.ATLAS, false);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'mark_country_visited', arguments: { country_code: 'FR' } });
@@ -212,7 +211,7 @@ describe('Atlas tools — addon gating', () => {
it('when atlas addon disabled, create_bucket_list_item is not registered', async () => {
const { user } = createUser(testDb);
isAddonEnabledMock.mockImplementation((id: string) => id !== 'atlas');
setAddonEnabled(testDb, ADDON_IDS.ATLAS, false);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'create_bucket_list_item', arguments: { name: 'Paris' } });
@@ -79,7 +79,11 @@ describe('Tool: move_assignment', () => {
});
const data = parseToolResult(result) as any;
expect(data.assignment).toBeDefined();
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'assignment:moved', expect.any(Object));
expect(broadcastMock).toHaveBeenCalledWith(
trip.id,
'assignment:moved',
expect.objectContaining({ oldDayId: day1.id, newDayId: day2.id }),
);
// Verify the assignment was moved
const updated = testDb.prepare('SELECT day_id FROM day_assignments WHERE id = ?').get(assignment.id) as any;
expect(updated.day_id).toBe(day2.id);
@@ -301,7 +301,11 @@ describe('Tool: reorder_day_assignments', () => {
const a = createDayAssignment(testDb, day.id, place.id);
await withHarness(user.id, async (h) => {
await h.client.callTool({ name: 'reorder_day_assignments', arguments: { tripId: trip.id, dayId: day.id, assignmentIds: [a.id] } });
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'assignment:reordered', expect.any(Object));
expect(broadcastMock).toHaveBeenCalledWith(
trip.id,
'assignment:reordered',
expect.objectContaining({ dayId: day.id, orderedIds: [a.id] }),
);
});
});
@@ -35,16 +35,14 @@ vi.mock('../../../src/config', () => ({
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
vi.mock('../../../src/services/adminService', () => ({
isAddonEnabled: vi.fn().mockReturnValue(true),
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
import { createUser, createBucketListItem, createVisitedCountry } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
import { setAddonEnabled } from '../../helpers/test-db';
import { ADDON_IDS } from '../../../src/addons';
beforeAll(() => {
createTables(testDb);
@@ -52,6 +50,7 @@ beforeAll(() => {
});
beforeEach(() => {
setAddonEnabled(testDb, ADDON_IDS.ATLAS, true);
resetTestDb(testDb);
broadcastMock.mockClear();
delete process.env.DEMO_MODE;
@@ -66,8 +65,11 @@ async function withHarness(userId: number, fn: (h: McpHarness) => Promise<void>)
try { await fn(h); } finally { await h.cleanup(); }
}
// The atlas resources register via the nest-mcp registry inside registerTools
// (AtlasMcp @Resource), so the harness must keep tools on for them to attach
// (same shape as tools-vacay.test.ts's withResourceHarness).
async function withResourceHarness(userId: number, fn: (h: McpHarness) => Promise<void>) {
const h = await createMcpHarness({ userId, withTools: false, withResources: true });
const h = await createMcpHarness({ userId, withResources: true });
try { await fn(h); } finally { await h.cleanup(); }
}
@@ -120,6 +122,28 @@ describe('Tool: list_visited_regions', () => {
// ---------------------------------------------------------------------------
describe('Tool: mark_region_visited', () => {
it('uppercases both codes like REST does (post-fold quirk fix)', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'mark_region_visited',
arguments: { regionCode: 'jp-13', regionName: 'Tokyo', countryCode: 'jp' },
});
const data = parseToolResult(result) as any;
// Legacy stored 'jp-13'/'jp' verbatim, creating rows REST's uppercased
// unmark could never hit; both codes now normalize.
expect(data.region.code).toBe('JP-13');
expect(data.region.country_code).toBe('JP');
const unmark = await h.client.callTool({
name: 'unmark_region_visited',
arguments: { regionCode: 'jp-13' },
});
expect(parseToolResult(unmark)).toEqual({ success: true });
const row = testDb.prepare('SELECT 1 FROM visited_regions WHERE user_id = ?').get(user.id);
expect(row).toBeUndefined();
});
});
it('inserts region and returns region object', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
@@ -204,6 +228,22 @@ describe('Tool: get_country_atlas_places', () => {
expect(Array.isArray(data.places)).toBe(true);
});
});
it('uppercases the country code like REST does (post-fold quirk fix)', async () => {
const { user } = createUser(testDb);
testDb.prepare('INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(user.id, 'JP');
// A trip so countryPlaces reaches the visited_countries lookup pre-quirk-fix too.
testDb.prepare('INSERT INTO trips (user_id, title) VALUES (?, ?)').run(user.id, 'Japan');
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'get_country_atlas_places',
arguments: { countryCode: 'jp' },
});
const data = parseToolResult(result) as any;
// Legacy passed 'jp' through verbatim and the lookup matched nothing.
expect(data.manually_marked).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
@@ -255,6 +295,22 @@ describe('Tool: update_bucket_list_item', () => {
});
});
it('returns isError when the edit would land on another wish (#1898)', async () => {
const { user } = createUser(testDb);
const insert = testDb.prepare('INSERT INTO bucket_list (user_id, name, target_date) VALUES (?, ?, ?)');
insert.run(user.id, 'Japan', '2027-05');
const itemId = insert.run(user.id, 'Japan', '2028-09').lastInsertRowid as number;
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'update_bucket_list_item',
arguments: { itemId, target_date: '2027-05' },
});
expect(result.isError).toBe(true);
const row = testDb.prepare('SELECT target_date FROM bucket_list WHERE id = ?').get(itemId) as { target_date: string };
expect(row.target_date).toBe('2028-09');
});
});
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
@@ -314,3 +370,68 @@ describe('Resource: trek://atlas/regions', () => {
});
});
});
// ---------------------------------------------------------------------------
// Resource: trek://bucket-list (moved from resources.test.ts with the fold —
// that suite's withTools:false harness never attaches registry resources)
// ---------------------------------------------------------------------------
describe('Resource: trek://bucket-list', () => {
it('returns only the current user\'s bucket list items', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
createBucketListItem(testDb, user.id, { name: 'Tokyo' });
createBucketListItem(testDb, other.id, { name: 'Rome' });
await withResourceHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: 'trek://bucket-list' });
const items = parseResourceResult(result) as any[];
expect(items).toHaveLength(1);
expect(items[0].name).toBe('Tokyo');
});
});
it('returns empty array for user with no items', async () => {
const { user } = createUser(testDb);
await withResourceHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: 'trek://bucket-list' });
const items = parseResourceResult(result) as any[];
expect(items).toEqual([]);
});
});
});
// ---------------------------------------------------------------------------
// Resource: trek://visited-countries (moved from resources.test.ts, same reason)
// ---------------------------------------------------------------------------
describe('Resource: trek://visited-countries', () => {
it('returns only the current user\'s visited countries', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
createVisitedCountry(testDb, user.id, 'FR');
createVisitedCountry(testDb, user.id, 'JP');
createVisitedCountry(testDb, other.id, 'DE');
await withResourceHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: 'trek://visited-countries' });
const countries = parseResourceResult(result) as any[];
expect(countries).toHaveLength(2);
const codes = countries.map((c) => c.country_code);
expect(codes).toContain('FR');
expect(codes).toContain('JP');
expect(codes).not.toContain('DE');
});
});
it('returns empty array for user with no visited countries', async () => {
const { user } = createUser(testDb);
await withResourceHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: 'trek://visited-countries' });
const countries = parseResourceResult(result) as any[];
expect(countries).toEqual([]);
});
});
});
+30
View File
@@ -162,6 +162,36 @@ describe('Tool: create_bucket_list_item', () => {
});
});
it('takes a target date, so the same place can be planned for several dates (#1898)', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const first = await h.client.callTool({
name: 'create_bucket_list_item',
arguments: { name: 'Japan', country_code: 'JP', target_date: '2027-05' },
});
expect((parseToolResult(first) as any).item.target_date).toBe('2027-05');
const second = await h.client.callTool({
name: 'create_bucket_list_item',
arguments: { name: 'Japan', country_code: 'JP', target_date: '2028-09' },
});
expect((parseToolResult(second) as any).item.target_date).toBe('2028-09');
});
});
it('reports the duplicate instead of appending a second row (#1898)', async () => {
const { user } = createUser(testDb);
createBucketListItem(testDb, user.id, { name: 'Japan', country_code: 'JP' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_bucket_list_item',
arguments: { name: 'Japan', country_code: 'JP' },
});
expect(result.isError).toBe(true);
expect((testDb.prepare('SELECT COUNT(*) AS n FROM bucket_list WHERE user_id = ?').get(user.id) as { n: number }).n).toBe(1);
});
});
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
@@ -38,7 +38,7 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createBudgetItem, addTripMember } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
@@ -49,9 +49,14 @@ beforeEach(() => {
resetTestDb(testDb);
broadcastMock.mockClear();
delete process.env.DEMO_MODE;
// get_settlement_summary calls getRates(), which is a real fetch to
// api.frankfurter.dev with a 10 s abort. One case used to stub this inline;
// hoisted so a second settlement case cannot quietly reintroduce the call.
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); }));
});
afterAll(() => {
vi.unstubAllGlobals();
testDb.close();
});
@@ -83,7 +88,13 @@ describe('Tool: set_budget_item_members', () => {
// Regression: returns a hydrated item, not the raw row from updateMembers.
expect(data.item.members.map((m: any) => m.user_id)).toEqual([user.id]);
expect(Array.isArray(data.item.payers)).toBe(true);
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'budget:members-updated', expect.any(Object));
// Quirk fix: the broadcast carries the REST payload shape (the legacy
// MCP-specific { item } shape was a silent no-op in the client handler).
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'budget:members-updated', expect.objectContaining({
itemId: item.id,
members: expect.arrayContaining([expect.objectContaining({ user_id: user.id })]),
persons: 1,
}));
});
});
@@ -215,7 +226,9 @@ describe('Tool: toggle_budget_member_paid', () => {
});
const data = parseToolResult(result) as any;
expect(data.member).toBeDefined();
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'budget:member-paid-updated', expect.any(Object));
// Quirk fix: the broadcast carries the REST payload shape (the legacy
// MCP-specific { itemId, member } shape was a silent no-op in the client).
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'budget:member-paid-updated', expect.objectContaining({ itemId: item.id, userId: user.id, paid: 1 }));
});
});
@@ -320,8 +333,6 @@ describe('Settlement tools', () => {
});
it('get_settlement_summary returns balances and flows', async () => {
// Avoid a real exchange-rate network call: force getRates() to fail closed.
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); }));
try {
const { user, other, trip } = tripWithTwo();
// user paid 100 for an item split between both → other owes user 50.
@@ -353,7 +364,7 @@ describe('Resource: trek://trips/{tripId}/budget/per-person', () => {
const trip = createTrip(testDb, user.id);
await withResourceHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/budget/per-person` });
const data = JSON.parse(result.contents[0].text as string);
const data = parseResourceResult(result);
expect(Array.isArray(data)).toBe(true);
});
});
@@ -364,7 +375,7 @@ describe('Resource: trek://trips/{tripId}/budget/per-person', () => {
const trip = createTrip(testDb, other.id);
await withResourceHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/budget/per-person` });
const data = JSON.parse(result.contents[0].text as string);
const data = parseResourceResult(result) as { error?: string };
expect(data.error).toBeDefined();
});
});
@@ -380,7 +391,9 @@ describe('Resource: trek://trips/{tripId}/budget/settlement', () => {
const trip = createTrip(testDb, user.id);
await withResourceHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/budget/settlement` });
const data = JSON.parse(result.contents[0].text as string);
// The resource may answer with a summary object or a bare array, and the
// assertion below accepts either, so keep the balances field optional.
const data = parseResourceResult(result) as { balances?: unknown };
expect(data).toBeDefined();
expect(Array.isArray(data.balances) || Array.isArray(data)).toBe(true);
});
+33 -1
View File
@@ -36,7 +36,7 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createBudgetItem, addTripMember } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
@@ -304,3 +304,35 @@ describe('Tool: delete_budget_item', () => {
});
});
});
// ---------------------------------------------------------------------------
// Resource: trek://trips/{tripId}/budget (moved from the legacy resources.ts
// registrar to the DI-discovered BudgetMcp — attached via the nest-mcp registry)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/budget', () => {
it('returns budget items for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createBudgetItem(testDb, trip.id, { name: 'Hotel', category: 'Accommodation', total_price: 200 });
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/budget` });
const items = parseResourceResult(result) as { name: string }[];
expect(items).toHaveLength(1);
expect(items[0].name).toBe('Hotel');
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/budget` });
const data = parseResourceResult(result) as { error?: string };
expect(data.error).toBeTruthy();
});
});
});
@@ -0,0 +1,155 @@
/**
* Unit tests for the categories MCP surface (CategoriesMcp, DI-discovered):
* the list_categories tool and the trek://categories resource.
*
* Both attach via the nest-mcp registry inside registerTools, so every harness
* here keeps withTools on (the resource is NOT registered by the legacy
* registerResources fan-out anymore).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
async function withHarness(
userId: number,
fn: (h: McpHarness) => Promise<void>,
scopes: string[] | null = null,
) {
const h = await createMcpHarness({ userId, withResources: false, scopes });
try { await fn(h); } finally { await h.cleanup(); }
}
// ---------------------------------------------------------------------------
// list_categories
// ---------------------------------------------------------------------------
describe('Tool: list_categories', () => {
it('returns all categories with id, name, color, icon', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'list_categories', arguments: {} });
const data = parseToolResult(result) as any;
expect(data.categories).toBeDefined();
expect(data.categories.length).toBeGreaterThan(0);
const cat = data.categories[0];
expect(cat).toHaveProperty('id');
expect(cat).toHaveProperty('name');
expect(cat).toHaveProperty('color');
expect(cat).toHaveProperty('icon');
});
});
it('returns categories from all users, ordered by name', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
testDb.prepare('INSERT INTO categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)').run('Zzz Mine', '#111111', '🅰️', user.id);
testDb.prepare('INSERT INTO categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)').run('Zzz Other', '#222222', '🅱️', other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'list_categories', arguments: {} });
const names = (parseToolResult(result) as any).categories.map((c: { name: string }) => c.name);
expect(names).toContain('Zzz Mine');
expect(names).toContain('Zzz Other');
expect(names).toEqual([...names].sort());
});
});
});
// ---------------------------------------------------------------------------
// list_categories scope gating (places:read, registration-time)
// ---------------------------------------------------------------------------
describe('Tool: list_categories — scope gating', () => {
async function listToolNames(userId: number, scopes: string[] | null): Promise<string[]> {
const h = await createMcpHarness({ userId, withResources: false, scopes });
try {
return (await h.client.listTools()).tools.map((t) => t.name);
} finally {
await h.cleanup();
}
}
it('registers with null scopes (full access)', async () => {
const { user } = createUser(testDb);
expect(await listToolNames(user.id, null)).toContain('list_categories');
});
it('registers with places:read', async () => {
const { user } = createUser(testDb);
expect(await listToolNames(user.id, ['places:read'])).toContain('list_categories');
});
it('does not register for an unrelated scope', async () => {
const { user } = createUser(testDb);
expect(await listToolNames(user.id, ['budget:read'])).not.toContain('list_categories');
});
});
// ---------------------------------------------------------------------------
// trek://categories resource (first production @Resource)
// ---------------------------------------------------------------------------
describe('Resource: trek://categories', () => {
it('returns all categories', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: 'trek://categories' });
const categories = parseResourceResult(result) as any[];
expect(categories.length).toBeGreaterThan(0);
expect(categories[0]).toHaveProperty('id');
expect(categories[0]).toHaveProperty('name');
expect(categories[0]).toHaveProperty('color');
expect(categories[0]).toHaveProperty('icon');
});
});
it('stays readable under restricted non-places scopes (legacy ungated behavior)', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: 'trek://categories' });
const categories = parseResourceResult(result) as any[];
expect(Array.isArray(categories)).toBe(true);
expect(categories.length).toBeGreaterThan(0);
}, ['trips:read']);
});
});
@@ -2,7 +2,8 @@
* Unit tests for MCP collab polls and chat tools (collab addon-gated):
* list_collab_polls, create_collab_poll, vote_collab_poll, close_collab_poll,
* delete_collab_poll, list_collab_messages, send_collab_message,
* delete_collab_message, react_collab_message.
* delete_collab_message, react_collab_message (CollabMcp, DI-discovered —
* attached via the nest-mcp registry inside registerTools).
* Resources: trek://trips/{tripId}/collab/polls, trek://trips/{tripId}/collab/messages.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -36,16 +37,14 @@ vi.mock('../../../src/config', () => ({
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
vi.mock('../../../src/services/adminService', () => ({
isAddonEnabled: vi.fn().mockReturnValue(true),
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
import { setAddonEnabled } from '../../helpers/test-db';
import { ADDON_IDS } from '../../../src/addons';
beforeAll(() => {
createTables(testDb);
@@ -53,6 +52,7 @@ beforeAll(() => {
});
beforeEach(() => {
setAddonEnabled(testDb, ADDON_IDS.COLLAB, true);
resetTestDb(testDb);
broadcastMock.mockClear();
delete process.env.DEMO_MODE;
@@ -177,6 +177,24 @@ describe('Tool: vote_collab_poll', () => {
});
});
it('blocks demo user (gate added with the DI migration — the legacy registrar missed it)', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
const trip = createTrip(testDb, user.id);
const pollId = (testDb.prepare(
`INSERT INTO collab_polls (trip_id, user_id, question, options, created_at) VALUES (?, ?, ?, ?, datetime('now'))`
).run(trip.id, user.id, 'Best city?', JSON.stringify(['Paris', 'Rome'])) as any).lastInsertRowid;
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'vote_collab_poll',
arguments: { tripId: trip.id, pollId: Number(pollId), optionIndex: 0 },
});
expect(result.isError).toBe(true);
expect(testDb.prepare('SELECT COUNT(*) as c FROM collab_poll_votes WHERE poll_id = ?').get(pollId)).toEqual({ c: 0 });
});
});
it('returns access denied for non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
@@ -0,0 +1,530 @@
/**
* Unit tests for the collections MCP surface (CollectionsMcp, DI-discovered):
* the 25 tools ported 1:1 from the legacy src/mcp/tools/collections.ts
* registrar. New with the DI fold — the legacy registrar had no tool-level
* suite — so this is a characterization of the ported behavior: payload
* shapes, error texts (the service's thrown httpError messages surfaced via
* fail()), the owner-only available-users gate, demo denial on writes, the
* collections read/write scope gating, and — since the post-fold quirk pass —
* the collections-addon `when:` gate (the legacy registrar registered
* unconditionally while REST and the plugin host gated; the port fixed that).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock, broadcastToUser } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const broadcastToUser = vi.fn();
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: number | string, userId: number) =>
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
isOwner: (tripId: number | string, userId: number) =>
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
};
return { testDb: db, dbMock: mock, broadcastToUser };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser }));
const { notifSend } = vi.hoisted(() => ({ notifSend: vi.fn().mockResolvedValue(undefined) }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { createUser, createTrip, createPlace, createCategory } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { ADDON_IDS } from '../../../src/addons';
function clearCollections() {
testDb.exec(`
DELETE FROM collection_place_labels;
DELETE FROM collection_labels;
DELETE FROM collection_place_tags;
DELETE FROM collection_place_ratings;
DELETE FROM collection_places;
DELETE FROM collection_members;
DELETE FROM collections;
DELETE FROM place_tags;
DELETE FROM places;
DELETE FROM trip_members;
DELETE FROM trips;
DELETE FROM users;
`);
}
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
// The collections addon is seeded DISABLED by default and every tool rides
// the `when:` addon gate (post-fold quirk fix) — enable it for the suite.
testDb.prepare('UPDATE addons SET enabled = 1 WHERE id = ?').run(ADDON_IDS.COLLECTIONS);
});
beforeEach(() => {
clearCollections();
broadcastToUser.mockClear();
notifSend.mockClear();
delete process.env.DEMO_MODE;
});
afterAll(() => {
testDb.close();
});
async function withHarness(userId: number, fn: (h: McpHarness) => Promise<void>) {
const h = await createMcpHarness({ userId, withResources: false });
try { await fn(h); } finally { await h.cleanup(); }
}
function errorText(result: Awaited<ReturnType<McpHarness['client']['callTool']>>): string {
const text = (result.content as { type: string; text?: string }[]).find((c) => c.type === 'text');
return text?.text ?? '';
}
/** Seed a collection directly (owner_id row only — no service round trip). */
function seedCollection(ownerId: number, name = 'List'): number {
return Number(testDb.prepare('INSERT INTO collections (owner_id, name, sort_order) VALUES (?, ?, 0)').run(ownerId, name).lastInsertRowid);
}
function addMember(colId: number, userId: number, role: 'viewer' | 'editor' | 'admin' = 'editor', status: 'accepted' | 'pending' = 'accepted') {
testDb.prepare('INSERT INTO collection_members (collection_id, user_id, status, role) VALUES (?, ?, ?, ?)').run(colId, userId, status, role);
}
function seedPlace(colId: number, ownerId: number, name: string, extra: Record<string, unknown> = {}): number {
return Number(testDb.prepare(
'INSERT INTO collection_places (collection_id, owner_id, saved_by, name, lat, lng, status) VALUES (?, ?, ?, ?, ?, ?, ?)',
).run(colId, ownerId, ownerId, name, extra.lat ?? null, extra.lng ?? null, extra.status ?? 'idea').lastInsertRowid);
}
// ---------------------------------------------------------------------------
// Read tools
// ---------------------------------------------------------------------------
describe('Tool: list_collections', () => {
it('lists owned collections plus incoming invites', async () => {
const { user } = createUser(testDb);
const { user: inviter } = createUser(testDb);
seedCollection(user.id, 'Mine');
const invitedTo = seedCollection(inviter.id, 'Theirs');
addMember(invitedTo, user.id, 'editor', 'pending');
await withHarness(user.id, async (h) => {
const data = parseToolResult(await h.client.callTool({ name: 'list_collections', arguments: {} })) as {
collections: { name: string }[]; incomingInvites: { collection_id: number }[];
};
expect(data.collections.map((c) => c.name)).toEqual(['Mine']);
expect(data.incomingInvites.map((i) => i.collection_id)).toEqual([invitedTo]);
});
});
});
describe('Tool: get_collection', () => {
it('returns the detail with places, labels and members', async () => {
const { user } = createUser(testDb);
const col = seedCollection(user.id, 'Detail');
seedPlace(col, user.id, 'Louvre');
await withHarness(user.id, async (h) => {
const data = parseToolResult(await h.client.callTool({ name: 'get_collection', arguments: { collectionId: col } })) as {
collection: { id: number; labels: unknown[] }; places: { name: string }[];
};
expect(data.collection.id).toBe(col);
expect(data.places.map((p) => p.name)).toEqual(['Louvre']);
});
});
it('surfaces the 404 error text for an inaccessible collection', async () => {
const { user } = createUser(testDb);
const { user: owner } = createUser(testDb);
const col = seedCollection(owner.id, 'Hidden');
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'get_collection', arguments: { collectionId: col } });
expect(result.isError).toBe(true);
expect(errorText(result)).toBe('Collection not found');
});
});
});
describe('Tool: available_collection_users', () => {
it('is owner-only: owner 200, accepted member gets the bespoke error, stranger a 404 text', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const { user: invitable } = createUser(testDb);
const col = seedCollection(owner.id, 'Members');
addMember(col, member.id);
await withHarness(owner.id, async (h) => {
const data = parseToolResult(await h.client.callTool({ name: 'available_collection_users', arguments: { collectionId: col } })) as { users: { id: number }[] };
const ids = data.users.map((u) => u.id);
expect(ids).toContain(invitable.id);
expect(ids).not.toContain(owner.id);
expect(ids).not.toContain(member.id);
});
await withHarness(member.id, async (h) => {
const result = await h.client.callTool({ name: 'available_collection_users', arguments: { collectionId: col } });
expect(result.isError).toBe(true);
expect(errorText(result)).toBe('Only the collection owner can view invitable users.');
});
await withHarness(stranger.id, async (h) => {
const result = await h.client.callTool({ name: 'available_collection_users', arguments: { collectionId: col } });
expect(result.isError).toBe(true);
expect(errorText(result)).toBe('Collection not found');
});
});
});
// ---------------------------------------------------------------------------
// Collections CRUD
// ---------------------------------------------------------------------------
describe('Tool: create_collection / update_collection / delete_collection / reorder_collections', () => {
it('create → update → reorder → delete round trip', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const created = parseToolResult(await h.client.callTool({ name: 'create_collection', arguments: { name: 'Italy' } })) as { collection: { id: number; name: string; is_owner: boolean } };
expect(created.collection.name).toBe('Italy');
expect(created.collection.is_owner).toBe(true);
const updated = parseToolResult(await h.client.callTool({ name: 'update_collection', arguments: { collectionId: created.collection.id, name: 'Italia' } })) as { collection: { name: string } };
expect(updated.collection.name).toBe('Italia');
const second = parseToolResult(await h.client.callTool({ name: 'create_collection', arguments: { name: 'France' } })) as { collection: { id: number } };
const reordered = parseToolResult(await h.client.callTool({ name: 'reorder_collections', arguments: { orderedIds: [second.collection.id, created.collection.id] } }));
expect(reordered).toEqual({ success: true });
expect(testDb.prepare('SELECT sort_order FROM collections WHERE id = ?').get(second.collection.id)).toEqual({ sort_order: 0 });
const deleted = parseToolResult(await h.client.callTool({ name: 'delete_collection', arguments: { collectionId: created.collection.id } }));
expect(deleted).toEqual({ success: true });
expect(testDb.prepare('SELECT COUNT(*) n FROM collections WHERE id = ?').get(created.collection.id)).toEqual({ n: 0 });
});
});
it('delete_collection is owner-only (bespoke 403 text) and update surfaces the viewer 403', async () => {
const { user: owner } = createUser(testDb);
const { user: viewer } = createUser(testDb);
const col = seedCollection(owner.id, 'Guarded');
addMember(col, viewer.id, 'viewer');
await withHarness(viewer.id, async (h) => {
const del = await h.client.callTool({ name: 'delete_collection', arguments: { collectionId: col } });
expect(del.isError).toBe(true);
expect(errorText(del)).toBe('Only the owner can delete this list');
const upd = await h.client.callTool({ name: 'update_collection', arguments: { collectionId: col, name: 'Nope' } });
expect(upd.isError).toBe(true);
expect(errorText(upd)).toBe('You have read-only access to this list');
});
});
it('blocks demo user on writes', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'create_collection', arguments: { name: 'X' } });
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// Places
// ---------------------------------------------------------------------------
describe('Tool: save_place_to_collection', () => {
it('saves a place and returns the duplicate marker on a re-save', async () => {
const { user } = createUser(testDb);
const col = seedCollection(user.id, 'Dedup');
await withHarness(user.id, async (h) => {
const saved = parseToolResult(await h.client.callTool({ name: 'save_place_to_collection', arguments: { collection_id: col, name: 'Eiffel Tower' } })) as { place?: { id: number } };
expect(saved.place).toBeDefined();
const dup = parseToolResult(await h.client.callTool({ name: 'save_place_to_collection', arguments: { collection_id: col, name: 'eiffel tower' } })) as { duplicate?: boolean; duplicateOf?: { name: string } };
expect(dup.duplicate).toBe(true);
expect(dup.duplicateOf?.name).toBe('Eiffel Tower');
});
});
});
describe('Tool: save_trip_places_to_collection', () => {
it('copies trip places, skipping duplicates', async () => {
const { user } = createUser(testDb);
createCategory(testDb);
const trip = createTrip(testDb, user.id);
const p1 = createPlace(testDb, trip.id, { name: 'Colosseum' });
const p2 = createPlace(testDb, trip.id, { name: 'Pantheon' });
const col = seedCollection(user.id, 'From trip');
seedPlace(col, user.id, 'Pantheon'); // pre-existing → duplicate
await withHarness(user.id, async (h) => {
const data = parseToolResult(await h.client.callTool({
name: 'save_trip_places_to_collection',
arguments: { collectionId: col, tripId: trip.id, placeIds: [p1.id, p2.id] },
})) as { copied: number; skipped: { name: string }[] };
expect(data.copied).toBe(1);
expect(data.skipped.map((s) => s.name)).toEqual(['Pantheon']);
});
});
});
describe('Tool: update_collection_place / set_collection_place_status / rate_collection_place', () => {
it('updates fields, sets status, and stores/clears a rating', async () => {
const { user } = createUser(testDb);
const col = seedCollection(user.id, 'P');
const pid = seedPlace(col, user.id, 'Gate');
await withHarness(user.id, async (h) => {
const upd = parseToolResult(await h.client.callTool({ name: 'update_collection_place', arguments: { placeId: pid, name: 'Brandenburg Gate' } })) as { place: { name: string } };
expect(upd.place.name).toBe('Brandenburg Gate');
const status = parseToolResult(await h.client.callTool({ name: 'set_collection_place_status', arguments: { placeId: pid, status: 'want' } })) as { place: { status: string } };
expect(status.place.status).toBe('want');
const rated = parseToolResult(await h.client.callTool({ name: 'rate_collection_place', arguments: { placeId: pid, rating: 5 } })) as { place: { rating_avg: number | null; rating_count: number } };
expect(rated.place.rating_avg).toBe(5);
expect(rated.place.rating_count).toBe(1);
// omitted rating clears the vote (legacy `rating ?? null`)
const cleared = parseToolResult(await h.client.callTool({ name: 'rate_collection_place', arguments: { placeId: pid } })) as { place: { rating_avg: number | null; rating_count: number } };
expect(cleared.place.rating_avg).toBeNull();
expect(cleared.place.rating_count).toBe(0);
});
});
});
describe('Tool: delete_collection_place', () => {
it('deletes a place; an unknown id surfaces the 404 text', async () => {
const { user } = createUser(testDb);
const col = seedCollection(user.id, 'D');
const pid = seedPlace(col, user.id, 'Gone');
await withHarness(user.id, async (h) => {
expect(parseToolResult(await h.client.callTool({ name: 'delete_collection_place', arguments: { placeId: pid } }))).toEqual({ success: true });
const missing = await h.client.callTool({ name: 'delete_collection_place', arguments: { placeId: pid } });
expect(missing.isError).toBe(true);
expect(errorText(missing)).toBe('Place not found');
});
});
});
describe('Tool: copy_collection_places_to_trip', () => {
it('copies saved places into a trip the user can edit', async () => {
const { user } = createUser(testDb);
createCategory(testDb);
const trip = createTrip(testDb, user.id);
const col = seedCollection(user.id, 'Plan');
const pid = seedPlace(col, user.id, 'Trevi Fountain');
await withHarness(user.id, async (h) => {
const data = parseToolResult(await h.client.callTool({ name: 'copy_collection_places_to_trip', arguments: { trip_id: trip.id, place_ids: [pid] } })) as { copied: number };
expect(data.copied).toBe(1);
expect(testDb.prepare("SELECT COUNT(*) n FROM places WHERE trip_id = ? AND name = 'Trevi Fountain'").get(trip.id)).toEqual({ n: 1 });
});
});
it('surfaces the 404 text for a trip the user cannot access', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
createCategory(testDb);
const trip = createTrip(testDb, other.id);
const col = seedCollection(user.id, 'C');
const pid = seedPlace(col, user.id, 'X');
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'copy_collection_places_to_trip', arguments: { trip_id: trip.id, place_ids: [pid] } });
expect(result.isError).toBe(true);
expect(errorText(result)).toBe('Trip not found');
});
});
});
// ---------------------------------------------------------------------------
// Labels
// ---------------------------------------------------------------------------
describe('Label tools', () => {
it('create → assign → update → unassign → delete a label', async () => {
const { user } = createUser(testDb);
const col = seedCollection(user.id, 'DE');
const pid = seedPlace(col, user.id, 'Gate');
await withHarness(user.id, async (h) => {
const created = parseToolResult(await h.client.callTool({ name: 'create_collection_label', arguments: { collection_id: col, name: 'Berlin', color: '#ff0000' } })) as { label: { id: number; name: string } };
expect(created.label.name).toBe('Berlin');
const assigned = parseToolResult(await h.client.callTool({ name: 'assign_collection_labels', arguments: { label_ids: [created.label.id], place_ids: [pid] } })) as { changed: number };
expect(assigned.changed).toBe(1);
const renamed = parseToolResult(await h.client.callTool({ name: 'update_collection_label', arguments: { labelId: created.label.id, name: 'Museums' } })) as { label: { name: string } };
expect(renamed.label.name).toBe('Museums');
const removed = parseToolResult(await h.client.callTool({ name: 'assign_collection_labels', arguments: { label_ids: [created.label.id], place_ids: [pid], remove: true } })) as { changed: number };
expect(removed.changed).toBe(1);
expect(parseToolResult(await h.client.callTool({ name: 'delete_collection_label', arguments: { labelId: created.label.id } }))).toEqual({ success: true });
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_labels WHERE collection_id = ?').get(col)).toEqual({ n: 0 });
});
});
it('duplicate label name surfaces the 409 text', async () => {
const { user } = createUser(testDb);
const col = seedCollection(user.id, 'DE');
await withHarness(user.id, async (h) => {
await h.client.callTool({ name: 'create_collection_label', arguments: { collection_id: col, name: 'Berlin' } });
const dup = await h.client.callTool({ name: 'create_collection_label', arguments: { collection_id: col, name: 'berlin' } });
expect(dup.isError).toBe(true);
expect(errorText(dup)).toBe('A label with this name already exists');
});
});
});
// ---------------------------------------------------------------------------
// Sharing
// ---------------------------------------------------------------------------
describe('Sharing tools', () => {
it('invite → accept → set role → remove member round trip', async () => {
const { user: owner } = createUser(testDb);
const { user: target } = createUser(testDb);
const col = seedCollection(owner.id, 'Shared');
await withHarness(owner.id, async (h) => {
const invited = parseToolResult(await h.client.callTool({ name: 'invite_to_collection', arguments: { collection_id: col, user_id: target.id } }));
expect(invited).toEqual({ success: true });
expect(broadcastToUser).toHaveBeenCalledWith(target.id, expect.objectContaining({ type: 'collections:invite' }));
});
await withHarness(target.id, async (h) => {
expect(parseToolResult(await h.client.callTool({ name: 'accept_collection_invite', arguments: { collectionId: col } }))).toEqual({ success: true });
});
await withHarness(owner.id, async (h) => {
expect(parseToolResult(await h.client.callTool({ name: 'set_collection_member_role', arguments: { collectionId: col, userId: target.id, role: 'admin' } }))).toEqual({ success: true });
expect(testDb.prepare('SELECT role FROM collection_members WHERE collection_id = ? AND user_id = ?').get(col, target.id)).toEqual({ role: 'admin' });
expect(parseToolResult(await h.client.callTool({ name: 'remove_collection_member', arguments: { collectionId: col, userId: target.id } }))).toEqual({ success: true });
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_members WHERE collection_id = ?').get(col)).toEqual({ n: 0 });
});
});
it('invite errors come back as isError text (self-invite / not owner)', async () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const col = seedCollection(owner.id, 'OwnerOnly');
await withHarness(owner.id, async (h) => {
const self = await h.client.callTool({ name: 'invite_to_collection', arguments: { collection_id: col, user_id: owner.id } });
expect(self.isError).toBe(true);
expect(errorText(self)).toBe('Cannot invite yourself');
});
await withHarness(other.id, async (h) => {
const notOwner = await h.client.callTool({ name: 'invite_to_collection', arguments: { collection_id: col, user_id: owner.id } });
expect(notOwner.isError).toBe(true);
expect(errorText(notOwner)).toBe('Not allowed');
});
});
it('accept without a pending invite → error text; decline and cancel clear the pending row', async () => {
const { user: owner } = createUser(testDb);
const { user: target } = createUser(testDb);
const col = seedCollection(owner.id, 'Pending');
await withHarness(target.id, async (h) => {
const noInvite = await h.client.callTool({ name: 'accept_collection_invite', arguments: { collectionId: col } });
expect(noInvite.isError).toBe(true);
expect(errorText(noInvite)).toBe('No pending invite');
});
addMember(col, target.id, 'editor', 'pending');
await withHarness(target.id, async (h) => {
expect(parseToolResult(await h.client.callTool({ name: 'decline_collection_invite', arguments: { collectionId: col } }))).toEqual({ success: true });
});
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_members WHERE collection_id = ?').get(col)).toEqual({ n: 0 });
addMember(col, target.id, 'editor', 'pending');
await withHarness(owner.id, async (h) => {
expect(parseToolResult(await h.client.callTool({ name: 'cancel_collection_invite', arguments: { collectionId: col, userId: target.id } }))).toEqual({ success: true });
});
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_members WHERE collection_id = ?').get(col)).toEqual({ n: 0 });
});
it('leave_collection: member leaves; the owner gets the bespoke 400 text', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const col = seedCollection(owner.id, 'Leavable');
addMember(col, member.id);
await withHarness(member.id, async (h) => {
expect(parseToolResult(await h.client.callTool({ name: 'leave_collection', arguments: { collectionId: col } }))).toEqual({ success: true });
});
await withHarness(owner.id, async (h) => {
const blocked = await h.client.callTool({ name: 'leave_collection', arguments: { collectionId: col } });
expect(blocked.isError).toBe(true);
expect(errorText(blocked)).toBe('Owner cannot leave; delete the list');
});
});
});
// ---------------------------------------------------------------------------
// Scope gating (collections read/write, registration-time)
// ---------------------------------------------------------------------------
const READ_TOOLS = ['list_collections', 'get_collection', 'available_collection_users'];
const WRITE_TOOLS = [
'create_collection', 'update_collection', 'delete_collection', 'reorder_collections',
'save_place_to_collection', 'save_trip_places_to_collection', 'update_collection_place',
'set_collection_place_status', 'rate_collection_place', 'delete_collection_place',
'copy_collection_places_to_trip', 'create_collection_label', 'update_collection_label',
'delete_collection_label', 'assign_collection_labels', 'invite_to_collection',
'set_collection_member_role', 'remove_collection_member', 'cancel_collection_invite',
'accept_collection_invite', 'decline_collection_invite', 'leave_collection',
];
describe('Collection tools — scope gating', () => {
async function listToolNames(userId: number, scopes: string[] | null): Promise<string[]> {
const h = await createMcpHarness({ userId, withResources: false, scopes });
try {
return (await h.client.listTools()).tools.map((t) => t.name);
} finally {
await h.cleanup();
}
}
it('registers all 25 tools with null scopes (full access)', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, null);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).toContain(tool);
});
it('registers only the read tools with collections:read', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['collections:read']);
for (const tool of READ_TOOLS) expect(names).toContain(tool);
for (const tool of WRITE_TOOLS) expect(names).not.toContain(tool);
});
it('registers no collection tools for an unrelated scope', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['budget:read']);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).not.toContain(tool);
});
});
// ---------------------------------------------------------------------------
// Addon gating — added with the post-fold quirk pass: the legacy registrar
// registered unconditionally (unlike the REST CollectionsAddonGuard and the
// plugin host's requireAddon); every entry now rides the collections addon
// via the `when:` predicate.
// ---------------------------------------------------------------------------
describe('Collection tools — collections addon gating', () => {
it('registers nothing when the collections addon is disabled', async () => {
const { user } = createUser(testDb);
testDb.prepare('UPDATE addons SET enabled = 0 WHERE id = ?').run(ADDON_IDS.COLLECTIONS);
try {
await withHarness(user.id, async (h) => {
const names = (await h.client.listTools()).tools.map((t) => t.name);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).not.toContain(tool);
});
} finally {
testDb.prepare('UPDATE addons SET enabled = 1 WHERE id = ?').run(ADDON_IDS.COLLECTIONS);
}
});
});
@@ -1,7 +1,10 @@
/**
* Unit tests for MCP day and accommodation tools:
* create_day, delete_day,
* create_accommodation, update_accommodation, delete_accommodation.
* create_accommodation, create_place_accommodation, update_accommodation,
* delete_accommodation — plus the trek://trips/{tripId}/accommodations
* resource (moved from resources.test.ts when the legacy registrar was
* ported to the DI-discovered DaysMcp).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -15,7 +18,18 @@ const { testDb, dbMock } = vi.hoisted(() => {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
// Real-SQL implementation: create_place_accommodation's createPlace
// returns getPlaceWithTags(placeId) — a null stub would make the tool's
// atomic branch throw before the accommodation insert.
getPlaceWithTags: (placeId: number | string) => {
const place = db.prepare(`
SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
FROM places p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?
`).get(placeId) as { category_id: number | null; category_name: string; category_color: string; category_icon: string } | undefined;
if (!place) return null;
const tags = db.prepare(`SELECT t.* FROM tags t JOIN place_tags pt ON t.id = pt.tag_id WHERE pt.place_id = ?`).all(placeId);
return { ...place, category: place.category_id ? { id: place.category_id, name: place.category_name, color: place.category_color, icon: place.category_icon } : null, tags };
},
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
isOwner: (tripId: any, userId: number) =>
@@ -38,7 +52,7 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, createDayAccommodation } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
@@ -94,6 +108,27 @@ describe('Tool: create_day', () => {
});
});
it('reports every bad reference in one message rather than the first', async () => {
// The validator returns a list and the tool joins it. Without a case that
// produces more than zero errors, that join is never executed, and a tool
// that silently created a stay against a foreign place would look fine.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id, { date: '2025-06-15' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_accommodation',
arguments: { tripId: trip.id, place_id: 999999, start_day_id: 999998, end_day_id: day.id },
});
expect(result.isError).toBe(true);
const text = (result.content as { text: string }[])[0].text;
expect(text).toContain('Place not found');
expect(text).toContain('Start day not found');
expect(text).toContain(', ');
});
expect(testDb.prepare('SELECT COUNT(*) AS n FROM day_accommodations').get()).toEqual({ n: 0 });
});
it('returns access denied for non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
@@ -131,7 +166,7 @@ describe('Tool: delete_day', () => {
});
const data = parseToolResult(result) as any;
expect(data.success).toBe(true);
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'day:deleted', expect.objectContaining({ id: day.id }));
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'day:deleted', expect.objectContaining({ dayId: day.id }));
expect(testDb.prepare('SELECT id FROM days WHERE id = ?').get(day.id)).toBeUndefined();
});
});
@@ -294,3 +329,79 @@ describe('Tool: delete_accommodation', () => {
});
});
});
// ---------------------------------------------------------------------------
// create_place_accommodation
// ---------------------------------------------------------------------------
describe('Tool: create_place_accommodation', () => {
it('creates the place and the accommodation atomically and broadcasts both', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_place_accommodation',
arguments: {
tripId: trip.id, name: 'Ryokan Sakura', start_day_id: day.id, end_day_id: day.id,
check_in: '15:00', accommodation_notes: 'Tatami room',
},
});
const data = parseToolResult(result) as { place: { id: number; name: string }; accommodation: { id: number } };
expect(data.place.name).toBe('Ryokan Sakura');
expect(data.accommodation).toMatchObject({ place_id: data.place.id, start_day_id: day.id, end_day_id: day.id, notes: 'Tatami room' });
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'place:created', expect.objectContaining({ place: expect.anything() }));
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'accommodation:created', expect.objectContaining({ accommodation: expect.anything() }));
// The partner hotel reservation rides along.
const linked = testDb.prepare('SELECT type FROM reservations WHERE accommodation_id = ?').get(data.accommodation.id) as { type: string };
expect(linked.type).toBe('hotel');
});
});
it('reports the day-validation errors without creating anything', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_place_accommodation',
arguments: { tripId: trip.id, name: 'Nowhere Inn', start_day_id: 99999, end_day_id: 99999 },
});
expect(result.isError).toBe(true);
expect(testDb.prepare('SELECT COUNT(*) as n FROM places WHERE trip_id = ?').get(trip.id)).toMatchObject({ n: 0 });
});
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/accommodations resource (moved from resources.test.ts)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/accommodations', () => {
it('returns accommodations for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day1 = createDay(testDb, trip.id, { day_number: 1 });
const day2 = createDay(testDb, trip.id, { day_number: 2 });
const place = createPlace(testDb, trip.id, { name: 'Grand Hotel' });
createDayAccommodation(testDb, trip.id, place.id, day1.id, day2.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/accommodations` });
const items = parseResourceResult(result) as any[];
expect(items).toHaveLength(1);
expect(items[0].place_name).toBe('Grand Hotel');
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/accommodations` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
+59 -3
View File
@@ -1,5 +1,7 @@
/**
* Unit tests for MCP day tools: update_day.
* Unit tests for the DI-discovered DaysMcp: the update_day tool and the
* trek://trips/{tripId}/days resource (moved from resources.test.ts when the
* legacy registrar was ported).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -35,8 +37,8 @@ vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createUser, createTrip, createDay, createPlace, createDayAssignment } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
@@ -93,6 +95,22 @@ describe('Tool: update_day', () => {
});
});
it('setting a title preserves the day notes (post-port defect fix)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
testDb.prepare('UPDATE days SET notes = ? WHERE id = ?').run('Walking day', day.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'update_day',
arguments: { tripId: trip.id, dayId: day.id, title: 'Arrival' },
});
const data = parseToolResult(result) as { day: { title: string; notes: string } };
expect(data.day).toMatchObject({ title: 'Arrival', notes: 'Walking day' });
});
});
it('broadcasts day:updated event', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
@@ -140,3 +158,41 @@ describe('Tool: update_day', () => {
});
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/days resource (moved from resources.test.ts)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/days', () => {
it('returns days with assignments in order', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day1 = createDay(testDb, trip.id, { day_number: 1 });
const day2 = createDay(testDb, trip.id, { day_number: 2 });
const place = createPlace(testDb, trip.id);
createDayAssignment(testDb, day1.id, place.id);
void day2;
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/days` });
const days = parseResourceResult(result) as any[];
expect(days).toHaveLength(2);
expect(days[0].day_number).toBe(1);
expect(days[0].assignments).toHaveLength(1);
expect(days[1].day_number).toBe(2);
expect(days[1].assignments).toHaveLength(0);
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/days` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
+494 -7
View File
@@ -34,16 +34,13 @@ vi.mock('../../../src/config', () => ({
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock, broadcastToUser: broadcastMock }));
vi.mock('../../../src/services/adminService', async (importOriginal) => {
const original = await importOriginal() as Record<string, unknown>;
return { ...original, isAddonEnabled: vi.fn().mockReturnValue(true) };
});
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createUser, createTrip } from '../../helpers/factories';
import { setAddonEnabled } from '../../helpers/test-db';
import { ADDON_IDS } from '../../../src/addons';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
@@ -52,6 +49,9 @@ beforeAll(() => {
beforeEach(() => {
resetTestDb(testDb);
// The `when:` gate reads the injected AddonsService, so the toggle is the row
// the admin panel writes — and this addon ships disabled by default.
setAddonEnabled(testDb, ADDON_IDS.JOURNEY, true);
broadcastMock.mockClear();
delete process.env.DEMO_MODE;
});
@@ -144,3 +144,490 @@ describe('Tool: update_journey_preferences', () => {
});
});
});
// ---------------------------------------------------------------------------
// The rest of the surface. The legacy registrar had no test file of its own —
// the two hydration cases above were the whole of it — so every tool below is
// covered here for the first time: the happy path, the "not found or access
// denied" branch a non-member hits, and the demo-mode denial on writes.
// ---------------------------------------------------------------------------
/** A journey owned by someone else — every access check must refuse it. */
function foreignJourney() {
const { user: other } = createUser(testDb);
const j = testDb.prepare(
'INSERT INTO journeys (user_id, title, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
).run(other.id, 'Not yours', 'draft', Date.now(), Date.now());
return { otherId: other.id, journeyId: Number(j.lastInsertRowid) };
}
async function seedJourney(h: McpHarness, title = 'J') {
return (parseToolResult(await h.client.callTool({
name: 'create_journey', arguments: { title },
})) as any).journey;
}
describe('journey read tools', () => {
it('list_journeys returns the caller-visible journeys', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
await seedJourney(h, 'Alpha');
const data = parseToolResult(await h.client.callTool({ name: 'list_journeys', arguments: {} })) as any;
expect(data.journeys.map((j: any) => j.title)).toContain('Alpha');
});
});
it('get_journey hydrates entries, contributors and trips', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
const data = parseToolResult(await h.client.callTool({
name: 'get_journey', arguments: { journeyId: journey.id },
})) as any;
expect(data.journey.id).toBe(journey.id);
expect(Array.isArray(data.journey.entries)).toBe(true);
});
});
it('get_journey refuses a journey the caller cannot see', async () => {
const { user } = createUser(testDb);
const { journeyId } = foreignJourney();
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'get_journey', arguments: { journeyId } });
expect(result.isError).toBe(true);
});
});
it('list_journey_entries returns the entries', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
await h.client.callTool({
name: 'create_journey_entry', arguments: { journeyId: journey.id, entry_date: '2026-07-01', title: 'D1' },
});
const data = parseToolResult(await h.client.callTool({
name: 'list_journey_entries', arguments: { journeyId: journey.id },
})) as any;
expect(data.entries).toHaveLength(1);
});
});
it('list_journey_entries refuses a foreign journey', async () => {
const { user } = createUser(testDb);
const { journeyId } = foreignJourney();
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'list_journey_entries', arguments: { journeyId } });
expect(result.isError).toBe(true);
});
});
it('list_journey_contributors returns the contributor rows', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
const data = parseToolResult(await h.client.callTool({
name: 'list_journey_contributors', arguments: { journeyId: journey.id },
})) as any;
expect(Array.isArray(data.contributors)).toBe(true);
});
});
it('list_journey_contributors refuses a foreign journey', async () => {
const { user } = createUser(testDb);
const { journeyId } = foreignJourney();
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'list_journey_contributors', arguments: { journeyId } });
expect(result.isError).toBe(true);
});
});
it('get_journey_suggestions and list_journey_available_trips answer with arrays', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const s = parseToolResult(await h.client.callTool({ name: 'get_journey_suggestions', arguments: {} })) as any;
const t = parseToolResult(await h.client.callTool({ name: 'list_journey_available_trips', arguments: {} })) as any;
expect(Array.isArray(s.trips)).toBe(true);
expect(Array.isArray(t.trips)).toBe(true);
});
});
});
describe('journey write tools', () => {
it('update_journey applies the change and refuses a foreign journey', async () => {
const { user } = createUser(testDb);
const { journeyId } = foreignJourney();
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
const updated = parseToolResult(await h.client.callTool({
name: 'update_journey', arguments: { journeyId: journey.id, title: 'Renamed', status: 'active' },
})) as any;
expect(updated.journey.title).toBe('Renamed');
const denied = await h.client.callTool({ name: 'update_journey', arguments: { journeyId, title: 'X' } });
expect(denied.isError).toBe(true);
});
});
it('delete_journey removes it and refuses a foreign journey', async () => {
const { user } = createUser(testDb);
const { journeyId } = foreignJourney();
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
const gone = parseToolResult(await h.client.callTool({
name: 'delete_journey', arguments: { journeyId: journey.id },
})) as any;
expect(gone.success).toBe(true);
const denied = await h.client.callTool({ name: 'delete_journey', arguments: { journeyId } });
expect(denied.isError).toBe(true);
});
});
it('add_journey_trip links a trip, remove_journey_trip unlinks it', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
const added = parseToolResult(await h.client.callTool({
name: 'add_journey_trip', arguments: { journeyId: journey.id, tripId: trip.id },
})) as any;
expect(added.success).toBe(true);
const removed = parseToolResult(await h.client.callTool({
name: 'remove_journey_trip', arguments: { journeyId: journey.id, tripId: trip.id },
})) as any;
expect(removed.success).toBe(true);
});
});
it('add_journey_trip refuses a foreign journey; remove_journey_trip is idempotent but refuses one', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const { journeyId } = foreignJourney();
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
expect((await h.client.callTool({
name: 'add_journey_trip', arguments: { journeyId, tripId: trip.id },
})).isError).toBe(true);
// Unlinking a trip that was never linked is a no-op, not an error — the
// gate is journey ownership, not whether the row existed.
expect((parseToolResult(await h.client.callTool({
name: 'remove_journey_trip', arguments: { journeyId: journey.id, tripId: trip.id },
})) as any).success).toBe(true);
expect((await h.client.callTool({
name: 'remove_journey_trip', arguments: { journeyId, tripId: trip.id },
})).isError).toBe(true);
});
});
it('create_journey_entry refuses a foreign journey', async () => {
const { user } = createUser(testDb);
const { journeyId } = foreignJourney();
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_journey_entry', arguments: { journeyId, entry_date: '2026-07-01' },
});
expect(result.isError).toBe(true);
});
});
it('update_journey_entry and delete_journey_entry refuse an unknown entry', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
expect((await h.client.callTool({
name: 'update_journey_entry', arguments: { entryId: 999999, title: 'X' },
})).isError).toBe(true);
expect((await h.client.callTool({
name: 'delete_journey_entry', arguments: { entryId: 999999 },
})).isError).toBe(true);
});
});
it('delete_journey_entry removes an owned entry', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
const entry = (parseToolResult(await h.client.callTool({
name: 'create_journey_entry', arguments: { journeyId: journey.id, entry_date: '2026-07-01' },
})) as any).entry;
const data = parseToolResult(await h.client.callTool({
name: 'delete_journey_entry', arguments: { entryId: entry.id },
})) as any;
expect(data.success).toBe(true);
});
});
it('reorder_journey_entries reorders, and rejects IDs from outside the journey', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
const a = (parseToolResult(await h.client.callTool({
name: 'create_journey_entry', arguments: { journeyId: journey.id, entry_date: '2026-07-01', title: 'A' },
})) as any).entry;
const b = (parseToolResult(await h.client.callTool({
name: 'create_journey_entry', arguments: { journeyId: journey.id, entry_date: '2026-07-02', title: 'B' },
})) as any).entry;
const reordered = parseToolResult(await h.client.callTool({
name: 'reorder_journey_entries', arguments: { journeyId: journey.id, orderedIds: [b.id, a.id] },
})) as any;
expect(reordered.success).toBe(true);
expect((await h.client.callTool({
name: 'reorder_journey_entries', arguments: { journeyId: journey.id, orderedIds: [999999] },
})).isError).toBe(true);
});
});
it('contributor tools add, re-role and remove; each refuses a foreign journey', async () => {
const { user } = createUser(testDb);
const { user: guest } = createUser(testDb);
const { journeyId } = foreignJourney();
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
expect((parseToolResult(await h.client.callTool({
name: 'add_journey_contributor', arguments: { journeyId: journey.id, targetUserId: guest.id, role: 'editor' },
})) as any).success).toBe(true);
expect((parseToolResult(await h.client.callTool({
name: 'update_journey_contributor_role', arguments: { journeyId: journey.id, targetUserId: guest.id, role: 'viewer' },
})) as any).success).toBe(true);
expect((parseToolResult(await h.client.callTool({
name: 'remove_journey_contributor', arguments: { journeyId: journey.id, targetUserId: guest.id },
})) as any).success).toBe(true);
for (const name of ['add_journey_contributor', 'update_journey_contributor_role']) {
expect((await h.client.callTool({
name, arguments: { journeyId, targetUserId: guest.id, role: 'editor' },
})).isError).toBe(true);
}
expect((await h.client.callTool({
name: 'remove_journey_contributor', arguments: { journeyId, targetUserId: guest.id },
})).isError).toBe(true);
});
});
it('update_journey_preferences refuses a foreign journey', async () => {
const { user } = createUser(testDb);
const { journeyId } = foreignJourney();
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'update_journey_preferences', arguments: { journeyId, hide_skeletons: true },
});
expect(result.isError).toBe(true);
});
});
});
describe('journey share-link tools', () => {
it('creates, reads and revokes the link', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
// No link yet — the tool answers with a null shareLink, not an error.
const empty = parseToolResult(await h.client.callTool({
name: 'get_journey_share_link', arguments: { journeyId: journey.id },
})) as any;
expect(empty.shareLink ?? null).toBeNull();
const created = parseToolResult(await h.client.callTool({
name: 'create_journey_share_link', arguments: { journeyId: journey.id },
})) as any;
expect(created.shareLink).toBeTruthy();
const read = parseToolResult(await h.client.callTool({
name: 'get_journey_share_link', arguments: { journeyId: journey.id },
})) as any;
expect(read.shareLink).toBeTruthy();
const revoked = parseToolResult(await h.client.callTool({
name: 'delete_journey_share_link', arguments: { journeyId: journey.id },
})) as any;
expect(revoked.success).toBe(true);
});
});
it('passes the share flags through, and an omitted flag keeps its value', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const journey = await seedJourney(h);
await h.client.callTool({
name: 'create_journey_share_link',
arguments: { journeyId: journey.id, share_gallery: false, newest_first: true },
});
// Calling it again without the flags must not re-publish the gallery.
await h.client.callTool({ name: 'create_journey_share_link', arguments: { journeyId: journey.id } });
const read = parseToolResult(await h.client.callTool({
name: 'get_journey_share_link', arguments: { journeyId: journey.id },
})) as any;
expect(read.shareLink.share_gallery).toBe(false);
expect(read.shareLink.newest_first).toBe(true);
expect(read.shareLink.share_timeline).toBe(true);
});
});
it('get_journey_share_link is owner-only, like create and delete', async () => {
const { user: owner } = createUser(testDb);
const { user: guest } = createUser(testDb);
let journeyId = 0;
await withHarness(owner.id, async (h) => {
const journey = await seedJourney(h);
journeyId = journey.id;
await h.client.callTool({ name: 'create_journey_share_link', arguments: { journeyId } });
});
testDb.prepare(
'INSERT INTO journey_contributors (journey_id, user_id, role, added_at) VALUES (?, ?, ?, ?)',
).run(journeyId, guest.id, 'viewer', Date.now());
await withHarness(guest.id, async (h) => {
// The token is the whole credential: a contributor must not be able to
// read out a link that keeps working after they are removed.
expect((await h.client.callTool({
name: 'get_journey_share_link', arguments: { journeyId },
})).isError).toBe(true);
});
});
it('every share tool refuses a foreign journey', async () => {
const { user } = createUser(testDb);
const { journeyId } = foreignJourney();
await withHarness(user.id, async (h) => {
for (const name of ['get_journey_share_link', 'create_journey_share_link', 'delete_journey_share_link']) {
expect((await h.client.callTool({ name, arguments: { journeyId } })).isError).toBe(true);
}
});
});
});
describe('demo mode', () => {
// The read tools are deliberately NOT demo-gated, matching the legacy
// registrar: only the writes and the share-link mutations refuse.
const WRITES: Array<[string, Record<string, unknown>]> = [
['create_journey', { title: 'X' }],
['update_journey', { journeyId: 1, title: 'X' }],
['delete_journey', { journeyId: 1 }],
['add_journey_trip', { journeyId: 1, tripId: 1 }],
['remove_journey_trip', { journeyId: 1, tripId: 1 }],
['create_journey_entry', { journeyId: 1, entry_date: '2026-07-01' }],
['update_journey_entry', { entryId: 1, title: 'X' }],
['delete_journey_entry', { entryId: 1 }],
['reorder_journey_entries', { journeyId: 1, orderedIds: [1] }],
['add_journey_contributor', { journeyId: 1, targetUserId: 2, role: 'editor' }],
['update_journey_contributor_role', { journeyId: 1, targetUserId: 2, role: 'viewer' }],
['remove_journey_contributor', { journeyId: 1, targetUserId: 2 }],
['update_journey_preferences', { journeyId: 1, hide_skeletons: true }],
['create_journey_share_link', { journeyId: 1 }],
['delete_journey_share_link', { journeyId: 1 }],
];
it.each(WRITES)('%s is blocked for a demo user', async (name, args) => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name, arguments: args });
expect(result.isError).toBe(true);
});
});
it('list_journeys still answers for a demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
await withHarness(user.id, async (h) => {
const data = parseToolResult(await h.client.callTool({ name: 'list_journeys', arguments: {} })) as any;
expect(Array.isArray(data.journeys)).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// Resources (first-time coverage, added when the four journey resources moved
// from src/mcp/resources.ts onto the nest-mcp registry — same URIs, names and
// payload shapes as the legacy registrar)
// ---------------------------------------------------------------------------
async function createJourney(h: McpHarness, title = 'Eurotrip'): Promise<any> {
return (parseToolResult(await h.client.callTool({
name: 'create_journey', arguments: { title },
})) as any).journey;
}
describe('Resource: trek://journeys', () => {
it('returns the journeys of the current user', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const journey = await createJourney(h);
const data = parseResourceResult(await h.client.readResource({ uri: 'trek://journeys' })) as any[];
expect(Array.isArray(data)).toBe(true);
expect(data.map((j) => j.id)).toContain(journey.id);
});
});
});
describe('Resource: trek://journeys/{journeyId}', () => {
it('returns the hydrated journey', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const journey = await createJourney(h);
const data = parseResourceResult(await h.client.readResource({ uri: `trek://journeys/${journey.id}` })) as any;
expect(data.title).toBe('Eurotrip');
expect(Array.isArray(data.entries)).toBe(true);
expect(Array.isArray(data.contributors)).toBe(true);
});
});
it('answers the legacy denial payload for a bad id and an inaccessible journey', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await withHarness(other.id, async (hOther) => {
const foreign = await createJourney(hOther, 'Private');
await withHarness(user.id, async (h) => {
for (const uri of ['trek://journeys/abc', `trek://journeys/${foreign.id}`]) {
const data = parseResourceResult(await h.client.readResource({ uri })) as any;
expect(data).toEqual({ error: 'Trip not found or access denied' });
}
});
});
});
});
describe('Resource: trek://journeys/{journeyId}/entries', () => {
it('returns the enriched entries', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const journey = await createJourney(h);
await h.client.callTool({
name: 'create_journey_entry',
arguments: { journeyId: journey.id, entry_date: '2026-07-01', title: 'Day 1', story: 'Arrived' },
});
const data = parseResourceResult(await h.client.readResource({ uri: `trek://journeys/${journey.id}/entries` })) as any[];
expect(data).toHaveLength(1);
expect(data[0].title).toBe('Day 1');
expect(Array.isArray(data[0].tags)).toBe(true);
});
});
});
describe('Resource: trek://journeys/{journeyId}/contributors', () => {
it('returns the contributors, with the legacy [] fallback shape', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const journey = await createJourney(h);
const data = parseResourceResult(await h.client.readResource({ uri: `trek://journeys/${journey.id}/contributors` })) as any[];
expect(Array.isArray(data)).toBe(true);
expect(data.map((c) => c.user_id ?? c.id)).toContain(user.id);
});
});
});
describe('Journey resource gating', () => {
it('does not register the resources when the journey addon is off', async () => {
const { user } = createUser(testDb);
setAddonEnabled(testDb, ADDON_IDS.JOURNEY, false);
await withHarness(user.id, async (h) => {
await expect(h.client.readResource({ uri: 'trek://journeys' })).rejects.toThrow();
});
});
it('does not register the resources without the journey:read scope', async () => {
const { user } = createUser(testDb);
const h = await createMcpHarness({ userId: user.id, scopes: ['trips:read'] });
try {
await expect(h.client.readResource({ uri: 'trek://journeys' })).rejects.toThrow();
} finally {
await h.cleanup();
}
});
});
@@ -0,0 +1,299 @@
/**
* Unit tests for MCP leg-mode tools: set_leg_transport_mode,
* set_day_default_transport_mode.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
isOwner: (tripId: any, userId: number) =>
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, createDayAssignment } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
broadcastMock.mockClear();
delete process.env.DEMO_MODE;
});
afterAll(() => {
testDb.close();
});
async function withHarness(userId: number, fn: (h: McpHarness) => Promise<void>) {
const h = await createMcpHarness({ userId, withResources: false });
try { await fn(h); } finally { await h.cleanup(); }
}
// ---------------------------------------------------------------------------
// set_leg_transport_mode
// ---------------------------------------------------------------------------
describe('Tool: set_leg_transport_mode', () => {
it('sets the outgoing leg mode (default direction)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
// Seed the incoming column so the assertion below proves it survives; the factory
// leaves it NULL, so without this it would pass whether or not the tool touched it.
testDb.prepare('UPDATE day_assignments SET incoming_leg_transport_mode = ? WHERE id = ?').run('walking', assignment.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_leg_transport_mode',
arguments: { tripId: trip.id, assignmentId: assignment.id, transport_mode: 'cycling' },
});
const data = parseToolResult(result) as any;
expect(data.assignment.leg_transport_mode).toBe('cycling');
expect(data.assignment.incoming_leg_transport_mode).toBe('walking'); // outgoing must not touch incoming (panel item 4)
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'assignment:updated', expect.any(Object));
});
});
it('sets the incoming leg mode without clobbering the outgoing column (column independence)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
// Seed the outgoing column so we prove incoming does NOT touch it (panel item 4).
testDb.prepare('UPDATE day_assignments SET leg_transport_mode = ? WHERE id = ?').run('driving', assignment.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_leg_transport_mode',
arguments: { tripId: trip.id, assignmentId: assignment.id, transport_mode: 'walking', direction: 'incoming' },
});
const data = parseToolResult(result) as any;
expect(data.assignment.incoming_leg_transport_mode).toBe('walking');
expect(data.assignment.leg_transport_mode).toBe('driving'); // outgoing untouched
});
});
it('rejects an assignment belonging to another trip (cross-trip join)', async () => {
// Proves the `AND d.trip_id = ?` join in getAssignmentForTrip; a 99999 id cannot.
const { user } = createUser(testDb);
const trip1 = createTrip(testDb, user.id);
const trip2 = createTrip(testDb, user.id);
const day2 = createDay(testDb, trip2.id);
const place2 = createPlace(testDb, trip2.id);
const assignment2 = createDayAssignment(testDb, day2.id, place2.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_leg_transport_mode',
arguments: { tripId: trip1.id, assignmentId: assignment2.id, transport_mode: 'walking' },
});
expect(result.isError).toBe(true);
});
});
it('clears the leg mode with null (inherit day default)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
testDb.prepare('UPDATE day_assignments SET leg_transport_mode = ? WHERE id = ?').run('cycling', assignment.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_leg_transport_mode',
arguments: { tripId: trip.id, assignmentId: assignment.id, transport_mode: null },
});
const data = parseToolResult(result) as any;
expect(data.assignment.leg_transport_mode).toBeNull();
});
});
it('returns error when assignment not found', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_leg_transport_mode',
arguments: { tripId: trip.id, assignmentId: 99999, transport_mode: 'walking' },
});
expect(result.isError).toBe(true);
});
});
it('returns access denied for non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_leg_transport_mode',
arguments: { tripId: trip.id, assignmentId: assignment.id, transport_mode: 'walking' },
});
expect(result.isError).toBe(true);
});
});
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_leg_transport_mode',
arguments: { tripId: trip.id, assignmentId: assignment.id, transport_mode: 'walking' },
});
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// set_day_default_transport_mode
// ---------------------------------------------------------------------------
describe('Tool: set_day_default_transport_mode', () => {
it('sets the day default transport mode', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_day_default_transport_mode',
arguments: { tripId: trip.id, dayId: day.id, transport_mode: 'driving' },
});
const data = parseToolResult(result) as any;
expect(data.day.default_transport_mode).toBe('driving');
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'day:updated', expect.any(Object));
});
});
it('clears the day default with null', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
testDb.prepare('UPDATE days SET default_transport_mode = ? WHERE id = ?').run('driving', day.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_day_default_transport_mode',
arguments: { tripId: trip.id, dayId: day.id, transport_mode: null },
});
const data = parseToolResult(result) as any;
expect(data.day.default_transport_mode).toBeNull();
});
});
it('returns the day with its populated assignments array', async () => {
// setDefaultTransportMode returns { ...day, assignments }; exercise the non-empty case (panel item 4).
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_day_default_transport_mode',
arguments: { tripId: trip.id, dayId: day.id, transport_mode: 'driving' },
});
const data = parseToolResult(result) as any;
expect(Array.isArray(data.day.assignments)).toBe(true);
expect(data.day.assignments).toHaveLength(1);
expect(data.day.assignments[0].id).toBe(assignment.id);
});
});
it('rejects a day belonging to another trip (cross-trip join)', async () => {
const { user } = createUser(testDb);
const trip1 = createTrip(testDb, user.id);
const trip2 = createTrip(testDb, user.id);
const day2 = createDay(testDb, trip2.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_day_default_transport_mode',
arguments: { tripId: trip1.id, dayId: day2.id, transport_mode: 'walking' },
});
expect(result.isError).toBe(true);
});
});
it('returns error when day not found', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_day_default_transport_mode',
arguments: { tripId: trip.id, dayId: 99999, transport_mode: 'walking' },
});
expect(result.isError).toBe(true);
});
});
it('returns access denied for non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
const day = createDay(testDb, trip.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_day_default_transport_mode',
arguments: { tripId: trip.id, dayId: day.id, transport_mode: 'walking' },
});
expect(result.isError).toBe(true);
});
});
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'set_day_default_transport_mode',
arguments: { tripId: trip.id, dayId: day.id, transport_mode: 'walking' },
});
expect(result.isError).toBe(true);
});
});
});
+116 -3
View File
@@ -1,6 +1,9 @@
/**
* Unit tests for MCP note tools: create_day_note, update_day_note, delete_day_note,
* create_collab_note, update_collab_note, delete_collab_note.
* Unit tests for MCP note tools: create_day_note, update_day_note, delete_day_note
* (DayNotesMcp, DI-discovered — attached via the nest-mcp registry inside
* registerTools, so every harness here keeps withTools on) and
* create_collab_note, update_collab_note, delete_collab_note (CollabMcp,
* DI-discovered via the same registry).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -44,7 +47,7 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createDayNote, createCollabNote } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
@@ -258,6 +261,84 @@ describe('Tool: delete_day_note', () => {
});
});
// ---------------------------------------------------------------------------
// Scope gating (trips write, registration-time — the legacy registerDayTools
// whole-registrar `canWrite(scopes, 'trips')` early return, now the
// declarative access marker on every DayNotesMcp tool)
// ---------------------------------------------------------------------------
describe('Day-note tools — scope gating', () => {
const WRITE_TOOLS = ['create_day_note', 'update_day_note', 'delete_day_note'];
async function listToolNames(userId: number, scopes: string[] | null): Promise<string[]> {
const h = await createMcpHarness({ userId, withResources: false, scopes });
try {
return (await h.client.listTools()).tools.map((t) => t.name);
} finally {
await h.cleanup();
}
}
it('registers all three tools with null scopes (full access)', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, null);
for (const tool of WRITE_TOOLS) expect(names).toContain(tool);
});
it('registers no day-note tools with trips:read only (all three are writes)', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['trips:read']);
for (const tool of WRITE_TOOLS) expect(names).not.toContain(tool);
});
it('registers no day-note tools for an unrelated scope', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['budget:read']);
for (const tool of WRITE_TOOLS) expect(names).not.toContain(tool);
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/days/{dayId}/notes resource (moved from the legacy
// registerResources to DayNotesMcp)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/days/{dayId}/notes', () => {
it('returns the day notes ordered by sort_order', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
createDayNote(testDb, day.id, trip.id, { text: 'Second', sort_order: 5 });
createDayNote(testDb, day.id, trip.id, { text: 'First', sort_order: 1 });
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/days/${day.id}/notes` });
const notes = parseResourceResult(result) as { text: string }[];
expect(notes).toHaveLength(2);
expect(notes[0].text).toBe('First');
expect(notes[1].text).toBe('Second');
});
});
it('returns the access-denied payload for a non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
const day = createDay(testDb, trip.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/days/${day.id}/notes` });
expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
});
});
it('returns the access-denied payload for a malformed id', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: 'trek://trips/1/days/not-a-number/notes' });
expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
});
});
});
// ---------------------------------------------------------------------------
// create_collab_note
// ---------------------------------------------------------------------------
@@ -429,3 +510,35 @@ describe('Tool: delete_collab_note', () => {
});
});
});
// Moved from resources.test.ts with the collab migration: the resource now
// registers via the nest-mcp registry inside registerTools (CollabMcp
// @ResourceTemplate), which resources.test.ts's withTools: false harness
// never attaches.
describe('Resource: trek://trips/{tripId}/collab-notes', () => {
it('returns collab notes with username', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createCollabNote(testDb, trip.id, user.id, { title: 'Ideas' });
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/collab-notes` });
const notes = parseResourceResult(result) as any[];
expect(notes).toHaveLength(1);
expect(notes[0].title).toBe('Ideas');
expect(notes[0].username).toBeTruthy();
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/collab-notes` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
@@ -1,9 +1,13 @@
/**
* Unit tests for MCP notification tools:
* Unit tests for the notifications MCP surface (NotificationsMcp,
* DI-discovered since the notifications fold):
* list_notifications, get_unread_notification_count, mark_notification_read,
* mark_notification_unread, mark_all_notifications_read, delete_notification,
* delete_all_notifications.
* mark_notification_unread, mark_all_notifications_read.
* Also covers the resource trek://notifications/in-app.
*
* All of it attaches via the nest-mcp registry inside registerTools, so every
* harness here keeps withTools on (the resource is NOT registered by the
* legacy registerResources fan-out anymore).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -80,7 +84,9 @@ async function withHarness(userId: number, fn: (h: McpHarness) => Promise<void>)
}
async function withResourceHarness(userId: number, fn: (h: McpHarness) => Promise<void>) {
const h = await createMcpHarness({ userId, withTools: false, withResources: true });
// The in-app resource attaches via the nest-mcp registry (withTools), not
// the legacy registerResources fan-out.
const h = await createMcpHarness({ userId, withTools: true, withResources: false });
try { await fn(h); } finally { await h.cleanup(); }
}
@@ -1,9 +1,10 @@
/**
* Unit tests for MCP packing advanced tools:
* Unit tests for the advanced packing MCP tools (PackingMcp, DI-discovered):
* reorder_packing_items, list_packing_bags, create_packing_bag, update_packing_bag,
* delete_packing_bag, set_bag_members, get_packing_category_assignees,
* set_packing_category_assignees, apply_packing_template, save_packing_template,
* bulk_import_packing.
* bulk_import_packing. The basic item tools + scope/addon gating + resources
* live in tools-packing.test.ts.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -234,7 +235,8 @@ describe('Tool: delete_packing_bag', () => {
});
const data = parseToolResult(result) as any;
expect(data.success).toBe(true);
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'packing:bag-deleted', expect.any(Object));
// { bagId } — aligned with the REST route and the plugin host.
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'packing:bag-deleted', expect.objectContaining({ bagId }));
expect(testDb.prepare('SELECT id FROM packing_bags WHERE id = ?').get(bagId)).toBeUndefined();
});
});
+264 -3
View File
@@ -1,6 +1,14 @@
/**
* Unit tests for MCP packing tools: create_packing_item, update_packing_item,
* toggle_packing_item, delete_packing_item.
* Unit tests for the packing MCP surface (PackingMcp, DI-discovered):
* create_packing_item, update_packing_item, toggle_packing_item,
* delete_packing_item, plus the registration-time scope/addon gating and the
* trek://trips/{tripId}/packing + .../packing/bags resources (moved from the
* legacy registerResources — see resources.test.ts). The advanced tools live
* in tools-packing-advanced.test.ts.
*
* All of it attaches via the nest-mcp registry inside registerTools, so every
* harness here keeps withTools on (the resources are NOT registered by the
* legacy registerResources fan-out anymore).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -37,7 +45,8 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createPackingItem } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
import { ADDON_IDS } from '../../../src/addons';
beforeAll(() => {
createTables(testDb);
@@ -285,3 +294,255 @@ describe('Tool: delete_packing_item', () => {
});
});
});
// ---------------------------------------------------------------------------
// Scope gating (packing read/write, registration-time)
// ---------------------------------------------------------------------------
describe('Packing tools — scope gating', () => {
const READ_TOOLS = ['list_packing_bags', 'get_packing_category_assignees', 'list_packing_templates'];
const WRITE_TOOLS = [
'create_packing_item', 'toggle_packing_item', 'delete_packing_item', 'update_packing_item',
'reorder_packing_items', 'create_packing_bag', 'update_packing_bag', 'delete_packing_bag',
'set_bag_members', 'set_packing_category_assignees', 'apply_packing_template',
'save_packing_template', 'delete_packing_template', 'bulk_import_packing',
];
async function listToolNames(userId: number, scopes: string[] | null): Promise<string[]> {
const h = await createMcpHarness({ userId, withResources: false, scopes });
try {
return (await h.client.listTools()).tools.map((t) => t.name);
} finally {
await h.cleanup();
}
}
it('registers all seventeen tools with null scopes (full access)', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, null);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).toContain(tool);
});
it('registers only the read tools with packing:read', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['packing:read']);
for (const tool of READ_TOOLS) expect(names).toContain(tool);
for (const tool of WRITE_TOOLS) expect(names).not.toContain(tool);
});
it('registers no packing tools for an unrelated scope', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['budget:read']);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).not.toContain(tool);
});
});
// ---------------------------------------------------------------------------
// Addon gating (packing addon, the legacy whole-registrar early return —
// now the `when` predicate on every PackingMcp entry)
// ---------------------------------------------------------------------------
describe('Packing tools — packing addon gating', () => {
it('registers nothing (tools or resources) when the packing addon is disabled', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('UPDATE addons SET enabled = 0 WHERE id = ?').run(ADDON_IDS.PACKING);
try {
await withHarness(user.id, async (h) => {
const names = (await h.client.listTools()).tools.map((t) => t.name);
expect(names).not.toContain('create_packing_item');
expect(names).not.toContain('list_packing_bags');
await expect(h.client.readResource({ uri: `trek://trips/${trip.id}/packing` })).rejects.toThrow();
await expect(h.client.readResource({ uri: `trek://trips/${trip.id}/packing/bags` })).rejects.toThrow();
});
} finally {
testDb.prepare('UPDATE addons SET enabled = 1 WHERE id = ?').run(ADDON_IDS.PACKING);
}
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/packing resource (moved from the legacy registerResources)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/packing', () => {
it('returns packing items for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPackingItem(testDb, trip.id, { name: 'Passport' });
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/packing` });
const items = parseResourceResult(result) as { name: string }[];
expect(items).toHaveLength(1);
expect(items[0].name).toBe('Passport');
});
});
it('hides another member\'s private items from the requesting user (#858)', async () => {
const { user } = createUser(testDb);
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, sort_order, is_private, owner_id) VALUES (?, ?, 0, 0, 1, ?)')
.run(trip.id, 'Secret gift', owner.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/packing` });
expect(parseResourceResult(result)).toEqual([]);
});
});
it('returns the access-denied payload for a non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/packing` });
expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
});
});
it('returns the access-denied payload for a malformed trip id', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: 'trek://trips/not-a-number/packing' });
expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
});
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/packing/bags resource (moved from the legacy registerResources)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/packing/bags', () => {
it('returns the bags with their members', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const bagId = Number(testDb.prepare('INSERT INTO packing_bags (trip_id, name) VALUES (?, ?)').run(trip.id, 'Carry-On').lastInsertRowid);
testDb.prepare('INSERT INTO packing_bag_members (bag_id, user_id) VALUES (?, ?)').run(bagId, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/packing/bags` });
const bags = parseResourceResult(result) as { name: string; members: { user_id: number }[] }[];
expect(bags).toHaveLength(1);
expect(bags[0].name).toBe('Carry-On');
expect(bags[0].members.map((m) => m.user_id)).toEqual([user.id]);
});
});
it('returns the access-denied payload for a non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/packing/bags` });
expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
});
});
});
// ---------------------------------------------------------------------------
// Private items over MCP (#1976)
// ---------------------------------------------------------------------------
/**
* A restricted packing item, changed through a tool, must reach only the people
* who may see it.
*
* The REST and RPC surfaces have scoped this since #858 — they go through
* emitToViewers, which hands the event to the owner and the recipients. The MCP
* tools broadcast to the whole trip room instead, so asking an assistant to
* tick off something on your own list pushed that row to every other member.
*
* It did not stop at the wire either: the client stores what arrives
* (remoteEventHandler -> putPackingItem -> bulkPut) with no owner check, and the
* offline read path returns every cached row for the trip. So the leaked item
* stayed in the other member's IndexedDB and rendered whenever their next read
* fell back to the cache.
*
* These cases pin the wire, which is where it has to be fixed: a room-wide call
* still takes three arguments, so nothing about a shared item changes.
*/
describe('a restricted packing item over MCP', () => {
const makePrivate = (itemId: number, ownerId: number) =>
testDb.prepare('UPDATE packing_items SET is_private = 1, owner_id = ? WHERE id = ?').run(ownerId, itemId);
it('is ticked off for its owner alone, not for the whole trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createPackingItem(testDb, trip.id);
makePrivate(item.id, user.id);
await withHarness(user.id, async (h) => {
await h.client.callTool({
name: 'toggle_packing_item',
arguments: { tripId: trip.id, itemId: item.id, checked: true },
});
});
// The assertion that would have caught the leak: a fifth argument naming
// the only user this may reach.
expect(broadcastMock).toHaveBeenCalledWith(
trip.id, 'packing:updated', expect.any(Object), undefined, user.id,
);
expect(broadcastMock).not.toHaveBeenCalledWith(trip.id, 'packing:updated', expect.any(Object));
});
it('is renamed for its owner alone', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createPackingItem(testDb, trip.id);
makePrivate(item.id, user.id);
await withHarness(user.id, async (h) => {
await h.client.callTool({
name: 'update_packing_item',
arguments: { tripId: trip.id, itemId: item.id, name: 'Insulin pens' },
});
});
expect(broadcastMock).toHaveBeenCalledWith(
trip.id, 'packing:updated', expect.any(Object), undefined, user.id,
);
expect(broadcastMock).not.toHaveBeenCalledWith(trip.id, 'packing:updated', expect.any(Object));
});
/*
* The delete carries only an id, which looks harmless — but it names an id
* the other members were never told about, and it removes a row from their
* store that a leak had put there. Scoped the same way, from the row the
* delete hands back.
*/
it('is deleted for its owner alone', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createPackingItem(testDb, trip.id);
makePrivate(item.id, user.id);
await withHarness(user.id, async (h) => {
await h.client.callTool({
name: 'delete_packing_item',
arguments: { tripId: trip.id, itemId: item.id },
});
});
expect(broadcastMock).toHaveBeenCalledWith(
trip.id, 'packing:deleted', expect.any(Object), undefined, user.id,
);
expect(broadcastMock).not.toHaveBeenCalledWith(trip.id, 'packing:deleted', expect.any(Object));
});
it('still tells the whole room about a shared one, unchanged', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createPackingItem(testDb, trip.id);
await withHarness(user.id, async (h) => {
await h.client.callTool({
name: 'toggle_packing_item',
arguments: { tripId: trip.id, itemId: item.id, checked: true },
});
});
// Three arguments exactly, which is what every other packing case asserts.
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'packing:updated', expect.any(Object));
});
});
+336 -24
View File
@@ -1,5 +1,11 @@
/**
* Unit tests for MCP place tools: create_place, update_place, delete_place, list_categories, search_place.
* Unit tests for MCP place tools: create_place, update_place, delete_place, search_place.
* (list_categories moved to tools-categories.test.ts with the CategoriesMcp migration.)
*
* Since the place DI fold these run through the decorator-driven PlacesMcp in
* src/nest/places/places.mcp.ts — the harness attaches it via the hand-wired
* registry in tests/helpers/mcp-test-controllers.ts, so the assertions below
* exercise the @Tool/@ResourceTemplate path instead of the deleted registrar.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -38,13 +44,17 @@ const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
const { searchPlacesMock } = vi.hoisted(() => ({ searchPlacesMock: vi.fn() }));
vi.mock('../../../src/services/mapsService', () => ({ searchPlaces: searchPlacesMock }));
// PlacesMcp and PlacesService both inject MapsService (search_place and the
// import enrichment), so the geo calls are stubbed on the prototype — see
// beforeEach — rather than through a module mock.
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createPlace, createDay, createDayAssignment, createJourney } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
import { MapsService } from '../../../src/nest/maps/maps.service';
import { PlacesService } from '../../../src/nest/places/places.service';
/** Link a journey to a trip so journey-skeleton sync has a target. */
function linkJourney(journeyId: number, tripId: number) {
@@ -63,6 +73,7 @@ beforeEach(() => {
resetTestDb(testDb);
broadcastMock.mockClear();
searchPlacesMock.mockClear();
vi.spyOn(MapsService.prototype, 'searchPlaces').mockImplementation(searchPlacesMock as never);
delete process.env.DEMO_MODE;
});
@@ -280,6 +291,21 @@ describe('Tool: delete_place', () => {
});
});
it('takes the linked expense with it and announces that too (#1298)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id);
const itemId = Number(testDb
.prepare("INSERT INTO budget_items (trip_id, name, total_price, place_id) VALUES (?, 'Tickets', 34, ?)")
.run(trip.id, place.id).lastInsertRowid);
await withHarness(user.id, async (h) => {
await h.client.callTool({ name: 'delete_place', arguments: { tripId: trip.id, placeId: place.id } });
expect(testDb.prepare('SELECT id FROM budget_items WHERE id = ?').get(itemId)).toBeUndefined();
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'budget:deleted', expect.objectContaining({ itemId }));
});
});
it('broadcasts place:deleted event', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
@@ -356,27 +382,6 @@ describe('Tool: create_and_assign_place', () => {
});
});
// ---------------------------------------------------------------------------
// list_categories
// ---------------------------------------------------------------------------
describe('Tool: list_categories', () => {
it('returns all categories with id, name, color, icon', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'list_categories', arguments: {} });
const data = parseToolResult(result) as any;
expect(data.categories).toBeDefined();
expect(data.categories.length).toBeGreaterThan(0);
const cat = data.categories[0];
expect(cat).toHaveProperty('id');
expect(cat).toHaveProperty('name');
expect(cat).toHaveProperty('color');
expect(cat).toHaveProperty('icon');
});
});
});
// ---------------------------------------------------------------------------
// search_place
// ---------------------------------------------------------------------------
@@ -525,3 +530,310 @@ describe('Tool: list_places', () => {
});
});
});
// ---------------------------------------------------------------------------
// rate_place (#1435)
// ---------------------------------------------------------------------------
describe('Tool: rate_place', () => {
it('stores the acting user\'s vote and reports the aggregate', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Rated' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'rate_place', arguments: { tripId: trip.id, placeId: place.id, rating: 4 } });
const data = parseToolResult(result) as any;
expect(data.place.id).toBe(place.id);
const rows = testDb.prepare('SELECT user_id, rating FROM place_ratings WHERE place_id = ?').all(place.id);
expect(rows).toEqual([{ user_id: user.id, rating: 4 }]);
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'place:updated', expect.any(Object));
});
});
it('an omitted rating clears the vote', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Rated' });
await withHarness(user.id, async (h) => {
await h.client.callTool({ name: 'rate_place', arguments: { tripId: trip.id, placeId: place.id, rating: 5 } });
const result = await h.client.callTool({ name: 'rate_place', arguments: { tripId: trip.id, placeId: place.id } });
const data = parseToolResult(result) as any;
expect(data.place.id).toBe(place.id);
const rows = testDb.prepare('SELECT COUNT(*) AS n FROM place_ratings WHERE place_id = ?').get(place.id) as { n: number };
expect(rows.n).toBe(0);
});
});
it('returns error for a place outside the trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const place = createPlace(testDb, other.id, { name: 'Elsewhere' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'rate_place', arguments: { tripId: trip.id, placeId: place.id, rating: 3 } });
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// bulk_delete_places
// ---------------------------------------------------------------------------
describe('Tool: bulk_delete_places', () => {
it('deletes the trip-scoped ids, skips foreign ones and broadcasts each', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const a = createPlace(testDb, trip.id, { name: 'A' });
const b = createPlace(testDb, trip.id, { name: 'B' });
const foreign = createPlace(testDb, other.id, { name: 'Foreign' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'bulk_delete_places',
arguments: { tripId: trip.id, placeIds: [a.id, b.id, foreign.id] },
});
const data = parseToolResult(result) as any;
expect(data.count).toBe(2);
expect(data.deleted.sort()).toEqual([a.id, b.id].sort());
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'place:deleted', { placeId: a.id, _source: 'mcp' });
// The other trip's place survives.
expect(testDb.prepare('SELECT id FROM places WHERE id = ?').get(foreign.id)).toBeTruthy();
});
});
it('returns access denied for non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
const place = createPlace(testDb, trip.id, { name: 'Theirs' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'bulk_delete_places', arguments: { tripId: trip.id, placeIds: [place.id] } });
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/places resource (moved from resources.test.ts)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/places', () => {
it('returns all places for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
createPlace(testDb, trip.id, { name: 'Louvre' });
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/places` });
const places = parseResourceResult(result) as any[];
expect(places).toHaveLength(2);
const names = places.map((p) => p.name);
expect(names).toContain('Eiffel Tower');
expect(names).toContain('Louvre');
});
});
// The ?assignment= filter the description advertises is read off
// uri.searchParams inside the handler, but the SDK's template matcher rejects
// a URI carrying a query string before the handler runs — same as the legacy
// resource this was moved from, so it stays untested here.
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/places` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
// ---------------------------------------------------------------------------
// import_places_from_url
// ---------------------------------------------------------------------------
describe('Tool: import_places_from_url', () => {
it('imports a google list, broadcasts each place and reports the count', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const spy = vi.spyOn(PlacesService.prototype, 'importGoogleList').mockResolvedValue({
places: [{ id: 1, name: 'A' }, { id: 2, name: 'B' }] as never,
listName: 'Weekend',
skipped: 3,
});
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'import_places_from_url',
arguments: { tripId: trip.id, url: 'https://maps.app.goo.gl/x', source: 'google-list' },
});
const data = parseToolResult(result) as any;
expect(data).toMatchObject({ count: 2, listName: 'Weekend', skipped: 3 });
expect(spy).toHaveBeenCalledWith(String(trip.id), 'https://maps.app.goo.gl/x');
expect(broadcastMock).toHaveBeenCalledTimes(2);
});
spy.mockRestore();
});
it('surfaces the naver importer\'s { error, status } as a tool error', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const spy = vi.spyOn(PlacesService.prototype, 'importNaverList').mockResolvedValue({ error: 'List is empty or could not be read', status: 400 });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'import_places_from_url',
arguments: { tripId: trip.id, url: 'https://naver.me/x', source: 'naver-list' },
});
expect(result.isError).toBe(true);
expect((result.content as { text: string }[])[0].text).toBe('List is empty or could not be read');
});
spy.mockRestore();
});
it('returns access denied for non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'import_places_from_url',
arguments: { tripId: trip.id, url: 'https://maps.app.goo.gl/x', source: 'google-list' },
});
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// create_and_assign_place failure path
// ---------------------------------------------------------------------------
describe('Tool: create_and_assign_place (failure paths)', () => {
it('reports a missing day without writing the place', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_and_assign_place',
arguments: { tripId: trip.id, dayId: 99999, name: 'Nowhere' },
});
expect(result.isError).toBe(true);
expect((result.content as { text: string }[])[0].text).toBe('Day not found.');
expect(testDb.prepare('SELECT COUNT(*) AS n FROM places WHERE trip_id = ?').get(trip.id)).toEqual({ n: 0 });
});
});
it('rolls the transaction back and reports failure when the place write throws', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const spy = vi.spyOn(PlacesService.prototype, 'create').mockImplementation(() => { throw new Error('db exploded'); });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_and_assign_place',
arguments: { tripId: trip.id, dayId: day.id, name: 'Doomed' },
});
expect(result.isError).toBe(true);
expect((result.content as { text: string }[])[0].text).toBe('Failed to create place and assignment.');
expect(testDb.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE day_id = ?').get(day.id)).toEqual({ n: 0 });
});
spy.mockRestore();
});
});
// ---------------------------------------------------------------------------
// Journey-hook scoping + ordering on the delete paths (#1745)
// ---------------------------------------------------------------------------
/** Materialise a skeleton entry for an assigned place (same shape the sync writes). */
function seedSkeleton(journeyId: number, tripId: number, placeId: number, userId: number, name: string) {
testDb.prepare(
`INSERT INTO journey_entries (journey_id, source_trip_id, source_place_id, author_id, type, title, entry_date, sort_order, created_at, updated_at)
VALUES (?, ?, ?, ?, 'skeleton', ?, ?, 0, ?, ?)`,
).run(journeyId, tripId, placeId, userId, name, '2026-05-01', Date.now(), Date.now());
}
describe('journey hooks on the MCP delete paths', () => {
it("delete_place leaves a foreign trip's journey skeleton alone", async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const journey = createJourney(testDb, user.id);
linkJourney(journey.id, other.id);
const foreign = createPlace(testDb, other.id, { name: 'Theirs' });
const day = createDay(testDb, other.id);
createDayAssignment(testDb, day.id, foreign.id);
seedSkeleton(journey.id, other.id, foreign.id, user.id, 'Theirs');
expect(skeletonFor(journey.id, foreign.id)).toBeDefined();
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'delete_place', arguments: { tripId: trip.id, placeId: foreign.id } });
expect(result.isError).toBe(true);
});
// The other trip's skeleton entry still points at its place, and the row lives.
expect(skeletonFor(journey.id, foreign.id)).toBeDefined();
expect(testDb.prepare('SELECT id FROM places WHERE id = ?').get(foreign.id)).toBeDefined();
});
// Without the ordering fix the hook ran AFTER the DELETE, by which point
// journey_entries.source_place_id was already NULL (ON DELETE SET NULL) — so
// the entry survived as an orphan instead of being removed. Asserting on the
// entry count, not on source_place_id, is what tells the two apart.
it('bulk_delete_places detaches the skeletons before the rows go', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const journey = createJourney(testDb, user.id);
linkJourney(journey.id, trip.id);
const place = createPlace(testDb, trip.id, { name: 'Doomed' });
const day = createDay(testDb, trip.id);
createDayAssignment(testDb, day.id, place.id);
seedSkeleton(journey.id, trip.id, place.id, user.id, 'Doomed');
expect(skeletonFor(journey.id, place.id)).toBeDefined();
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'bulk_delete_places', arguments: { tripId: trip.id, placeIds: [place.id] } });
expect((parseToolResult(result) as any).count).toBe(1);
});
// The hook ran while the row still existed, so the entry is gone — not
// lingering with a NULL source_place_id.
expect(skeletonFor(journey.id, place.id)).toBeUndefined();
expect(testDb.prepare('SELECT COUNT(*) AS n FROM journey_entries WHERE journey_id = ?').get(journey.id)).toEqual({ n: 0 });
});
// The MCP bulk path already scoped correctly (it looped over removeMany's
// trip-scoped result), so this is a guard against the scoping regressing when
// the hook moved ahead of the delete — not a fix for a live bug.
it('bulk_delete_places leaves a foreign trip\'s skeleton alone', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const journey = createJourney(testDb, user.id);
linkJourney(journey.id, other.id);
const foreign = createPlace(testDb, other.id, { name: 'Theirs' });
const day = createDay(testDb, other.id);
createDayAssignment(testDb, day.id, foreign.id);
seedSkeleton(journey.id, other.id, foreign.id, user.id, 'Theirs');
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'bulk_delete_places', arguments: { tripId: trip.id, placeIds: [foreign.id] } });
expect((parseToolResult(result) as any).count).toBe(0);
});
expect(skeletonFor(journey.id, foreign.id)).toBeDefined();
});
});
+80 -8
View File
@@ -42,23 +42,92 @@ const { isAddonEnabledMock } = vi.hoisted(() => {
const isAddonEnabledMock = vi.fn().mockReturnValue(true);
return { isAddonEnabledMock };
});
vi.mock('../../../src/services/adminService', () => ({
// Was a module mock over addons.bridge. The `when:` gates read the controller's
// injected AddonsService now, so the toggle goes in through the constructor —
// which is the point of the change: the dependency is in the signature instead
// of behind an import path.
const addonsStub = {
isAddonEnabled: isAddonEnabledMock,
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
getCollabFeatures: () => ({ chat: true, notes: true, polls: true, whatsnext: true }),
} as unknown as AddonsService;
const { mockGetTripSummary } = vi.hoisted(() => ({
mockGetTripSummary: vi.fn(),
}));
vi.mock('../../../src/services/tripService', () => ({
getTripSummary: mockGetTripSummary,
}));
// The prompts read the summary through the injected read model (readModelStub
// below wraps the same controllable mock) — trips.bridge is deleted.
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, addTripMember, createPackingItem, createBudgetItem } from '../../helpers/factories';
import { registerMcpPrompts } from '../../../src/mcp/tools/prompts';
import { createTestRegistry } from '../../../src/nest-mcp';
import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../../../src/mcp/nest-mcp-policy';
import { TripsMcp } from '../../../src/nest/trips/trips.mcp';
import { TripPromptsMcp } from '../../../src/nest/trips/trip-prompts.mcp';
import { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import { PackingMcp } from '../../../src/nest/packing/packing.mcp';
import { PackingService } from '../../../src/nest/packing/packing.service';
import { BudgetMcp } from '../../../src/nest/budget/budget.mcp';
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 { DatabaseService } from '../../../src/nest/database/database.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';
// 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
// getTripSummary is the same controllable mock the legacy path used.
const tripsStub = {
canAccessTrip: (tripId: number, userId: number) => dbMock.canAccessTrip(tripId, userId),
} as unknown as TripsService;
// getTripSummary moved to TripReadModelService with the trip split; the mock is
// the same controllable one, one constructor slot further along.
const readModelStub = {
getTripSummary: (tripId: number, viewerUserId?: number) => mockGetTripSummary(tripId, viewerUserId),
} as never;
const promptGuards = new McpToolGuardsService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb)), new RealtimeService());
const tripsMcp = new TripsMcp(
tripsStub,
{ listItems: () => [] } as unknown as TodoService,
{ listPolls: () => [], countMessages: () => 0 } as unknown as CollabService,
undefined as never,
undefined as never,
undefined as never,
readModelStub,
addonsStub,
promptGuards,
);
// 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.
const promptDbs = () => new DatabaseService(testDb);
const authStub = { isDemoUser: () => false } as unknown as AuthService;
const promptPackingService = new PackingService(promptDbs(), new PermissionsService(promptDbs()), new RealtimeService(), notificationsStub());
const packingMcp = new PackingMcp(promptPackingService, authStub, addonsStub, promptGuards);
const budgetMcp = new BudgetMcp(
new BudgetService(promptDbs(), new PermissionsService(promptDbs()), new ExchangeRatesService(), new RealtimeService()),
new ExchangeRatesService(),
promptDbs(),
new RuntimeEnvService(),
new TripMembershipService(promptDbs()),
addonsStub,
promptGuards,
);
// The packing-list / budget-overview prompts live here since the trips.bridge
// fold; the summary rides the same readModelStub the trip-summary prompt uses.
const tripPromptsMcp = new TripPromptsMcp(tripsStub, readModelStub, promptPackingService, addonsStub);
const authMcp = new AuthMcp();
beforeAll(() => {
createTables(testDb);
@@ -109,7 +178,10 @@ afterAll(() => {
/** Build a fresh McpServer with prompts registered for the given userId. */
function buildServer(userId: number, opts: { isStaticToken?: boolean } = {}): McpServer {
const server = new McpServer({ name: 'trek-test', version: '1.0.0' });
registerMcpPrompts(server, userId, opts.isStaticToken ?? false);
// Every prompt is DI-discovered now; attach them the way registerTools does in
// production, including the isStaticToken flag the notice's `when` gate reads.
createTestRegistry([tripsMcp, tripPromptsMcp, packingMcp, budgetMcp, authMcp], { accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess })
.attach(server, { userId, scopes: null, isStaticToken: opts.isStaticToken ?? false });
return server;
}
@@ -37,7 +37,7 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, createReservation, createDayAssignment } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
@@ -79,6 +79,20 @@ describe('Tool: create_reservation', () => {
});
});
it('creates a parking reservation (#1444)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_reservation',
arguments: { tripId: trip.id, title: 'Airport Parking P1', type: 'parking' },
});
const data = parseToolResult(result) as any;
expect(data.reservation.title).toBe('Airport Parking P1');
expect(data.reservation.type).toBe('parking');
});
});
it('creates a hotel reservation and links accommodation', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
@@ -436,3 +450,35 @@ describe('Tool: link_hotel_accommodation', () => {
});
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/reservations resource (moved from the legacy
// registerResources into the DI-discovered ReservationsMcp)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/reservations', () => {
it('returns reservations for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createReservation(testDb, trip.id, { title: 'Flight to Paris', type: 'flight' });
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/reservations` });
const items = parseResourceResult(result) as { title: string }[];
expect(items).toHaveLength(1);
expect(items[0].title).toBe('Flight to Paris');
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/reservations` });
const data = parseResourceResult(result) as { error?: string };
expect(data.error).toBeTruthy();
});
});
});
+131
View File
@@ -0,0 +1,131 @@
/**
* Unit tests for the share-link MCP surface (ShareMcp, DI-discovered):
* get_share_link, create_share_link, delete_share_link — moved here from the
* legacy src/mcp/tools/trips.ts registrar with the trip DI port. All three
* ride the canShareTrips predicate (no declarative trips:share mode exists).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
isOwner: (tripId: any, userId: number) =>
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
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 { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
delete process.env.DEMO_MODE;
});
afterAll(() => {
testDb.close();
});
async function withHarness(userId: number, fn: (h: McpHarness) => Promise<void>) {
const h = await createMcpHarness({ userId, withResources: false });
try { await fn(h); } finally { await h.cleanup(); }
}
describe('Tool: get_share_link', () => {
it('returns null when the trip has no share link, then the token after creation', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const empty = parseToolResult(await h.client.callTool({ name: 'get_share_link', arguments: { tripId: trip.id } })) as any;
expect(empty.link).toBeNull();
const created = parseToolResult(await h.client.callTool({ name: 'create_share_link', arguments: { tripId: trip.id } })) as any;
const link = parseToolResult(await h.client.callTool({ name: 'get_share_link', arguments: { tripId: trip.id } })) as any;
expect(link.link.token).toBe(created.token);
});
});
it('returns access denied for a non-member trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'get_share_link', arguments: { tripId: trip.id } });
expect(result.isError).toBe(true);
});
});
});
describe('Tool: create_share_link', () => {
it('creates with the legacy defaults, then updates in place (created=false)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const first = parseToolResult(await h.client.callTool({ name: 'create_share_link', arguments: { tripId: trip.id } })) as any;
expect(first.created).toBe(true);
const row = testDb.prepare('SELECT share_map, share_bookings, share_packing, share_budget, share_collab FROM share_tokens WHERE trip_id = ?').get(trip.id) as any;
expect(row).toEqual({ share_map: 1, share_bookings: 1, share_packing: 0, share_budget: 0, share_collab: 0 });
const second = parseToolResult(await h.client.callTool({ name: 'create_share_link', arguments: { tripId: trip.id, share_budget: true } })) as any;
expect(second.created).toBe(false);
expect(second.token).toBe(first.token);
});
});
it('denies without trip access; blocks demo users', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const foreign = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
expect((await h.client.callTool({ name: 'create_share_link', arguments: { tripId: foreign.id } })).isError).toBe(true);
});
process.env.DEMO_MODE = 'true';
const { user: demo } = createUser(testDb, { email: 'demo@nomad.app' });
const trip = createTrip(testDb, demo.id);
await withHarness(demo.id, async (h) => {
expect((await h.client.callTool({ name: 'create_share_link', arguments: { tripId: trip.id } })).isError).toBe(true);
});
});
});
describe('Tool: delete_share_link', () => {
it('revokes the link; denies without access', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
await h.client.callTool({ name: 'create_share_link', arguments: { tripId: trip.id } });
const result = parseToolResult(await h.client.callTool({ name: 'delete_share_link', arguments: { tripId: trip.id } })) as any;
expect(result.success).toBe(true);
expect(testDb.prepare('SELECT id FROM share_tokens WHERE trip_id = ?').get(trip.id)).toBeUndefined();
});
const { user: stranger } = createUser(testDb);
await withHarness(stranger.id, async (h) => {
expect((await h.client.callTool({ name: 'delete_share_link', arguments: { tripId: trip.id } })).isError).toBe(true);
});
});
});
@@ -35,14 +35,7 @@ vi.mock('../../../src/config', () => ({
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
vi.mock('../../../src/services/mapsService', () => ({
searchPlaces: vi.fn(),
getPlaceDetails: vi.fn().mockResolvedValue({ name: 'Eiffel Tower', address: 'Paris' }),
reverseGeocode: vi.fn().mockResolvedValue({ name: 'Paris', address: 'France' }),
resolveGoogleMapsUrl: vi.fn().mockResolvedValue({ lat: 48.8566, lng: 2.3522, name: 'Paris' }),
}));
vi.mock('../../../src/services/weatherService', () => ({
vi.mock('../../../src/nest/weather/weather.impl', () => ({
getWeather: vi.fn().mockResolvedValue({ temp: 20, condition: 'sunny' }),
getDetailedWeather: vi.fn().mockResolvedValue({ hourly: [] }),
}));
@@ -52,7 +45,23 @@ import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import * as mapsService from '../../../src/services/mapsService';
import { MapsService } from '../../../src/nest/maps/maps.service';
import { getWeather, getDetailedWeather } from '../../../src/nest/weather/weather.impl';
// The geo tools live on the DI-discovered maps.mcp.ts since the maps fold; the
// test registry builds a real MapsService over the mocked db proxy, so stub the
// provider methods on the prototype (no auto-restore in the vitest config —
// these survive across tests, exactly like the old module mock did).
vi.spyOn(MapsService.prototype, 'getPlaceDetails').mockResolvedValue({
name: 'Eiffel Tower',
address: 'Paris',
} as never);
vi.spyOn(MapsService.prototype, 'reverseGeocode').mockResolvedValue({ name: 'Paris', address: 'France' });
vi.spyOn(MapsService.prototype, 'resolveGoogleMapsUrl').mockResolvedValue({
lat: 48.8566,
lng: 2.3522,
name: 'Paris',
} as never);
beforeAll(() => {
createTables(testDb);
@@ -178,6 +187,21 @@ describe('Tool: update_tag', () => {
expect(result.isError).toBe(true);
});
});
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
const r = testDb.prepare('INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)').run(user.id, 'Demo Tag', '#aaaaaa');
const tagId = r.lastInsertRowid as number;
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'update_tag',
arguments: { tagId, name: 'Blocked' },
});
expect(result.isError).toBe(true);
expect(testDb.prepare('SELECT name FROM tags WHERE id = ?').get(tagId)).toEqual({ name: 'Demo Tag' });
});
});
});
// ---------------------------------------------------------------------------
@@ -199,6 +223,76 @@ describe('Tool: delete_tag', () => {
expect(testDb.prepare('SELECT id FROM tags WHERE id = ?').get(tagId)).toBeUndefined();
});
});
it('returns isError for non-existent tagId', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'delete_tag',
arguments: { tagId: 99999 },
});
expect(result.isError).toBe(true);
});
});
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
const r = testDb.prepare('INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)').run(user.id, 'Demo Tag', '#aaaaaa');
const tagId = r.lastInsertRowid as number;
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'delete_tag',
arguments: { tagId },
});
expect(result.isError).toBe(true);
expect(testDb.prepare('SELECT id FROM tags WHERE id = ?').get(tagId)).toBeDefined();
});
});
});
// ---------------------------------------------------------------------------
// tags scope gating (places:read / places:write, registration-time)
// ---------------------------------------------------------------------------
describe('Tags tools: scope gating', () => {
const TAG_TOOLS = ['list_tags', 'create_tag', 'update_tag', 'delete_tag'];
async function listToolNames(userId: number, scopes: string[] | null): Promise<string[]> {
const h = await createMcpHarness({ userId, withResources: false, scopes });
try {
return (await h.client.listTools()).tools.map((t) => t.name);
} finally {
await h.cleanup();
}
}
it('registers all four tag tools with null scopes (full access)', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, null);
for (const tool of TAG_TOOLS) expect(names).toContain(tool);
});
it('registers only list_tags with places:read', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['places:read']);
expect(names).toContain('list_tags');
expect(names).not.toContain('create_tag');
expect(names).not.toContain('update_tag');
expect(names).not.toContain('delete_tag');
});
it('registers all four tag tools with places:write (write implies read)', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['places:write']);
for (const tool of TAG_TOOLS) expect(names).toContain(tool);
});
it('registers no tag tools for an unrelated scope', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['budget:read']);
for (const tool of TAG_TOOLS) expect(names).not.toContain(tool);
});
});
// ---------------------------------------------------------------------------
@@ -219,18 +313,9 @@ describe('Tool: get_place_details', () => {
});
});
it('returns isError when service returns null', async () => {
const { getPlaceDetails } = await import('../../../src/services/mapsService');
(getPlaceDetails as ReturnType<typeof vi.fn>).mockResolvedValueOnce(null);
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'get_place_details',
arguments: { placeId: 'nonexistent-place-id' },
});
expect(result.isError).toBe(true);
});
});
// The former "isError when service returns null" case pinned a dead branch —
// MapsService.getPlaceDetails throws or returns an object, never null — and
// died with the guard in the fix(maps) quirk pass.
});
// ---------------------------------------------------------------------------
@@ -310,3 +395,115 @@ describe('Tool: get_detailed_weather', () => {
});
});
});
// ---------------------------------------------------------------------------
// Weather failure path
//
// Both weather tools swallow a provider failure and answer with isError plus
// the upstream message, rather than letting it surface as a transport-level
// error. That branch never had a case: the tools lived in src/mcp/, which the
// coverage gate does not measure, and the move into src/nest/ exposed it.
// ---------------------------------------------------------------------------
describe('Weather tools: provider failure', () => {
it('get_weather answers isError with the upstream message', async () => {
const { user } = createUser(testDb);
vi.mocked(getWeather).mockRejectedValueOnce(new Error('Open-Meteo unreachable'));
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'get_weather',
arguments: { lat: 48.8566, lng: 2.3522, date: '2025-07-01' },
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toBe('Open-Meteo unreachable');
});
});
it('get_weather falls back to a generic message when the rejection is not an Error', async () => {
const { user } = createUser(testDb);
// A non-Error rejection has no .message, which is the only way the ?? fallback
// fires — `new Error('')` still carries an (empty) message and passes through.
vi.mocked(getWeather).mockRejectedValueOnce('boom' as unknown as Error);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'get_weather',
arguments: { lat: 48.8566, lng: 2.3522, date: '2025-07-01' },
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toBe('Weather service not available.');
});
});
it('get_detailed_weather answers isError with the upstream message', async () => {
const { user } = createUser(testDb);
vi.mocked(getDetailedWeather).mockRejectedValueOnce(new Error('rate limited'));
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'get_detailed_weather',
arguments: { lat: 48.8566, lng: 2.3522, date: '2025-07-01' },
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toBe('rate limited');
});
});
});
// ---------------------------------------------------------------------------
// Airports
//
// The airport lookups had no coverage at all before they moved out of the
// legacy registrar — the same blind spot as the weather catch above.
// ---------------------------------------------------------------------------
describe('Tool: search_airports', () => {
it('returns matches for a city name, capped by limit', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'search_airports', arguments: { query: 'zurich', limit: 5 } });
const data = parseToolResult(result) as { airports: { iata: string }[] };
expect(Array.isArray(data.airports)).toBe(true);
expect(data.airports.length).toBeGreaterThan(0);
expect(data.airports.length).toBeLessThanOrEqual(5);
expect(data.airports.some(a => a.iata === 'ZRH')).toBe(true);
});
});
it('applies the default limit of 10 when none is given', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'search_airports', arguments: { query: 'a' } });
const data = parseToolResult(result) as { airports: unknown[] };
expect(data.airports.length).toBeLessThanOrEqual(10);
});
});
it('returns an empty list for a query that matches nothing', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'search_airports', arguments: { query: 'zzzzzznotanairport' } });
const data = parseToolResult(result) as { airports: unknown[] };
expect(data.airports).toEqual([]);
});
});
});
describe('Tool: get_airport', () => {
it('returns the airport for a known IATA code, lowercase input included', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'get_airport', arguments: { iata: 'zrh' } });
const data = parseToolResult(result) as { airport: { iata: string; tz: string } };
expect(data.airport.iata).toBe('ZRH');
expect(typeof data.airport.tz).toBe('string');
});
});
it('answers isError for an unknown code rather than a null airport', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'get_airport', arguments: { iata: 'QQQ' } });
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toBe('Airport not found.');
});
});
});
+107 -3
View File
@@ -1,7 +1,12 @@
/**
* Unit tests for MCP todo tools:
* Unit tests for the todo MCP surface (TodoMcp, DI-discovered):
* create_todo, update_todo, toggle_todo, delete_todo, reorder_todos,
* list_todos, get_todo_category_assignees, set_todo_category_assignees.
* list_todos, get_todo_category_assignees, set_todo_category_assignees,
* plus the trek://trips/{tripId}/todos resource.
*
* All of it attaches via the nest-mcp registry inside registerTools, so every
* harness here keeps withTools on (the resource is NOT registered by the
* legacy registerResources fan-out anymore).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -38,7 +43,8 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createTodoItem } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
import { ADDON_IDS } from '../../../src/addons';
beforeAll(() => {
createTables(testDb);
@@ -436,3 +442,101 @@ describe('Tool: set_todo_category_assignees', () => {
});
});
});
// ---------------------------------------------------------------------------
// Scope gating (todos read/write, registration-time)
// ---------------------------------------------------------------------------
describe('Todo tools — scope gating', () => {
const READ_TOOLS = ['list_todos', 'get_todo_category_assignees'];
const WRITE_TOOLS = ['create_todo', 'update_todo', 'toggle_todo', 'delete_todo', 'reorder_todos', 'set_todo_category_assignees'];
async function listToolNames(userId: number, scopes: string[] | null): Promise<string[]> {
const h = await createMcpHarness({ userId, withResources: false, scopes });
try {
return (await h.client.listTools()).tools.map((t) => t.name);
} finally {
await h.cleanup();
}
}
it('registers all eight tools with null scopes (full access)', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, null);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).toContain(tool);
});
it('registers only the read tools with todos:read', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['todos:read']);
for (const tool of READ_TOOLS) expect(names).toContain(tool);
for (const tool of WRITE_TOOLS) expect(names).not.toContain(tool);
});
it('registers no todo tools for an unrelated scope', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['budget:read']);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).not.toContain(tool);
});
});
// ---------------------------------------------------------------------------
// Addon gating (packing addon, the legacy whole-registrar early return —
// now the `when` predicate on every TodoMcp entry)
// ---------------------------------------------------------------------------
describe('Todo tools — packing addon gating', () => {
it('registers nothing (tools or resource) when the packing addon is disabled', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('UPDATE addons SET enabled = 0 WHERE id = ?').run(ADDON_IDS.PACKING);
try {
await withHarness(user.id, async (h) => {
const names = (await h.client.listTools()).tools.map((t) => t.name);
expect(names).not.toContain('list_todos');
expect(names).not.toContain('create_todo');
await expect(h.client.readResource({ uri: `trek://trips/${trip.id}/todos` })).rejects.toThrow();
});
} finally {
testDb.prepare('UPDATE addons SET enabled = 1 WHERE id = ?').run(ADDON_IDS.PACKING);
}
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/todos resource (moved from the legacy registerResources)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/todos', () => {
it('returns the trip todos ordered by position', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createTodoItem(testDb, trip.id, { name: 'First' });
createTodoItem(testDb, trip.id, { name: 'Second' });
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/todos` });
const items = parseResourceResult(result) as any[];
expect(items).toHaveLength(2);
expect(items[0].name).toBe('First');
expect(items[1].name).toBe('Second');
});
});
it('returns the access-denied payload for a non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/todos` });
expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
});
});
it('returns the access-denied payload for a malformed trip id', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: 'trek://trips/not-a-number/todos' });
expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
});
});
});
+31 -16
View File
@@ -1,6 +1,8 @@
import { runMigrations } from '../../../src/db/migrations';
import { createTables } from '../../../src/db/schema';
import { invalidatePermissionsCache, savePermissions } from '../../../src/services/permissions';
import { invalidatePermissionsCache } from '../../../src/nest/permissions/permissions-cache';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { addTripMember, createDay, createTrip, createUser } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { resetTestDb } from '../../helpers/test-db';
@@ -28,30 +30,39 @@ const { testDb, dbMock } = vi.hoisted(() => {
return { testDb: db, dbMock: mock };
});
const { geocodeMock, planMock, broadcastMock, notifyBookingChangeMock } = vi.hoisted(() => ({
geocodeMock: vi.fn(),
planMock: vi.fn(),
const { broadcastMock } = vi.hoisted(() => ({
broadcastMock: vi.fn(),
notifyBookingChangeMock: vi.fn(),
}));
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/services/transitService', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/services/transitService')>()),
geocode: geocodeMock,
plan: planMock,
}));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
vi.mock('../../../src/services/reservationService', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/services/reservationService')>()),
notifyBookingChange: notifyBookingChangeMock,
}));
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { ReservationsService } from '../../../src/nest/reservations/reservations.service';
import type { TransitPlace } from '../../../src/nest/transit/transit.helpers';
import { TransitService } from '../../../src/nest/transit/transit.service';
// savePermissions is no longer bridged; write through a service instance — the
// permissions cache is module-scoped, so the MCP _shared checkPermission path
// sees the write immediately.
const permissionsService = new PermissionsService(new DatabaseService(testDb));
const savePermissions = permissionsService.savePermissions.bind(permissionsService);
// The transit tools live on the DI-discovered transit.mcp.ts since the transit
// fold; the test registry builds a real TransitService (and injects a real
// ReservationsService over the mocked db proxy), so stub the provider methods
// on the prototype (no auto-restore in the vitest config — these survive
// across tests, exactly like the old module mocks did).
const geocodeMock = vi.spyOn(TransitService.prototype, 'geocode');
const planMock = vi.spyOn(TransitService.prototype, 'plan');
const notifyBookingChangeMock = vi
.spyOn(ReservationsService.prototype, 'notifyBookingChange')
.mockImplementation(() => {});
const from = { name: 'Namba', lat: 34.667, lng: 135.501 };
const to = { name: 'Umeda', lat: 34.702, lng: 135.496 };
const itinerary = {
@@ -118,7 +129,8 @@ beforeEach(() => {
geocodeMock.mockReset();
planMock.mockReset();
broadcastMock.mockReset();
notifyBookingChangeMock.mockReset();
// mockReset would fall back to the real notification write — keep it stubbed.
notifyBookingChangeMock.mockReset().mockImplementation(() => {});
delete process.env.DEMO_MODE;
invalidatePermissionsCache();
});
@@ -154,7 +166,10 @@ describe('MCP transit tools', () => {
it('forwards stop and route searches and replaces provider endpoint names', async () => {
const { user } = createUser(testDb);
geocodeMock.mockResolvedValue({ results: [from] });
// `from` is a tool-input place (name/lat/lng). A geocode result is a TransitPlace,
// which also carries `type` and `area`; the stop search only reads the name back out,
// so the fixture stays as it is instead of growing fields nothing here looks at.
geocodeMock.mockResolvedValue({ results: [from as TransitPlace] });
planMock.mockResolvedValue({
itineraries: [
itinerary,
+842 -1
View File
@@ -38,7 +38,7 @@ vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { createUser, createTrip, createDay } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
@@ -66,6 +66,18 @@ const flightEndpoints = [
{ role: 'to', sequence: 1, name: 'Paris CDG', code: 'CDG' },
];
// The booking from the report (#1914): AMS → CDG → FCO with a stop in Paris.
const stopoverEndpoints = [
{ role: 'from', sequence: 0, name: 'Amsterdam (AMS)', code: 'AMS' },
{ role: 'stop', sequence: 1, name: 'Paris (CDG)', code: 'CDG' },
{ role: 'to', sequence: 2, name: 'Rome (FCO)', code: 'FCO' },
];
const errorText = (result: unknown) => (result as { content: { text: string }[] }).content[0].text;
const storedMetadata = (reservationId: number) => JSON.parse(
(testDb.prepare('SELECT metadata FROM reservations WHERE id = ?').get(reservationId) as { metadata: string }).metadata
);
describe('Tool: create_transport', () => {
it('backfills lat/lng/timezone for code-only flight endpoints', async () => {
const { user } = createUser(testDb);
@@ -199,3 +211,832 @@ describe('Tool: update_transport', () => {
});
});
});
// ---------------------------------------------------------------------------
// Guards, the budget link and delete
//
// These paths were never covered: the tools lived in src/mcp/, which the
// coverage gate does not measure. Moving them into reservations.mcp.ts put them
// inside src/nest/** and made the gap visible.
// ---------------------------------------------------------------------------
describe('Transport tools: access and validation', () => {
it('create_transport refuses a trip the caller cannot see', async () => {
const { user } = createUser(testDb);
const { user: stranger } = createUser(testDb, { username: 'stranger' });
const trip = createTrip(testDb, stranger.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'flight', title: 'ZRH → CDG' },
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toContain('Trip not found');
});
});
it('create_transport rejects a start_day_id from another trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const otherTrip = createTrip(testDb, user.id);
const foreignDay = Number(testDb.prepare("INSERT INTO days (trip_id, date, day_number) VALUES (?, '2026-07-01', 1)").run(otherTrip.id).lastInsertRowid);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'train', title: 'ICE', start_day_id: foreignDay },
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toBe('start_day_id does not belong to this trip.');
});
});
it('create_transport rejects an end_day_id from another trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const otherTrip = createTrip(testDb, user.id);
const foreignDay = Number(testDb.prepare("INSERT INTO days (trip_id, date, day_number) VALUES (?, '2026-07-02', 1)").run(otherTrip.id).lastInsertRowid);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'train', title: 'ICE', end_day_id: foreignDay },
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toBe('end_day_id does not belong to this trip.');
});
});
});
describe('Transport tools: the price link', () => {
it('create_transport with a price creates the budget item and broadcasts it', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'flight', title: 'ZRH → CDG', price: 240, budget_category: 'Flights' },
});
const data = parseToolResult(result) as { reservation: { id: number } };
const item = testDb.prepare('SELECT name, category, total_price FROM budget_items WHERE reservation_id = ?').get(data.reservation.id) as { name: string; category: string; total_price: number };
expect(item).toMatchObject({ name: 'ZRH → CDG', category: 'Flights', total_price: 240 });
// The price also rides along in the reservation metadata, as the REST path does.
expect(broadcastMock.mock.calls.some(c => c[1] === 'budget:created')).toBe(true);
});
});
it('create_transport falls back to the transport type as the budget category', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'train', title: 'ICE 599', price: 89 },
});
const data = parseToolResult(result) as { reservation: { id: number } };
const item = testDb.prepare('SELECT category FROM budget_items WHERE reservation_id = ?').get(data.reservation.id) as { category: string };
expect(item.category).toBe('train');
});
});
it('create_transport with price 0 records no budget item', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'car', title: 'Rental', price: 0 },
});
const data = parseToolResult(result) as { reservation: { id: number } };
expect(testDb.prepare('SELECT id FROM budget_items WHERE reservation_id = ?').get(data.reservation.id)).toBeUndefined();
});
});
});
describe('Tool: update_transport (guards)', () => {
it('404s an unknown reservation id', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'update_transport',
arguments: { tripId: trip.id, reservationId: 999999, title: 'nope' },
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toBe('Transport not found.');
});
});
it('refuses a reservation that is not a transport type', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = await h.client.callTool({
name: 'create_reservation',
arguments: { tripId: trip.id, type: 'restaurant', title: 'Dinner' },
});
const { reservation } = parseToolResult(created) as { reservation: { id: number } };
const result = await h.client.callTool({
name: 'update_transport',
arguments: { tripId: trip.id, reservationId: reservation.id, title: 'still dinner' },
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toBe('Reservation is not a transport type. Use update_reservation instead.');
});
});
it('rejects a start_day_id from another trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const otherTrip = createTrip(testDb, user.id);
const foreignDay = Number(testDb.prepare("INSERT INTO days (trip_id, date, day_number) VALUES (?, '2026-08-01', 1)").run(otherTrip.id).lastInsertRowid);
await withHarness(user.id, async (h) => {
const created = await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'flight', title: 'ZRH → CDG', endpoints: flightEndpoints },
});
const { reservation } = parseToolResult(created) as { reservation: { id: number } };
const result = await h.client.callTool({
name: 'update_transport',
arguments: { tripId: trip.id, reservationId: reservation.id, start_day_id: foreignDay },
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toBe('start_day_id does not belong to this trip.');
});
});
it('errors on an unresolvable airport code when replacing endpoints', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'flight', title: 'ZRH → CDG', endpoints: flightEndpoints },
});
const { reservation } = parseToolResult(created) as { reservation: { id: number } };
const result = await h.client.callTool({
name: 'update_transport',
arguments: {
tripId: trip.id,
reservationId: reservation.id,
endpoints: [{ role: 'from', sequence: 0, name: 'Nowhere', code: 'QQQ' }],
},
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toContain('Could not resolve airport code');
});
});
});
describe('Tool: delete_transport', () => {
it('deletes the booking and broadcasts it', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'flight', title: 'ZRH → CDG', endpoints: flightEndpoints },
});
const { reservation } = parseToolResult(created) as { reservation: { id: number } };
broadcastMock.mockClear();
const result = await h.client.callTool({
name: 'delete_transport',
arguments: { tripId: trip.id, reservationId: reservation.id },
});
expect(parseToolResult(result)).toEqual({ success: true });
expect(testDb.prepare('SELECT id FROM reservations WHERE id = ?').get(reservation.id)).toBeUndefined();
expect(broadcastMock.mock.calls.some(c => c[1] === 'reservation:deleted')).toBe(true);
});
});
it('404s an unknown reservation id', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'delete_transport',
arguments: { tripId: trip.id, reservationId: 999999 },
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toBe('Transport not found.');
});
});
it('refuses a trip the caller cannot see', async () => {
const { user } = createUser(testDb);
const { user: stranger } = createUser(testDb, { username: 'stranger2' });
const trip = createTrip(testDb, stranger.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'delete_transport',
arguments: { tripId: trip.id, reservationId: 1 },
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect((result as { content: { text: string }[] }).content[0].text).toContain('Trip not found');
});
});
});
// ---------------------------------------------------------------------------
// Multi-leg bookings (#1914)
//
// The per-segment times of a stopover live in metadata.legs; the endpoints only
// carry the onward departure. Before this the tools pinned metadata to string
// values and had no legs parameter, so a stopover created over MCP showed the
// stop's departure as its arrival too.
// ---------------------------------------------------------------------------
describe('Tool: create_transport (multi-leg)', () => {
it('stores the per-leg times of the reported AMS to CDG to FCO stopover', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id, { date: '2026-02-04' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO',
endpoints: stopoverEndpoints,
legs: [
{ from: 'AMS', to: 'CDG', dep_day_id: day.id, dep_time: '09:00', arr_time: '10:00' },
{ from: 'CDG', to: 'FCO', dep_time: '11:00', arr_time: '12:00' },
],
},
});
const data = parseToolResult(result) as any;
expect(storedMetadata(data.reservation.id).legs).toEqual([
{ from: 'AMS', to: 'CDG', dep_day_id: day.id, dep_time: '09:00', arr_day_id: null, arr_time: '10:00' },
{ from: 'CDG', to: 'FCO', dep_day_id: null, dep_time: '11:00', arr_day_id: null, arr_time: '12:00' },
]);
// Blank endpoint times are filled the way the form writes them: the onward
// departure on every waypoint but the last, the arrival on the last.
expect(data.reservation.endpoints.map((e: any) => e.local_time)).toEqual(['09:00', '11:00', '12:00']);
expect(data.reservation.endpoints[0].local_date).toBe('2026-02-04');
// The span follows the first and last leg.
expect(data.reservation.day_id).toBe(day.id);
expect(data.reservation.reservation_time).toBe('2026-02-04T09:00');
expect(data.reservation.reservation_end_time).toBe('12:00');
});
});
it('mirrors the flat metadata keys off the first and last leg', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const data = parseToolResult(await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO',
endpoints: stopoverEndpoints,
legs: [
{ from: 'AMS', to: 'CDG', airline: 'KLM', flight_number: 'KL1233', seat: '14A' },
{ from: 'CDG', to: 'FCO', airline: 'Air France', flight_number: 'AF1204' },
],
},
})) as any;
const meta = storedMetadata(data.reservation.id);
expect(meta.departure_airport).toBe('AMS');
expect(meta.arrival_airport).toBe('FCO');
expect(meta.airline).toBe('KLM');
expect(meta.flight_number).toBe('KL1233');
expect(meta.seat).toBe('14A');
});
});
it('stores a per-segment booking reference and leaves the booking-level one alone (#1943)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const data = parseToolResult(await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO',
endpoints: stopoverEndpoints,
legs: [
{ from: 'AMS', to: 'CDG', confirmation_number: 'ABC123' },
{ from: 'CDG', to: 'FCO' },
],
},
})) as any;
const meta = storedMetadata(data.reservation.id);
expect(meta.legs[0].confirmation_number).toBe('ABC123');
// A leg without one gets no key at all, rather than an undefined that
// serialises away and back as null.
expect(Object.keys(meta.legs[1])).not.toContain('confirmation_number');
// The reference of a single segment must never become the booking's: that
// is a column of its own, fed only by the tool's own parameter.
expect(meta.confirmation_number).toBeUndefined();
expect(data.reservation.confirmation_number).toBeNull();
});
});
it('never overwrites a flat key the caller set itself', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const data = parseToolResult(await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO',
metadata: { airline: 'KLM Cityhopper' },
endpoints: stopoverEndpoints,
legs: [
{ from: 'AMS', to: 'CDG', airline: 'KLM' },
{ from: 'CDG', to: 'FCO', airline: 'Air France' },
],
},
})) as any;
const meta = storedMetadata(data.reservation.id);
expect(meta.airline).toBe('KLM Cityhopper');
expect(meta.legs[0].airline).toBe('KLM');
});
});
it('fills from/to from the endpoint codes when the leg omits them', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const data = parseToolResult(await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO',
endpoints: stopoverEndpoints,
legs: [{ dep_time: '09:00', arr_time: '10:00' }, { dep_time: '11:00', arr_time: '12:00' }],
},
})) as any;
const meta = storedMetadata(data.reservation.id);
expect(meta.legs.map((l: any) => [l.from, l.to])).toEqual([['AMS', 'CDG'], ['CDG', 'FCO']]);
});
});
it('accepts a multi-leg train and mirrors its flat keys', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const data = parseToolResult(await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'train', title: 'Basel to Milano',
endpoints: [
{ role: 'from', sequence: 0, name: 'Basel SBB', lat: 47.5, lng: 7.6 },
{ role: 'stop', sequence: 1, name: 'Lugano', lat: 46.0, lng: 8.9 },
{ role: 'to', sequence: 2, name: 'Milano Centrale', lat: 45.5, lng: 9.2 },
],
legs: [
{ train_number: 'EC 57', platform: '8', dep_time: '08:33', arr_time: '11:20' },
{ train_number: 'EC 317', platform: '3', dep_time: '11:40', arr_time: '12:55' },
],
},
})) as any;
const meta = storedMetadata(data.reservation.id);
// Station endpoints carry no code, so the labels come from their names.
expect(meta.legs.map((l: any) => [l.from, l.to])).toEqual([
['Basel SBB', 'Lugano'], ['Lugano', 'Milano Centrale'],
]);
expect(meta.train_number).toBe('EC 57');
expect(meta.platform).toBe('8');
expect(data.reservation.endpoints.map((e: any) => e.local_time)).toEqual(['08:33', '11:40', '12:55']);
});
});
it('rejects a leg count that does not match the endpoints', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'ZRH to CDG',
endpoints: flightEndpoints,
legs: [{ from: 'ZRH', to: 'CDG' }, { from: 'CDG', to: 'FCO' }],
},
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect(errorText(result)).toBe('legs must contain exactly one entry fewer than endpoints (got 2 legs for 2 endpoints).');
});
});
it('rejects a single leg, which no reader would treat as multi-segment', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'ZRH to CDG',
endpoints: flightEndpoints,
legs: [{ from: 'ZRH', to: 'CDG', dep_time: '09:00', arr_time: '10:00' }],
},
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect(errorText(result)).toContain('at least 2 entries');
});
});
it('rejects legs on a transport type that has none', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'car', title: 'Rental',
legs: [{ from: 'A', to: 'B' }, { from: 'B', to: 'C' }],
},
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect(errorText(result)).toBe('legs are only supported for flight and train bookings.');
});
});
it('rejects a leg day that belongs to another trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const otherTrip = createTrip(testDb, user.id);
const foreignDay = createDay(testDb, otherTrip.id, { date: '2026-02-04' });
await withHarness(user.id, async (h) => {
const depResult = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO',
endpoints: stopoverEndpoints,
legs: [{ from: 'AMS', to: 'CDG', dep_day_id: foreignDay.id }, { from: 'CDG', to: 'FCO' }],
},
});
expect(errorText(depResult)).toBe('legs[0].dep_day_id does not belong to this trip.');
const arrResult = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO',
endpoints: stopoverEndpoints,
legs: [{ from: 'AMS', to: 'CDG' }, { from: 'CDG', to: 'FCO', arr_day_id: foreignDay.id }],
},
});
expect(errorText(arrResult)).toBe('legs[1].arr_day_id does not belong to this trip.');
});
});
it('rejects a leg airport that contradicts its endpoint', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const wrongTo = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO',
endpoints: stopoverEndpoints,
legs: [{ from: 'AMS', to: 'FCO' }, { from: 'CDG', to: 'FCO' }],
},
});
expect(errorText(wrongTo)).toBe('legs[0].to (FCO) does not match endpoints[1] (CDG).');
const wrongFrom = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO',
endpoints: stopoverEndpoints,
legs: [{ from: 'AMS', to: 'CDG' }, { from: 'ORY', to: 'FCO' }],
},
});
expect(errorText(wrongFrom)).toBe('legs[1].from (ORY) does not match endpoints[1] (CDG).');
});
});
it('rejects a leg time that contradicts an endpoint time already set', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const withTimes = [
{ ...stopoverEndpoints[0], local_time: '09:00' },
{ ...stopoverEndpoints[1], local_time: '11:30' },
{ ...stopoverEndpoints[2], local_time: '12:30' },
];
await withHarness(user.id, async (h) => {
const depClash = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO', endpoints: withTimes,
legs: [
{ from: 'AMS', to: 'CDG', dep_time: '09:00', arr_time: '10:00' },
{ from: 'CDG', to: 'FCO', dep_time: '11:00', arr_time: '12:30' },
],
},
});
expect(errorText(depClash)).toContain('legs[1].dep_time (11:00) does not match endpoints[1].local_time (11:30)');
const arrClash = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO', endpoints: withTimes,
legs: [
{ from: 'AMS', to: 'CDG', dep_time: '09:00', arr_time: '10:00' },
{ from: 'CDG', to: 'FCO', dep_time: '11:30', arr_time: '12:00' },
],
},
});
expect(errorText(arrClash)).toContain('legs[1].arr_time (12:00) does not match endpoints[2].local_time (12:30)');
});
});
it('rejects a span that contradicts the first or last leg', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const dayOne = createDay(testDb, trip.id, { date: '2026-02-04' });
const dayTwo = createDay(testDb, trip.id, { date: '2026-02-05' });
await withHarness(user.id, async (h) => {
const startClash = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO', start_day_id: dayOne.id,
endpoints: stopoverEndpoints,
legs: [{ from: 'AMS', to: 'CDG', dep_day_id: dayTwo.id }, { from: 'CDG', to: 'FCO' }],
},
});
expect(errorText(startClash)).toBe(`start_day_id (${dayOne.id}) does not match legs[0].dep_day_id (${dayTwo.id}).`);
const endClash = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO', end_day_id: dayOne.id,
endpoints: stopoverEndpoints,
legs: [{ from: 'AMS', to: 'CDG' }, { from: 'CDG', to: 'FCO', arr_day_id: dayTwo.id }],
},
});
expect(errorText(endClash)).toBe(`end_day_id (${dayOne.id}) does not match legs[1].arr_day_id (${dayTwo.id}).`);
});
});
it('refuses segments smuggled through metadata.legs and names the legs parameter', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_transport',
arguments: {
tripId: trip.id, type: 'flight', title: 'AMS to FCO',
endpoints: stopoverEndpoints,
metadata: { legs: '[{"from":"AMS","to":"CDG"}]' },
},
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect(errorText(result)).toContain('in the legs parameter, not in metadata.legs');
});
});
});
describe('Tool: update_transport (multi-leg)', () => {
const seedStopover = async (h: McpHarness, tripId: number) => parseToolResult(await h.client.callTool({
name: 'create_transport',
arguments: {
tripId, type: 'flight', title: 'AMS to FCO',
endpoints: stopoverEndpoints,
legs: [
{ from: 'AMS', to: 'CDG', dep_time: '09:00', arr_time: '10:00' },
{ from: 'CDG', to: 'FCO', dep_time: '11:00', arr_time: '12:00' },
],
},
})) as any;
it('keeps the stored metadata and the day-plan positions when only legs are sent', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = await seedStopover(h, trip.id);
// What an AirTrail import leaves behind: sync ids plus per-leg planner positions.
testDb.prepare('UPDATE reservations SET metadata = ? WHERE id = ?').run(JSON.stringify({
departure_airport: 'AMS', arrival_airport: 'FCO', airtrail_ids: ['17', '18'],
legs: [
{ from: 'AMS', to: 'CDG', dep_time: '09:00', arr_time: '10:00', day_positions: { 5: 2 } },
{ from: 'CDG', to: 'FCO', dep_time: '11:00', arr_time: '12:00' },
],
}), created.reservation.id);
const result = await h.client.callTool({
name: 'update_transport',
arguments: {
tripId: trip.id, reservationId: created.reservation.id,
legs: [
{ from: 'AMS', to: 'CDG', dep_time: '09:00', arr_time: '10:15' },
{ from: 'CDG', to: 'FCO', dep_time: '11:00', arr_time: '12:00' },
],
},
});
const meta = storedMetadata((parseToolResult(result) as any).reservation.id);
expect(meta.airtrail_ids).toEqual(['17', '18']);
expect(meta.departure_airport).toBe('AMS');
expect(meta.legs[0].arr_time).toBe('10:15');
expect(meta.legs[0].day_positions).toEqual({ 5: 2 });
expect(meta.legs[1].day_positions).toBeUndefined();
});
});
it('keeps a per-segment booking reference through a legs-only update (#1943)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = await seedStopover(h, trip.id);
const result = await h.client.callTool({
name: 'update_transport',
arguments: {
tripId: trip.id, reservationId: created.reservation.id,
legs: [
{ from: 'AMS', to: 'CDG', dep_time: '09:00', arr_time: '10:00', confirmation_number: 'ABC123' },
{ from: 'CDG', to: 'FCO', dep_time: '11:00', arr_time: '12:00', confirmation_number: 'XYZ789' },
],
},
});
const meta = storedMetadata((parseToolResult(result) as any).reservation.id);
// The copy-through list in applyLegs is what carries the field: a field
// missing from it is accepted by the schema and then silently dropped.
expect(meta.legs.map((l: any) => l.confirmation_number)).toEqual(['ABC123', 'XYZ789']);
expect(meta.confirmation_number).toBeUndefined();
});
});
it('uses the supplied metadata as the base when both are sent', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = await seedStopover(h, trip.id);
const result = await h.client.callTool({
name: 'update_transport',
arguments: {
tripId: trip.id, reservationId: created.reservation.id,
metadata: { confirmation_source: 'email' },
legs: [
{ from: 'AMS', to: 'CDG', dep_time: '09:00', arr_time: '10:00' },
{ from: 'CDG', to: 'FCO', dep_time: '11:00', arr_time: '12:00' },
],
},
});
const meta = storedMetadata((parseToolResult(result) as any).reservation.id);
expect(meta.confirmation_source).toBe('email');
expect(meta.legs).toHaveLength(2);
// departure_airport is mirrored back in because the supplied metadata dropped it.
expect(meta.departure_airport).toBe('AMS');
});
});
it('leaves the metadata alone when neither legs nor metadata are sent', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = await seedStopover(h, trip.id);
const before = storedMetadata(created.reservation.id);
await h.client.callTool({
name: 'update_transport',
arguments: { tripId: trip.id, reservationId: created.reservation.id, status: 'confirmed' },
});
expect(storedMetadata(created.reservation.id)).toEqual(before);
});
});
it('counts the stored endpoints when the caller does not replace them', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = parseToolResult(await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'flight', title: 'ZRH to CDG', endpoints: flightEndpoints },
})) as any;
const result = await h.client.callTool({
name: 'update_transport',
arguments: {
tripId: trip.id, reservationId: created.reservation.id,
legs: [{ from: 'ZRH', to: 'CDG' }, { from: 'CDG', to: 'FCO' }],
},
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect(errorText(result)).toBe('legs must contain exactly one entry fewer than endpoints (got 2 legs for 2 endpoints).');
});
});
it('leaves the endpoint rows untouched when the legs change nothing about them', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = await seedStopover(h, trip.id);
const idsBefore = (testDb.prepare('SELECT id FROM reservation_endpoints WHERE reservation_id = ? ORDER BY sequence')
.all(created.reservation.id) as any[]).map(r => r.id);
await h.client.callTool({
name: 'update_transport',
arguments: {
tripId: trip.id, reservationId: created.reservation.id,
legs: [
{ from: 'AMS', to: 'CDG', dep_time: '09:00', arr_time: '10:30' },
{ from: 'CDG', to: 'FCO', dep_time: '11:00', arr_time: '12:00' },
],
},
});
const idsAfter = (testDb.prepare('SELECT id FROM reservation_endpoints WHERE reservation_id = ? ORDER BY sequence')
.all(created.reservation.id) as any[]).map(r => r.id);
expect(idsAfter).toEqual(idsBefore);
});
});
it('fills the endpoint times when the stored endpoints have none', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = parseToolResult(await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'flight', title: 'AMS to FCO', endpoints: stopoverEndpoints },
})) as any;
const result = await h.client.callTool({
name: 'update_transport',
arguments: {
tripId: trip.id, reservationId: created.reservation.id,
legs: [
{ from: 'AMS', to: 'CDG', dep_time: '09:00', arr_time: '10:00' },
{ from: 'CDG', to: 'FCO', dep_time: '11:00', arr_time: '12:00' },
],
},
});
const data = parseToolResult(result) as any;
expect(data.reservation.endpoints.map((e: any) => e.local_time)).toEqual(['09:00', '11:00', '12:00']);
});
});
it('survives a booking whose stored metadata is not valid JSON', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = await seedStopover(h, trip.id);
testDb.prepare('UPDATE reservations SET metadata = ? WHERE id = ?').run('not json at all', created.reservation.id);
const result = await h.client.callTool({
name: 'update_transport',
arguments: {
tripId: trip.id, reservationId: created.reservation.id,
legs: [
{ from: 'AMS', to: 'CDG', dep_time: '09:00', arr_time: '10:00' },
{ from: 'CDG', to: 'FCO', dep_time: '11:00', arr_time: '12:00' },
],
},
});
expect((result as { isError?: boolean }).isError).toBeFalsy();
expect(storedMetadata((parseToolResult(result) as any).reservation.id).legs).toHaveLength(2);
});
});
it('recovers legs from double-encoded metadata instead of losing the positions', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = await seedStopover(h, trip.id);
testDb.prepare('UPDATE reservations SET metadata = ? WHERE id = ?').run(JSON.stringify(JSON.stringify({
legs: [{ from: 'AMS', to: 'CDG', day_positions: { 9: 1 } }, { from: 'CDG', to: 'FCO' }],
})), created.reservation.id);
const result = await h.client.callTool({
name: 'update_transport',
arguments: {
tripId: trip.id, reservationId: created.reservation.id,
legs: [
{ from: 'AMS', to: 'CDG', dep_time: '09:00', arr_time: '10:00' },
{ from: 'CDG', to: 'FCO', dep_time: '11:00', arr_time: '12:00' },
],
},
});
expect(storedMetadata((parseToolResult(result) as any).reservation.id).legs[0].day_positions).toEqual({ 9: 1 });
});
});
it('rejects legs on a booking that is not a flight or train', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = parseToolResult(await h.client.callTool({
name: 'create_transport',
arguments: { tripId: trip.id, type: 'car', title: 'Rental' },
})) as any;
const result = await h.client.callTool({
name: 'update_transport',
arguments: {
tripId: trip.id, reservationId: created.reservation.id,
legs: [{ from: 'A', to: 'B' }, { from: 'B', to: 'C' }],
},
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect(errorText(result)).toBe('legs are only supported for flight and train bookings.');
});
});
it('refuses segments smuggled through metadata.legs', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const created = await seedStopover(h, trip.id);
const result = await h.client.callTool({
name: 'update_transport',
arguments: {
tripId: trip.id, reservationId: created.reservation.id,
metadata: { legs: '[{"from":"AMS","to":"CDG"}]' },
},
});
expect((result as { isError?: boolean }).isError).toBe(true);
expect(errorText(result)).toContain('in the legs parameter, not in metadata.legs');
});
});
});
+210 -2
View File
@@ -1,5 +1,11 @@
/**
* Unit tests for MCP trip tools: create_trip, update_trip, delete_trip, list_trips, get_trip_summary.
* Unit tests for the trip MCP surface (TripsMcp, DI-discovered): create_trip,
* update_trip, delete_trip, list_trips, get_trip_summary tools, the
* trek://trips / trek://trips/{tripId} resources (moved here from
* resources.test.ts with the DI port — the withTools harness attaches the
* nest-mcp registry that now registers them), the fire-once deprecation
* notice riding the attach ctx, and the scope gating (declarative
* trips:write markers + the canReadTrips/canDeleteTrips predicates).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -36,7 +42,7 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, addTripMember, createBudgetItem, createPackingItem, createReservation, createDayNote, createCollabNote, createDayAssignment, createDayAccommodation } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
@@ -503,3 +509,205 @@ describe('Tool: get_trip_summary', () => {
});
});
});
// ---------------------------------------------------------------------------
// Resources (moved from resources.test.ts with the DI port — the registry the
// withTools harness attaches now registers them)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips', () => {
it('returns all trips the user owns or is a member of', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
createTrip(testDb, user.id, { title: 'My Trip' });
const sharedTrip = createTrip(testDb, other.id, { title: 'Shared Trip' });
addTripMember(testDb, sharedTrip.id, user.id);
// Trip from another user (not accessible)
createTrip(testDb, other.id, { title: 'Other Trip' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://trips' });
const trips = parseResourceResult(result) as any[];
expect(trips).toHaveLength(2);
const titles = trips.map((t) => t.title);
expect(titles).toContain('My Trip');
expect(titles).toContain('Shared Trip');
expect(titles).not.toContain('Other Trip');
});
});
it('excludes archived trips', async () => {
const { user } = createUser(testDb);
createTrip(testDb, user.id, { title: 'Active Trip' });
const archived = createTrip(testDb, user.id, { title: 'Archived Trip' });
testDb.prepare('UPDATE trips SET is_archived = 1 WHERE id = ?').run(archived.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://trips' });
const trips = parseResourceResult(result) as any[];
expect(trips).toHaveLength(1);
expect(trips[0].title).toBe('Active Trip');
});
});
it('returns empty array when user has no trips', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://trips' });
const trips = parseResourceResult(result) as any[];
expect(trips).toEqual([]);
});
});
});
describe('Resource: trek://trips/{tripId}', () => {
it('returns trip data for an accessible trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}` });
const data = parseResourceResult(result) as any;
expect(data.title).toBe('Paris Trip');
expect(data.id).toBe(trip.id);
});
});
it('returns access denied for inaccessible trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const otherTrip = createTrip(testDb, other.id, { title: 'Private' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${otherTrip.id}` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
it('returns access denied for non-existent ID', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: 'trek://trips/99999' });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
describe('Resource: trek://trips/{tripId}/members', () => {
it('returns owner and collaborators', async () => {
const { user } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, user.id);
addTripMember(testDb, trip.id, member.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/members` });
const data = parseResourceResult(result) as any;
expect(data.owner).toBeTruthy();
expect(data.owner.id).toBe(user.id);
expect(data.members).toHaveLength(1);
expect(data.members[0].id).toBe(member.id);
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/members` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
// ---------------------------------------------------------------------------
// Deprecation notice (fire-once closure riding the registry attach ctx)
// ---------------------------------------------------------------------------
describe('static-token deprecation notice', () => {
it('list_trips surfaces the notice exactly once and still carries the payload', async () => {
const { user } = createUser(testDb);
createTrip(testDb, user.id, { title: 'Noticed' });
// Mirror the fire-once closure built per session in src/mcp/index.ts.
let emitted = false;
const getDeprecationNotice = () => {
if (emitted) return null;
emitted = true;
return 'static tokens are deprecated';
};
const h = await createMcpHarness({ userId: user.id, withResources: false, isStaticToken: true, getDeprecationNotice });
try {
const first = await h.client.callTool({ name: 'list_trips', arguments: {} });
expect(first.isError).toBe(true);
const texts = (first.content as { type: string; text: string }[]).map((c) => c.text);
expect(texts[0]).toContain('deprecated');
expect(JSON.parse(texts[1]).trips[0].title).toBe('Noticed');
// Second call: the closure already fired — plain payload, no error.
const second = await h.client.callTool({ name: 'list_trips', arguments: {} });
expect(second.isError).toBeFalsy();
expect((parseToolResult(second) as any).trips).toHaveLength(1);
} finally {
await h.cleanup();
}
});
});
// ---------------------------------------------------------------------------
// Scope gating — declarative trips:write markers plus the predicate escape
// hatches (canReadTrips accepts trips:delete / trips:share; delete_trip rides
// trips:delete, the share tools trips:share)
// ---------------------------------------------------------------------------
describe('scope gating', () => {
async function toolNames(scopes: string[] | null): Promise<string[]> {
const h = await createMcpHarness({ userId: 1, withResources: false, scopes });
try {
const { tools } = await h.client.listTools();
return tools.map((t) => t.name);
} finally {
await h.cleanup();
}
}
const WRITE_TOOLS = ['create_trip', 'update_trip', 'add_trip_member', 'remove_trip_member', 'copy_trip'];
const READ_TOOLS = ['list_trip_members', 'export_trip_ics'];
const NAV_TOOLS = ['list_trips', 'get_trip_summary'];
const SHARE_TOOLS = ['get_share_link', 'create_share_link', 'delete_share_link'];
it('null scopes (trek_ PAT) exposes the full surface', async () => {
const names = await toolNames(null);
for (const t of [...WRITE_TOOLS, ...READ_TOOLS, ...NAV_TOOLS, 'delete_trip', ...SHARE_TOOLS]) {
expect(names).toContain(t);
}
});
it('trips:read exposes reads + navigation but no writes/delete/share', async () => {
const names = await toolNames(['trips:read']);
for (const t of [...READ_TOOLS, ...NAV_TOOLS]) expect(names).toContain(t);
for (const t of [...WRITE_TOOLS, 'delete_trip', ...SHARE_TOOLS]) expect(names).not.toContain(t);
});
it('trips:delete alone still grants the trip reads (canReadTrips parity) plus delete_trip', async () => {
const names = await toolNames(['trips:delete']);
expect(names).toContain('delete_trip');
for (const t of [...READ_TOOLS, ...NAV_TOOLS]) expect(names).toContain(t);
for (const t of WRITE_TOOLS) expect(names).not.toContain(t);
});
it('trips:share alone grants the share tools and the trip reads, nothing else', async () => {
const names = await toolNames(['trips:share']);
for (const t of [...SHARE_TOOLS, ...READ_TOOLS, ...NAV_TOOLS]) expect(names).toContain(t);
for (const t of [...WRITE_TOOLS, 'delete_trip']) expect(names).not.toContain(t);
});
it('an unrelated scope keeps only the navigation tools', async () => {
const names = await toolNames(['weather:read']);
for (const t of NAV_TOOLS) expect(names).toContain(t);
for (const t of [...WRITE_TOOLS, ...READ_TOOLS, 'delete_trip', ...SHARE_TOOLS]) expect(names).not.toContain(t);
});
});
+179 -21
View File
@@ -1,12 +1,15 @@
/**
* Unit tests for MCP vacay tools (vacay addon-gated):
* Unit tests for MCP vacay tools (vacay addon-gated, VacayMcp — DI-discovered
* via the hand-built test registry in tests/helpers/mcp-test-controllers.ts):
* get_vacay_plan, update_vacay_plan, set_vacay_color,
* list_vacay_years, add_vacay_year, delete_vacay_year,
* get_vacay_entries, toggle_vacay_entry, toggle_company_holiday,
* get_vacay_stats, update_vacay_stats,
* add_holiday_calendar, update_holiday_calendar, delete_holiday_calendar,
* list_holiday_countries, list_holidays.
* Resources: trek://vacay/plan, trek://vacay/entries/{year}.
* Resources: trek://vacay/plan, trek://vacay/entries/{year},
* trek://vacay/holidays/{year} — these ride the registry too (attached inside
* registerTools), so `withTools` must stay on even for resource reads.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -39,29 +42,25 @@ vi.mock('../../../src/config', () => ({
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
vi.mock('../../../src/services/adminService', () => ({
isAddonEnabled: vi.fn().mockReturnValue(true),
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
// Mock async service functions that make external calls
vi.mock('../../../src/services/vacayService', async (importOriginal) => {
const original = await importOriginal() as Record<string, unknown>;
return {
...original,
updatePlan: vi.fn().mockResolvedValue({
plan: { id: 1, block_weekends: true, holidays_enabled: false, company_holidays_enabled: false, carry_over_enabled: false, holiday_calendars: [] },
}),
getCountries: vi.fn().mockResolvedValue({ data: [{ code: 'US', name: 'United States' }] }),
getHolidays: vi.fn().mockResolvedValue({ data: [{ date: '2025-01-01', name: 'New Year' }] }),
};
});
// share_vacay_calendar fires a user notification after inserting; stub it out
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
import { setAddonEnabled } from '../../helpers/test-db';
import { ADDON_IDS } from '../../../src/addons';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
import { VacayService } from '../../../src/nest/vacay/vacay.service';
// Stub the async methods that make external calls (VacayService is DI-native;
// the registry constructs a real instance, so spy on the prototype — the
// successor of the legacy path-level partial mock of services/vacayService).
vi.spyOn(VacayService.prototype, 'updatePlan').mockResolvedValue({
plan: { id: 1, block_weekends: true, holidays_enabled: false, company_holidays_enabled: false, carry_over_enabled: false, holiday_calendars: [] },
} as never);
vi.spyOn(VacayService.prototype, 'getCountries').mockResolvedValue({ data: [{ code: 'US', name: 'United States' }] });
vi.spyOn(VacayService.prototype, 'getHolidays').mockResolvedValue({ data: [{ date: '2025-01-01', name: 'New Year' }] });
beforeAll(() => {
createTables(testDb);
@@ -70,6 +69,9 @@ beforeAll(() => {
beforeEach(() => {
resetTestDb(testDb);
// The `when:` gate reads the injected AddonsService, so the toggle is the row
// the admin panel writes — and this addon ships disabled by default.
setAddonEnabled(testDb, ADDON_IDS.VACAY, true);
broadcastMock.mockClear();
delete process.env.DEMO_MODE;
});
@@ -250,7 +252,7 @@ describe('Tool: toggle_vacay_entry', () => {
it('toggles entry and returns action', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'toggle_vacay_entry', arguments: { date: '2025-06-15' } });
const result = await h.client.callTool({ name: 'toggle_vacay_entry', arguments: { date: '2025-06-16' } });
const data = parseToolResult(result) as any;
expect(data.action).toBeDefined();
});
@@ -260,7 +262,7 @@ describe('Tool: toggle_vacay_entry', () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'toggle_vacay_entry', arguments: { date: '2025-06-15' } });
const result = await h.client.callTool({ name: 'toggle_vacay_entry', arguments: { date: '2025-06-16' } });
expect(result.isError).toBe(true);
});
});
@@ -457,6 +459,122 @@ describe('Tool: list_holidays', () => {
});
});
// ---------------------------------------------------------------------------
// list_vacay_shares
// ---------------------------------------------------------------------------
describe('Tool: list_vacay_shares', () => {
it('returns outgoing and incoming shares', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await withHarness(user.id, async (h) => {
await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: other.id } });
const result = await h.client.callTool({ name: 'list_vacay_shares', arguments: {} });
const data = parseToolResult(result) as any;
expect(Array.isArray(data.outgoing)).toBe(true);
expect(Array.isArray(data.incoming)).toBe(true);
expect(data.outgoing).toHaveLength(1);
expect(data.outgoing[0].user_id).toBe(other.id);
});
});
});
// ---------------------------------------------------------------------------
// share_vacay_calendar
// ---------------------------------------------------------------------------
describe('Tool: share_vacay_calendar', () => {
it('creates a share and returns success', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: other.id } });
const data = parseToolResult(result) as any;
expect(data.success).toBe(true);
const row = testDb.prepare('SELECT id FROM vacay_shares WHERE owner_id = ? AND user_id = ?').get(user.id, other.id);
expect(row).toBeDefined();
});
});
it('errors when sharing with yourself', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: user.id } });
expect(result.isError).toBe(true);
});
});
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
const { user: other } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: other.id } });
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// unshare_vacay_calendar
// ---------------------------------------------------------------------------
describe('Tool: unshare_vacay_calendar', () => {
it('removes an existing share and returns success', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await withHarness(user.id, async (h) => {
await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: other.id } });
const shareId = (testDb.prepare('SELECT id FROM vacay_shares WHERE owner_id = ?').get(user.id) as any).id;
const result = await h.client.callTool({ name: 'unshare_vacay_calendar', arguments: { shareId } });
const data = parseToolResult(result) as any;
expect(data.success).toBe(true);
expect(testDb.prepare('SELECT id FROM vacay_shares WHERE id = ?').get(shareId)).toBeUndefined();
});
});
it('errors when the share does not exist', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'unshare_vacay_calendar', arguments: { shareId: 99999 } });
expect(result.isError).toBe(true);
});
});
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'unshare_vacay_calendar', arguments: { shareId: 1 } });
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// get_shared_vacay_calendars
// ---------------------------------------------------------------------------
describe('Tool: get_shared_vacay_calendars', () => {
it('returns the sharer entries for the viewer', async () => {
const { user: owner } = createUser(testDb);
const { user: viewer } = createUser(testDb);
await withHarness(owner.id, async (h) => {
await h.client.callTool({ name: 'toggle_vacay_entry', arguments: { date: '2025-06-16' } });
await h.client.callTool({ name: 'share_vacay_calendar', arguments: { targetUserId: viewer.id } });
});
await withHarness(viewer.id, async (h) => {
const result = await h.client.callTool({ name: 'get_shared_vacay_calendars', arguments: { year: 2025 } });
const data = parseToolResult(result) as any;
expect(Array.isArray(data.calendars)).toBe(true);
expect(data.calendars).toHaveLength(1);
expect(data.calendars[0].owner_id).toBe(owner.id);
expect(data.calendars[0].entries.map((e: any) => e.date)).toContain('2025-06-16');
});
});
});
// ---------------------------------------------------------------------------
// Resources
// ---------------------------------------------------------------------------
@@ -483,3 +601,43 @@ describe('Resource: trek://vacay/entries/{year}', () => {
});
});
});
describe('Resource: trek://vacay/holidays/{year}', () => {
it('returns [] while public holidays are disabled or no region is set', async () => {
const { user } = createUser(testDb);
await withResourceHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: 'trek://vacay/holidays/2025' });
const data = parseResourceResult(result) as unknown[];
expect(data).toEqual([]);
});
});
});
// ---------------------------------------------------------------------------
// decline_vacay_invite (demo guard added by the vacay quirk-fix commit — the
// legacy registrar was the only vacay write without it)
// ---------------------------------------------------------------------------
describe('Tool: decline_vacay_invite', () => {
it('declines a pending invite', async () => {
const { user: owner } = createUser(testDb);
const { user: invitee } = createUser(testDb);
await withHarness(owner.id, async (h) => {
await h.client.callTool({ name: 'send_vacay_invite', arguments: { targetUserId: invitee.id } });
});
await withHarness(invitee.id, async (h) => {
const result = await h.client.callTool({ name: 'decline_vacay_invite', arguments: { planId: testDb.prepare('SELECT plan_id FROM vacay_plan_members WHERE user_id = ?').get(invitee.id)!.plan_id } });
const data = parseToolResult(result) as any;
expect(data.success).toBe(true);
});
});
it('blocks demo user', async () => {
process.env.DEMO_MODE = 'true';
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'decline_vacay_invite', arguments: { planId: 1 } });
expect(result.isError).toBe(true);
});
});
});
-184
View File
@@ -1,184 +0,0 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import jwt from 'jsonwebtoken';
vi.mock('../../../src/db/database', () => ({
db: { prepare: vi.fn(() => ({ get: vi.fn(), all: vi.fn() })) },
}));
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret' }));
import { extractToken, authenticate, adminOnly } from '../../../src/middleware/auth';
import { db } from '../../../src/db/database';
import type { Request, Response, NextFunction } from 'express';
function makeReq(overrides: {
cookies?: Record<string, string>;
headers?: Record<string, string>;
} = {}): Request {
return {
cookies: overrides.cookies || {},
headers: overrides.headers || {},
} as unknown as Request;
}
function makeRes(): { res: Response; status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn> } {
const json = vi.fn();
const status = vi.fn(() => ({ json }));
const res = { status } as unknown as Response;
return { res, status, json };
}
// ── extractToken ─────────────────────────────────────────────────────────────
describe('extractToken', () => {
it('returns cookie value when trek_session cookie is set', () => {
const req = makeReq({ cookies: { trek_session: 'cookie-token' } });
expect(extractToken(req)).toBe('cookie-token');
});
it('returns Bearer token from Authorization header when no cookie', () => {
const req = makeReq({ headers: { authorization: 'Bearer header-token' } });
expect(extractToken(req)).toBe('header-token');
});
it('prefers cookie over Authorization header when both are present', () => {
const req = makeReq({
cookies: { trek_session: 'cookie-token' },
headers: { authorization: 'Bearer header-token' },
});
expect(extractToken(req)).toBe('cookie-token');
});
it('returns null when neither cookie nor header are present', () => {
expect(extractToken(makeReq())).toBeNull();
});
it('returns null for Authorization header without a token (empty Bearer)', () => {
const req = makeReq({ headers: { authorization: 'Bearer ' } });
expect(extractToken(req)).toBeNull();
});
it('returns null for Authorization header without Bearer prefix', () => {
const req = makeReq({ headers: { authorization: 'Basic sometoken' } });
// split(' ')[1] returns 'sometoken' — this IS returned (not a null case)
// The function simply splits on space and takes index 1
expect(extractToken(req)).toBe('sometoken');
});
});
// ── authenticate ─────────────────────────────────────────────────────────────
describe('authenticate', () => {
it('returns 401 when no token is present', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status, json } = makeRes();
authenticate(makeReq(), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ code: 'AUTH_REQUIRED' }));
});
it('returns 401 when JWT is invalid', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
authenticate(makeReq({ cookies: { trek_session: 'invalid.jwt.token' } }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
});
it('AUTH-MW-003: calls next() and sets req.user for a valid JWT', () => {
const mockUser = { id: 1, username: 'alice', email: 'alice@example.com', role: 'user' };
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => mockUser), all: vi.fn() } as any);
const token = jwt.sign({ id: 1 }, 'test-secret', { algorithm: 'HS256' });
const req = makeReq({ cookies: { trek_session: token } });
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
authenticate(req, res, next);
expect(next).toHaveBeenCalledOnce();
expect((req as any).user).toEqual(mockUser);
});
it('AUTH-MW-004: returns 401 for a valid JWT when user does not exist in DB', () => {
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => undefined), all: vi.fn() } as any);
const token = jwt.sign({ id: 99999 }, 'test-secret', { algorithm: 'HS256' });
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
authenticate(makeReq({ cookies: { trek_session: token } }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
});
it('AUTH-MW-005: returns 401 for an expired JWT', () => {
const expiredToken = jwt.sign(
{ id: 1, exp: Math.floor(Date.now() / 1000) - 3600 },
'test-secret',
{ algorithm: 'HS256' }
);
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
authenticate(makeReq({ cookies: { trek_session: expiredToken } }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
});
it('AUTH-MW-006: returns 401 for a JWT signed with the wrong secret', () => {
const tamperedToken = jwt.sign({ id: 1 }, 'wrong-secret', { algorithm: 'HS256' });
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
authenticate(makeReq({ cookies: { trek_session: tamperedToken } }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
});
it('AUTH-MW-007: rejects a purpose-scoped mfa_login token even when the user is valid', () => {
// The token issued after the password check but before TOTP is signed with
// the same secret. It must never authenticate a normal request, otherwise
// password alone grants full access and MFA is bypassed.
const mockUser = { id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 0 };
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => mockUser), all: vi.fn() } as any);
const mfaToken = jwt.sign({ id: 1, purpose: 'mfa_login', pv: 0 }, 'test-secret', { algorithm: 'HS256' });
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
authenticate(makeReq({ headers: { authorization: `Bearer ${mfaToken}` } }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
});
});
// ── adminOnly ─────────────────────────────────────────────────────────────────
describe('adminOnly', () => {
it('returns 403 when user role is not admin', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status, json } = makeRes();
const req = { ...makeReq(), user: { id: 1, role: 'user' } } as unknown as Request;
adminOnly(req, res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(403);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringContaining('Admin') }));
});
it('calls next() when user role is admin', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
const req = { ...makeReq(), user: { id: 1, role: 'admin' } } as unknown as Request;
adminOnly(req, res, next);
expect(next).toHaveBeenCalled();
});
it('returns 403 when req.user is undefined', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
adminOnly(makeReq() as unknown as Request, res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(403);
});
});
@@ -0,0 +1,105 @@
import { describe, it, expect, afterEach } from 'vitest';
import express from 'express';
import request from 'supertest';
import { applyGlobalMiddleware } from '../../../src/middleware/globalMiddleware';
async function directiveSources(name: string): Promise<string[]> {
const app = express();
applyGlobalMiddleware(app);
app.get('/probe', (_req, res) => res.json({ ok: true }));
const res = await request(app).get('/probe');
const csp = String(res.headers['content-security-policy'] || '');
const directive = csp
.split(';')
.map(d => d.trim())
.find(d => d.startsWith(name));
return directive ? directive.split(/\s+/).slice(1) : [];
}
const connectSrcSources = () => directiveSources('connect-src');
describe('global CSP: OpenStreetMap tile hosts (#1733)', () => {
it('allows the bare tile.openstreetmap.org host', async () => {
// A CSP wildcard host never matches the apex, so `*.tile.openstreetmap.org`
// alone would block the tile prefetcher's fetch() against the single host
// OSM has served from since it retired a/b/c/d sharding.
expect(await connectSrcSources()).toContain('https://tile.openstreetmap.org');
});
it('still allows the sharded hosts for templates saved earlier', async () => {
expect(await connectSrcSources()).toContain('https://*.tile.openstreetmap.org');
});
});
describe('global CSP: script-src', () => {
it("allows 'wasm-unsafe-eval' so the WASM decoders keep running", async () => {
expect(await directiveSources('script-src')).toContain("'wasm-unsafe-eval'");
});
it("still allows 'unsafe-eval', which heic-to needs to decode an iPhone photo", async () => {
// Pinned so the next tidy-up of this list finds the reason before the
// consequence: libheif initialises embind with new Function(), and without
// this every .heic upload fails in the browser. See the comment on the
// directive for how to actually get rid of it.
expect(await directiveSources('script-src')).toContain("'unsafe-eval'");
});
});
describe('forced-HTTPS redirect', () => {
const saved = { FORCE_HTTPS: process.env.FORCE_HTTPS, APP_URL: process.env.APP_URL };
afterEach(() => {
process.env.FORCE_HTTPS = saved.FORCE_HTTPS;
process.env.APP_URL = saved.APP_URL;
if (saved.FORCE_HTTPS === undefined) delete process.env.FORCE_HTTPS;
if (saved.APP_URL === undefined) delete process.env.APP_URL;
});
async function redirectLocation(): Promise<string> {
const app = express();
applyGlobalMiddleware(app);
app.get('/trips', (_req, res) => res.json({ ok: true }));
const res = await request(app).get('/trips').set('Host', 'evil.example.com');
return String(res.headers.location || '');
}
it('redirects to the configured APP_URL host, not the Host header the caller sent', async () => {
process.env.FORCE_HTTPS = 'true';
process.env.APP_URL = 'https://trip.pakulat.org';
expect(await redirectLocation()).toBe('https://trip.pakulat.org/trips');
});
it('falls back to the request host when APP_URL is unset', async () => {
process.env.FORCE_HTTPS = 'true';
delete process.env.APP_URL;
expect(await redirectLocation()).toBe('https://evil.example.com/trips');
});
it('falls back to the request host when APP_URL is not a URL', async () => {
// A typo in the env should not take the instance down, and it should not
// produce a redirect to a host built from a half-parsed string either.
process.env.FORCE_HTTPS = 'true';
process.env.APP_URL = 'not a url';
expect(await redirectLocation()).toBe('https://evil.example.com/trips');
});
it('leaves an already-secure request alone, and never redirects the health probe', async () => {
process.env.FORCE_HTTPS = 'true';
process.env.APP_URL = 'https://trip.pakulat.org';
const app = express();
applyGlobalMiddleware(app);
app.get('/trips', (_req, res) => res.json({ ok: true }));
app.get('/api/health', (_req, res) => res.json({ ok: true }));
// The proxy already terminated TLS, so there is nothing to upgrade.
const forwarded = await request(app).get('/trips').set('X-Forwarded-Proto', 'https');
expect(forwarded.status).toBe(200);
// The container probe talks plain HTTP on the loopback and must not be
// bounced to a hostname it cannot resolve.
const probe = await request(app).get('/api/health');
expect(probe.status).toBe(200);
});
});
@@ -0,0 +1,89 @@
import { describe, it, expect } from 'vitest';
import { redact, SENSITIVE_KEYS } from '../../../src/middleware/globalMiddleware';
describe('globalMiddleware request-log redaction', () => {
it('redacts secretAccessKey (any casing) — storage admin PUT bodies land in the same debug log line', () => {
expect(redact({ secretAccessKey: 'sk-super-secret' })).toEqual({ secretAccessKey: '[REDACTED]' });
expect(redact({ SecretAccessKey: 'sk-super-secret' })).toEqual({ SecretAccessKey: '[REDACTED]' });
expect(redact({ secretaccesskey: 'sk-super-secret' })).toEqual({ secretaccesskey: '[REDACTED]' });
});
it('lists secretaccesskey in the lowercase lookup set (lookup lowercases the key first)', () => {
expect(SENSITIVE_KEYS.has('secretaccesskey')).toBe(true);
});
it('still redacts every pre-existing sensitive key (no regression)', () => {
const input = {
password: 'p',
new_password: 'p',
current_password: 'p',
token: 't',
jwt: 'j',
authorization: 'a',
cookie: 'c',
client_secret: 's',
mfa_token: 'm',
code: '123456',
smtp_pass: 's',
};
const out = redact(input) as Record<string, unknown>;
for (const key of Object.keys(input)) {
expect(out[key]).toBe('[REDACTED]');
}
});
it('redacts nested objects and arrays, leaving non-sensitive fields untouched', () => {
const out = redact({
name: 'off-box',
options: { secretAccessKey: 'sk-1', accessKeyId: 'ak-1' },
backends: [{ secretAccessKey: 'sk-2' }, { accessKeyId: 'ak-2' }],
});
expect(out).toEqual({
name: 'off-box',
options: { secretAccessKey: '[REDACTED]', accessKeyId: 'ak-1' },
backends: [{ secretAccessKey: '[REDACTED]' }, { accessKeyId: 'ak-2' }],
});
});
it('redacts secret-shaped keys by suffix — the OAuth token body and the settings API keys', () => {
const out = redact({
refresh_token: 'rt-1',
code_verifier: 'cv-1',
llm_api_key: 'sk-1',
mapbox_access_token: 'pk-1',
grant_type: 'refresh_token',
}) as Record<string, unknown>;
expect(out.refresh_token).toBe('[REDACTED]');
expect(out.code_verifier).toBe('[REDACTED]');
expect(out.llm_api_key).toBe('[REDACTED]');
expect(out.mapbox_access_token).toBe('[REDACTED]');
expect(out.grant_type).toBe('refresh_token');
});
it('redacts the value of a {key, value} settings body when the key names a secret', () => {
expect(redact({ key: 'carto_api_key', value: 'carto-secret' })).toEqual({
key: 'carto_api_key',
value: '[REDACTED]',
});
expect(redact({ key: 'mapbox_access_token', value: 'pk-1' })).toEqual({
key: 'mapbox_access_token',
value: '[REDACTED]',
});
// A harmless setting keeps its value: the name is what decides.
expect(redact({ key: 'map_tile_url', value: 'https://tiles.example/{z}/{x}/{y}.png' })).toEqual({
key: 'map_tile_url',
value: 'https://tiles.example/{z}/{x}/{y}.png',
});
});
it('matches the suffix on the end of the key only, so identifiers stay readable', () => {
expect(redact({ accessKeyId: 'ak-1', tokenCount: 5 })).toEqual({ accessKeyId: 'ak-1', tokenCount: 5 });
});
it('passes non-object values through untouched', () => {
expect(redact('plain string')).toBe('plain string');
expect(redact(42)).toBe(42);
expect(redact(null)).toBe(null);
expect(redact(undefined)).toBe(undefined);
});
});
@@ -1,176 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// ── In-memory store + DB mock using vi.hoisted ────────────────────────────────
const { rows, dbMock } = vi.hoisted(() => {
const rows: Record<string, { status_code: number; response_body: string }> = {};
const dbMock = {
db: {
prepare: vi.fn((sql: string) => ({
get: vi.fn((...args: unknown[]) => {
const [key, userId, method, path] = args;
return rows[`${key}:${userId}:${method}:${path}`] ?? undefined;
}),
run: vi.fn((...args: unknown[]) => {
const [key, userId, method, path, status_code, response_body] = args as [string, number, string, string, number, string];
const k = `${key}:${userId}:${method}:${path}`;
if (!rows[k]) rows[k] = { status_code, response_body };
}),
})),
},
};
return { rows, dbMock };
});
vi.mock('../../../src/db/database', () => dbMock);
import { applyIdempotency } from '../../../src/middleware/idempotency';
import type { Request, Response, NextFunction } from 'express';
function makeReq(method = 'POST', headers: Record<string, string> = {}, path = '/api/test'): Request {
return { method, path, headers } as unknown as Request;
}
function makeRes(statusCode = 200): Response {
const ctx = { status: statusCode };
const res = {
get statusCode() { return ctx.status; },
status(code: number) { ctx.status = code; return res; },
json: vi.fn((_body: unknown) => res),
} as unknown as Response;
return res;
}
beforeEach(() => {
Object.keys(rows).forEach(k => delete rows[k]);
vi.clearAllMocks();
});
describe('applyIdempotency', () => {
it('calls next() for GET requests', () => {
const req = makeReq('GET', { 'x-idempotency-key': 'key1' });
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 1);
expect(next).toHaveBeenCalledOnce();
});
it('calls next() when header is absent for POST', () => {
const req = makeReq('POST', {});
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 1);
expect(next).toHaveBeenCalledOnce();
});
it('replays cached response when key+user+method+path already stored', () => {
rows['cached-key:42:POST:/api/test'] = { status_code: 201, response_body: JSON.stringify({ id: 99 }) };
const req = makeReq('POST', { 'x-idempotency-key': 'cached-key' });
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 42);
expect(next).not.toHaveBeenCalled();
expect(res.json as ReturnType<typeof vi.fn>).toHaveBeenCalledWith({ id: 99 });
});
it('different user same key does NOT replay', () => {
rows['cached-key:1:POST:/api/test'] = { status_code: 200, response_body: JSON.stringify({ ok: true }) };
const req = makeReq('POST', { 'x-idempotency-key': 'cached-key' });
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 99); // different user
expect(next).toHaveBeenCalledOnce();
});
it('same key+user on different path does NOT replay (scoped cache)', () => {
// Key 'dual-key' is cached under /api/a but reused against /api/b.
// Without the (key, user_id, method, path) scoping, /api/b would
// have replayed /api/a's body — a silent cross-endpoint leak.
rows['dual-key:7:POST:/api/a'] = { status_code: 200, response_body: JSON.stringify({ from: 'a' }) };
const req = makeReq('POST', { 'x-idempotency-key': 'dual-key' }, '/api/b');
const res = makeRes();
const next = vi.fn(() => {
(res.json as ReturnType<typeof vi.fn>)({ from: 'b' });
});
applyIdempotency(req, res, next, 7);
expect(next).toHaveBeenCalledOnce();
expect(rows['dual-key:7:POST:/api/b']).toBeDefined();
expect(JSON.parse(rows['dual-key:7:POST:/api/b'].response_body)).toEqual({ from: 'b' });
// /api/a's row is untouched.
expect(JSON.parse(rows['dual-key:7:POST:/api/a'].response_body)).toEqual({ from: 'a' });
});
it('same key+user+path but different method does NOT replay', () => {
rows['m-key:3:POST:/api/x'] = { status_code: 201, response_body: JSON.stringify({ m: 'post' }) };
const req = makeReq('PATCH', { 'x-idempotency-key': 'm-key' }, '/api/x');
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 3);
expect(next).toHaveBeenCalledOnce();
});
it('stores 2xx response on first execution via wrapped res.json', () => {
const req = makeReq('POST', { 'x-idempotency-key': 'new-key' });
const res = makeRes(201);
const next = vi.fn(() => {
// Simulate handler calling res.json
(res.json as ReturnType<typeof vi.fn>)({ id: 5 });
});
applyIdempotency(req, res, next, 7);
expect(next).toHaveBeenCalledOnce();
expect(rows['new-key:7:POST:/api/test']).toBeDefined();
expect(rows['new-key:7:POST:/api/test'].status_code).toBe(201);
expect(JSON.parse(rows['new-key:7:POST:/api/test'].response_body)).toEqual({ id: 5 });
});
it('does NOT store 4xx responses', () => {
const req = makeReq('POST', { 'x-idempotency-key': 'fail-key' });
const res = makeRes(422);
const next = vi.fn(() => {
(res.json as ReturnType<typeof vi.fn>)({ error: 'Invalid' });
});
applyIdempotency(req, res, next, 3);
expect(rows['fail-key:3:POST:/api/test']).toBeUndefined();
});
it('returns 400 when X-Idempotency-Key exceeds 128 characters', () => {
const longKey = 'a'.repeat(129);
const req = makeReq('POST', { 'x-idempotency-key': longKey });
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 1);
expect(next).not.toHaveBeenCalled();
expect(res.json as ReturnType<typeof vi.fn>).toHaveBeenCalledWith(
expect.objectContaining({ error: expect.stringContaining('128') }),
);
});
it('does NOT cache response body exceeding 256 KiB', () => {
const req = makeReq('POST', { 'x-idempotency-key': 'big-key' });
const res = makeRes(200);
const originalJsonSpy = res.json as ReturnType<typeof vi.fn>;
const largePayload = { data: 'x'.repeat(256 * 1024 + 1) };
const next = vi.fn(() => {
// res.json is now the wrapper; calling it exercises the size-cap branch
res.json(largePayload);
});
applyIdempotency(req, res, next, 5);
expect(next).toHaveBeenCalledOnce();
// Underlying spy was called (response reached the client)
expect(originalJsonSpy).toHaveBeenCalledWith(largePayload);
// But NOT stored in the idempotency store
expect(rows['big-key:5:POST:/api/test']).toBeUndefined();
});
it('handles PUT, PATCH, and DELETE the same as POST', () => {
for (const method of ['PUT', 'PATCH', 'DELETE'] as const) {
const req = makeReq(method, { 'x-idempotency-key': `key-${method}` });
const res = makeRes(200);
const next = vi.fn();
applyIdempotency(req, res, next, 1);
expect(next).toHaveBeenCalled();
vi.clearAllMocks();
}
});
});
@@ -1,100 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('../../../src/db/database', () => ({
db: { prepare: () => ({ get: vi.fn(), all: vi.fn() }) },
}));
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret' }));
import { isPublicApiPath, isMfaSetupExemptPath } from '../../../src/middleware/mfaPolicy';
// ── isPublicApiPath ──────────────────────────────────────────────────────────
describe('isPublicApiPath', () => {
// AUTH-001 — Public paths must bypass MFA
it('AUTH-001: GET /api/health is public', () => {
expect(isPublicApiPath('GET', '/api/health')).toBe(true);
});
it('GET /api/auth/app-config is public', () => {
expect(isPublicApiPath('GET', '/api/auth/app-config')).toBe(true);
});
it('POST /api/auth/login is public', () => {
expect(isPublicApiPath('POST', '/api/auth/login')).toBe(true);
});
it('POST /api/auth/register is public', () => {
expect(isPublicApiPath('POST', '/api/auth/register')).toBe(true);
});
it('POST /api/auth/demo-login is public', () => {
expect(isPublicApiPath('POST', '/api/auth/demo-login')).toBe(true);
});
it('GET /api/auth/invite/<token> is public', () => {
expect(isPublicApiPath('GET', '/api/auth/invite/abc123')).toBe(true);
expect(isPublicApiPath('GET', '/api/auth/invite/xyz-789')).toBe(true);
});
it('POST /api/auth/mfa/verify-login is public', () => {
expect(isPublicApiPath('POST', '/api/auth/mfa/verify-login')).toBe(true);
});
it('OIDC paths are public (any method)', () => {
expect(isPublicApiPath('GET', '/api/auth/oidc/callback')).toBe(true);
expect(isPublicApiPath('POST', '/api/auth/oidc/login')).toBe(true);
expect(isPublicApiPath('GET', '/api/auth/oidc/discovery')).toBe(true);
});
it('GET /api/trips is not public', () => {
expect(isPublicApiPath('GET', '/api/trips')).toBe(false);
});
it('POST /api/auth/login with wrong method (GET) is not public', () => {
expect(isPublicApiPath('GET', '/api/auth/login')).toBe(false);
});
it('GET /api/auth/me is not public', () => {
expect(isPublicApiPath('GET', '/api/auth/me')).toBe(false);
});
it('DELETE /api/auth/logout is not public', () => {
expect(isPublicApiPath('DELETE', '/api/auth/logout')).toBe(false);
});
});
// ── isMfaSetupExemptPath ─────────────────────────────────────────────────────
describe('isMfaSetupExemptPath', () => {
it('GET /api/auth/me is MFA-setup exempt', () => {
expect(isMfaSetupExemptPath('GET', '/api/auth/me')).toBe(true);
});
it('POST /api/auth/mfa/setup is MFA-setup exempt', () => {
expect(isMfaSetupExemptPath('POST', '/api/auth/mfa/setup')).toBe(true);
});
it('POST /api/auth/mfa/enable is MFA-setup exempt', () => {
expect(isMfaSetupExemptPath('POST', '/api/auth/mfa/enable')).toBe(true);
});
it('GET /api/auth/app-settings is MFA-setup exempt', () => {
expect(isMfaSetupExemptPath('GET', '/api/auth/app-settings')).toBe(true);
});
it('PUT /api/auth/app-settings is MFA-setup exempt', () => {
expect(isMfaSetupExemptPath('PUT', '/api/auth/app-settings')).toBe(true);
});
it('POST /api/auth/app-settings is NOT exempt (wrong method)', () => {
expect(isMfaSetupExemptPath('POST', '/api/auth/app-settings')).toBe(false);
});
it('GET /api/trips is NOT exempt', () => {
expect(isMfaSetupExemptPath('GET', '/api/trips')).toBe(false);
});
it('GET /api/auth/logout is NOT exempt', () => {
expect(isMfaSetupExemptPath('GET', '/api/auth/logout')).toBe(false);
});
});
@@ -1,137 +0,0 @@
/**
* Unit tests for requireTripAccess and requireTripOwner middleware.
* TRIP-ACCESS-001 through TRIP-ACCESS-010.
* canAccessTrip and isOwner are mocked; no DB required.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import type { Request, Response, NextFunction } from 'express';
const mockCanAccessTrip = vi.fn();
const mockIsOwner = vi.fn();
vi.mock('../../../src/db/database', () => ({
canAccessTrip: (...args: any[]) => mockCanAccessTrip(...args),
isOwner: (...args: any[]) => mockIsOwner(...args),
}));
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret' }));
import { requireTripAccess, requireTripOwner } from '../../../src/middleware/tripAccess';
function makeRes(): { res: Response; status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn> } {
const json = vi.fn();
const status = vi.fn(() => ({ json }));
const res = { status } as unknown as Response;
return { res, status, json };
}
function makeReq(params: Record<string, string> = {}, userId = 1): Request {
return {
params,
user: { id: userId },
} as unknown as Request;
}
beforeEach(() => {
mockCanAccessTrip.mockReset();
mockIsOwner.mockReset();
});
// ── requireTripAccess ─────────────────────────────────────────────────────────
describe('requireTripAccess', () => {
it('TRIP-ACCESS-001: returns 400 when no tripId param', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status, json } = makeRes();
requireTripAccess(makeReq({}), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(400);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
});
it('TRIP-ACCESS-002: returns 404 when canAccessTrip returns null (not a member)', () => {
mockCanAccessTrip.mockReturnValue(null);
const next = vi.fn() as unknown as NextFunction;
const { res, status, json } = makeRes();
requireTripAccess(makeReq({ tripId: '42' }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(404);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
});
it('TRIP-ACCESS-003: calls next and attaches trip when user has access', () => {
const fakeTrip = { id: 42, user_id: 1 };
mockCanAccessTrip.mockReturnValue(fakeTrip);
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
const req = makeReq({ tripId: '42' }, 1);
requireTripAccess(req, res, next);
expect(next).toHaveBeenCalledOnce();
expect((req as any).trip).toEqual(fakeTrip);
});
it('TRIP-ACCESS-004: accepts req.params.id as fallback when tripId is absent', () => {
const fakeTrip = { id: 7, user_id: 2 };
mockCanAccessTrip.mockReturnValue(fakeTrip);
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
requireTripAccess(makeReq({ id: '7' }), res, next);
expect(mockCanAccessTrip).toHaveBeenCalledWith(7, expect.any(Number));
expect(next).toHaveBeenCalledOnce();
});
it('TRIP-ACCESS-005: passes numeric tripId to canAccessTrip', () => {
mockCanAccessTrip.mockReturnValue({ id: 99, user_id: 3 });
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
requireTripAccess(makeReq({ tripId: '99' }, 3), res, next);
expect(mockCanAccessTrip).toHaveBeenCalledWith(99, 3);
});
});
// ── requireTripOwner ──────────────────────────────────────────────────────────
describe('requireTripOwner', () => {
it('TRIP-ACCESS-006: returns 400 when no tripId param', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status, json } = makeRes();
requireTripOwner(makeReq({}), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(400);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
});
it('TRIP-ACCESS-007: returns 403 when user is not the owner', () => {
mockIsOwner.mockReturnValue(false);
const next = vi.fn() as unknown as NextFunction;
const { res, status, json } = makeRes();
requireTripOwner(makeReq({ tripId: '10' }, 2), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(403);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
});
it('TRIP-ACCESS-008: calls next when user is the owner', () => {
mockIsOwner.mockReturnValue(true);
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
requireTripOwner(makeReq({ tripId: '10' }, 1), res, next);
expect(next).toHaveBeenCalledOnce();
});
it('TRIP-ACCESS-009: accepts req.params.id as fallback when tripId is absent', () => {
mockIsOwner.mockReturnValue(true);
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
requireTripOwner(makeReq({ id: '5' }, 1), res, next);
expect(mockIsOwner).toHaveBeenCalledWith(5, 1);
expect(next).toHaveBeenCalledOnce();
});
it('TRIP-ACCESS-010: passes numeric tripId to isOwner', () => {
mockIsOwner.mockReturnValue(true);
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
requireTripOwner(makeReq({ tripId: '77' }, 4), res, next);
expect(mockIsOwner).toHaveBeenCalledWith(77, 4);
});
});
@@ -1,109 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { maxLength, validateStringLengths } from '../../../src/middleware/validate';
import type { Request, Response, NextFunction } from 'express';
function makeReq(body: Record<string, unknown> = {}): Request {
return { body } as Request;
}
function makeRes(): { res: Response; status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn> } {
const json = vi.fn();
const status = vi.fn(() => ({ json }));
const res = { status } as unknown as Response;
return { res, status, json };
}
// ── maxLength ────────────────────────────────────────────────────────────────
describe('maxLength', () => {
it('calls next() when field is absent from body', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
maxLength('name', 10)(makeReq({}), res, next);
expect(next).toHaveBeenCalled();
});
it('calls next() when field is not a string (number)', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
maxLength('count', 5)(makeReq({ count: 999 }), res, next);
expect(next).toHaveBeenCalled();
});
it('calls next() when string length is within limit', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
maxLength('name', 10)(makeReq({ name: 'hello' }), res, next);
expect(next).toHaveBeenCalled();
});
it('calls next() when string length equals max exactly', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
maxLength('name', 5)(makeReq({ name: 'hello' }), res, next);
expect(next).toHaveBeenCalled();
});
it('returns 400 when field exceeds max', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status, json } = makeRes();
maxLength('name', 4)(makeReq({ name: 'hello' }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(400);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringContaining('name') }));
});
it('error message includes field name and max length', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, json } = makeRes();
maxLength('title', 3)(makeReq({ title: 'toolong' }), res, next);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringMatching(/title.*3|3.*title/i) }));
});
});
// ── validateStringLengths ────────────────────────────────────────────────────
describe('validateStringLengths', () => {
it('calls next() when all fields are within limits', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
validateStringLengths({ name: 10, bio: 100 })(makeReq({ name: 'Alice', bio: 'A short bio' }), res, next);
expect(next).toHaveBeenCalled();
});
it('returns 400 on first field that exceeds its limit', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
validateStringLengths({ name: 3 })(makeReq({ name: 'toolong' }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(400);
});
it('skips fields not present in body', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
validateStringLengths({ name: 10, missing: 5 })(makeReq({ name: 'Alice' }), res, next);
expect(next).toHaveBeenCalled();
});
it('skips non-string fields', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
validateStringLengths({ count: 5 })(makeReq({ count: 999999 }), res, next);
expect(next).toHaveBeenCalled();
});
it('handles empty maxLengths object — calls next()', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
validateStringLengths({})(makeReq({ anything: 'value' }), res, next);
expect(next).toHaveBeenCalled();
});
it('calls next() only once even if multiple fields are valid', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
validateStringLengths({ a: 10, b: 10 })(makeReq({ a: 'ok', b: 'ok' }), res, next);
expect(next).toHaveBeenCalledOnce();
});
});
+304
View File
@@ -0,0 +1,304 @@
import {
createTestRegistry,
McpController,
McpRegistry,
Prompt,
Resource,
ResourceTemplate,
Tool,
type McpAccessPolicy,
type McpContext,
} from '../../../src/nest-mcp';
import { createAttachHarness, type AttachHarness, type TestCtx } from './harness';
import { afterEach, describe, expect, it } from 'vitest';
import { z } from 'zod';
class Greeter {
greet(name: string): string {
return `hello ${name}`;
}
}
@McpController()
class FixtureMcp {
constructor(private readonly greeter: Greeter) {}
@Tool({
name: 'read_tool',
description: 'Reads.',
inputSchema: { name: z.string() },
annotations: { readOnlyHint: true },
access: { group: 'trips', mode: 'read' },
})
async readTool({ name }: { name: string }, ctx: TestCtx) {
return {
content: [{ type: 'text', text: JSON.stringify({ greeting: this.greeter.greet(name), userId: ctx.userId }) }],
};
}
@Tool({ name: 'write_tool', inputSchema: {}, access: { group: 'trips', mode: 'write' } })
async writeTool(_args: Record<string, never>, ctx: TestCtx) {
return { content: [{ type: 'text', text: `wrote as ${ctx.userId}` }] };
}
@Tool({ name: 'predicate_tool', access: (ctx: McpContext) => (ctx as TestCtx).allow === true })
async predicateTool(args: Record<string, never>, ctx: TestCtx) {
return { content: [{ type: 'text', text: JSON.stringify({ args, userId: ctx.userId }) }] };
}
@Tool({ name: 'open_tool' })
async openTool(args: Record<string, never>, ctx: TestCtx) {
return { content: [{ type: 'text', text: JSON.stringify({ args, userId: ctx.userId }) }] };
}
@Resource({
name: 'fixture_doc',
uri: 'test://doc',
mimeType: 'text/plain',
access: { group: 'trips', mode: 'read' },
})
async readDoc(uri: URL, ctx: TestCtx) {
return { contents: [{ uri: uri.href, text: `doc for ${ctx.userId}` }] };
}
@ResourceTemplate({ name: 'fixture_item', uriTemplate: 'test://item/{id}' })
async readItem(uri: URL, variables: { id: string }, ctx: TestCtx) {
return { contents: [{ uri: uri.href, text: `item ${variables.id} for ${ctx.userId}` }] };
}
@Prompt({ name: 'fixture_prompt', description: 'Prompts.', argsSchema: { topic: z.string() } })
async fixturePrompt({ topic }: { topic: string }, ctx: TestCtx) {
return { messages: [{ role: 'user', content: { type: 'text', text: `${topic} for ${ctx.userId}` } }] };
}
}
@McpController()
class DeclarativeOnly {
@Tool({ name: 'gated_tool', access: { group: 'trips', mode: 'read' } })
async gated() {
return { content: [{ type: 'text', text: 'gated' }] };
}
}
@McpController()
class WhenMcp {
@Tool({
name: 'when_scoped_tool',
access: { group: 'trips', mode: 'read' },
when: (ctx: McpContext) => (ctx as TestCtx).allow === true,
})
async whenScoped() {
return { content: [{ type: 'text', text: 'ok' }] };
}
@Tool({ name: 'when_only_tool', when: (ctx: McpContext) => (ctx as TestCtx).allow === true })
async whenOnly() {
return { content: [{ type: 'text', text: 'ok' }] };
}
// Ungated: keeps the tools capability advertised even when every gated
// entry is filtered (an SDK server with zero tools rejects tools/list).
@Tool({ name: 'probe_tool' })
async probe() {
return { content: [{ type: 'text', text: 'ok' }] };
}
// The gate reads the DECLARING INSTANCE rather than a module-level value.
// This is the shape a host needs to answer "is this addon on" from an
// injected service: the options object is built when the class is defined,
// so without `self` the closure has nothing but imports to reach for.
@Tool({ name: 'self_gated_tool', when: (_ctx, self: WhenMcp) => self.featureOn })
async selfGated() {
return { content: [{ type: 'text', text: 'ok' }] };
}
featureOn = false;
}
const policy: McpAccessPolicy = ({ mode }, ctx) =>
mode === 'write' ? (ctx as TestCtx).canWrite === true : (ctx as TestCtx).canRead === true;
const buildRegistry = () => createTestRegistry([new FixtureMcp(new Greeter())], { accessPolicy: policy });
const textOf = (result: unknown): string => {
const content = (result as { content: { type: string; text: string }[] }).content;
const item = content.find((c) => c.type === 'text');
if (!item) throw new Error('no text content');
return item.text;
};
describe('McpRegistry.attach', () => {
let harness: AttachHarness | undefined;
afterEach(async () => {
await harness?.cleanup();
harness = undefined;
});
it('registers everything for a ctx passing all access checks', async () => {
harness = await createAttachHarness(buildRegistry(), { userId: 7, canRead: true, canWrite: true, allow: true });
const tools = (await harness.client.listTools()).tools.map((t) => t.name).sort();
expect(tools).toEqual(['open_tool', 'predicate_tool', 'read_tool', 'write_tool']);
const resources = (await harness.client.listResources()).resources.map((r) => r.name);
expect(resources).toEqual(['fixture_doc']);
const templates = (await harness.client.listResourceTemplates()).resourceTemplates.map((t) => t.name);
expect(templates).toEqual(['fixture_item']);
const prompts = (await harness.client.listPrompts()).prompts.map((p) => p.name);
expect(prompts).toEqual(['fixture_prompt']);
});
it('filters declarative access through the policy per mode', async () => {
harness = await createAttachHarness(buildRegistry(), { userId: 7, canRead: true, canWrite: false, allow: false });
const tools = (await harness.client.listTools()).tools.map((t) => t.name).sort();
expect(tools).toEqual(['open_tool', 'read_tool']);
});
it('filters everything gated when the ctx grants nothing, keeping ungated entries', async () => {
harness = await createAttachHarness(buildRegistry(), { userId: 7 });
const tools = (await harness.client.listTools()).tools.map((t) => t.name).sort();
expect(tools).toEqual(['open_tool']);
expect((await harness.client.listResources()).resources).toEqual([]);
const templates = (await harness.client.listResourceTemplates()).resourceTemplates.map((t) => t.name);
expect(templates).toEqual(['fixture_item']);
});
it('exposes tool metadata (description, annotations, input schema) to the client', async () => {
harness = await createAttachHarness(buildRegistry(), { userId: 7, canRead: true, canWrite: true, allow: true });
const read = (await harness.client.listTools()).tools.find((t) => t.name === 'read_tool');
expect(read?.description).toBe('Reads.');
expect(read?.annotations).toMatchObject({ readOnlyHint: true });
expect(read?.inputSchema).toMatchObject({ type: 'object', properties: { name: { type: 'string' } } });
});
it('binds (args, ctx) and preserves `this` on tool handlers', async () => {
harness = await createAttachHarness(buildRegistry(), { userId: 42, canRead: true, canWrite: true, allow: true });
const result = await harness.client.callTool({ name: 'read_tool', arguments: { name: 'trek' } });
expect(JSON.parse(textOf(result))).toEqual({ greeting: 'hello trek', userId: 42 });
});
it('normalizes args to {} for tools declared without an inputSchema', async () => {
harness = await createAttachHarness(buildRegistry(), { userId: 42 });
const result = await harness.client.callTool({ name: 'open_tool', arguments: {} });
expect(JSON.parse(textOf(result))).toEqual({ args: {}, userId: 42 });
});
it('serves fixed resources with (uri, ctx)', async () => {
harness = await createAttachHarness(buildRegistry(), { userId: 9, canRead: true });
const result = await harness.client.readResource({ uri: 'test://doc' });
expect(result.contents[0]).toMatchObject({ uri: 'test://doc', text: 'doc for 9' });
});
it('serves resource templates with (uri, variables, ctx)', async () => {
harness = await createAttachHarness(buildRegistry(), { userId: 9 });
const result = await harness.client.readResource({ uri: 'test://item/42' });
expect(result.contents[0]).toMatchObject({ uri: 'test://item/42', text: 'item 42 for 9' });
});
it('serves prompts with (args, ctx)', async () => {
harness = await createAttachHarness(buildRegistry(), { userId: 3 });
const result = await harness.client.getPrompt({ name: 'fixture_prompt', arguments: { topic: 'packing' } });
expect(result.messages[0]?.content).toMatchObject({ type: 'text', text: 'packing for 3' });
});
it('ANDs `when` in front of declarative access (both must pass)', async () => {
const registry = createTestRegistry([new WhenMcp()], { accessPolicy: policy });
harness = await createAttachHarness(registry, { userId: 7, canRead: true, allow: true });
const tools = (await harness.client.listTools()).tools.map((t) => t.name).sort();
expect(tools).toEqual(['probe_tool', 'when_only_tool', 'when_scoped_tool']);
});
it('hands `when` the instance that declared the entry, resolved at attach', async () => {
const controller = new WhenMcp();
const registry = createTestRegistry([controller], { accessPolicy: policy });
harness = await createAttachHarness(registry, { userId: 7 });
expect((await harness.client.listTools()).tools.map((t) => t.name)).not.toContain('self_gated_tool');
await harness.cleanup();
// Flipped AFTER registration: a gate that had captured a value when the
// class was defined could not see this, which is exactly why hosts reached
// for a module-level singleton instead of an injected one.
controller.featureOn = true;
harness = await createAttachHarness(registry, { userId: 7 });
expect((await harness.client.listTools()).tools.map((t) => t.name)).toContain('self_gated_tool');
});
it('skips entries whose `when` gate fails, even when access would pass', async () => {
const registry = createTestRegistry([new WhenMcp()], { accessPolicy: policy });
harness = await createAttachHarness(registry, { userId: 7, canRead: true, allow: false });
expect((await harness.client.listTools()).tools.map((t) => t.name)).toEqual(['probe_tool']);
});
it('skips when-gated entries whose access fails, keeping when-only ones', async () => {
const registry = createTestRegistry([new WhenMcp()], { accessPolicy: policy });
harness = await createAttachHarness(registry, { userId: 7, canRead: false, allow: true });
const tools = (await harness.client.listTools()).tools.map((t) => t.name).sort();
expect(tools).toEqual(['probe_tool', 'when_only_tool']);
});
it('createTestRegistry fails fast on declarative access without an accessPolicy', () => {
expect(() => createTestRegistry([new DeclarativeOnly()])).toThrow(
/declare declarative access but no accessPolicy was configured/,
);
});
it('attach itself still guards declarative access without a policy (defense in depth)', () => {
// Bypass createTestRegistry's validate() by assembling the registry by hand.
const registry = new McpRegistry();
registry.register(new DeclarativeOnly());
expect(() =>
registry.attach(
// attach never gets far enough to need a live server here
{} as Parameters<typeof registry.attach>[0],
{ userId: 1 } as McpContext,
),
).toThrow(/declares declarative access but no accessPolicy was configured/);
});
});
describe('McpAttachOptions.onInvoke', () => {
let harness: AttachHarness | undefined;
afterEach(async () => {
await harness?.cleanup();
harness = undefined;
});
const fullCtx: TestCtx = { userId: 7, canRead: true, canWrite: true, allow: true };
it('fires once per invocation with the entry kind and name — attach and listing stay silent', async () => {
const seen: Array<{ kind: string; name: string }> = [];
harness = await createAttachHarness(buildRegistry(), fullCtx, { onInvoke: (info) => seen.push(info) });
// Neither attach() nor the initialize handshake is an invocation.
expect(seen).toEqual([]);
await harness.client.callTool({ name: 'open_tool', arguments: {} });
expect(seen).toEqual([{ kind: 'tool', name: 'open_tool' }]);
// The inputSchema'd tool goes through the other normalization branch.
await harness.client.callTool({ name: 'read_tool', arguments: { name: 'x' } });
expect(seen[1]).toEqual({ kind: 'tool', name: 'read_tool' });
await harness.client.readResource({ uri: 'test://doc' });
expect(seen[2]).toEqual({ kind: 'resource', name: 'fixture_doc' });
await harness.client.readResource({ uri: 'test://item/5' });
expect(seen[3]).toEqual({ kind: 'resourceTemplate', name: 'fixture_item' });
await harness.client.getPrompt({ name: 'fixture_prompt', arguments: { topic: 't' } });
expect(seen[4]).toEqual({ kind: 'prompt', name: 'fixture_prompt' });
// Listing is not an invocation.
await harness.client.listTools();
expect(seen).toHaveLength(5);
});
it('runs before the handler, so a throwing hook fails the invocation it observes', async () => {
harness = await createAttachHarness(buildRegistry(), fullCtx, {
onInvoke: () => {
throw new Error('audit exploded');
},
});
const result = await harness.client.callTool({ name: 'open_tool', arguments: {} });
expect((result as { isError?: boolean }).isError).toBe(true);
});
});
@@ -0,0 +1,49 @@
import { createTestRegistry, McpController, McpRegistry, Tool, type McpAccessPolicy } from '../../../src/nest-mcp';
import type { TestCtx } from './harness';
import { describe, expect, it } from 'vitest';
@McpController()
class One {
@Tool({ name: 'one_tool' })
one() {}
}
@McpController()
class Two {
@Tool({ name: 'two_tool', access: { group: 'trips', mode: 'write' } })
two() {}
}
describe('createTestRegistry', () => {
it('builds a registry from hand-constructed instances without a Nest app', () => {
const registry = createTestRegistry([new One(), new Two()], { accessPolicy: () => true });
expect(registry).toBeInstanceOf(McpRegistry);
expect(registry.list().map((e) => e.name)).toEqual(['one_tool', 'two_tool']);
});
it('validates on construction (declarative access needs a policy)', () => {
expect(() => createTestRegistry([new One(), new Two()])).toThrow(/no accessPolicy was configured/);
});
it('surfaces a validateAccess rejection on construction', () => {
expect(() =>
createTestRegistry([new Two()], {
accessPolicy: () => true,
validateAccess: ({ group, mode }) => `unknown group '${group}' (mode '${mode}')`,
}),
).toThrow(/invalid access declarations: tool "two_tool" \(Two\.two\): unknown group 'trips' \(mode 'write'\)/);
});
it('forwards the accessPolicy option', () => {
const calls: string[] = [];
const policy: McpAccessPolicy = (access, ctx) => {
calls.push(`${access.group}:${access.mode}:${(ctx as TestCtx).userId}`);
return false;
};
const registry = createTestRegistry([new Two()], { accessPolicy: policy });
// A denied entry is filtered before any server interaction, so a stub suffices.
registry.attach({} as Parameters<McpRegistry['attach']>[0], { userId: 1 } as Parameters<McpRegistry['attach']>[1]);
expect(calls).toEqual(['trips:write:1']);
});
});
@@ -0,0 +1,106 @@
import { McpController, Prompt, Resource, ResourceTemplate, Tool } from '../../../src/nest-mcp';
import { getEntry, isMcpController, type ClassRef } from '../../../src/nest-mcp/metadata';
import { describe, expect, it } from 'vitest';
import { z } from 'zod';
@McpController()
class Decorated {
@Tool({
name: 'do_thing',
description: 'Does a thing.',
inputSchema: { what: z.string() },
annotations: { readOnlyHint: true },
access: { group: 'places', mode: 'read' },
})
doThing() {}
@Resource({ name: 'thing_doc', uri: 'trek://thing', mimeType: 'application/json' })
readThing() {}
@ResourceTemplate({ name: 'thing_by_id', uriTemplate: 'trek://thing/{id}' })
readThingById() {}
@Prompt({ name: 'thing_prompt', description: 'Prompt.', argsSchema: { topic: z.string() } })
promptThing() {}
undecorated() {}
}
class Plain {
@Tool({ name: 'orphan_tool' })
orphan() {}
}
@McpController()
class Child extends Decorated {
@Tool({ name: 'child_tool' })
childThing() {}
}
const ctor = (c: unknown): ClassRef => c as ClassRef;
describe('nest-mcp decorators', () => {
it('@McpController marks the class', () => {
expect(isMcpController(Decorated)).toBe(true);
expect(isMcpController(Plain)).toBe(false);
expect(isMcpController(42)).toBe(false);
});
it('@McpController applies @Injectable (Nest watermark present)', () => {
expect(Reflect.getMetadata('__injectable__', Decorated)).toBe(true);
expect(Reflect.getMetadata('__injectable__', Plain)).toBeUndefined();
});
it('records one entry per decorated method with kind, name and options', () => {
const tool = getEntry(ctor(Decorated), 'doThing');
expect(tool).toMatchObject({
kind: 'tool',
methodName: 'doThing',
options: {
name: 'do_thing',
description: 'Does a thing.',
annotations: { readOnlyHint: true },
access: { group: 'places', mode: 'read' },
},
});
expect(getEntry(ctor(Decorated), 'readThing')).toMatchObject({
kind: 'resource',
options: { name: 'thing_doc', uri: 'trek://thing', mimeType: 'application/json' },
});
expect(getEntry(ctor(Decorated), 'readThingById')).toMatchObject({
kind: 'resourceTemplate',
options: { name: 'thing_by_id', uriTemplate: 'trek://thing/{id}' },
});
expect(getEntry(ctor(Decorated), 'promptThing')).toMatchObject({
kind: 'prompt',
options: { name: 'thing_prompt' },
});
});
it('passes the Zod raw shape through untouched', () => {
const tool = getEntry(ctor(Decorated), 'doThing');
expect(tool?.kind).toBe('tool');
if (tool?.kind === 'tool') {
expect(tool.options.inputSchema?.what).toBeInstanceOf(z.ZodString);
}
});
it('returns nothing for undecorated methods', () => {
expect(getEntry(ctor(Decorated), 'undecorated')).toBeUndefined();
expect(getEntry(ctor(Decorated), 'nope')).toBeUndefined();
});
it('entries decorated on a class without @McpController are still recorded per-method', () => {
// The controller marker gates discovery/registration, not metadata capture.
expect(getEntry(ctor(Plain), 'orphan')).toMatchObject({ kind: 'tool', options: { name: 'orphan_tool' } });
});
it('subclasses see inherited entries through the constructor prototype chain', () => {
expect(getEntry(ctor(Child), 'doThing')).toMatchObject({ options: { name: 'do_thing' } });
expect(getEntry(ctor(Child), 'childThing')).toMatchObject({ options: { name: 'child_tool' } });
// parent does not see the child's entries
expect(getEntry(ctor(Decorated), 'childThing')).toBeUndefined();
});
});
@@ -0,0 +1,109 @@
import { McpController, McpModule, McpRegistryService, Tool, type McpAccessPolicy } from '../../../src/nest-mcp';
import { 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 } from 'vitest';
import { z } from 'zod';
@Injectable()
class CounterService {
private n = 0;
next(): number {
return ++this.n;
}
}
@McpController()
class CounterMcp {
constructor(private readonly counter: CounterService) {}
@Tool({ name: 'count', inputSchema: { by: z.number().optional() }, access: { group: 'trips', mode: 'read' } })
async count(_args: { by?: number }, ctx: TestCtx) {
return { content: [{ type: 'text', text: JSON.stringify({ value: this.counter.next(), userId: ctx.userId }) }] };
}
}
@Injectable()
class PlainProvider {
ignoredMethod() {}
}
@Module({ providers: [CounterService, CounterMcp], exports: [] })
class CounterModule {}
const policy: McpAccessPolicy = (_access, ctx) => (ctx as TestCtx).canRead === true;
describe('McpRegistryService discovery', () => {
let harness: AttachHarness | undefined;
afterEach(async () => {
await harness?.cleanup();
harness = undefined;
});
it('discovers only @McpController providers, across feature modules', async () => {
const moduleRef = await Test.createTestingModule({
imports: [McpModule.forRoot({ accessPolicy: policy }), CounterModule],
providers: [PlainProvider],
}).compile();
await moduleRef.init();
const registry = moduleRef.get(McpRegistryService);
expect(registry.list()).toEqual([
expect.objectContaining({ kind: 'tool', name: 'count', className: 'CounterMcp', methodName: 'count' }),
]);
await moduleRef.close();
});
it('registers boot-discovered entries with working constructor injection', async () => {
const moduleRef = await Test.createTestingModule({
imports: [McpModule.forRoot({ accessPolicy: policy }), CounterModule],
}).compile();
await moduleRef.init();
const registry = moduleRef.get(McpRegistryService);
harness = await createAttachHarness(registry, { userId: 5, canRead: true });
const result = await harness.client.callTool({ name: 'count', arguments: {} });
const text = (result.content as { type: string; text: string }[]).find((c) => c.type === 'text');
expect(JSON.parse(text?.text ?? '')).toEqual({ value: 1, userId: 5 });
await moduleRef.close();
});
it('fails app boot (onModuleInit) on duplicate tool names', async () => {
@McpController()
class CountClone {
@Tool({ name: 'count' })
async countAgain() {
return { content: [{ type: 'text', text: 'clone' }] };
}
}
const moduleRef = await Test.createTestingModule({
imports: [McpModule.forRoot({ accessPolicy: policy }), CounterModule],
providers: [CountClone],
}).compile();
await expect(moduleRef.init()).rejects.toThrow(/duplicate MCP registrations: tool "count"/);
});
it('boots without an accessPolicy and still attaches predicate/ungated entries', async () => {
@McpController()
class OpenMcp {
@Tool({ name: 'open' })
async open() {
return { content: [{ type: 'text', text: 'ok' }] };
}
}
const moduleRef = await Test.createTestingModule({
imports: [McpModule.forRoot()],
providers: [OpenMcp],
}).compile();
await moduleRef.init();
const registry = moduleRef.get(McpRegistryService);
harness = await createAttachHarness(registry, {});
expect((await harness.client.listTools()).tools.map((t) => t.name)).toEqual(['open']);
await moduleRef.close();
});
});
+49
View File
@@ -0,0 +1,49 @@
import type { McpAttachOptions, McpContext, McpRegistry } from '../../../src/nest-mcp';
import { Client } from '@modelcontextprotocol/sdk/client/index';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
/** Test context shape — stands in for whatever a host app augments McpContext with. */
export interface TestCtx {
userId?: number;
canRead?: boolean;
canWrite?: boolean;
allow?: boolean;
}
export const asCtx = (ctx: TestCtx): McpContext => ctx as McpContext;
export interface AttachHarness {
client: Client;
server: McpServer;
cleanup: () => Promise<void>;
}
/** Bare McpServer + Client over an in-memory transport with the registry attached. */
export async function createAttachHarness(
registry: McpRegistry,
ctx: TestCtx,
opts?: McpAttachOptions,
): Promise<AttachHarness> {
const server = new McpServer({ name: 'nest-mcp-test', version: '1.0.0' });
registry.attach(server, asCtx(ctx), opts);
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: 'test-client', version: '1.0.0' });
await server.connect(serverTransport);
await client.connect(clientTransport);
const cleanup = async () => {
try {
await client.close();
} catch {
/* ignore */
}
try {
await server.close();
} catch {
/* ignore */
}
};
return { client, server, cleanup };
}
@@ -0,0 +1,72 @@
import {
demoDenied,
errorResult,
ok,
TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
TOOL_ANNOTATIONS_READONLY,
TOOL_ANNOTATIONS_WRITE,
} from '../../../src/nest-mcp';
import { describe, expect, it } from 'vitest';
describe('result helpers', () => {
it('ok() wraps data as one pretty-printed JSON text block, without isError', () => {
const result = ok({ a: 1 });
expect(result).toEqual({ content: [{ type: 'text', text: JSON.stringify({ a: 1 }, null, 2) }] });
expect('isError' in result).toBe(false);
});
it('errorResult() carries the message verbatim with isError', () => {
expect(errorResult('Tag not found.')).toEqual({
content: [{ type: 'text', text: 'Tag not found.' }],
isError: true,
});
});
it('demoDenied() uses the canned demo-mode message', () => {
expect(demoDenied()).toEqual({
content: [{ type: 'text', text: 'Write operations are disabled in demo mode.' }],
isError: true,
});
});
});
describe('tool annotation presets', () => {
it('encode the read/write/delete/idempotency matrix', () => {
expect(TOOL_ANNOTATIONS_READONLY).toEqual({
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
});
expect(TOOL_ANNOTATIONS_WRITE).toEqual({
readOnlyHint: false,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
});
expect(TOOL_ANNOTATIONS_DELETE).toEqual({
readOnlyHint: false,
destructiveHint: true,
idempotentHint: true,
openWorldHint: false,
});
expect(TOOL_ANNOTATIONS_NON_IDEMPOTENT).toEqual({
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: false,
});
});
it('open-world variants only flip openWorldHint', () => {
expect(TOOL_ANNOTATIONS_OPEN_WORLD_READONLY).toEqual({ ...TOOL_ANNOTATIONS_READONLY, openWorldHint: true });
expect(TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT).toEqual({
...TOOL_ANNOTATIONS_NON_IDEMPOTENT,
openWorldHint: true,
});
});
});
+181
View File
@@ -0,0 +1,181 @@
import { McpController, McpRegistry, Resource, Tool, type McpAccessValidator } from '../../../src/nest-mcp';
import { describe, expect, it, vi } from 'vitest';
@McpController()
class Alpha {
@Tool({ name: 'alpha_one' })
one() {}
@Tool({ name: 'alpha_two', access: { group: 'trips', mode: 'write' } })
two() {}
helper() {}
}
@McpController()
class Beta extends Alpha {
@Tool({ name: 'beta_one' })
betaOne() {}
}
class NotAController {
@Tool({ name: 'nope' })
nope() {}
}
describe('McpRegistry.register / list', () => {
it('records every decorated method and lists it with class/method names', () => {
const registry = new McpRegistry();
registry.register(new Alpha());
expect(registry.list()).toEqual([
expect.objectContaining({ kind: 'tool', name: 'alpha_one', className: 'Alpha', methodName: 'one' }),
expect.objectContaining({
kind: 'tool',
name: 'alpha_two',
className: 'Alpha',
methodName: 'two',
access: { group: 'trips', mode: 'write' },
}),
]);
});
it('includes inherited decorated methods', () => {
const registry = new McpRegistry();
registry.register(new Beta());
const names = registry.list().map((e) => e.name);
expect(names).toContain('beta_one');
expect(names).toContain('alpha_one');
expect(names).toContain('alpha_two');
});
it('respects an explicit methodNames narrowing and dedupes repeats', () => {
const registry = new McpRegistry();
registry.register(new Alpha(), ['one', 'one', 'helper']);
expect(registry.list().map((e) => e.name)).toEqual(['alpha_one']);
});
it('throws for instances whose class is not @McpController-decorated', () => {
const registry = new McpRegistry();
expect(() => registry.register(new NotAController())).toThrow(/not decorated with @McpController/);
});
});
@McpController()
class AlphaClone {
@Tool({ name: 'alpha_one' })
cloned() {}
}
@McpController()
class DuplicateResources {
@Resource({ name: 'doc_a', uri: 'test://same' })
a() {}
@Resource({ name: 'doc_b', uri: 'test://same' })
b() {}
}
describe('McpRegistry.validate', () => {
it('passes for a well-formed registry', () => {
const registry = new McpRegistry({ accessPolicy: () => true });
registry.register(new Alpha());
expect(() => registry.validate()).not.toThrow();
});
it('reports duplicate tool names across classes with their origins', () => {
const registry = new McpRegistry({ accessPolicy: () => true });
registry.register(new Alpha());
registry.register(new AlphaClone());
expect(() => registry.validate()).toThrow(
/duplicate MCP registrations: tool "alpha_one" \(Alpha\.one and AlphaClone\.cloned\)/,
);
});
it('reports duplicate fixed-resource URIs (names may differ)', () => {
const registry = new McpRegistry();
registry.register(new DuplicateResources());
expect(() => registry.validate()).toThrow(/duplicate MCP registrations: resource uri "test:\/\/same"/);
});
it('reports declarative access without a configured accessPolicy', () => {
const registry = new McpRegistry();
registry.register(new Alpha());
expect(() => registry.validate()).toThrow(
/declare declarative access but no accessPolicy was configured.*tool "alpha_two" \(Alpha\.two\)/,
);
});
});
@McpController()
class MixedAccess {
@Tool({ name: 'open_tool' })
open() {}
@Tool({ name: 'predicate_tool', access: () => true })
predicated() {}
@Tool({ name: 'declared_read', access: { group: 'trips', mode: 'read' } })
declaredRead() {}
@Tool({ name: 'declared_write', access: { group: 'places', mode: 'write' } })
declaredWrite() {}
}
describe('McpRegistry.validate — validateAccess hook', () => {
it('invokes the hook once per declarative entry, never for predicate/omitted access', () => {
const validateAccess = vi.fn<McpAccessValidator>(() => null);
const registry = new McpRegistry({ accessPolicy: () => true, validateAccess });
registry.register(new MixedAccess());
expect(() => registry.validate()).not.toThrow();
expect(validateAccess).toHaveBeenCalledTimes(2);
expect(validateAccess).toHaveBeenCalledWith(
{ group: 'trips', mode: 'read' },
expect.objectContaining({
kind: 'tool',
name: 'declared_read',
className: 'MixedAccess',
methodName: 'declaredRead',
}),
);
expect(validateAccess).toHaveBeenCalledWith(
{ group: 'places', mode: 'write' },
expect.objectContaining({
kind: 'tool',
name: 'declared_write',
className: 'MixedAccess',
methodName: 'declaredWrite',
}),
);
});
it('accepts null and undefined returns', () => {
const returns: (string | null | undefined)[] = [null, undefined];
const registry = new McpRegistry({ accessPolicy: () => true, validateAccess: () => returns.shift() });
registry.register(new MixedAccess());
expect(() => registry.validate()).not.toThrow();
});
it('aggregates every rejected entry into one error naming each origin', () => {
const registry = new McpRegistry({
accessPolicy: () => true,
validateAccess: ({ group, mode }) => `no '${group}:${mode}' scope`,
});
registry.register(new MixedAccess());
expect(() => registry.validate()).toThrow(
/Invalid MCP registry: invalid access declarations: tool "declared_read" \(MixedAccess\.declaredRead\): no 'trips:read' scope, tool "declared_write" \(MixedAccess\.declaredWrite\): no 'places:write' scope/,
);
});
it('composes with duplicate-name problems in the same aggregated error', () => {
const registry = new McpRegistry({
accessPolicy: () => true,
validateAccess: ({ mode }) => (mode === 'write' ? 'bad group' : null),
});
registry.register(new Alpha());
registry.register(new AlphaClone());
expect(() => registry.validate()).toThrow(
/duplicate MCP registrations: tool "alpha_one".*; invalid access declarations: tool "alpha_two" \(Alpha\.two\): bad group/,
);
});
});
@@ -1,7 +1,7 @@
import { describe, it, expect, vi } from 'vitest';
import { HttpException } from '@nestjs/common';
import { AccommodationsController } from '../../../src/nest/reservations/accommodations.controller';
import type { AccommodationsService } from '../../../src/nest/reservations/accommodations.service';
import { AccommodationsController } from '../../../src/nest/accommodations/accommodations.controller';
import type { AccommodationsService } from '../../../src/nest/accommodations/accommodations.service';
import type { User } from '../../../src/types';
const user = { id: 1, role: 'user', email: 'u@example.test' } as User;
@@ -28,10 +28,6 @@ function thrown(fn: () => unknown): { status: number; body: unknown } {
}
describe('AccommodationsController (parity with the legacy accommodations sub-router)', () => {
it('404 when trip not accessible', () => {
const svc = makeService({ verifyTripAccess: vi.fn().mockReturnValue(undefined) });
expect(thrown(() => new AccommodationsController(svc).list(user, '5'))).toEqual({ status: 404, body: { error: 'Trip not found' } });
});
it('GET / lists (no permission gate)', () => {
const svc = makeService({ list: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AccommodationsService>);
@@ -39,10 +35,6 @@ describe('AccommodationsController (parity with the legacy accommodations sub-ro
});
describe('POST /', () => {
it('403 without day_edit', () => {
const svc = makeService({ canEdit: vi.fn().mockReturnValue(false) });
expect(thrown(() => new AccommodationsController(svc).create(user, '5', refs))).toEqual({ status: 403, body: { error: 'No permission' } });
});
it('400 when refs are missing', () => {
expect(thrown(() => new AccommodationsController(makeService()).create(user, '5', { place_id: 2 }))).toEqual({
@@ -89,7 +81,10 @@ describe('AccommodationsController (parity with the legacy accommodations sub-ro
it('emits the linked reservation/budget cascade then accommodation:deleted', () => {
const get = vi.fn().mockReturnValue({ id: 9 });
const remove = vi.fn().mockReturnValue({ linkedReservationId: 4, deletedBudgetItemId: 7 });
const remove = vi.fn().mockReturnValue({
linkedReservationId: 4, deletedBudgetItemId: 7,
linkedReservationIds: [4], deletedBudgetItemIds: [7],
});
const broadcast = vi.fn();
const svc = makeService({ get, remove, broadcast } as Partial<AccommodationsService>);
expect(new AccommodationsController(svc).remove(user, '5', '9', 'sock')).toEqual({ success: true });
@@ -97,5 +92,18 @@ describe('AccommodationsController (parity with the legacy accommodations sub-ro
expect(broadcast).toHaveBeenCalledWith('5', 'budget:deleted', { itemId: 7 }, 'sock');
expect(broadcast).toHaveBeenCalledWith('5', 'accommodation:deleted', { accommodationId: 9 }, 'sock');
});
it('emits one event per booking when a stay carried more than one (#1869)', () => {
const get = vi.fn().mockReturnValue({ id: 9 });
const remove = vi.fn().mockReturnValue({
linkedReservationId: 4, deletedBudgetItemId: null,
linkedReservationIds: [4, 5], deletedBudgetItemIds: [],
});
const broadcast = vi.fn();
const svc = makeService({ get, remove, broadcast } as Partial<AccommodationsService>);
new AccommodationsController(svc).remove(user, '5', '9', 'sock');
expect(broadcast).toHaveBeenCalledWith('5', 'reservation:deleted', { reservationId: 4 }, 'sock');
expect(broadcast).toHaveBeenCalledWith('5', 'reservation:deleted', { reservationId: 5 }, 'sock');
});
});
});
@@ -0,0 +1,599 @@
/**
* Unit tests for AccommodationsService. DAY-SVC-016..026, 029 and 035 moved here
* 1:1 with the SQL they cover when accommodations became their own domain; the
* case ids are unchanged so the diff reads as a move. Real in-memory SQLite.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
return {
testDb: db,
dbMock: {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`
SELECT t.id, t.user_id FROM trips t
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
`).get(userId, tripId, userId),
isOwner: (tripId: any, userId: number) =>
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
},
};
});
vi.mock('../../../src/db/database', () => dbMock);
const { broadcast } = vi.hoisted(() => ({ broadcast: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, createDayAccommodation, addTripMember } from '../../helpers/factories';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { AccommodationsService } from '../../../src/nest/accommodations/accommodations.service';
import { AccommodationsModule } from '../../../src/nest/accommodations/accommodations.module';
import { AccommodationsController } from '../../../src/nest/accommodations/accommodations.controller';
import { expectRegisteredProvider, expectRegisteredController } from '../../helpers/module-providers';
// Named `svc` so the moved cases read exactly as they did on DaysService.
const svc = new AccommodationsService(
new DatabaseService(testDb),
new PermissionsService(new DatabaseService(testDb)),
new RealtimeService(),
);
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
describe('validateAccommodationRefs', () => {
it('DAY-SVC-016 — returns no errors when all refs are valid', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const errors = svc.validateAccommodationRefs(trip.id, place.id, day.id, day.id);
expect(errors).toHaveLength(0);
});
it('DAY-SVC-017 — returns error when place does not exist in trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const errors = svc.validateAccommodationRefs(trip.id, 99999, day.id, day.id);
expect(errors.some((e: any) => e.field === 'place_id')).toBe(true);
});
it('DAY-SVC-018 — returns error when start_day_id is invalid', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const errors = svc.validateAccommodationRefs(trip.id, place.id, 99999, day.id);
expect(errors.some((e: any) => e.field === 'start_day_id')).toBe(true);
});
it('ACC-003 — reports every bad ref, end_day_id included', () => {
// The controller only surfaces errors[0], so an unchecked end_day_id would let a
// stay point at a day from another trip and never be reported.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const errors = svc.validateAccommodationRefs(trip.id, 99999, 99998, 99997);
expect(errors.map((e: any) => e.field)).toEqual(['place_id', 'start_day_id', 'end_day_id']);
});
it('ACC-004 — skips the refs the caller left undefined', () => {
// The plugin update path (accommodations.rpc) passes only the fields it changes.
// If an absent ref were validated, every partial update would 403 "Place not found".
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(svc.validateAccommodationRefs(trip.id)).toHaveLength(0);
expect(svc.validateAccommodationRefs(trip.id, undefined, undefined, undefined)).toHaveLength(0);
});
});
describe('createAccommodation', () => {
it('DAY-SVC-019 — creates accommodation and returns it with place info', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Grand Hotel' }) as any;
const accom = svc.createAccommodation(trip.id, {
place_id: place.id,
start_day_id: day.id,
end_day_id: day.id,
check_in: '15:00',
check_out: '11:00',
}) as any;
expect(accom).toBeDefined();
expect(accom.place_name).toBe('Grand Hotel');
});
it('DAY-SVC-020 — auto-creates a linked reservation', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'City Hotel' }) as any;
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
const reservation = testDb.prepare('SELECT * FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
expect(reservation).toBeDefined();
expect(reservation.type).toBe('hotel');
expect(reservation.status).toBe('confirmed');
});
it('ACC-005 — titles the partner reservation "Hotel" when the stay has no place', () => {
// day_accommodations.place_id is nullable (ON DELETE SET NULL) while
// reservations.title is NOT NULL: without the fallback the reservation insert
// fails and takes the whole transaction — and the stay — down with it.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const accom = svc.createAccommodation(trip.id, {
place_id: null as unknown as number, start_day_id: day.id, end_day_id: day.id,
}) as any;
expect(accom.place_name).toBeNull();
const reservation = testDb.prepare('SELECT title FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
expect(reservation.title).toBe('Hotel');
});
});
describe('getAccommodation', () => {
it('DAY-SVC-021 — returns accommodation for valid id and trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = createDayAccommodation(testDb, trip.id, place.id, day.id, day.id) as any;
const found = svc.getAccommodation(accom.id, trip.id) as any;
expect(found).toBeDefined();
expect(found.id).toBe(accom.id);
});
it('DAY-SVC-022 — returns undefined for non-existent accommodation', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(svc.getAccommodation(99999, trip.id)).toBeUndefined();
});
});
describe('updateAccommodation', () => {
it('DAY-SVC-023 — updates check-in and check-out times', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
const existing = svc.getAccommodation(accom.id, trip.id)!;
const updated = svc.updateAccommodation(accom.id, existing as any, { check_in: '16:00', check_out: '12:00' }) as any;
expect(updated).toBeDefined();
// Verify linked reservation metadata was synced
const reservation = testDb.prepare('SELECT * FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
expect(reservation).toBeDefined();
const meta = JSON.parse(reservation.metadata || '{}');
expect(meta.check_in_time).toBe('16:00');
expect(meta.check_out_time).toBe('12:00');
});
it('DAY-SVC-024 — preserves existing fields when not updated', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
confirmation: 'ABC123',
}) as any;
const existing = svc.getAccommodation(accom.id, trip.id)!;
svc.updateAccommodation(accom.id, existing as any, { check_in: '14:00' });
const row = svc.getAccommodation(accom.id, trip.id) as any;
expect(row.confirmation).toBe('ABC123');
});
it('ACC-006 — updates a stay that has no linked reservation', () => {
// Stays imported before the auto-reservation existed have no partner row. The sync
// block must be skipped for them, not throw on a missing reservation.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
// The factory writes the stay row directly, without the partner reservation.
const accom = createDayAccommodation(testDb, trip.id, place.id, day.id, day.id) as any;
const existing = svc.getAccommodation(accom.id, trip.id)!;
const updated = svc.updateAccommodation(accom.id, existing as any, { check_in: '15:00' }) as any;
expect(updated.check_in).toBe('15:00');
expect(testDb.prepare('SELECT COUNT(*) as n FROM reservations WHERE accommodation_id = ?').get(accom.id)).toMatchObject({ n: 0 });
});
it('ACC-007 — merges into the reservation metadata instead of replacing it', () => {
// The stay is created with a check-in, so the reservation already carries metadata.
// An update that only moves the check-out must parse and extend that object —
// writing a fresh one would silently drop the check-in window.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id, check_in: '15:00',
}) as any;
const existing = svc.getAccommodation(accom.id, trip.id)!;
svc.updateAccommodation(accom.id, existing as any, { check_in_end: '20:00', check_out: '11:00' });
const reservation = testDb.prepare('SELECT metadata FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
expect(JSON.parse(reservation.metadata)).toEqual({
check_in_time: '15:00', check_in_end_time: '20:00', check_out_time: '11:00',
});
});
it('ACC-008 — leaves the reservation confirmation number alone when the stay has none', () => {
// COALESCE(?, confirmation_number): a stay without a confirmation must not null out
// a number that was typed on the reservation itself.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
testDb.prepare('UPDATE reservations SET confirmation_number = ? WHERE accommodation_id = ?').run('RES-9', accom.id);
const existing = svc.getAccommodation(accom.id, trip.id)!;
svc.updateAccommodation(accom.id, existing as any, { check_in: '15:00' });
const reservation = testDb.prepare('SELECT confirmation_number FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
expect(reservation.confirmation_number).toBe('RES-9');
});
});
describe('deleteAccommodation', () => {
it('DAY-SVC-025 — deletes accommodation and its linked reservation', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
const reservation = testDb.prepare('SELECT id FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
const result = svc.deleteAccommodation(accom.id);
expect(result.linkedReservationId).toBe(reservation.id);
// Accommodation is gone
expect(svc.getAccommodation(accom.id, trip.id)).toBeUndefined();
// Reservation is gone
const deletedRes = testDb.prepare('SELECT id FROM reservations WHERE id = ?').get(reservation.id);
expect(deletedRes).toBeUndefined();
});
it('DAY-SVC-026 — returns null linkedReservationId when no reservation was linked', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = createDayAccommodation(testDb, trip.id, place.id, day.id, day.id) as any;
// Remove the auto-created reservation so there's no linked one
testDb.prepare('DELETE FROM reservations WHERE accommodation_id = ?').run(accom.id);
const result = svc.deleteAccommodation(accom.id);
expect(result.linkedReservationId).toBeNull();
});
it('ACC-009 — also deletes the budget item that hangs off the linked reservation', () => {
// The cost row references the reservation, not the stay, so the delete has to
// cascade twice. Skipping the second hop strands a budget line whose reservation
// is gone, and the costs view can no longer reach it to remove it.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
const reservation = testDb.prepare('SELECT id FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
const budgetItemId = testDb.prepare(
'INSERT INTO budget_items (trip_id, name, category, total_price, reservation_id) VALUES (?, ?, ?, ?, ?)'
).run(trip.id, 'Hotel stay', 'Accommodation', 240, reservation.id).lastInsertRowid as number;
const result = svc.deleteAccommodation(accom.id);
expect(result).toEqual({
linkedReservationId: reservation.id,
deletedBudgetItemId: budgetItemId,
linkedReservationIds: [reservation.id],
deletedBudgetItemIds: [budgetItemId],
});
expect(testDb.prepare('SELECT id FROM budget_items WHERE id = ?').get(budgetItemId)).toBeUndefined();
});
it('ACC-010 — a second booking pointed at the same stay goes too, instead of being orphaned', () => {
// reservations.accommodation_id carries no foreign key and no unique constraint,
// and the booking form lets a hotel booking pick an existing stay. Deleting only
// the first left the second behind, referencing a stay that no longer exists.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
const first = testDb.prepare('SELECT id FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
const second = testDb.prepare(
'INSERT INTO reservations (trip_id, type, title, accommodation_id) VALUES (?, ?, ?, ?)'
).run(trip.id, 'hotel', 'Second booking', accom.id).lastInsertRowid as number;
const result = svc.deleteAccommodation(accom.id);
expect(result.linkedReservationIds).toEqual([first.id, second]);
expect(result.linkedReservationId).toBe(first.id);
expect(testDb.prepare('SELECT COUNT(*) as n FROM reservations WHERE accommodation_id = ?').get(accom.id)).toMatchObject({ n: 0 });
});
it('ACC-011 — updating the stay syncs the times onto every linked booking', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
testDb.prepare(
'INSERT INTO reservations (trip_id, type, title, accommodation_id) VALUES (?, ?, ?, ?)'
).run(trip.id, 'hotel', 'Second booking', accom.id);
const existing = testDb.prepare('SELECT * FROM day_accommodations WHERE id = ?').get(accom.id) as any;
svc.updateAccommodation(accom.id, existing, { check_in: '15:00', check_out: '11:00' });
const rows = testDb.prepare('SELECT metadata FROM reservations WHERE accommodation_id = ?').all(accom.id) as Array<{ metadata: string | null }>;
expect(rows).toHaveLength(2);
for (const row of rows) {
expect(JSON.parse(row.metadata || '{}')).toMatchObject({ check_in_time: '15:00', check_out_time: '11:00' });
}
});
});
describe('listAccommodations', () => {
it('DAY-SVC-029 — listAccommodations returns the hydrated stays', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id, { name: 'Ryokan' });
createDayAccommodation(testDb, trip.id, place.id, day.id, day.id);
const rows = svc.listAccommodations(trip.id) as { place_name: string }[];
expect(rows).toHaveLength(1);
expect(rows[0].place_name).toBe('Ryokan');
});
});
describe('quirk fixes', () => {
it('DAY-SVC-035 — deleteAccommodation is atomic: a failed stay delete keeps the linked reservation', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id, { name: 'Hotel' });
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as { id: number };
testDb.exec("CREATE TRIGGER boom BEFORE DELETE ON day_accommodations BEGIN SELECT RAISE(ABORT, 'boom'); END");
try {
expect(() => svc.deleteAccommodation(accom.id)).toThrow();
// The earlier reservation delete inside the transaction rolled back.
expect(testDb.prepare('SELECT COUNT(*) as n FROM reservations WHERE accommodation_id = ?').get(accom.id)).toMatchObject({ n: 1 });
} finally {
testDb.exec('DROP TRIGGER boom');
}
});
});
describe('route-facing delegators', () => {
// list/validateRefs/get/create/update/remove are what the controller, the plugin RPC
// and trip-read-model call; the MCP tools call the long names. Both sets have to land
// on the same SQL, and the short ones get raw route params — strings where the long
// ones get numbers.
it('ACC-010 — list() returns what listAccommodations() returns, for a string and a number trip id', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Pension Alpen' }) as any;
createDayAccommodation(testDb, trip.id, place.id, day.id, day.id);
expect(svc.list(String(trip.id))).toEqual(svc.listAccommodations(trip.id));
expect((svc.list(trip.id) as any[])[0].place_name).toBe('Pension Alpen');
});
it('ACC-011 — validateRefs() returns the same errors validateAccommodationRefs() does', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
expect(svc.validateRefs(trip.id, place.id, day.id, day.id)).toHaveLength(0);
// The controller 404s with errors[0].message, so the shape matters, not just the count.
expect(svc.validateRefs(trip.id, 99999, day.id, day.id)).toEqual([{ field: 'place_id', message: 'Place not found' }]);
});
it('ACC-012 — create() writes the stay, get() reads it back trip-scoped', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const otherTrip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
// Both ids arrive from the route as strings.
const created = svc.create(String(trip.id), {
place_id: place.id, start_day_id: day.id, end_day_id: day.id, confirmation: 'XY-1',
}) as any;
expect(svc.get(String(created.id), String(trip.id))).toMatchObject({ id: created.id, confirmation: 'XY-1' });
// Trip-scoped: a stay must not be readable through another trip's URL.
expect(svc.get(created.id, otherTrip.id)).toBeUndefined();
});
it('ACC-013 — update() syncs the partner reservation even when the id is a string', () => {
// updateAccommodation looks the reservation up with Number(id); if that coercion
// regresses, the REST path silently stops syncing check-in times.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = svc.create(trip.id, { place_id: place.id, start_day_id: day.id, end_day_id: day.id }) as any;
const existing = svc.get(accom.id, trip.id)!;
const updated = svc.update(String(accom.id), existing as any, { check_in: '16:00', notes: 'late arrival' }) as any;
expect(updated).toMatchObject({ check_in: '16:00', notes: 'late arrival' });
const reservation = testDb.prepare('SELECT metadata FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
expect(JSON.parse(reservation.metadata).check_in_time).toBe('16:00');
});
it('ACC-014 — remove() reports the partner reservation it took with it', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = svc.create(trip.id, { place_id: place.id, start_day_id: day.id, end_day_id: day.id }) as any;
const reservation = testDb.prepare('SELECT id FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
// The controller broadcasts reservation:deleted off this return value.
expect(svc.remove(String(accom.id))).toEqual({
linkedReservationId: reservation.id,
deletedBudgetItemId: null,
linkedReservationIds: [reservation.id],
deletedBudgetItemIds: [],
});
expect(svc.get(accom.id, trip.id)).toBeUndefined();
});
});
describe('trip access and edit permission', () => {
it('ACC-015 — verifyTripAccess resolves the trip from a string id and from a number', () => {
// The REST path hands over the raw :tripId param, the MCP tools the parsed number.
// Without the Number() coercion one of the two callers stops finding its trip.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(svc.verifyTripAccess(String(trip.id), user.id)).toMatchObject({ id: trip.id, user_id: user.id });
expect(svc.verifyTripAccess(trip.id, user.id)).toMatchObject({ id: trip.id, user_id: user.id });
});
it('ACC-016 — verifyTripAccess returns nothing for a user who is neither owner nor member', () => {
const { user: owner } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
expect(svc.verifyTripAccess(trip.id, stranger.id)).toBeUndefined();
});
it('ACC-017 — canEdit lets the owner through on the default day_edit level', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const access = svc.verifyTripAccess(trip.id, user.id)!;
expect(svc.canEdit(access, user as any)).toBe(true);
});
it('ACC-018 — canEdit lets a member through: it derives isMember from the trip owner id', () => {
// day_edit defaults to trip_member. canEdit passes `trip.user_id !== user.id` as the
// isMember flag, so inverting that comparison would lock every invited traveller out
// of the day plan while the owner still edits fine.
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
const access = svc.verifyTripAccess(trip.id, member.id)!;
expect(svc.canEdit(access, member as any)).toBe(true);
});
it('ACC-019 — canEdit denies a member once day_edit is raised to trip_owner', () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
const permissions = new PermissionsService(new DatabaseService(testDb));
try {
permissions.savePermissions({ day_edit: 'trip_owner' });
expect(svc.canEdit(svc.verifyTripAccess(trip.id, member.id)!, member as any)).toBe(false);
// The owner keeps the right, otherwise the setting would lock out the whole trip.
expect(svc.canEdit(svc.verifyTripAccess(trip.id, owner.id)!, owner as any)).toBe(true);
} finally {
// The permission cache is module-scoped and outlives resetTestDb — drop the row and
// the cache together, or every later case in this file inherits the raised level.
testDb.prepare("DELETE FROM app_settings WHERE key = 'perm_day_edit'").run();
permissions.invalidatePermissionsCache();
}
});
it('ACC-020 — broadcast forwards the socket id so the originating client is not echoed', () => {
// The X-Socket-Id contract: the facade must pass the id straight through as the
// fourth argument. Dropping it makes the sender apply its own change twice.
broadcast.mockClear();
svc.broadcast('5', 'accommodation:deleted', { accommodationId: 9 }, 'sock-1');
expect(broadcast).toHaveBeenCalledWith('5', 'accommodation:deleted', { accommodationId: 9 }, 'sock-1');
svc.broadcast('5', 'accommodation:updated', { accommodation: { id: 9 } }, undefined);
expect(broadcast).toHaveBeenLastCalledWith('5', 'accommodation:updated', { accommodation: { id: 9 } }, undefined);
});
});
describe('AccommodationsService wiring', () => {
it('ACC-001: the module carries the controller, the service and the RPC surface', () => {
expectRegisteredController(AccommodationsModule, AccommodationsController);
expectRegisteredProvider(AccommodationsModule, AccommodationsService);
const exports = Reflect.getMetadata('exports', AccommodationsModule) as unknown[];
expect(Array.isArray(exports)).toBe(true);
expect(exports).toEqual(expect.arrayContaining([AccommodationsService]));
});
it('ACC-002: it does not import the days or reservations modules', () => {
const imports = (Reflect.getMetadata('imports', AccommodationsModule) as { name?: string }[]) ?? [];
expect(Array.isArray(imports)).toBe(true);
const names = imports.map((m) => m?.name);
expect(names).not.toContain('DaysModule');
expect(names).not.toContain('ReservationsModule');
});
});
+117
View File
@@ -0,0 +1,117 @@
/**
* The addon route gate.
*
* Three hand-written guards (collections, airtrail, journey) did the same thing
* and differed only in the addon id they read and the word leading the 404. They
* are one guard plus a @RequireAddon decorator now.
*
* The last describe matters as much as the first: with the addon id in a
* decorator, nothing in a controller's own tests notices if the decorator is
* dropped or points at the wrong addon. These assertions are what keeps the
* three route groups gated, and gated on the right thing.
*/
import { describe, it, expect, vi } from 'vitest';
import { HttpException } from '@nestjs/common';
import type { ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { RequireAddon, REQUIRE_ADDON, type RequireAddonMeta } from '../../../src/nest/addons/require-addon.decorator';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { ADDON_IDS } from '../../../src/addons';
import { JourneyController } from '../../../src/nest/journey/journey.controller';
import { CollectionsController } from '../../../src/nest/collections/collections.controller';
import { AirtrailController } from '../../../src/nest/integrations/airtrail.controller';
import { ReservationImportController } from '../../../src/nest/reservation-import/reservation-import.controller';
/** A context whose handler/class carry the decorator under test. */
function ctxFor(handler: object, cls: object = class {}): ExecutionContext {
return {
getHandler: () => handler,
getClass: () => cls,
} as unknown as ExecutionContext;
}
function addons(enabled: boolean): AddonsService {
return { isAddonEnabled: vi.fn(() => enabled) } as unknown as AddonsService;
}
function thrown(fn: () => unknown) {
try {
fn();
return undefined;
} catch (err) {
return err instanceof HttpException ? { status: err.getStatus(), body: err.getResponse() } : err;
}
}
/** Apply @RequireAddon to a throwaway class the way a controller would. */
function decorated(addonId: string, label: string) {
class Gated {}
RequireAddon(addonId, label)(Gated);
return Gated;
}
describe('AddonGuard', () => {
it('ADDON-GUARD-001: 404s with the decorator label when the addon is disabled', () => {
const cls = decorated(ADDON_IDS.JOURNEY, 'Journey');
const guard = new AddonGuard(addons(false), new Reflector());
expect(thrown(() => guard.canActivate(ctxFor(() => {}, cls))))
.toEqual({ status: 404, body: { error: 'Journey addon is not enabled' } });
});
it('ADDON-GUARD-002: passes when the addon is enabled, asking for the declared id', () => {
const cls = decorated(ADDON_IDS.COLLECTIONS, 'Collections');
const svc = addons(true);
const guard = new AddonGuard(svc, new Reflector());
expect(guard.canActivate(ctxFor(() => {}, cls))).toBe(true);
expect(svc.isAddonEnabled).toHaveBeenCalledWith(ADDON_IDS.COLLECTIONS);
});
it('ADDON-GUARD-003: is a no-op on a route that never asked for an addon', () => {
const svc = addons(false);
const guard = new AddonGuard(svc, new Reflector());
expect(guard.canActivate(ctxFor(() => {}, class {}))).toBe(true);
expect(svc.isAddonEnabled).not.toHaveBeenCalled();
});
it('ADDON-GUARD-004: a handler-level decorator overrides the controller-level one', () => {
const cls = decorated(ADDON_IDS.JOURNEY, 'Journey');
const handler = () => {};
RequireAddon(ADDON_IDS.AIRTRAIL, 'AirTrail')(handler);
const svc = addons(false);
expect(thrown(() => new AddonGuard(svc, new Reflector()).canActivate(ctxFor(handler, cls))))
.toEqual({ status: 404, body: { error: 'AirTrail addon is not enabled' } });
expect(svc.isAddonEnabled).toHaveBeenCalledWith(ADDON_IDS.AIRTRAIL);
});
});
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) ?? [];
it.each([
['JourneyController', JourneyController, ADDON_IDS.JOURNEY, 'Journey'],
['CollectionsController', CollectionsController, ADDON_IDS.COLLECTIONS, 'Collections'],
['AirtrailController', AirtrailController, ADDON_IDS.AIRTRAIL, 'AirTrail'],
])('ADDON-GUARD-005: %s gates on the right addon, with AddonGuard first', (_name, cls, addonId, label) => {
expect(metaOf(cls)).toEqual({ addonId, label });
// Order is the contract: a disabled addon has to answer 404 to anonymous
// callers, so the addon check must run before the 401.
expect(guardsOf(cls)[0]).toBe(AddonGuard);
});
it('ADDON-GUARD-006: the merged import controller gates AirTrail per handler, not per class', () => {
// A class-level requirement here would 404 the four file-upload routes
// whenever the AirTrail addon happens to be off. AddonGuard still runs first
// in the chain, so the 404 keeps beating the 401.
expect(metaOf(ReservationImportController)).toBeUndefined();
expect(Reflect.getMetadata(REQUIRE_ADDON, ReservationImportController.prototype.importAirtrail))
.toEqual({ addonId: ADDON_IDS.AIRTRAIL, label: 'AirTrail' });
expect(guardsOf(ReservationImportController)[0]).toBe(AddonGuard);
});
});
+196 -22
View File
@@ -7,46 +7,72 @@ const { dbMock } = vi.hoisted(() => {
return { dbMock: { prepare: vi.fn(() => stmt), _stmt: stmt } };
});
vi.mock('../../../src/db/database', () => ({ db: dbMock, closeDb: () => {}, reinitialize: () => {} }));
const { getBagTracking, getCollabFeatures } = vi.hoisted(() => ({
getBagTracking: vi.fn(() => ({ enabled: false })),
getCollabFeatures: vi.fn(() => ({})),
}));
vi.mock('../../../src/services/adminService', () => ({ getBagTracking, getCollabFeatures }));
import { db as dbConn } from '../../../src/db/database';
import { DatabaseService } from '../../../src/nest/database/database.service';
const { getPhotoProviderConfig } = vi.hoisted(() => ({ getPhotoProviderConfig: vi.fn(() => ({})) }));
vi.mock('../../../src/services/memories/helpersService', () => ({ getPhotoProviderConfig }));
vi.mock('../../../src/nest/memories/memories.helpers', () => ({ getPhotoProviderConfig }));
import { AddonsService } from '../../../src/nest/addons/addons.service';
function svc() {
return new AddonsService();
return new AddonsService(new DatabaseService(dbConn));
}
// Feed the three reads in order: addons, providers, fields.
function feedReads(addons: unknown[], providers: unknown[], fields: unknown[]) {
type ListAddon = ReturnType<AddonsService['list']>['addons'][number];
type PhotoProviderField = {
key: string;
label: string;
input_type: string;
placeholder: string;
hint: string | null;
required: boolean;
secret: boolean;
settings_key: string | null;
payload_key: string | null;
sort_order: number;
};
// list() spreads plain addons and photo providers into one array, and a provider
// object structurally extends a plain one. TypeScript reduces the element union
// to the plain shape, so `config` and `fields` are invisible on res.addons even
// though the provider entries carry them at runtime. Provider assertions read
// the fields through here instead of casting at every call site.
function providerFields(addon: ListAddon): PhotoProviderField[] {
return (addon as ListAddon & { fields: PhotoProviderField[] }).fields;
}
// Feed list()'s reads in call order: addons, providers, fields (.all), then the
// collab-features rows (.all) and the bag-tracking row (.get) from app_settings.
function feedReads(
addons: unknown[],
providers: unknown[],
fields: unknown[],
collabRows: unknown[] = [],
bagRow: { value: string } | undefined = undefined,
) {
dbMock._stmt.all
.mockReturnValueOnce(addons)
.mockReturnValueOnce(providers)
.mockReturnValueOnce(fields);
.mockReturnValueOnce(fields)
.mockReturnValueOnce(collabRows);
dbMock._stmt.get.mockReturnValueOnce(bagRow);
}
beforeEach(() => {
vi.clearAllMocks();
dbMock._stmt.all.mockReturnValue([]);
getCollabFeatures.mockReturnValue({});
getBagTracking.mockReturnValue({ enabled: false });
dbMock._stmt.get.mockReturnValue(undefined);
getPhotoProviderConfig.mockReturnValue({});
});
describe('AddonsService.list', () => {
it('returns the collab features and the bag-tracking flag from the admin service', () => {
getCollabFeatures.mockReturnValue({ comments: true });
getBagTracking.mockReturnValue({ enabled: true });
feedReads([], [], []);
it('returns the collab features and the bag-tracking flag from app_settings', () => {
feedReads([], [], [], [{ key: 'collab_chat_enabled', value: 'false' }], { value: 'true' });
const res = svc().list();
expect(res.collabFeatures).toEqual({ comments: true });
expect(res.collabFeatures).toEqual({ chat: false, notes: true, polls: true, whatsnext: true });
expect(res.bagTracking).toBe(true);
expect(res.addons).toEqual([]);
});
@@ -138,8 +164,7 @@ describe('AddonsService.list', () => {
);
const res = svc().list();
const provider = res.addons[0] as { fields: Array<Record<string, unknown>> };
expect(provider.fields).toEqual([
expect(providerFields(res.addons[0])).toEqual([
{
key: 'url',
label: 'URL',
@@ -186,7 +211,7 @@ describe('AddonsService.list', () => {
);
const res = svc().list();
const field = (res.addons[0] as { fields: Array<Record<string, unknown>> }).fields[0];
const field = providerFields(res.addons[0])[0];
expect(field).toMatchObject({
placeholder: '',
hint: null,
@@ -215,7 +240,7 @@ describe('AddonsService.list', () => {
);
const res = svc().list();
expect((res.addons[0] as { fields: unknown[] }).fields).toEqual([]);
expect(providerFields(res.addons[0])).toEqual([]);
});
it('concatenates regular addons before the photo providers', () => {
@@ -230,3 +255,152 @@ describe('AddonsService.list', () => {
expect((res.addons[1] as { type: string }).type).toBe('photo_provider');
});
});
// Direct coverage of the enablement reads/writers relocated from
// services/adminService (finding `admin-1`). The polarity asymmetry is on
// purpose: bag tracking is opt-in (=== 'true'), collab flags opt-out (!== 'false').
describe('AddonsService addon/feature flags', () => {
it('isAddonEnabled coerces the enabled column (1/0/missing row)', () => {
dbMock._stmt.get.mockReturnValueOnce({ enabled: 1 });
expect(svc().isAddonEnabled('budget')).toBe(true);
dbMock._stmt.get.mockReturnValueOnce({ enabled: 0 });
expect(svc().isAddonEnabled('budget')).toBe(false);
dbMock._stmt.get.mockReturnValueOnce(undefined);
expect(svc().isAddonEnabled('nope')).toBe(false);
});
it('getBagTracking is opt-in: only the literal string true enables it', () => {
dbMock._stmt.get.mockReturnValueOnce({ value: 'true' });
expect(svc().getBagTracking()).toEqual({ enabled: true });
dbMock._stmt.get.mockReturnValueOnce({ value: 'false' });
expect(svc().getBagTracking()).toEqual({ enabled: false });
dbMock._stmt.get.mockReturnValueOnce(undefined); // absent row → OFF
expect(svc().getBagTracking()).toEqual({ enabled: false });
});
it('updateBagTracking persists true/false strings and echoes the flag (ADMIN-SVC-030)', () => {
expect(svc().updateBagTracking(true)).toEqual({ enabled: true });
expect(dbMock._stmt.run).toHaveBeenCalledWith('true');
expect(svc().updateBagTracking(false)).toEqual({ enabled: false });
expect(dbMock._stmt.run).toHaveBeenCalledWith('false');
});
it('getCollabFeatures is opt-out: absent rows default ON, only false disables', () => {
dbMock._stmt.all.mockReturnValueOnce([
{ key: 'collab_chat_enabled', value: 'false' },
{ key: 'collab_polls_enabled', value: 'true' },
]);
expect(svc().getCollabFeatures()).toEqual({ chat: false, notes: true, polls: true, whatsnext: true });
});
it('updateCollabFeatures writes only the provided flags and reports changed (#1414, ADMIN-SVC-070)', () => {
// before-read: all default ON; after-read: chat flipped off → changed
dbMock._stmt.all.mockReturnValueOnce([]).mockReturnValueOnce([{ key: 'collab_chat_enabled', value: 'false' }]);
const first = svc().updateCollabFeatures({ chat: false });
expect(first.changed).toBe(true);
expect(first.features.chat).toBe(false);
expect(dbMock._stmt.run).toHaveBeenCalledTimes(1);
expect(dbMock._stmt.run).toHaveBeenCalledWith('collab_chat_enabled', 'false');
// identical save → before and after read the same → no change, MCP sessions must survive
dbMock._stmt.run.mockClear();
dbMock._stmt.all
.mockReturnValueOnce([{ key: 'collab_chat_enabled', value: 'false' }])
.mockReturnValueOnce([{ key: 'collab_chat_enabled', value: 'false' }]);
const second = svc().updateCollabFeatures({ chat: false });
expect(second.changed).toBe(false);
expect(dbMock._stmt.run).toHaveBeenCalledWith('collab_chat_enabled', 'false');
// undefined flags are not written
dbMock._stmt.run.mockClear();
dbMock._stmt.all.mockReturnValueOnce([]).mockReturnValueOnce([]);
const third = svc().updateCollabFeatures({});
expect(third.changed).toBe(false);
expect(dbMock._stmt.run).not.toHaveBeenCalled();
});
});
/**
* The three places flags moved here from AdminService, where they were raw
* app_settings SQL sitting next to flags that already delegated to this service.
* They are fail-CLOSED (`=== 'true'`), matching getBagTracking: unset used to read as
* ON (`!== 'false'`), and a migration backfills 'true' for existing installs so
* nobody loses a feature on upgrade.
*/
describe('AddonsService places flags', () => {
beforeEach(() => {
vi.clearAllMocks();
});
const cases = [
['getPlacesPhotos', 'updatePlacesPhotos', 'places_photos_enabled'],
['getPlacesAutocomplete', 'updatePlacesAutocomplete', 'places_autocomplete_enabled'],
['getPlacesDetails', 'updatePlacesDetails', 'places_details_enabled'],
] as const;
it('ADDONS-SVC-080 an unset flag reads as OFF, and anything but the literal true does too', () => {
for (const [getter, , key] of cases) {
dbMock._stmt.get.mockReturnValueOnce(undefined);
expect(svc()[getter]()).toEqual({ enabled: false });
expect(dbMock.prepare).toHaveBeenLastCalledWith('SELECT value FROM app_settings WHERE key = ?');
expect(dbMock._stmt.get).toHaveBeenLastCalledWith(key);
dbMock._stmt.get.mockReturnValueOnce({ value: 'garbage' });
expect(svc()[getter]()).toEqual({ enabled: false });
}
});
it('ADDONS-SVC-081 a stored "true" reads as ON', () => {
for (const [getter] of cases) {
dbMock._stmt.get.mockReturnValueOnce({ value: 'true' });
expect(svc()[getter]()).toEqual({ enabled: true });
}
});
it('ADDONS-SVC-082 the setters persist the literal string and echo the boolean back', () => {
for (const [, setter, key] of cases) {
expect(svc()[setter](true)).toEqual({ enabled: true });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith(key, 'true');
expect(svc()[setter](false)).toEqual({ enabled: false });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith(key, 'false');
}
});
});
/**
* Enrichment sits beside the three above and reads the opposite way round.
*
* They are fail-closed because a migration backfilled a row for every install
* that predates the change. This one is new: there is nothing to backfill, so
* fail-open reaches the same place without a migration for one boolean. What
* matters is that it agrees with PlaceEnrichmentService.enrichDisabled(), which
* reads the same key — if the two ever diverge the panel shows "off" while the
* feature runs.
*/
describe('AddonsService places enrichment flag', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('ADDONS-SVC-083 an unset flag reads as ON', () => {
dbMock._stmt.get.mockReturnValueOnce(undefined);
expect(svc().getPlacesEnrich()).toEqual({ enabled: true });
});
it('ADDONS-SVC-084 only the literal "false" switches it off', () => {
dbMock._stmt.get.mockReturnValueOnce({ value: 'false' });
expect(svc().getPlacesEnrich()).toEqual({ enabled: false });
for (const value of ['true', 'garbage', '']) {
dbMock._stmt.get.mockReturnValueOnce({ value });
expect(svc().getPlacesEnrich()).toEqual({ enabled: true });
}
});
it('ADDONS-SVC-085 the setter persists the literal string and echoes the boolean back', () => {
expect(svc().updatePlacesEnrich(false)).toEqual({ enabled: false });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith('places_enrich_enabled', 'false');
expect(svc().updatePlacesEnrich(true)).toEqual({ enabled: true });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith('places_enrich_enabled', 'true');
});
});
@@ -0,0 +1,83 @@
/**
* The account defaults, after the two routes moved off AdminController next to
* SettingsService, which owns them. Same path, same audit action, same 400 envelope on
* a rejected write — these cases came over with the routes.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HttpException } from '@nestjs/common';
import { AdminDefaultUserSettingsController } from '../../../src/nest/settings/settings.controller';
import { SettingsModule } from '../../../src/nest/settings/settings.module';
import type { SettingsService } from '../../../src/nest/settings/settings.service';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import type { User } from '../../../src/types';
import { expectRegisteredController } from '../../helpers/module-providers';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
const user = { id: 1, role: 'admin' } as User;
const req = { headers: {}, socket: {} } as never;
const writeAudit = vi.fn();
function controller(over: Partial<SettingsService> = {}) {
const settings = {
getAdminUserDefaults: vi.fn(() => ({ theme: 'dark' })),
setAdminUserDefaults: vi.fn(),
...over,
} as unknown as SettingsService;
return { c: new AdminDefaultUserSettingsController(settings, { writeAudit } as unknown as AuditService, { isManaged: () => false } as unknown as RuntimeEnvService), settings };
}
const thrown = (run: () => unknown) => {
try {
run();
return null;
} catch (e) {
return e instanceof HttpException ? { status: e.getStatus(), body: e.getResponse() } : e;
}
};
describe('AdminDefaultUserSettingsController', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('DEFAULTS-001 GET returns the stored defaults verbatim', () => {
expect(controller().c.get()).toEqual({ theme: 'dark' });
});
it('DEFAULTS-002 PUT writes, audits, and answers with the STORED defaults', () => {
const { c, settings } = controller();
// Not the request body: the service normalises and drops unknown keys, and the
// admin panel renders straight from this response.
expect(c.update(user, { theme: 'light' } as never, req)).toEqual({ theme: 'dark' });
expect(settings.setAdminUserDefaults).toHaveBeenCalledWith({ theme: 'light' });
expect(writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ userId: 1, action: 'admin.default_user_settings_update', details: { theme: 'light' } }),
);
});
it('DEFAULTS-003 a rejected write is a 400 carrying the message, and is not audited', () => {
const { c } = controller({
setAdminUserDefaults: vi.fn(() => {
throw new Error('unknown setting: nope');
}),
} as Partial<SettingsService>);
expect(thrown(() => c.update(user, { nope: 1 } as never, req))).toEqual({
status: 400,
body: { error: 'unknown setting: nope' },
});
expect(writeAudit).not.toHaveBeenCalled();
});
it('DEFAULTS-004 a non-Error throw is stringified rather than swallowed', () => {
const { c } = controller({
setAdminUserDefaults: vi.fn(() => {
throw 'plain string';
}),
} as Partial<SettingsService>);
expect(thrown(() => c.update(user, {} as never, req))).toEqual({ status: 400, body: { error: 'plain string' } });
});
it('DEFAULTS-005 the class is listed in its module controllers', () => {
expectRegisteredController(SettingsModule, AdminDefaultUserSettingsController);
});
});
+91
View File
@@ -0,0 +1,91 @@
/**
* The admin domain's cron providers — VersionCheckJob and DemoResetJob
* (moved from src/scheduler.ts). Registration, gating, and tick error
* containment; the version-check end-to-end path is VCJOB-001 in
* admin.service.test.ts.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
const logMock = vi.hoisted(() => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
const { resetDemoUserMock } = vi.hoisted(() => ({ resetDemoUserMock: vi.fn() }));
vi.mock('../../../src/nest/audit/audit-log.logger', () => logMock);
vi.mock('../../../src/demo/demo-reset', () => ({ resetDemoUser: resetDemoUserMock, saveBaseline: vi.fn(), hasBaseline: vi.fn() }));
import { VersionCheckJob } from '../../../src/nest/admin/version-check.job';
import { DemoResetJob } from '../../../src/nest/admin/demo-reset.job';
import type { AdminService } from '../../../src/nest/admin/admin.service';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import type { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';
function registrarStub(enabled = true) {
return {
isEnabled: vi.fn(() => enabled),
register: vi.fn(() => enabled),
unregister: vi.fn(),
};
}
beforeEach(() => vi.clearAllMocks());
describe('VersionCheckJob', () => {
it('AJOB-001 — registers the daily 9 AM cron, with no boot log (parity)', () => {
const registrar = registrarStub();
new VersionCheckJob({} as AdminService, registrar as unknown as CronRegistrarService, { isManaged: () => false } as unknown as RuntimeEnvService).onApplicationBootstrap();
expect(registrar.register).toHaveBeenCalledWith('version-check', '0 9 * * *', expect.any(Function));
expect(logMock.logInfo).not.toHaveBeenCalled();
});
it('AJOB-002 — does not register under the test gate', () => {
const registrar = registrarStub(false);
new VersionCheckJob({} as AdminService, registrar as unknown as CronRegistrarService, { isManaged: () => false } as unknown as RuntimeEnvService).onApplicationBootstrap();
expect(registrar.register).not.toHaveBeenCalled();
});
it('AJOB-003 — a throwing check is contained to the Version check log line', async () => {
const admin = { checkAndNotifyVersion: vi.fn().mockRejectedValue(new Error('github down')) } as unknown as AdminService;
const job = new VersionCheckJob(
admin,
registrarStub() as unknown as CronRegistrarService,
{ isManaged: () => false } as unknown as RuntimeEnvService,
);
await expect(job.tick()).resolves.toBeUndefined();
expect(logMock.logError).toHaveBeenCalledWith('Version check: github down');
});
});
describe('DemoResetJob', () => {
function make(demo: boolean, enabled = true) {
const registrar = registrarStub(enabled);
const runtimeEnv = { isDemoMode: () => demo } as RuntimeEnvService;
return { job: new DemoResetJob(runtimeEnv, registrar as unknown as CronRegistrarService), registrar };
}
it('AJOB-004 — registers the hourly server-local cron and logs the banner when demo mode is on', () => {
const { job, registrar } = make(true);
job.onApplicationBootstrap();
expect(registrar.register).toHaveBeenCalledWith('demo-reset', '0 * * * *', expect.any(Function), { timezone: 'none' });
expect(logMock.logInfo).toHaveBeenCalledWith('Demo hourly reset scheduled');
});
it('AJOB-005 — stays silent when demo mode is off or the gate is closed', () => {
const off = make(false);
off.job.onApplicationBootstrap();
expect(off.registrar.register).not.toHaveBeenCalled();
const gated = make(true, false);
gated.job.onApplicationBootstrap();
expect(gated.registrar.register).not.toHaveBeenCalled();
expect(logMock.logInfo).not.toHaveBeenCalled();
});
it('AJOB-006 — the tick runs resetDemoUser and contains a throw to the Demo reset log line', () => {
const { job } = make(true);
job.tick();
expect(resetDemoUserMock).toHaveBeenCalledTimes(1);
resetDemoUserMock.mockImplementation(() => { throw new Error('baseline gone'); });
expect(() => job.tick()).not.toThrow();
expect(logMock.logError).toHaveBeenCalledWith('Demo reset: baseline gone');
});
});
@@ -0,0 +1,52 @@
/**
* The admin-scope preference matrix, after the two routes moved off AdminController
* next to NotificationPreferencesService, which owns it. The 'admin' scope argument
* they always passed is now written once, at the only place that uses it.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { AdminNotificationPreferencesController } from '../../../src/nest/notifications/notifications.controller';
import { NotificationsModule } from '../../../src/nest/notifications/notifications.module';
import type { NotificationPreferencesService } from '../../../src/nest/notifications/notification-preferences.service';
import type { User } from '../../../src/types';
import { expectRegisteredController } from '../../helpers/module-providers';
const admin = { id: 1, role: 'admin' } as User;
function controller() {
const prefs = {
getPreferencesMatrix: vi.fn(() => ({ rows: [{ event: 'trip_reminder' }] })),
setAdminPreferences: vi.fn(),
} as unknown as NotificationPreferencesService;
return { c: new AdminNotificationPreferencesController(prefs), prefs };
}
describe('AdminNotificationPreferencesController', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('ADMINPREF-001 GET asks for the admin scope, not the user one', () => {
const { c, prefs } = controller();
expect(c.get(admin)).toEqual({ rows: [{ event: 'trip_reminder' }] });
expect(prefs.getPreferencesMatrix).toHaveBeenCalledWith(1, 'admin', 'admin');
});
it('ADMINPREF-002 PUT persists, then answers with the REFRESHED matrix', () => {
const { c, prefs } = controller();
// The admin panel renders straight from this response, so returning the write
// result instead of a fresh read would leave it showing stale rows.
expect(c.set(admin, { trip_reminder: { email: true } } as never)).toEqual({ rows: [{ event: 'trip_reminder' }] });
expect(prefs.setAdminPreferences).toHaveBeenCalledWith(1, { trip_reminder: { email: true } });
expect(prefs.getPreferencesMatrix).toHaveBeenCalledWith(1, 'admin', 'admin');
});
it('ADMINPREF-003 the acting user drives the lookup, never a body field', () => {
const { c, prefs } = controller();
c.get({ id: 7, role: 'admin' } as User);
expect(prefs.getPreferencesMatrix).toHaveBeenCalledWith(7, 'admin', 'admin');
});
it('ADMINPREF-004 the class is listed in its module controllers', () => {
expectRegisteredController(NotificationsModule, AdminNotificationPreferencesController);
});
});
@@ -0,0 +1,118 @@
/**
* The admin packing-template CRUD, after it moved off AdminController into the packing
* domain that owns the three template tables. Same paths, same {error,status}
* envelope, same create-201 split, same audit actions — these cases came over from
* admin.controller.test.ts with the routes.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HttpException } from '@nestjs/common';
import { AdminPackingTemplatesController } from '../../../src/nest/packing/admin-packing-templates.controller';
import { PackingModule } from '../../../src/nest/packing/packing.module';
import type { PackingService } from '../../../src/nest/packing/packing.service';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import type { User } from '../../../src/types';
import { expectRegisteredController } from '../../helpers/module-providers';
const user = { id: 1, role: 'admin' } as User;
const req = { headers: {}, socket: {} } as never;
const writeAudit = vi.fn();
function controller(over: Partial<PackingService> = {}) {
const packing = {
listPackingTemplates: vi.fn(() => [{ id: 1 }]),
getPackingTemplate: vi.fn(() => ({ template: { id: 1 } })),
createPackingTemplate: vi.fn(() => ({ template: { id: 9 } })),
updatePackingTemplate: vi.fn(() => ({ template: { id: 1 } })),
deletePackingTemplate: vi.fn(() => ({ name: 'Beach' })),
createTemplateCategory: vi.fn(() => ({ category: { id: 2 } })),
updateTemplateCategory: vi.fn(() => ({ category: { id: 2 } })),
deleteTemplateCategory: vi.fn(() => ({ ok: true })),
createTemplateItem: vi.fn(() => ({ item: { id: 3 } })),
updateTemplateItem: vi.fn(() => ({ item: { id: 3 } })),
deleteTemplateItem: vi.fn(() => ({ ok: true })),
...over,
} as unknown as PackingService;
return { c: new AdminPackingTemplatesController(packing, { writeAudit } as unknown as AuditService), packing };
}
/**
* An override whose return value the real method signature cannot produce. Every error
* branch in PackingService sets a status, so an error envelope without one is not part
* of the service's return type, yet the controller still has a fallback for it and
* PACKTPL-003 is the case that covers that fallback.
*/
function offContract<K extends keyof PackingService>(name: K, impl: () => unknown) {
return { [name]: vi.fn(impl) } as unknown as Partial<PackingService>;
}
const thrown = (run: () => unknown) => {
try {
run();
return null;
} catch (e) {
return e instanceof HttpException ? { status: e.getStatus(), body: e.getResponse() } : e;
}
};
describe('AdminPackingTemplatesController', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('PACKTPL-001 list wraps the service result in the { templates } envelope', () => {
expect(controller().c.list()).toEqual({ templates: [{ id: 1 }] });
});
it('PACKTPL-002 a service {error,status} becomes that HTTP status, not a 200 body', () => {
const { c } = controller({ getPackingTemplate: vi.fn(() => ({ error: 'not found', status: 404 })) });
expect(thrown(() => c.get('9'))).toEqual({ status: 404, body: { error: 'not found' } });
});
it('PACKTPL-003 an error without a status defaults to 400', () => {
const { c } = controller(offContract('createTemplateCategory', () => ({ error: 'name required' })));
expect(thrown(() => c.createCategory('1', { name: '' }))).toEqual({ status: 400, body: { error: 'name required' } });
});
it('PACKTPL-004 create audits with the new template id', () => {
const { c, packing } = controller();
expect(c.create(user, { name: 'Beach' }, req)).toEqual({ template: { id: 9 } });
expect(packing.createPackingTemplate).toHaveBeenCalledWith('Beach', 1);
expect(writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ action: 'admin.packing_template_create', resource: '9', details: { name: 'Beach' } }),
);
});
it('PACKTPL-005 delete audits the removed name and answers { success: true }', () => {
const { c } = controller();
expect(c.remove(user, '1', req)).toEqual({ success: true });
expect(writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ action: 'admin.packing_template_delete', resource: '1', details: { name: 'Beach' } }),
);
});
it('PACKTPL-006 the nested category and item routes forward their ids in order', () => {
const { c, packing } = controller();
c.createCategory('1', { name: 'Clothes' });
expect(packing.createTemplateCategory).toHaveBeenCalledWith('1', 'Clothes');
c.updateCategory('1', '2', { name: 'Warm' });
expect(packing.updateTemplateCategory).toHaveBeenCalledWith('1', '2', { name: 'Warm' });
expect(c.deleteCategory('1', '2')).toEqual({ success: true });
c.createItem('1', '2', { name: 'Socks' });
expect(packing.createTemplateItem).toHaveBeenCalledWith('1', '2', 'Socks');
c.updateItem('1', '3', { name: 'Wool socks' });
expect(packing.updateTemplateItem).toHaveBeenCalledWith('1', '3', { name: 'Wool socks' });
expect(c.deleteItem('1', '3')).toEqual({ success: true });
});
it('PACKTPL-007 the delete routes answer { success: true } rather than the service payload', () => {
// The client branches on `success`; leaking the raw service result here would be a
// silent shape change for every caller.
const { c } = controller();
expect(c.deleteCategory('1', '2')).toEqual({ success: true });
expect(c.deleteItem('1', '3')).toEqual({ success: true });
});
it('PACKTPL-008 the class is listed in its module controllers', () => {
expectRegisteredController(PackingModule, AdminPackingTemplatesController);
});
});
+134 -144
View File
@@ -2,14 +2,18 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { HttpException, NotFoundException } from '@nestjs/common';
import type { Request } from 'express';
vi.mock('../../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: vi.fn(() => '1.2.3.4'), logInfo: vi.fn() }));
vi.mock('../../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
vi.mock('../../../src/nest/audit/client-ip', () => ({ getClientIp: vi.fn(() => '1.2.3.4') }));
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logDebug: vi.fn(), logError: vi.fn(), logWarn: vi.fn() }));
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { AdminController } from '../../../src/nest/admin/admin.controller';
import type { TokenService } from '../../../src/nest/tokens/token.service';
import type { RegistrationInvitesService } from '../../../src/nest/auth/registration-invites.service';
import type { OauthService } from '../../../src/nest/oauth/oauth.service';
import type { AdminService } from '../../../src/nest/admin/admin.service';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import { writeAudit } from '../../../src/services/auditLog';
import { send as sendNotification } from '../../../src/services/notificationService';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import type { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import type { User } from '../../../src/types';
const user = { id: 1, role: 'admin', email: 'admin@example.test' } as User;
@@ -18,6 +22,36 @@ const req = { headers: {} } as Request;
function svc(o: Partial<AdminService> = {}): AdminService {
return { invalidateMcpSessions: vi.fn(), ...o } as unknown as AdminService;
}
// AuditService is constructor-injected since the auditLog DI migration; the
// wrapper keeps the historical construction sites positional.
const writeAudit = vi.fn();
const audit = { writeAudit } as unknown as AuditService;
// Notifications are a constructor-injected stub since the notifications fold
// (same behavior as the old services/notificationService path mock).
const sendNotification = vi.fn().mockResolvedValue(undefined);
const notifications = { send: sendNotification } as unknown as NotificationsService;
/** The flags live on AddonsService now; the toggle routes reach it directly. */
const addonsStub = () => ({
getBagTracking: vi.fn(() => ({ enabled: false })),
updateBagTracking: vi.fn((enabled: boolean) => ({ enabled })),
getPlacesPhotos: vi.fn(() => ({ enabled: false })),
updatePlacesPhotos: vi.fn((enabled: boolean) => ({ enabled })),
getPlacesAutocomplete: vi.fn(() => ({ enabled: false })),
updatePlacesAutocomplete: vi.fn((enabled: boolean) => ({ enabled })),
getPlacesDetails: vi.fn(() => ({ enabled: false })),
updatePlacesDetails: vi.fn((enabled: boolean) => ({ enabled })),
// Fail-open, unlike its three neighbours — see AddonsService.getPlacesEnrich.
getPlacesEnrich: vi.fn(() => ({ enabled: true })),
updatePlacesEnrich: vi.fn((enabled: boolean) => ({ enabled })),
getCollabFeatures: vi.fn(() => ({ chat: false })),
updateCollabFeatures: vi.fn(() => ({ features: { chat: true }, changed: true })),
}) as unknown as AddonsService;
// The MCP-token routes read TokenService now, not AdminService. Stubbed via a
// fourth, optional argument so every existing call site stays as it was.
const adminCtl = (s: AdminService, rt?: PluginRuntimeService, addons: AddonsService = addonsStub(), tokens: Partial<TokenService> = {}, invites: Partial<RegistrationInvitesService> = {}, oauth: Partial<OauthService> = {}) =>
new AdminController(s, addons, rt as unknown as PluginRuntimeService, audit, notifications, tokens as TokenService, invites as RegistrationInvitesService, oauth as OauthService);
function thrown(fn: () => unknown): { status: number; body: unknown } {
try { fn(); } catch (err) {
if (err instanceof NotFoundException) return { status: 404, body: err.getResponse() };
@@ -33,162 +67,108 @@ afterEach(() => { delete process.env.NODE_ENV; });
describe('AdminController users', () => {
it('lists, creates (201 + audit), maps an error', () => {
expect(new AdminController(svc({ listUsers: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listUsers()).toEqual({ users: [{ id: 1 }] });
expect(thrown(() => new AdminController(svc({ createUser: vi.fn().mockReturnValue({ error: 'Email taken', status: 409 }) } as Partial<AdminService>)).createUser(user, {}, req))).toEqual({ status: 409, body: { error: 'Email taken' } });
const c = new AdminController(svc({ createUser: vi.fn().mockReturnValue({ user: { id: 2 }, insertedId: 2, auditDetails: {} }) } as Partial<AdminService>));
expect(adminCtl(svc({ listUsers: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listUsers()).toEqual({ users: [{ id: 1 }] });
expect(thrown(() => adminCtl(svc({ createUser: vi.fn().mockReturnValue({ error: 'Email taken', status: 409 }) } as Partial<AdminService>)).createUser(user, {}, req))).toEqual({ status: 409, body: { error: 'Email taken' } });
const c = adminCtl(svc({ createUser: vi.fn().mockReturnValue({ user: { id: 2 }, insertedId: 2, auditDetails: {} }) } as Partial<AdminService>));
expect(c.createUser(user, { email: 'a@b.c' }, req)).toEqual({ user: { id: 2 } });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'admin.user_create' }));
});
it('update + delete audit and map errors', () => {
expect(new AdminController(svc({ updateUser: vi.fn().mockReturnValue({ user: { id: 2 }, previousEmail: 'a@b.c', changed: ['role'] }) } as Partial<AdminService>)).updateUser(user, '2', {}, req)).toEqual({ user: { id: 2 } });
expect(thrown(() => new AdminController(svc({ deleteUser: vi.fn().mockReturnValue({ error: 'Cannot delete self', status: 400 }) } as Partial<AdminService>)).deleteUser(user, '1', req))).toEqual({ status: 400, body: { error: 'Cannot delete self' } });
expect(new AdminController(svc({ deleteUser: vi.fn().mockReturnValue({ email: 'a@b.c' }) } as Partial<AdminService>)).deleteUser(user, '2', req)).toEqual({ success: true });
expect(adminCtl(svc({ updateUser: vi.fn().mockReturnValue({ user: { id: 2 }, previousEmail: 'a@b.c', changed: ['role'] }) } as Partial<AdminService>)).updateUser(user, '2', {}, req)).toEqual({ user: { id: 2 } });
expect(thrown(() => adminCtl(svc({ deleteUser: vi.fn().mockReturnValue({ error: 'Cannot delete self', status: 400 }) } as Partial<AdminService>)).deleteUser(user, '1', req))).toEqual({ status: 400, body: { error: 'Cannot delete self' } });
expect(adminCtl(svc({ deleteUser: vi.fn().mockReturnValue({ email: 'a@b.c' }) } as Partial<AdminService>)).deleteUser(user, '2', req)).toEqual({ success: true });
});
});
describe('AdminController permissions + oidc + misc', () => {
it('permissions: 400 without an object, else saves + audits', () => {
expect(thrown(() => new AdminController(svc()).savePermissions(user, {}, req))).toEqual({ status: 400, body: { error: 'permissions object required' } });
const c = new AdminController(svc({ savePermissions: vi.fn().mockReturnValue({ permissions: { x: 1 }, skipped: [] }) } as Partial<AdminService>));
it('permissions: saves + audits', () => {
const c = adminCtl(svc({ savePermissions: vi.fn().mockReturnValue({ permissions: { x: 1 }, skipped: [] }) } as Partial<AdminService>));
expect(c.savePermissions(user, { permissions: { x: 1 } }, req)).toEqual({ success: true, permissions: { x: 1 } });
});
it('permissions: includes skipped when present', () => {
const c = new AdminController(svc({ savePermissions: vi.fn().mockReturnValue({ permissions: {}, skipped: ['bad'] }) } as Partial<AdminService>));
const c = adminCtl(svc({ savePermissions: vi.fn().mockReturnValue({ permissions: {}, skipped: ['bad'] }) } as Partial<AdminService>));
expect(c.savePermissions(user, { permissions: {} }, req)).toEqual({ success: true, permissions: {}, skipped: ['bad'] });
});
it('oidc update maps error, else audits', () => {
expect(thrown(() => new AdminController(svc({ updateOidcSettings: vi.fn().mockReturnValue({ error: 'bad issuer', status: 400 }) } as Partial<AdminService>)).updateOidc(user, {}, req))).toEqual({ status: 400, body: { error: 'bad issuer' } });
expect(new AdminController(svc({ updateOidcSettings: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).updateOidc(user, { issuer: 'https://idp' }, req)).toEqual({ success: true });
});
it('save-demo-baseline maps error, else returns message', () => {
expect(thrown(() => new AdminController(svc({ saveDemoBaseline: vi.fn().mockReturnValue({ error: 'not demo', status: 400 }) } as Partial<AdminService>)).saveDemoBaseline(user, req))).toEqual({ status: 400, body: { error: 'not demo' } });
expect(new AdminController(svc({ saveDemoBaseline: vi.fn().mockReturnValue({ message: 'saved' }) } as Partial<AdminService>)).saveDemoBaseline(user, req)).toEqual({ success: true, message: 'saved' });
expect(thrown(() => adminCtl(svc({ saveDemoBaseline: vi.fn().mockReturnValue({ error: 'not demo', status: 400 }) } as Partial<AdminService>)).saveDemoBaseline(user, req))).toEqual({ status: 400, body: { error: 'not demo' } });
expect(adminCtl(svc({ saveDemoBaseline: vi.fn().mockReturnValue({ message: 'saved' }) } as Partial<AdminService>)).saveDemoBaseline(user, req)).toEqual({ success: true, message: 'saved' });
});
});
describe('AdminController invites + feature toggles', () => {
// The feature toggles and the packing-template CRUD moved to the addons and packing
// domains; their cases live in admin-feature-toggles.controller.test.ts and
// admin-packing-templates.controller.test.ts.
describe('AdminController invites', () => {
it('invites: create 201 + audit, delete maps error', () => {
const c = new AdminController(svc({ createInvite: vi.fn().mockReturnValue({ invite: { id: 5 }, inviteId: 5, uses: 1, expiresInDays: 7 }) } as Partial<AdminService>));
const c = adminCtl(svc(), undefined, undefined, {}, { createInvite: vi.fn().mockReturnValue({ invite: { id: 5 }, inviteId: 5, uses: 1, expiresInDays: 7 }) });
expect(c.createInvite(user, {}, req)).toEqual({ invite: { id: 5 } });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'admin.invite_create' }));
expect(thrown(() => new AdminController(svc({ deleteInvite: vi.fn().mockReturnValue({ error: 'not found', status: 404 }) } as Partial<AdminService>)).deleteInvite(user, '5', req))).toEqual({ status: 404, body: { error: 'not found' } });
expect(thrown(() => adminCtl(svc(), undefined, undefined, {}, { deleteInvite: vi.fn().mockReturnValue({ error: 'not found', status: 404 }) }).deleteInvite(user, '5', req))).toEqual({ status: 404, body: { error: 'not found' } });
});
it('places-photos: 400 on a non-boolean, else updates + audits', () => {
expect(thrown(() => new AdminController(svc()).updatePlacesPhotos(user, { enabled: 'yes' }, req))).toEqual({ status: 400, body: { error: 'enabled must be a boolean' } });
expect(new AdminController(svc({ updatePlacesPhotos: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>)).updatePlacesPhotos(user, { enabled: true }, req)).toEqual({ enabled: true });
});
it('collab-features update invalidates MCP sessions only when a flag actually flipped (#1414)', () => {
const invalidateMcpSessions = vi.fn();
const c = new AdminController(svc({ updateCollabFeatures: vi.fn().mockReturnValue({ features: { chat: true }, changed: true }), invalidateMcpSessions } as Partial<AdminService>));
expect(c.updateCollabFeatures(user, { chat: true }, req)).toEqual({ chat: true });
expect(invalidateMcpSessions).toHaveBeenCalled();
const noopInvalidate = vi.fn();
const noop = new AdminController(svc({ updateCollabFeatures: vi.fn().mockReturnValue({ features: { chat: true }, changed: false }), invalidateMcpSessions: noopInvalidate } as Partial<AdminService>));
expect(noop.updateCollabFeatures(user, { chat: true }, req)).toEqual({ chat: true });
expect(noopInvalidate).not.toHaveBeenCalled();
});
});
describe('AdminController packing templates', () => {
it('get 404, create 201, delete audits', () => {
expect(thrown(() => new AdminController(svc({ getPackingTemplate: vi.fn().mockReturnValue({ error: 'not found', status: 404 }) } as Partial<AdminService>)).getPackingTemplate('9'))).toEqual({ status: 404, body: { error: 'not found' } });
expect(new AdminController(svc({ createPackingTemplate: vi.fn().mockReturnValue({ id: 3, name: 'Beach' }) } as Partial<AdminService>)).createPackingTemplate(user, { name: 'Beach' })).toEqual({ id: 3, name: 'Beach' });
expect(new AdminController(svc({ deletePackingTemplate: vi.fn().mockReturnValue({ name: 'Beach' }) } as Partial<AdminService>)).deletePackingTemplate(user, '3', req)).toEqual({ success: true });
expect(new AdminController(svc({ createTemplateItem: vi.fn().mockReturnValue({ id: 7 }) } as Partial<AdminService>)).createTemplateItem('3', '4', { name: 'Towel' })).toEqual({ id: 7 });
});
});
describe('AdminController addons + sessions + jwt + defaults', () => {
it('addon update audits + invalidates MCP sessions only when the MCP surface changed (#1414)', async () => {
const invalidateMcpSessions = vi.fn();
const runtime = { deactivateForDisabledAddon: vi.fn() } as unknown as PluginRuntimeService;
const c = new AdminController(svc({ updateAddon: vi.fn().mockReturnValue({ addon: { id: 'mcp', enabled: true }, mcpAffected: true, auditDetails: {} }), invalidateMcpSessions } as Partial<AdminService>), runtime);
const c = adminCtl(svc({ updateAddon: vi.fn().mockReturnValue({ addon: { id: 'mcp', enabled: true }, mcpAffected: true, auditDetails: {} }), invalidateMcpSessions } as Partial<AdminService>), runtime);
expect(await c.updateAddon(user, 'mcp', { enabled: true }, req)).toEqual({ addon: { id: 'mcp', enabled: true } });
expect(invalidateMcpSessions).toHaveBeenCalled();
expect(runtime.deactivateForDisabledAddon).not.toHaveBeenCalled();
// Config-only saves / MCP-irrelevant addons keep live sessions alive.
const noopInvalidate = vi.fn();
const noop = new AdminController(svc({ updateAddon: vi.fn().mockReturnValue({ addon: { id: 'llm_parsing', enabled: true }, mcpAffected: false, auditDetails: {} }), invalidateMcpSessions: noopInvalidate } as Partial<AdminService>), runtime);
const noop = adminCtl(svc({ updateAddon: vi.fn().mockReturnValue({ addon: { id: 'llm_parsing', enabled: true }, mcpAffected: false, auditDetails: {} }), invalidateMcpSessions: noopInvalidate } as Partial<AdminService>), runtime);
expect(await noop.updateAddon(user, 'llm_parsing', { config: { model: 'x' } }, req)).toEqual({ addon: { id: 'llm_parsing', enabled: true } });
expect(noopInvalidate).not.toHaveBeenCalled();
// Disabling an addon cascades to the plugin runtime.
const runtime2 = { deactivateForDisabledAddon: vi.fn().mockResolvedValue(['p1']) } as unknown as PluginRuntimeService;
const disable = new AdminController(svc({ updateAddon: vi.fn().mockReturnValue({ addon: { id: 'budget', enabled: false }, mcpAffected: true, auditDetails: {} }), invalidateMcpSessions: vi.fn() } as Partial<AdminService>), runtime2);
const disable = adminCtl(svc({ updateAddon: vi.fn().mockReturnValue({ addon: { id: 'budget', enabled: false }, mcpAffected: true, auditDetails: {} }), invalidateMcpSessions: vi.fn() } as Partial<AdminService>), runtime2);
await disable.updateAddon(user, 'budget', { enabled: false }, req);
expect(runtime2.deactivateForDisabledAddon).toHaveBeenCalledWith('budget');
});
it('oauth-sessions revoke audits; rotate-jwt maps error', () => {
expect(new AdminController(svc({ revokeOAuthSession: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).revokeOAuthSession(user, '3', req)).toEqual({ success: true });
expect(thrown(() => new AdminController(svc({ rotateJwtSecret: vi.fn().mockReturnValue({ error: 'locked', status: 409 }) } as Partial<AdminService>)).rotateJwtSecret(user, req))).toEqual({ status: 409, body: { error: 'locked' } });
expect(new AdminController(svc({ rotateJwtSecret: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).rotateJwtSecret(user, req)).toEqual({ success: true });
expect(adminCtl(svc(), undefined, undefined, {}, {}, { adminRevokeOAuthSession: vi.fn().mockReturnValue({}) }).revokeOAuthSession(user, '3', req)).toEqual({ success: true });
expect(thrown(() => adminCtl(svc({ rotateJwtSecret: vi.fn().mockReturnValue({ error: 'locked', status: 409 }) } as Partial<AdminService>)).rotateJwtSecret(user, req))).toEqual({ status: 409, body: { error: 'locked' } });
expect(adminCtl(svc({ rotateJwtSecret: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).rotateJwtSecret(user, req)).toEqual({ success: true });
});
it('default-user-settings: 400 on a non-object, else sets + audits', () => {
expect(thrown(() => new AdminController(svc()).setDefaultUserSettings(user, [], req))).toEqual({ status: 400, body: { error: 'Object body required' } });
const setAdminUserDefaults = vi.fn();
const c = new AdminController(svc({ setAdminUserDefaults, getAdminUserDefaults: vi.fn().mockReturnValue({ theme: 'dark' }) } as Partial<AdminService>));
expect(c.setDefaultUserSettings(user, { theme: 'dark' }, req)).toEqual({ theme: 'dark' });
expect(setAdminUserDefaults).toHaveBeenCalled();
});
});
describe('AdminController error envelope fallbacks', () => {
it('ok() defaults to 400 when the error envelope omits a status', () => {
expect(thrown(() => new AdminController(svc({ createUser: vi.fn().mockReturnValue({ error: 'boom' }) } as Partial<AdminService>)).createUser(user, {}, req))).toEqual({ status: 400, body: { error: 'boom' } });
expect(thrown(() => adminCtl(svc({ createUser: vi.fn().mockReturnValue({ error: 'boom' }) } as Partial<AdminService>)).createUser(user, {}, req))).toEqual({ status: 400, body: { error: 'boom' } });
});
it('updateOidc defaults to 400 when the service error omits a status', () => {
expect(thrown(() => new AdminController(svc({ updateOidcSettings: vi.fn().mockReturnValue({ error: 'nope' }) } as Partial<AdminService>)).updateOidc(user, {}, req))).toEqual({ status: 400, body: { error: 'nope' } });
});
it('updateOidc audits issuer_set=false when no issuer is supplied', () => {
expect(new AdminController(svc({ updateOidcSettings: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).updateOidc(user, {}, req)).toEqual({ success: true });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'admin.oidc_update', details: { issuer_set: false } }));
});
});
describe('AdminController read-only getters', () => {
it('return service values verbatim', () => {
expect(new AdminController(svc({ resetUserPasskeys: vi.fn().mockReturnValue({ email: 'a@b.c', deleted: 2 }) } as Partial<AdminService>)).resetUserPasskeys(user, '4', req)).toEqual({ success: true, deleted: 2 });
expect(new AdminController(svc({ getStats: vi.fn().mockReturnValue({ users: 3 }) } as Partial<AdminService>)).stats()).toEqual({ users: 3 });
expect(new AdminController(svc({ getPermissions: vi.fn().mockReturnValue({ a: 1 }) } as Partial<AdminService>)).permissions()).toEqual({ a: 1 });
expect(new AdminController(svc({ getAuditLog: vi.fn().mockReturnValue({ entries: [] }) } as Partial<AdminService>)).auditLog({})).toEqual({ entries: [] });
expect(new AdminController(svc({ getOidcSettings: vi.fn().mockReturnValue({ issuer: 'x' }) } as Partial<AdminService>)).getOidc()).toEqual({ issuer: 'x' });
expect(new AdminController(svc({ checkVersion: vi.fn().mockResolvedValue({ current: '1' }) } as Partial<AdminService>)).versionCheck()).resolves.toEqual({ current: '1' });
expect(new AdminController(svc({ getPreferencesMatrix: vi.fn().mockReturnValue({ rows: [] }) } as Partial<AdminService>)).getNotificationPrefs(user)).toEqual({ rows: [] });
expect(new AdminController(svc({ listInvites: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listInvites()).toEqual({ invites: [{ id: 1 }] });
expect(new AdminController(svc({ getBagTracking: vi.fn().mockReturnValue({ enabled: false }) } as Partial<AdminService>)).getBagTracking()).toEqual({ enabled: false });
expect(new AdminController(svc({ getPlacesPhotos: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>)).getPlacesPhotos()).toEqual({ enabled: true });
expect(new AdminController(svc({ getPlacesAutocomplete: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>)).getPlacesAutocomplete()).toEqual({ enabled: true });
expect(new AdminController(svc({ getPlacesDetails: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>)).getPlacesDetails()).toEqual({ enabled: true });
expect(new AdminController(svc({ getCollabFeatures: vi.fn().mockReturnValue({ chat: false }) } as Partial<AdminService>)).getCollabFeatures()).toEqual({ chat: false });
expect(new AdminController(svc({ listPackingTemplates: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listPackingTemplates()).toEqual({ templates: [{ id: 1 }] });
expect(new AdminController(svc({ listAddons: vi.fn().mockReturnValue([{ id: 'mcp' }]) } as Partial<AdminService>)).listAddons()).toEqual({ addons: [{ id: 'mcp' }] });
expect(new AdminController(svc({ listMcpTokens: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listMcpTokens()).toEqual({ tokens: [{ id: 1 }] });
expect(new AdminController(svc({ listOAuthSessions: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listOAuthSessions()).toEqual({ sessions: [{ id: 1 }] });
expect(new AdminController(svc({ getAdminUserDefaults: vi.fn().mockReturnValue({ theme: 'dark' }) } as Partial<AdminService>)).getDefaultUserSettings()).toEqual({ theme: 'dark' });
it('return service values verbatim', async () => {
expect(adminCtl(svc({ resetUserPasskeys: vi.fn().mockReturnValue({ email: 'a@b.c', deleted: 2 }) } as Partial<AdminService>)).resetUserPasskeys(user, '4', req)).toEqual({ success: true, deleted: 2 });
expect(adminCtl(svc({ getStats: vi.fn().mockReturnValue({ users: 3 }) } as Partial<AdminService>)).stats()).toEqual({ users: 3 });
expect(adminCtl(svc({ getPermissions: vi.fn().mockReturnValue({ a: 1 }) } as Partial<AdminService>)).permissions()).toEqual({ a: 1 });
expect(adminCtl(svc({ getAuditLog: vi.fn().mockReturnValue({ entries: [] }) } as Partial<AdminService>)).auditLog({})).toEqual({ entries: [] });
await expect(adminCtl(svc({ checkVersion: vi.fn().mockResolvedValue({ current: '1' }) } as Partial<AdminService>)).versionCheck()).resolves.toEqual({ current: '1' });
expect(adminCtl(svc(), undefined, undefined, {}, { listInvites: vi.fn().mockReturnValue([{ id: 1 }]) }).listInvites()).toEqual({ invites: [{ id: 1 }] });
expect(adminCtl(svc({ listAddons: vi.fn().mockReturnValue([{ id: 'mcp' }]) } as Partial<AdminService>)).listAddons()).toEqual({ addons: [{ id: 'mcp' }] });
expect(adminCtl(svc(), undefined, undefined, { listAllMcpTokens: vi.fn().mockReturnValue([{ id: 1 }]) }).listMcpTokens()).toEqual({ tokens: [{ id: 1 }] });
expect(adminCtl(svc(), undefined, undefined, {}, {}, { listAllOAuthSessions: vi.fn().mockReturnValue([{ id: 1 }]) }).listOAuthSessions()).toEqual({ sessions: [{ id: 1 }] });
});
it('setNotificationPrefs persists then returns the refreshed matrix', () => {
const setAdminPreferences = vi.fn();
const c = new AdminController(svc({ setAdminPreferences, getPreferencesMatrix: vi.fn().mockReturnValue({ rows: [1] }) } as Partial<AdminService>));
expect(c.setNotificationPrefs(user, { x: 1 })).toEqual({ rows: [1] });
expect(setAdminPreferences).toHaveBeenCalledWith(user.id, { x: 1 });
});
it('githubReleases falls back to default paging when no query is given', async () => {
const getGithubReleases = vi.fn().mockResolvedValue([{ tag: 'v1' }]);
const c = new AdminController(svc({ getGithubReleases } as Partial<AdminService>));
const c = adminCtl(svc({ getGithubReleases } as Partial<AdminService>));
await expect(c.githubReleases()).resolves.toEqual([{ tag: 'v1' }]);
expect(getGithubReleases).toHaveBeenCalledWith('10', '1');
await c.githubReleases('5', '2');
@@ -196,75 +176,32 @@ describe('AdminController read-only getters', () => {
});
});
describe('AdminController feature toggles + audit', () => {
it('bag-tracking updates and audits', () => {
const c = new AdminController(svc({ updateBagTracking: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>));
expect(c.updateBagTracking(user, { enabled: true }, req)).toEqual({ enabled: true });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'admin.bag_tracking' }));
});
it('places-autocomplete: 400 on a non-boolean, else updates + audits', () => {
expect(thrown(() => new AdminController(svc()).updatePlacesAutocomplete(user, { enabled: 'yes' }, req))).toEqual({ status: 400, body: { error: 'enabled must be a boolean' } });
expect(new AdminController(svc({ updatePlacesAutocomplete: vi.fn().mockReturnValue({ enabled: false }) } as Partial<AdminService>)).updatePlacesAutocomplete(user, { enabled: false }, req)).toEqual({ enabled: false });
});
it('places-details: 400 on a non-boolean, else updates + audits', () => {
expect(thrown(() => new AdminController(svc()).updatePlacesDetails(user, { enabled: 1 }, req))).toEqual({ status: 400, body: { error: 'enabled must be a boolean' } });
expect(new AdminController(svc({ updatePlacesDetails: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>)).updatePlacesDetails(user, { enabled: true }, req)).toEqual({ enabled: true });
});
});
describe('AdminController packing template sub-routes', () => {
it('update/delete templates, categories and items map errors + return success', () => {
expect(new AdminController(svc({ updatePackingTemplate: vi.fn().mockReturnValue({ id: 3 }) } as Partial<AdminService>)).updatePackingTemplate('3', {})).toEqual({ id: 3 });
expect(new AdminController(svc({ createTemplateCategory: vi.fn().mockReturnValue({ id: 4 }) } as Partial<AdminService>)).createTemplateCategory('3', { name: 'Tops' })).toEqual({ id: 4 });
expect(new AdminController(svc({ updateTemplateCategory: vi.fn().mockReturnValue({ id: 4 }) } as Partial<AdminService>)).updateTemplateCategory('3', '4', {})).toEqual({ id: 4 });
expect(new AdminController(svc({ deleteTemplateCategory: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).deleteTemplateCategory('3', '4')).toEqual({ success: true });
expect(new AdminController(svc({ updateTemplateItem: vi.fn().mockReturnValue({ id: 7 }) } as Partial<AdminService>)).updateTemplateItem('7', {})).toEqual({ id: 7 });
expect(new AdminController(svc({ deleteTemplateItem: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).deleteTemplateItem('7')).toEqual({ success: true });
expect(thrown(() => new AdminController(svc({ deleteTemplateItem: vi.fn().mockReturnValue({ error: 'gone', status: 404 }) } as Partial<AdminService>)).deleteTemplateItem('9'))).toEqual({ status: 404, body: { error: 'gone' } });
});
});
describe('AdminController tokens + sessions', () => {
it('mcp token + oauth session deletes return success and map errors', () => {
expect(new AdminController(svc({ deleteMcpToken: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).deleteMcpToken('2')).toEqual({ success: true });
expect(thrown(() => new AdminController(svc({ deleteMcpToken: vi.fn().mockReturnValue({ error: 'no token', status: 404 }) } as Partial<AdminService>)).deleteMcpToken('9'))).toEqual({ status: 404, body: { error: 'no token' } });
expect(thrown(() => new AdminController(svc({ revokeOAuthSession: vi.fn().mockReturnValue({ error: 'no session', status: 404 }) } as Partial<AdminService>)).revokeOAuthSession(user, '9', req))).toEqual({ status: 404, body: { error: 'no session' } });
expect(adminCtl(svc(), undefined, undefined, { adminDeleteMcpToken: vi.fn().mockReturnValue({}) }).deleteMcpToken(user, '2', req)).toEqual({ success: true });
expect(thrown(() => adminCtl(svc(), undefined, undefined, { adminDeleteMcpToken: vi.fn().mockReturnValue({ error: 'no token', status: 404 }) }).deleteMcpToken(user, '9', req))).toEqual({ status: 404, body: { error: 'no token' } });
expect(thrown(() => adminCtl(svc(), undefined, undefined, {}, {}, { adminRevokeOAuthSession: vi.fn().mockReturnValue({ error: 'no session', status: 404 }) }).revokeOAuthSession(user, '9', req))).toEqual({ status: 404, body: { error: 'no session' } });
});
});
describe('AdminController default-user-settings error path', () => {
it('400 with an Error message when setAdminUserDefaults throws an Error', () => {
const c = new AdminController(svc({ setAdminUserDefaults: vi.fn(() => { throw new Error('bad default'); }) } as Partial<AdminService>));
expect(thrown(() => c.setDefaultUserSettings(user, { theme: 'x' }, req))).toEqual({ status: 400, body: { error: 'bad default' } });
});
it('400 stringifies a non-Error throw', () => {
const c = new AdminController(svc({ setAdminUserDefaults: vi.fn(() => { throw 'plain string'; }) } as Partial<AdminService>));
expect(thrown(() => c.setDefaultUserSettings(user, { theme: 'x' }, req))).toEqual({ status: 400, body: { error: 'plain string' } });
});
it('400 when the body is null', () => {
expect(thrown(() => new AdminController(svc()).setDefaultUserSettings(user, null, req))).toEqual({ status: 400, body: { error: 'Object body required' } });
});
});
describe('AdminController dev test-notification', () => {
it('404 outside development', async () => {
delete process.env.NODE_ENV;
await expect(new AdminController(svc()).devTestNotification(user, {})).rejects.toBeInstanceOf(NotFoundException);
await expect(adminCtl(svc()).devTestNotification(user, {})).rejects.toBeInstanceOf(NotFoundException);
});
it('sends in development', async () => {
process.env.NODE_ENV = 'development';
const res = await new AdminController(svc()).devTestNotification(user, { event: 'trip_reminder' });
const res = await adminCtl(svc()).devTestNotification(user, { event: 'trip_reminder' });
expect(res).toEqual({ success: true });
});
it('applies notification defaults when the body is empty', async () => {
process.env.NODE_ENV = 'development';
const res = await new AdminController(svc()).devTestNotification(user, {});
const res = await adminCtl(svc()).devTestNotification(user, {});
expect(res).toEqual({ success: true });
expect(sendNotification).toHaveBeenCalledWith(expect.objectContaining({ event: 'trip_reminder', scope: 'user', targetId: user.id }));
});
@@ -272,12 +209,65 @@ describe('AdminController dev test-notification', () => {
it('maps an Error from the notification service to 400', async () => {
process.env.NODE_ENV = 'development';
(sendNotification as unknown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('send failed'));
await expect(new AdminController(svc()).devTestNotification(user, { event: 'trip_reminder' })).rejects.toMatchObject({ response: { error: 'send failed' } });
await expect(adminCtl(svc()).devTestNotification(user, { event: 'trip_reminder' })).rejects.toMatchObject({ response: { error: 'send failed' } });
});
it('stringifies a non-Error notification failure to 400', async () => {
process.env.NODE_ENV = 'development';
(sendNotification as unknown as ReturnType<typeof vi.fn>).mockRejectedValueOnce('weird');
await expect(new AdminController(svc()).devTestNotification(user, { event: 'trip_reminder' })).rejects.toMatchObject({ response: { error: 'weird' } });
await expect(adminCtl(svc()).devTestNotification(user, { event: 'trip_reminder' })).rejects.toMatchObject({ response: { error: 'weird' } });
});
});
// The feature toggles now go straight to AddonsService — these cases used to assert
// the same thing through AdminService pass-throughs that no longer exist.
describe('AdminController feature toggles', () => {
it('ADMIN-TOGGLE-001 each toggle forwards to AddonsService and writes its own audit action', () => {
const addons = addonsStub();
const c = adminCtl(svc(), undefined, addons);
const cases: Array<[() => unknown, string, keyof AddonsService]> = [
[() => c.updateBagTracking(user, { enabled: true }, req), 'admin.bag_tracking', 'updateBagTracking'],
[() => c.updatePlacesPhotos(user, { enabled: true }, req), 'admin.places_photos', 'updatePlacesPhotos'],
[() => c.updatePlacesAutocomplete(user, { enabled: true }, req), 'admin.places_autocomplete', 'updatePlacesAutocomplete'],
[() => c.updatePlacesDetails(user, { enabled: true }, req), 'admin.places_details', 'updatePlacesDetails'],
];
for (const [run, action, method] of cases) {
writeAudit.mockClear();
expect(run()).toEqual({ enabled: true });
expect(addons[method]).toHaveBeenCalledWith(true);
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action, details: { enabled: true } }));
}
});
it('ADMIN-TOGGLE-002 the getters return the AddonsService value verbatim', () => {
const c = adminCtl(svc());
expect(c.getBagTracking()).toEqual({ enabled: false });
expect(c.getPlacesPhotos()).toEqual({ enabled: false });
expect(c.getPlacesAutocomplete()).toEqual({ enabled: false });
expect(c.getPlacesDetails()).toEqual({ enabled: false });
expect(c.getPlacesEnrich()).toEqual({ enabled: true });
expect(c.getCollabFeatures()).toEqual({ chat: false });
});
it('ADMIN-TOGGLE-002b places-enrich updates through the addons domain and is audited', () => {
const c = adminCtl(svc());
expect(c.updatePlacesEnrich(user, { enabled: false }, req)).toEqual({ enabled: false });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'admin.places_enrich' }));
});
it('ADMIN-TOGGLE-003 collab-features invalidates MCP sessions only when a flag flipped (#1414)', () => {
const invalidateMcpSessions = vi.fn();
const c = adminCtl(svc({ invalidateMcpSessions } as Partial<AdminService>));
expect(c.updateCollabFeatures(user, { chat: true }, req)).toEqual({ chat: true });
expect(invalidateMcpSessions).toHaveBeenCalled();
const noopInvalidate = vi.fn();
const noop = adminCtl(
svc({ invalidateMcpSessions: noopInvalidate } as Partial<AdminService>),
undefined,
{ ...addonsStub(), updateCollabFeatures: vi.fn(() => ({ features: { chat: true }, changed: false })) } as unknown as AddonsService,
);
expect(noop.updateCollabFeatures(user, { chat: true }, req)).toEqual({ chat: true });
expect(noopInvalidate).not.toHaveBeenCalled();
});
});
@@ -1,7 +1,13 @@
/**
* Unit tests for adminService — ADMIN-SVC-001 through ADMIN-SVC-050.
* Uses a real in-memory SQLite DB. Focuses on validation/error branches
* that the integration tests don't exercise.
* Unit tests for the DI-native AdminService — ADMIN-SVC-001 through
* ADMIN-SVC-069, moved 1:1 from tests/unit/services/adminService.test.ts with
* the 2026-08 fold (IDs preserved, including the pre-existing 029/030 gap and
* the duplicated 069). The packing-template cases (031-044, 056-064) moved with
* their functions to tests/unit/nest/packing.service.test.ts.
* Constructs the service directly over a real in-memory SQLite DB (repo
* convention — no TestingModule). Focuses on validation/error branches that the
* integration tests don't exercise. VCJOB-001 pins the version-check cron path
* (it replaced ADMIN-BR-001 when the old admin bridge died with the cron move).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
@@ -30,13 +36,18 @@ vi.mock('../../../src/config', () => ({
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/services/apiKeyCrypto', () => ({
vi.mock('../../../src/nest/common/crypto/apiKeyCrypto', () => ({
encrypt_api_key: (v: string) => v,
decrypt_api_key: (v: string) => v,
maybe_encrypt_api_key: (v: string) => v,
}));
vi.mock('../../../src/mcp', () => ({
revokeUserSessions: vi.fn(),
invalidateMcpSessions: vi.fn(),
}));
vi.mock('../../../src/mcp/sessionManager', () => ({
revokeUserSessions: vi.fn(),
revokeUserSessionsForClient: vi.fn(),
}));
vi.mock('../../../src/demo/demo-reset', () => ({
saveBaseline: vi.fn(),
@@ -45,43 +56,68 @@ vi.mock('../../../src/demo/demo-reset', () => ({
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createAdmin, createInviteToken } from '../../helpers/factories';
import {
listUsers,
createUser as svcCreateUser,
updateUser,
deleteUser,
getStats,
getPermissions,
savePermissions,
getAuditLog,
listInvites,
createInvite,
deleteInvite,
getBagTracking,
updateBagTracking,
listPackingTemplates,
createPackingTemplate,
updatePackingTemplate,
deletePackingTemplate,
createTemplateCategory,
updateTemplateCategory,
deleteTemplateCategory,
getPackingTemplate,
createTemplateItem,
updateTemplateItem,
deleteTemplateItem,
getOidcSettings,
updateOidcSettings,
saveDemoBaseline,
getGithubReleases,
checkVersion,
listAddons,
updateAddon,
updateCollabFeatures,
listMcpTokens,
deleteMcpToken,
} from '../../../src/services/adminService';
import { createUser, createUserWithMfa, createAdmin, createInviteToken } from '../../helpers/factories';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { SettingsService } from '../../../src/nest/settings/settings.service';
import { AtlasService } from '../../../src/nest/atlas/atlas.service';
import { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import { UserCleanupService } from '../../../src/nest/auth/user-cleanup.service';
import { MailerService } from '../../../src/nest/notifications/mailer/mailer.service';
import { WebauthnConfigService } from '../../../src/nest/auth/webauthn-config.service';
import { AuthService } from '../../../src/nest/auth/auth.service';
import { PasskeyService } from '../../../src/nest/auth/passkey.service';
import { PackingService } from '../../../src/nest/packing/packing.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { BudgetService } from '../../../src/nest/budget/budget.service';
import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service';
import { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import { AdminService } from '../../../src/nest/admin/admin.service';
import { VersionCheckJob } from '../../../src/nest/admin/version-check.job';
import type { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { __clearVersionCacheForTests } from '../../../src/nest/admin/admin.helpers';
import { makeNotificationsService, makeNotificationPreferencesService } from '../../helpers/notifications';
import { EphemeralTokenService } from '../../../src/nest/auth/ephemeral-token.service';
import { AllowedFileTypesService } from '../../../src/nest/files/allowed-file-types.service';
const dbs = new DatabaseService(testDb);
const realtime = new RealtimeService();
const permissions = new PermissionsService(dbs);
const webauthn = new WebauthnConfigService(dbs);
const userCleanup = new UserCleanupService(dbs, new BudgetService(dbs, permissions, new ExchangeRatesService(), realtime));
// Positional and previously wrong: an AtlasService sat in the membership slot
// and the mailer was missing entirely, so `auth` was built with its last four
// collaborators shifted by one. Nothing failed, because none of the cases below
// reach a path that uses them.
const auth = new AuthService(dbs, permissions, new TripMembershipService(dbs), webauthn, userCleanup, new MailerService(dbs), new EphemeralTokenService(), new AllowedFileTypesService(dbs));
const svc = new AdminService(
dbs,
new AddonsService(dbs),
new PasskeyService(dbs, auth, webauthn),
auth,
permissions,
makeNotificationsService(dbs, realtime),
userCleanup,
realtime,
);
// Legacy free-function names bound to the service, so the moved cases below read
// exactly as they did before the fold.
const listUsers = () => svc.listUsers();
const svcCreateUser = (d: Parameters<AdminService['createUser']>[0]) => svc.createUser(d);
const updateUser = (id: string, d: Parameters<AdminService['updateUser']>[1]) => svc.updateUser(id, d);
const deleteUser = (id: string, actingId: number) => svc.deleteUser(id, actingId);
const getStats = () => svc.getStats();
const getPermissions = () => svc.getPermissions();
const savePermissions = (p: Record<string, string>) => svc.savePermissions(p);
const getAuditLog = (q: { limit?: string; offset?: string }) => svc.getAuditLog(q);
const saveDemoBaseline = () => svc.saveDemoBaseline();
const getGithubReleases = (perPage?: string, page?: string) => svc.getGithubReleases(perPage, page);
const checkVersion = () => svc.checkVersion();
const listAddons = () => svc.listAddons();
const updateAddon = (id: string, d: Parameters<AdminService['updateAddon']>[1]) => svc.updateAddon(id, d);
beforeAll(() => {
createTables(testDb);
@@ -271,160 +307,6 @@ describe('getAuditLog', () => {
});
});
// ── Invites ───────────────────────────────────────────────────────────────────
describe('Invites', () => {
it('ADMIN-SVC-024 — createInvite returns invite with token', () => {
const { user: admin } = createAdmin(testDb);
const result = createInvite(admin.id, { max_uses: 5 }) as any;
expect(result.invite.token).toBeDefined();
expect(result.invite.max_uses).toBe(5);
});
it('ADMIN-SVC-025 — createInvite defaults to 1 use', () => {
const { user: admin } = createAdmin(testDb);
const result = createInvite(admin.id, {}) as any;
expect(result.uses).toBe(1);
});
it('ADMIN-SVC-026 — listInvites returns array', () => {
const { user: admin } = createAdmin(testDb);
createInvite(admin.id, {});
const invites = listInvites() as any[];
expect(invites.length).toBeGreaterThanOrEqual(1);
});
it('ADMIN-SVC-027 — deleteInvite removes invite', () => {
const { user: admin } = createAdmin(testDb);
const invite = createInviteToken(testDb, { created_by: admin.id }) as any;
const result = deleteInvite(String(invite.id)) as any;
expect(result.error).toBeUndefined();
const check = testDb.prepare('SELECT id FROM invite_tokens WHERE id = ?').get(invite.id);
expect(check).toBeUndefined();
});
it('ADMIN-SVC-028 — deleteInvite returns 404 for non-existent invite', () => {
const result = deleteInvite('99999') as any;
expect(result.status).toBe(404);
});
});
// ── Bag tracking ──────────────────────────────────────────────────────────────
describe('Bag tracking', () => {
it('ADMIN-SVC-029 — getBagTracking returns enabled state', () => {
const result = getBagTracking() as any;
expect(typeof result.enabled).toBe('boolean');
});
it('ADMIN-SVC-030 — updateBagTracking persists the value', () => {
updateBagTracking(true);
expect((getBagTracking() as any).enabled).toBe(true);
updateBagTracking(false);
expect((getBagTracking() as any).enabled).toBe(false);
});
});
// ── Packing templates ─────────────────────────────────────────────────────────
describe('Packing templates', () => {
it('ADMIN-SVC-031 — createPackingTemplate returns template', () => {
const { user: admin } = createAdmin(testDb);
const result = createPackingTemplate('Beach Trip', admin.id) as any;
expect(result.template.name).toBe('Beach Trip');
});
it('ADMIN-SVC-032 — createPackingTemplate returns 400 for empty name', () => {
const { user: admin } = createAdmin(testDb);
const result = createPackingTemplate('', admin.id) as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-033 — listPackingTemplates returns array', () => {
const { user: admin } = createAdmin(testDb);
createPackingTemplate('Template A', admin.id);
const templates = listPackingTemplates() as any[];
expect(templates.length).toBeGreaterThanOrEqual(1);
});
it('ADMIN-SVC-034 — updatePackingTemplate updates name', () => {
const { user: admin } = createAdmin(testDb);
const created = createPackingTemplate('Old Name', admin.id) as any;
const result = updatePackingTemplate(String(created.template.id), { name: 'New Name' }) as any;
expect(result.template.name).toBe('New Name');
});
it('ADMIN-SVC-035 — updatePackingTemplate returns 404 for non-existent', () => {
const result = updatePackingTemplate('99999', { name: 'Ghost' }) as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-036 — deletePackingTemplate removes template', () => {
const { user: admin } = createAdmin(testDb);
const created = createPackingTemplate('To Delete', admin.id) as any;
const result = deletePackingTemplate(String(created.template.id)) as any;
expect(result.name).toBe('To Delete');
});
it('ADMIN-SVC-037 — deletePackingTemplate returns 404 for non-existent', () => {
const result = deletePackingTemplate('99999') as any;
expect(result.status).toBe(404);
});
});
// ── Template categories ───────────────────────────────────────────────────────
describe('Template categories', () => {
it('ADMIN-SVC-038 — createTemplateCategory creates a category', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const result = createTemplateCategory(String(tpl.template.id), 'Clothing') as any;
expect(result.category.name).toBe('Clothing');
});
it('ADMIN-SVC-039 — createTemplateCategory returns 400 for empty name', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const result = createTemplateCategory(String(tpl.template.id), '') as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-040 — createTemplateCategory returns 404 for missing template', () => {
const result = createTemplateCategory('99999', 'Clothing') as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-041 — updateTemplateCategory updates name', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Old') as any;
const result = updateTemplateCategory(String(tpl.template.id), String(cat.category.id), { name: 'New' }) as any;
expect(result.category.name).toBe('New');
});
it('ADMIN-SVC-042 — updateTemplateCategory returns 404 for missing category', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const result = updateTemplateCategory(String(tpl.template.id), '99999', { name: 'X' }) as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-043 — deleteTemplateCategory removes category', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Remove Me') as any;
const result = deleteTemplateCategory(String(tpl.template.id), String(cat.category.id)) as any;
expect(result.error).toBeUndefined();
});
it('ADMIN-SVC-044 — deleteTemplateCategory returns 404 for missing', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const result = deleteTemplateCategory(String(tpl.template.id), '99999') as any;
expect(result.status).toBe(404);
});
});
// ── getAuditLog — JSON details parsing ───────────────────────────────────────
describe('getAuditLog — JSON details', () => {
@@ -440,7 +322,7 @@ describe('getAuditLog — JSON details', () => {
expect(entry.details).toEqual({ key: 'val' });
});
it('ADMIN-SVC-046 — handles invalid JSON gracefully with _parse_error flag', () => {
it('ADMIN-SVC-046 — falls back to the raw string when details are not valid JSON', () => {
const { user } = createUser(testDb);
testDb.prepare('INSERT INTO audit_log (user_id, action, details) VALUES (?, ?, ?)').run(
user.id, 'bad_json_action', 'not-valid-json{'
@@ -448,38 +330,14 @@ describe('getAuditLog — JSON details', () => {
const result = getAuditLog({}) as any;
const entry = result.entries.find((e: any) => e.action === 'bad_json_action');
expect(entry).toBeDefined();
expect(entry.details).toEqual({ _parse_error: true });
// Was { _parse_error: true } before the 2026-08 quirk fix — the admin UI
// rendered that sentinel literally.
expect(entry.details).toBe('not-valid-json{');
});
});
// ── OIDC Settings ─────────────────────────────────────────────────────────────
describe('OIDC Settings', () => {
it('ADMIN-SVC-047 — getOidcSettings returns default empty values when no OIDC configured', () => {
const result = getOidcSettings() as any;
expect(result.issuer).toBe('');
expect(result.client_id).toBe('');
expect(result.oidc_only).toBe(false);
expect(result.client_secret_set).toBe(false);
expect(result.display_name).toBe('');
expect(result.discovery_url).toBe('');
});
it('ADMIN-SVC-048 — updateOidcSettings persists issuer and client_id, then getOidcSettings returns them', () => {
updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
const result = getOidcSettings() as any;
expect(result.issuer).toBe('https://auth.example.com');
expect(result.client_id).toBe('my-client');
});
it('ADMIN-SVC-049 — updateOidcSettings does not write oidc_only (replaced by granular toggles)', () => {
updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
const result = getOidcSettings() as any;
// oidc_only is no longer managed by updateOidcSettings; use password_login/oidc_login toggles
expect(result.oidc_only).toBe(false);
});
});
// ── saveDemoBaseline ──────────────────────────────────────────────────────────
describe('saveDemoBaseline', () => {
@@ -529,6 +387,7 @@ describe('getGithubReleases', () => {
];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => JSON.stringify(mockReleases),
json: async () => mockReleases,
}));
const result = await getGithubReleases();
@@ -536,6 +395,31 @@ describe('getGithubReleases', () => {
expect(result).toHaveLength(2);
expect((result as any[])[0].tag_name).toBe('v3.0.0');
});
it('ADMIN-SVC-053a — clamps the paging query instead of interpolating it raw', async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true, text: async () => '[]' });
vi.stubGlobal('fetch', fetchMock);
await getGithubReleases('9999', '0');
expect(fetchMock.mock.calls[0][0]).toBe(
'https://api.github.com/repos/liketrek/TREK/releases?per_page=100&page=1',
);
await getGithubReleases('10&per_page=999', 'abc');
expect(fetchMock.mock.calls[1][0]).toBe(
'https://api.github.com/repos/liketrek/TREK/releases?per_page=10&page=1',
);
});
it('ADMIN-SVC-053b — round-trips the paging the admin UI actually sends', async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true, text: async () => '[]' });
vi.stubGlobal('fetch', fetchMock);
await getGithubReleases('20', '2');
expect(fetchMock.mock.calls[0][0]).toBe(
'https://api.github.com/repos/liketrek/TREK/releases?per_page=20&page=2',
);
});
});
// ── checkVersion ──────────────────────────────────────────────────────────────
@@ -545,6 +429,10 @@ describe('checkVersion', () => {
vi.unstubAllGlobals();
});
// Since the 2026-08 quirk fix, failures cache too (on a 60s TTL), so each case
// clears the module-scoped cache rather than reading the previous one's result.
beforeEach(() => { __clearVersionCacheForTests(); });
it('ADMIN-SVC-054 — returns update_available:false when fetch fails', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network error')));
const result = await checkVersion() as any;
@@ -556,6 +444,7 @@ describe('checkVersion', () => {
it('ADMIN-SVC-055 — returns update_available:true when latest version is greater than current', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ tag_name: 'v999.0.0', html_url: 'https://github.com/example/releases/tag/v999.0.0' }),
json: async () => ({ tag_name: 'v999.0.0', html_url: 'https://github.com/example/releases/tag/v999.0.0' }),
}));
const result = await checkVersion() as any;
@@ -563,89 +452,13 @@ describe('checkVersion', () => {
expect(result.latest).toBe('999.0.0');
expect(result.release_url).toBe('https://github.com/example/releases/tag/v999.0.0');
});
});
// ── getPackingTemplate ────────────────────────────────────────────────────────
describe('getPackingTemplate', () => {
it('ADMIN-SVC-056 — returns template with categories and items when template exists', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Full Template', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Clothing') as any;
createTemplateItem(String(tpl.template.id), String(cat.category.id), 'T-Shirt');
const result = getPackingTemplate(String(tpl.template.id)) as any;
expect(result.template).toBeDefined();
expect(result.template.name).toBe('Full Template');
expect(Array.isArray(result.categories)).toBe(true);
expect(result.categories.length).toBeGreaterThanOrEqual(1);
expect(Array.isArray(result.items)).toBe(true);
expect(result.items.length).toBeGreaterThanOrEqual(1);
expect(result.items[0].name).toBe('T-Shirt');
});
it('ADMIN-SVC-057 — returns 404 for non-existent template', () => {
const result = getPackingTemplate('99999') as any;
expect(result.status).toBe(404);
expect(result.error).toBeDefined();
});
});
// ── Template items ────────────────────────────────────────────────────────────
describe('Template items', () => {
it('ADMIN-SVC-058 — createTemplateItem returns item with name', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any;
const result = createTemplateItem(String(tpl.template.id), String(cat.category.id), 'Backpack') as any;
expect(result.item).toBeDefined();
expect(result.item.name).toBe('Backpack');
});
it('ADMIN-SVC-059 — createTemplateItem returns 400 for empty name', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any;
const result = createTemplateItem(String(tpl.template.id), String(cat.category.id), '') as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-060 — createTemplateItem returns 404 for non-existent category', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const result = createTemplateItem(String(tpl.template.id), '99999', 'Item') as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-061 — updateTemplateItem updates name', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any;
const item = createTemplateItem(String(tpl.template.id), String(cat.category.id), 'Old Item') as any;
const result = updateTemplateItem(String(item.item.id), { name: 'New Item' }) as any;
expect(result.item.name).toBe('New Item');
});
it('ADMIN-SVC-062 — updateTemplateItem returns 404 for non-existent item', () => {
const result = updateTemplateItem('99999', { name: 'Ghost' }) as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-063 — deleteTemplateItem removes item', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any;
const item = createTemplateItem(String(tpl.template.id), String(cat.category.id), 'To Delete') as any;
const result = deleteTemplateItem(String(item.item.id)) as any;
expect(result.error).toBeUndefined();
const check = testDb.prepare('SELECT id FROM packing_template_items WHERE id = ?').get(item.item.id);
expect(check).toBeUndefined();
});
it('ADMIN-SVC-064 — deleteTemplateItem returns 404 for non-existent item', () => {
const result = deleteTemplateItem('99999') as any;
expect(result.status).toBe(404);
it('ADMIN-SVC-070 — a failed check is cached briefly instead of refetching per call', async () => {
const fetchMock = vi.fn().mockRejectedValue(new Error('Network error'));
vi.stubGlobal('fetch', fetchMock);
await checkVersion();
await checkVersion();
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
@@ -695,31 +508,157 @@ describe('updateAddon', () => {
});
});
describe('updateCollabFeatures', () => {
it('ADMIN-SVC-070 — reports whether a flag actually flipped (#1414)', () => {
const first = updateCollabFeatures({ chat: false });
expect(first.changed).toBe(true);
expect(first.features.chat).toBe(false);
// identical save → no change, MCP sessions must survive
const second = updateCollabFeatures({ chat: false });
expect(second.changed).toBe(false);
const third = updateCollabFeatures({ chat: true });
expect(third.changed).toBe(true);
// ── version-check cron ────────────────────────────────────────────────────────
describe('version-check job', () => {
const registrarStub = { isEnabled: () => true, register: vi.fn(() => true), unregister: vi.fn() } as unknown as CronRegistrarService;
const envStub = { isManaged: () => false } as unknown as RuntimeEnvService;
it('VCJOB-001 — the cron tick notifies and shares the module-scoped version cache with the route', async () => {
createAdmin(testDb);
__clearVersionCacheForTests();
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ tag_name: 'v99.9.9', html_url: 'https://example.test/r' }),
json: async () => ({ tag_name: 'v99.9.9', html_url: 'https://example.test/r' }),
});
vi.stubGlobal('fetch', fetchMock);
await new VersionCheckJob(svc, registrarStub, envStub).tick();
const notified = testDb
.prepare('SELECT value FROM app_settings WHERE key = ?')
.get('last_notified_version') as { value: string } | undefined;
expect(notified?.value).toBe('99.9.9');
// The version cache is module-scoped in admin.helpers, so the cron and
// GET /api/admin/version-check hit GitHub once between them.
expect(await svc.checkVersion()).toMatchObject({ latest: '99.9.9' });
expect(fetchMock).toHaveBeenCalledTimes(1);
vi.unstubAllGlobals();
__clearVersionCacheForTests();
});
});
// ── MCP Tokens ────────────────────────────────────────────────────────────────
// ── Quirk fixes landed after the 2026-08 fold ─────────────────────────────────
describe('MCP Tokens', () => {
it('ADMIN-SVC-068 — listMcpTokens returns empty array initially', () => {
const result = listMcpTokens() as any[];
expect(Array.isArray(result)).toBe(true);
expect(result).toHaveLength(0);
describe('admin quirk fixes (post-fold)', () => {
it('ADMIN-SVC-072 — updateUser rejects an empty username/email instead of silently no-opping', () => {
const { user } = createUser(testDb);
expect(updateUser(String(user.id), { username: '' }) as any).toMatchObject({ status: 400, error: 'Username cannot be empty' });
expect(updateUser(String(user.id), { email: ' ' }) as any).toMatchObject({ status: 400, error: 'Email cannot be empty' });
// The row is untouched.
const row = testDb.prepare('SELECT username FROM users WHERE id = ?').get(user.id) as { username: string };
expect(row.username).toBe(user.username);
});
it('ADMIN-SVC-069 — deleteMcpToken returns 404 for non-existent token', () => {
const result = deleteMcpToken('99999') as any;
expect(result.status).toBe(404);
expect(result.error).toBeDefined();
});
// ── What an admin password reset ends, and what an ordinary edit must not ─────
const pv = (id: number): number =>
(testDb.prepare('SELECT password_version FROM users WHERE id = ?').get(id) as { password_version: number | null })
?.password_version ?? 0;
const mcpTokenCount = (id: number): number =>
(testDb.prepare('SELECT COUNT(*) AS n FROM mcp_tokens WHERE user_id = ?').get(id) as { n: number }).n;
describe('admin password reset revokes what an intruder already holds', () => {
it('ADMIN-SVC-080 — setting a password bumps password_version, so existing cookies stop working', () => {
// An admin sets somebody else's password for one reason: the account is
// believed compromised. Without the bump, verifyJwtAndLoadUser keeps
// accepting every cookie the intruder holds, and the one action taken to
// lock them out is the one action that did not.
const { user } = createUser(testDb);
const before = pv(user.id);
updateUser(String(user.id), { password: 'ANewStrongPass123!' });
expect(pv(user.id)).toBe(before + 1);
});
it('ADMIN-SVC-081 — and clears the MCP tokens, which the version bump does not reach', () => {
const { user } = createUser(testDb);
testDb.prepare("INSERT INTO mcp_tokens (user_id, token_hash, token_prefix, name) VALUES (?, 'hash', 'trek_ab', 'cli')").run(user.id);
updateUser(String(user.id), { password: 'ANewStrongPass123!' });
expect(mcpTokenCount(user.id)).toBe(0);
});
it('ADMIN-SVC-082 — renaming a user touches neither, so an ordinary edit stays ordinary', () => {
const { user } = createUser(testDb);
const before = pv(user.id);
testDb.prepare("INSERT INTO mcp_tokens (user_id, token_hash, token_prefix, name) VALUES (?, 'hash', 'trek_ab', 'cli')").run(user.id);
updateUser(String(user.id), { username: 'renamed' });
expect(pv(user.id)).toBe(before);
expect(mcpTokenCount(user.id)).toBe(1);
});
});
describe('resetUserMfa', () => {
it('ADMIN-SVC-083 — clears the three columns disableMfa clears, so both paths leave one state', () => {
// The passkey half has existed since passkeys landed; TOTP never had an
// answer, which left "somebody on the trip lost their phone" with no way out
// short of an operator reaching into the database.
const admin = createAdmin(testDb);
const { user } = createUserWithMfa(testDb);
const result = svc.resetUserMfa(String(user.id), admin.user.id) as { success?: boolean; email?: string };
expect(result.success).toBe(true);
expect(result.email).toBe(user.email);
const row = testDb
.prepare('SELECT mfa_enabled, mfa_secret, mfa_backup_codes FROM users WHERE id = ?')
.get(user.id) as { mfa_enabled: number; mfa_secret: string | null; mfa_backup_codes: string | null };
expect(row.mfa_enabled).toBe(0);
expect(row.mfa_secret).toBeNull();
expect(row.mfa_backup_codes).toBeNull();
});
it('ADMIN-SVC-084 — refuses to strip the callers own second factor', () => {
// Reachable from a stolen admin session otherwise, and it would take the
// second factor off the very account that session came from. The
// self-service path in Settings asks for the current password.
const admin = createAdmin(testDb);
const result = svc.resetUserMfa(String(admin.user.id), admin.user.id) as { error?: string; status?: number };
expect(result.status).toBe(400);
expect(result.error).toMatch(/your own/i);
});
it('ADMIN-SVC-085 — 404 for a user that is not there', () => {
const admin = createAdmin(testDb);
expect(svc.resetUserMfa('99999', admin.user.id) as { status?: number }).toMatchObject({ status: 404 });
});
});
describe('checkVersion on a centrally administered install', () => {
afterEach(() => {
vi.unstubAllEnvs();
__clearVersionCacheForTests();
});
it('ADMIN-SVC-086 — answers "up to date" without asking GitHub', () => {
// Answered rather than refused: the admin page calls this on open, and a 403
// would put an error where a quiet surface belongs. The operator decides when
// this instance upgrades, so from inside it there is nothing available.
const fetchSpy = vi.fn();
vi.stubGlobal('fetch', fetchSpy);
vi.stubEnv('TREK_MANAGED', 'true');
vi.stubEnv('APP_VERSION', '3.4.1');
return checkVersion().then((info) => {
expect(info.update_available).toBe(false);
expect(info.latest).toBe('3.4.1');
expect(info.current).toBe('3.4.1');
expect(fetchSpy).not.toHaveBeenCalled();
});
});
});
@@ -1,10 +1,14 @@
/**
* Unit tests for checkAndNotifyVersion() in adminService.
* Covers VNOTIF-001 to VNOTIF-007.
* Unit tests for AdminService.checkAndNotifyVersion() — VNOTIF-001 to
* VNOTIF-007, moved from tests/unit/services/versionNotification.test.ts with
* the 2026-08 admin fold, IDs preserved. Kept separate from admin.service.test.ts
* because it stubs global fetch and drives the module-scoped version cache per
* case, which would leak into the ADMIN-SVC-* suite. The notification path runs
* for real against the temp db's notifications table.
*/
import { runMigrations } from '../../../src/db/migrations';
import { createTables } from '../../../src/db/schema';
import { checkAndNotifyVersion, __clearVersionCacheForTests } from '../../../src/services/adminService';
import { __clearVersionCacheForTests } from '../../../src/nest/admin/admin.helpers';
import { createAdmin } from '../../helpers/factories';
import { resetTestDb } from '../../helpers/test-db';
@@ -34,7 +38,50 @@ vi.mock('../../../src/config', () => ({
}));
vi.mock('../../../src/websocket', () => ({ broadcastToUser: vi.fn() }));
// Mock MCP to avoid session side-effects
vi.mock('../../../src/mcp', () => ({ revokeUserSessions: vi.fn() }));
vi.mock('../../../src/mcp', () => ({ revokeUserSessions: vi.fn(), invalidateMcpSessions: vi.fn() }));
vi.mock('../../../src/mcp/sessionManager', () => ({ revokeUserSessions: vi.fn(), revokeUserSessionsForClient: vi.fn() }));
import { DatabaseService } from '../../../src/nest/database/database.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { SettingsService } from '../../../src/nest/settings/settings.service';
import { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import { UserCleanupService } from '../../../src/nest/auth/user-cleanup.service';
import { MailerService } from '../../../src/nest/notifications/mailer/mailer.service';
import { WebauthnConfigService } from '../../../src/nest/auth/webauthn-config.service';
import { AuthService } from '../../../src/nest/auth/auth.service';
import { PasskeyService } from '../../../src/nest/auth/passkey.service';
import { PackingService } from '../../../src/nest/packing/packing.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { BudgetService } from '../../../src/nest/budget/budget.service';
import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service';
import { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import { AdminService } from '../../../src/nest/admin/admin.service';
import { makeNotificationsService, makeNotificationPreferencesService } from '../../helpers/notifications';
import { EphemeralTokenService } from '../../../src/nest/auth/ephemeral-token.service';
import { AllowedFileTypesService } from '../../../src/nest/files/allowed-file-types.service';
const dbs = new DatabaseService(testDb);
const realtime = new RealtimeService();
const permissions = new PermissionsService(dbs);
const webauthn = new WebauthnConfigService(dbs);
const userCleanup = new UserCleanupService(dbs, new BudgetService(dbs, permissions, new ExchangeRatesService(), realtime));
// Positional and previously wrong: an AtlasService sat in the membership slot
// and the mailer was missing entirely, so `auth` was built with its last four
// collaborators shifted by one. Nothing failed, because the version-check path
// below never reaches them.
const auth = new AuthService(dbs, permissions, new TripMembershipService(dbs), webauthn, userCleanup, new MailerService(dbs), new EphemeralTokenService(), new AllowedFileTypesService(dbs));
const svc = new AdminService(
dbs,
new AddonsService(dbs),
new PasskeyService(dbs, auth, webauthn),
auth,
permissions,
makeNotificationsService(dbs, realtime),
userCleanup,
realtime,
);
const checkAndNotifyVersion = () => svc.checkAndNotifyVersion();
// Helper: mock the GitHub releases/latest endpoint
function mockGitHubLatest(tagName: string, ok = true): void {
@@ -42,6 +89,8 @@ function mockGitHubLatest(tagName: string, ok = true): void {
'fetch',
vi.fn().mockResolvedValue({
ok,
// fetchGithub reads text() and parses it itself (size cap), so stub both.
text: async () => JSON.stringify({ tag_name: tagName, html_url: `https://github.com/liketrek/TREK/releases/tag/${tagName}` }),
json: async () => ({ tag_name: tagName, html_url: `https://github.com/liketrek/TREK/releases/tag/${tagName}` }),
}),
);
@@ -0,0 +1,96 @@
/**
* The bundled airport dataset — AIRPORT-DATA-001..010.
*
* These have no predecessor: the file lived in services/, outside the coverage
* gate, so its scoring ladder was only ever exercised incidentally through the
* e2e route. Moving it into src/nest made the gap visible.
*
* fs is stubbed with a four-airport fixture rather than reading the real
* assets/airports.json, so the ranking assertions stay deterministic and the
* missing-file branch is reachable.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
const { readFileSync, existsSync } = vi.hoisted(() => ({
readFileSync: vi.fn(),
existsSync: vi.fn(() => true),
}));
vi.mock('node:fs', () => ({ default: { readFileSync, existsSync }, readFileSync, existsSync }));
const FIXTURE = [
{ iata: 'FRA', icao: 'EDDF', name: 'Frankfurt Airport', city: 'Frankfurt', country: 'DE', lat: 50, lng: 8.5, tz: 'Europe/Berlin' },
{ iata: 'FRO', icao: 'ENFL', name: 'Floro Airport', city: 'Floro', country: 'NO', lat: 61, lng: 5, tz: 'Europe/Oslo' },
{ iata: 'JFK', icao: 'KJFK', name: 'John F Kennedy International', city: 'New York', country: 'US', lat: 40, lng: -73, tz: 'America/New_York' },
{ iata: 'BER', icao: 'EDDB', name: 'Berlin Brandenburg', city: 'Berlin', country: 'DE', lat: 52, lng: 13, tz: 'Europe/Berlin' },
];
/** A fresh module registry per case: the dataset is cached after the first load. */
async function load(opts: { missing?: boolean; body?: string } = {}) {
vi.resetModules();
existsSync.mockReturnValue(!opts.missing);
readFileSync.mockReturnValue(opts.body ?? JSON.stringify(FIXTURE));
return import('../../../../src/nest/airports/airports.data');
}
beforeEach(() => vi.clearAllMocks());
describe('findByIata', () => {
it('AIRPORT-DATA-001: finds an airport by its IATA code, case-insensitively', async () => {
const { findByIata } = await load();
expect(findByIata('fra')?.name).toBe('Frankfurt Airport');
expect(findByIata('FRA')?.icao).toBe('EDDF');
});
it('AIRPORT-DATA-002: returns null for an unknown code', async () => {
const { findByIata } = await load();
expect(findByIata('ZZZ')).toBeNull();
});
it('AIRPORT-DATA-003: returns null for every code when the dataset file is missing', async () => {
const { findByIata } = await load({ missing: true });
expect(findByIata('FRA')).toBeNull();
});
});
describe('searchAirports ranking', () => {
it('AIRPORT-DATA-004: an exact three-letter IATA match short-circuits to that one airport', async () => {
const { searchAirports } = await load();
expect(searchAirports('JFK').map(a => a.iata)).toEqual(['JFK']);
});
it('AIRPORT-DATA-005: an exact ICAO match outranks a prefix match', async () => {
const { searchAirports } = await load();
// 'EDDF' is FRA's ICAO; nothing else starts with it.
expect(searchAirports('EDDF')[0].iata).toBe('FRA');
});
it('AIRPORT-DATA-006: an IATA prefix outranks a city prefix', async () => {
const { searchAirports } = await load();
// 'FR' prefixes the IATA of FRA and FRO, and the city of Frankfurt.
const iatas = searchAirports('FR').map(a => a.iata);
expect(iatas.slice(0, 2).sort()).toEqual(['FRA', 'FRO']);
});
it('AIRPORT-DATA-007: a city prefix outranks a substring match', async () => {
const { searchAirports } = await load();
// 'Berlin' is BER's city (prefix) and appears inside its name too.
expect(searchAirports('Berlin')[0].iata).toBe('BER');
});
it('AIRPORT-DATA-008: matches a name substring when nothing better applies', async () => {
const { searchAirports } = await load();
expect(searchAirports('Kennedy').map(a => a.iata)).toEqual(['JFK']);
});
it('AIRPORT-DATA-009: an empty or whitespace query returns nothing', async () => {
const { searchAirports } = await load();
expect(searchAirports('')).toEqual([]);
expect(searchAirports(' ')).toEqual([]);
});
it('AIRPORT-DATA-010: honours the result limit', async () => {
const { searchAirports } = await load();
// Every fixture airport matches on country or name somewhere; cap it at one.
expect(searchAirports('a', 1)).toHaveLength(1);
});
});
-28
View File
@@ -1,28 +0,0 @@
/**
* zodToOpenApi (#1412): Zod → OpenAPI 3.0 conversion + the degrade path.
* The end-to-end enricher behaviour is covered by tests/integration/api-docs.
*/
import { describe, it, expect } from 'vitest';
import { z } from 'zod';
import { zodToOpenApi } from '../../../src/nest/common/api-zod';
describe('zodToOpenApi', () => {
it('converts an object schema with required/optional split', () => {
const out = zodToOpenApi(z.object({ name: z.string(), count: z.number().optional() })) as {
type: string; properties: Record<string, unknown>; required: string[];
};
expect(out.type).toBe('object');
expect(out.properties.name).toEqual({ type: 'string' });
expect(out.properties.count).toEqual({ type: 'number' });
expect(out.required).toEqual(['name']);
});
it('survives transform-heavy schemas via unrepresentable: any', () => {
const out = zodToOpenApi(z.object({ when: z.string().transform((s) => new Date(s)) }));
expect((out as { type: string }).type).toBe('object');
});
it('degrades to a bare object instead of throwing on a broken schema', () => {
expect(zodToOpenApi({} as never)).toEqual({ type: 'object' });
});
});
+95
View File
@@ -0,0 +1,95 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import { Test } from '@nestjs/testing';
import { ConfigService, ConfigType } from '@nestjs/config';
import { AppConfigModule } from '../../../src/nest/app-config/app-config.module';
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { httpConfig, mcpConfig, BOOT_STABLE_TOKENS } from '../../../src/nest/app-config/tokens';
describe('RuntimeEnvService', () => {
const service = new RuntimeEnvService();
let prevDemo: string | undefined;
beforeEach(() => {
prevDemo = process.env.DEMO_MODE;
});
afterEach(() => {
if (prevDemo === undefined) delete process.env.DEMO_MODE;
else process.env.DEMO_MODE = prevDemo;
});
it('reads live — a mid-lifetime env mutation is visible on the next call', () => {
process.env.DEMO_MODE = 'true';
expect(service.isDemoMode()).toBe(true);
process.env.DEMO_MODE = 'off';
expect(service.isDemoMode()).toBe(false);
delete process.env.DEMO_MODE;
expect(service.isDemoMode()).toBe(false);
});
it('env() exposes the full live-derived namespaces', () => {
process.env.DEMO_MODE = 'yes';
expect(service.env().demo.enabled).toBe(true);
expect(service.env().app.port).toBeTypeOf('number');
});
});
describe('boot-stable tokens', () => {
it('factories re-derive from the current env on each invocation', () => {
const prev = process.env.FORCE_HTTPS;
try {
process.env.FORCE_HTTPS = 'on';
expect(httpConfig().forceHttps).toBe(true);
process.env.FORCE_HTTPS = 'off';
expect(httpConfig().forceHttps).toBe(false);
} finally {
if (prev === undefined) delete process.env.FORCE_HTTPS;
else process.env.FORCE_HTTPS = prev;
}
});
it('every token carries a namespaced KEY for @Inject', () => {
for (const token of BOOT_STABLE_TOKENS) {
expect(token.KEY).toMatch(/^CONFIGURATION\(.+\)$/);
}
});
});
describe('AppConfigModule', () => {
it('provides ConfigService, RuntimeEnvService and the loaded namespaces', async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppConfigModule] }).compile();
try {
const config = moduleRef.get(ConfigService);
const runtime = moduleRef.get(RuntimeEnvService);
const mcp = moduleRef.get<ConfigType<typeof mcpConfig>>(mcpConfig.KEY);
expect(runtime).toBeInstanceOf(RuntimeEnvService);
expect(mcp.rateLimitMax).toBe(300);
// Plain get() falls through to live process.env (cache: false).
expect(config.get('NODE_ENV')).toBe('test');
} finally {
await moduleRef.close();
}
});
// Guards `ignoreEnvFile: true`: a marker var present only in server/.env must
// stay invisible. Skipped locally when a real server/.env exists (we won't
// clobber it); CI has none, so the regression is always covered there.
const envPath = path.resolve(process.cwd(), '.env');
it.skipIf(fs.existsSync(envPath))('never reads a .env file (dotenv stays index.ts-only)', async () => {
fs.writeFileSync(envPath, 'TREK_TEST_ENVFILE_MARKER=leaked\n');
try {
const moduleRef = await Test.createTestingModule({ imports: [AppConfigModule] }).compile();
try {
const config = moduleRef.get(ConfigService);
expect(config.get('TREK_TEST_ENVFILE_MARKER')).toBeUndefined();
expect(process.env.TREK_TEST_ENVFILE_MARKER).toBeUndefined();
} finally {
await moduleRef.close();
}
} finally {
fs.rmSync(envPath, { force: true });
}
});
});
@@ -25,9 +25,11 @@ function thrown(fn: () => unknown): { status: number; body: unknown } {
}
describe('DayAssignmentsController (parity with the legacy day-assignments routes)', () => {
it('404 trip, then 404 day on GET', () => {
expect(thrown(() => new DayAssignmentsController(svc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) })).list(user, '5', '3'))).toEqual({ status: 404, body: { error: 'Trip not found' } });
expect(thrown(() => new DayAssignmentsController(svc({ dayExists: vi.fn().mockReturnValue(false) } as Partial<AssignmentsService>)).list(user, '5', '3'))).toEqual({ status: 404, body: { error: 'Day not found' } });
// The 404 "Trip not found" and 403 "No permission" cases moved to
// trip-access.guard.test.ts with the check itself.
it('404 day on GET', () => {
const s = svc({ dayExists: vi.fn().mockReturnValue(false) } as Partial<AssignmentsService>);
expect(thrown(() => new DayAssignmentsController(s).list(user, '5', '9'))).toEqual({ status: 404, body: { error: 'Day not found' } });
});
it('GET returns assignments (access-only, no permission gate)', () => {
@@ -36,8 +38,7 @@ describe('DayAssignmentsController (parity with the legacy day-assignments route
});
describe('POST', () => {
it('403 without day_edit; 404 place not found; then creates + hooks', () => {
expect(thrown(() => new DayAssignmentsController(svc({ canEdit: vi.fn().mockReturnValue(false) })).create(user, '5', '3', { place_id: 2 }))).toEqual({ status: 403, body: { error: 'No permission' } });
it('404 place not found; then creates + hooks', () => {
expect(thrown(() => new DayAssignmentsController(svc({ placeExists: vi.fn().mockReturnValue(false) } as Partial<AssignmentsService>)).create(user, '5', '3', { place_id: 2 }))).toEqual({ status: 404, body: { error: 'Place not found' } });
const createAssignment = vi.fn().mockReturnValue({ id: 9 }); const broadcast = vi.fn(); const reconcile = vi.fn();
const s = svc({ createAssignment, broadcast, reconcile } as Partial<AssignmentsService>);
@@ -49,9 +50,10 @@ describe('DayAssignmentsController (parity with the legacy day-assignments route
});
it('PUT /reorder 404 day, else reorders + broadcasts', () => {
expect(thrown(() => new DayAssignmentsController(svc({ dayExists: vi.fn().mockReturnValue(false) } as Partial<AssignmentsService>)).reorder(user, '5', '3', [1, 2]))).toEqual({ status: 404, body: { error: 'Day not found' } });
expect(thrown(() => new DayAssignmentsController(svc({ dayExists: vi.fn().mockReturnValue(false) } as Partial<AssignmentsService>)).reorder(user, '5', '3', { orderedIds: [1, 2] }))).toEqual({ status: 404, body: { error: 'Day not found' } });
const reorderAssignments = vi.fn(); const broadcast = vi.fn();
expect(new DayAssignmentsController(svc({ reorderAssignments, broadcast } as Partial<AssignmentsService>)).reorder(user, '5', '3', [2, 1], 'sock')).toEqual({ success: true });
expect(new DayAssignmentsController(svc({ reorderAssignments, broadcast } as Partial<AssignmentsService>)).reorder(user, '5', '3', { orderedIds: [2, 1] }, 'sock')).toEqual({ success: true });
expect(reorderAssignments).toHaveBeenCalledWith('3', [2, 1]);
expect(broadcast).toHaveBeenCalledWith('5', 'assignment:reordered', { dayId: 3, orderedIds: [2, 1] }, 'sock');
});
@@ -68,16 +70,18 @@ describe('AssignmentOpsController (parity with the per-assignment op routes)', (
it('PUT /:id/move 404 assignment, 404 target day, else moves', () => {
expect(thrown(() => new AssignmentOpsController(svc({ getAssignmentForTrip: vi.fn().mockReturnValue(undefined) } as Partial<AssignmentsService>)).move(user, '5', '9', { new_day_id: 4 }))).toEqual({ status: 404, body: { error: 'Assignment not found' } });
expect(thrown(() => new AssignmentOpsController(svc({ getAssignmentForTrip: vi.fn().mockReturnValue({ day_id: 3 }), dayExists: vi.fn().mockReturnValue(false) } as Partial<AssignmentsService>)).move(user, '5', '9', { new_day_id: 4 }))).toEqual({ status: 404, body: { error: 'Target day not found' } });
const moveAssignment = vi.fn().mockReturnValue({ assignment: { id: 9 } }); const broadcast = vi.fn(); const reconcile = vi.fn();
const moveAssignment = vi.fn().mockReturnValue({ assignment: { id: 9 }, oldDayId: 3 }); const broadcast = vi.fn(); const reconcile = vi.fn();
const s = svc({ getAssignmentForTrip: vi.fn().mockReturnValue({ day_id: 3 }), moveAssignment, broadcast, reconcile } as Partial<AssignmentsService>);
expect(new AssignmentOpsController(s).move(user, '5', '9', { new_day_id: 4, order_index: 0 }, 'sock')).toEqual({ assignment: { id: 9 } });
expect(moveAssignment).toHaveBeenCalledWith('9', 4, 0, 3);
expect(moveAssignment).toHaveBeenCalledWith('9', 4, 0);
expect(broadcast).toHaveBeenCalledWith('5', 'assignment:moved', { assignment: { id: 9 }, oldDayId: 3, newDayId: 4 }, 'sock');
expect(reconcile).toHaveBeenCalledWith('5', 'sock');
});
it('GET /:id/participants returns participants (access-only)', () => {
const s = svc({ getParticipants: vi.fn().mockReturnValue([{ user_id: 2 }]) } as Partial<AssignmentsService>);
it('GET /:id/participants 404 when the assignment is on another trip, else returns participants (access-only)', () => {
expect(thrown(() => new AssignmentOpsController(svc({ getAssignmentForTrip: vi.fn().mockReturnValue(undefined) } as Partial<AssignmentsService>)).participants(user, '5', '9')))
.toEqual({ status: 404, body: { error: 'Assignment not found' } });
const s = svc({ getAssignmentForTrip: vi.fn().mockReturnValue({ id: 9 }), getParticipants: vi.fn().mockReturnValue([{ user_id: 2 }]) } as Partial<AssignmentsService>);
expect(new AssignmentOpsController(s).participants(user, '5', '9')).toEqual({ participants: [{ user_id: 2 }] });
});
@@ -90,10 +94,15 @@ describe('AssignmentOpsController (parity with the per-assignment op routes)', (
expect(reconcile).toHaveBeenCalledWith('5', 'sock');
});
it('PUT /:id/participants 400 not array, else sets + broadcasts', () => {
expect(thrown(() => new AssignmentOpsController(svc()).setParticipants(user, '5', '9', 'no'))).toEqual({ status: 400, body: { error: 'user_ids must be an array' } });
it('PUT /:id/participants 404 on a foreign assignment, else sets + broadcasts (non-array bodies are the Zod pipe\'s 400, covered in e2e)', () => {
const setParticipants = vi.fn().mockReturnValue([{ user_id: 2 }]); const broadcast = vi.fn();
expect(new AssignmentOpsController(svc({ setParticipants, broadcast } as Partial<AssignmentsService>)).setParticipants(user, '5', '9', [2], 'sock')).toEqual({ participants: [{ user_id: 2 }] });
expect(thrown(() => new AssignmentOpsController(svc({ getAssignmentForTrip: vi.fn().mockReturnValue(undefined), setParticipants } as Partial<AssignmentsService>)).setParticipants(user, '5', '9', { user_ids: [2] })))
.toEqual({ status: 404, body: { error: 'Assignment not found' } });
expect(setParticipants).not.toHaveBeenCalled();
const s = svc({ getAssignmentForTrip: vi.fn().mockReturnValue({ id: 9 }), setParticipants, broadcast } as Partial<AssignmentsService>);
expect(new AssignmentOpsController(s).setParticipants(user, '5', '9', { user_ids: [2] }, 'sock')).toEqual({ participants: [{ user_id: 2 }] });
// The trip comes along so the service can confine the ids to its roster.
expect(setParticipants).toHaveBeenCalledWith('9', [2], '5');
expect(broadcast).toHaveBeenCalledWith('5', 'assignment:participants', { assignmentId: 9, participants: [{ user_id: 2 }] }, 'sock');
});
});
@@ -0,0 +1,420 @@
/**
* Unit tests for the DI-native AssignmentsService — ASG-SVC-001 through
* ASG-SVC-028 (written for the DI migration: the legacy
* services/assignmentService.ts had no dedicated unit suite, so these pin the
* relocated SQL — MAX(order_index)+1 ordering, post-write re-selects, the
* time-driven auto-sort with its '99:99' sentinel — plus the hardening that
* followed the move: transactional writes, the DB-derived move source day,
* empty-string time clearing, and the unified compact tag projection; the
* bridge-delegation case died with assignments.bridge). Uses a real in-memory SQLite DB so SQL
* logic is exercised faithfully.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: unknown, userId: number) =>
db.prepare(`
SELECT t.id, t.user_id FROM trips t
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
`).get(userId, tripId, userId),
isOwner: (tripId: unknown, userId: number) =>
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, addTripMember, createDay, createPlace, createDayAssignment, createTag } from '../../helpers/factories';
import { DatabaseService, type TripAccess } from '../../../src/nest/database/database.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { AssignmentsService } from '../../../src/nest/assignments/assignments.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
const dbs = new DatabaseService(testDb);
const realtime = new RealtimeService();
const svc = new AssignmentsService(
dbs,
new PermissionsService(dbs),
realtime,
new QueryHelpersService(dbs),
// Real collaborator rather than a stub: reconcile() runs after every mutation
// and needs the same connection to see the rows these cases write.
new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs)),
);
/**
* canEdit only reads trip.user_id, so the case below hands it just that field.
* The cast names the omission instead of padding the fixture with an id and a
* currency no assertion looks at.
*/
function tripOwnedBy(userId: number): TripAccess {
return { user_id: userId } as TripAccess;
}
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
/** owner + trip + one day + one place — the minimal itinerary fixture. */
function fixture() {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id, { name: 'Louvre' });
return { user, trip, day, place };
}
// ── verifyTripAccess / canEdit ────────────────────────────────────────────────
describe('verifyTripAccess', () => {
it('ASG-SVC-001: returns trip for owner', () => {
const { user, trip } = fixture();
const result = svc.verifyTripAccess(trip.id, user.id);
expect(result).toBeDefined();
expect((result as { user_id: number }).user_id).toBe(user.id);
});
it('ASG-SVC-002: returns falsy for non-member', () => {
const { trip } = fixture();
const { user: stranger } = createUser(testDb);
expect(svc.verifyTripAccess(trip.id, stranger.id)).toBeFalsy();
});
});
describe('canEdit', () => {
it('ASG-SVC-003: owner and member pass day_edit (default trip_member)', () => {
const { user, trip } = fixture();
const { user: member } = createUser(testDb);
addTripMember(testDb, trip.id, member.id);
expect(svc.canEdit(tripOwnedBy(trip.user_id), user)).toBe(true);
expect(svc.canEdit(tripOwnedBy(trip.user_id), member)).toBe(true);
});
});
// ── existence checks ──────────────────────────────────────────────────────────
describe('dayExists / placeExists / assignmentExistsInDay', () => {
it('ASG-SVC-004: dayExists is trip-scoped', () => {
const { trip, day } = fixture();
const { user: other } = createUser(testDb);
const otherTrip = createTrip(testDb, other.id);
expect(svc.dayExists(day.id, trip.id)).toBe(true);
expect(svc.dayExists(day.id, otherTrip.id)).toBe(false);
expect(svc.dayExists(9999, trip.id)).toBe(false);
});
it('ASG-SVC-005: placeExists is trip-scoped', () => {
const { trip, place } = fixture();
const { user: other } = createUser(testDb);
const otherTrip = createTrip(testDb, other.id);
expect(svc.placeExists(place.id, trip.id)).toBe(true);
expect(svc.placeExists(place.id, otherTrip.id)).toBe(false);
});
it('ASG-SVC-006: assignmentExistsInDay requires matching day AND trip', () => {
const { trip, day, place } = fixture();
const otherDay = createDay(testDb, trip.id);
const a = createDayAssignment(testDb, day.id, place.id);
expect(svc.assignmentExistsInDay(a.id, day.id, trip.id)).toBe(true);
expect(svc.assignmentExistsInDay(a.id, otherDay.id, trip.id)).toBe(false);
expect(svc.assignmentExistsInDay(a.id, day.id, trip.id + 1)).toBe(false);
});
});
// ── createAssignment ──────────────────────────────────────────────────────────
describe('createAssignment', () => {
it('ASG-SVC-007: first assignment gets order_index 0, then MAX+1 appends', () => {
const { day, place } = fixture();
const first = svc.createAssignment(day.id, place.id, null);
const second = svc.createAssignment(day.id, place.id, null);
expect(first!.order_index).toBe(0);
expect(second!.order_index).toBe(1);
});
it('ASG-SVC-008: empty-string notes coerce to null (`notes || null`)', () => {
const { day, place } = fixture();
const a = svc.createAssignment(day.id, place.id, '');
expect(a!.notes).toBeNull();
});
it('ASG-SVC-009: returns the re-selected nested shape with place, category and compact tags', () => {
const { user, trip, day, place } = fixture();
const tag = createTag(testDb, user.id, { name: 'museum' });
testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(place.id, tag.id);
const a = svc.createAssignment(day.id, place.id, 'skip the line');
expect(a).toMatchObject({
day_id: day.id,
place_id: place.id,
notes: 'skip the line',
assignment_time: null,
assignment_end_time: null,
leg_transport_mode: null,
participants: [],
place: { id: place.id, name: 'Louvre' },
});
// The same compact tag projection as listDayAssignments — id/name/color/
// created_at only, no user_id — so both read paths share one wire shape.
expect(a!.place.tags).toEqual([{ id: tag.id, name: 'museum', color: '#10b981', created_at: (tag as { created_at?: string }).created_at }]);
void trip;
});
});
// ── listDayAssignments ────────────────────────────────────────────────────────
describe('listDayAssignments', () => {
it('ASG-SVC-010: orders by order_index and formats with compact tags + participants', () => {
const { user, trip, day, place } = fixture();
const second = createPlace(testDb, trip.id, { name: 'Orsay' });
const tag = createTag(testDb, user.id, { name: 'art' });
testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(place.id, tag.id);
const a1 = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
const a2 = createDayAssignment(testDb, day.id, second.id, { order_index: 0 });
svc.setParticipants(a1.id, [user.id], trip.id);
const list = svc.listDayAssignments(day.id);
expect(list.map(a => a.id)).toEqual([a2.id, a1.id]);
// Compact tag projection (id/name/color/created_at only — no user_id key).
expect(list[1].place.tags).toEqual([{ id: tag.id, name: 'art', color: '#10b981', created_at: (tag as { created_at?: string }).created_at }]);
expect(list[1].participants).toEqual([{ user_id: user.id, username: user.username, avatar: null }]);
expect(list[0].participants).toEqual([]);
expect(list[0].place.tags).toEqual([]);
});
it('ASG-SVC-011: returns [] for an empty day', () => {
const { day } = fixture();
expect(svc.listDayAssignments(day.id)).toEqual([]);
});
});
// ── delete / reorder ──────────────────────────────────────────────────────────
describe('deleteAssignment / reorderAssignments', () => {
it('ASG-SVC-012: deleteAssignment removes the row', () => {
const { day, place } = fixture();
const a = createDayAssignment(testDb, day.id, place.id);
svc.deleteAssignment(a.id);
expect(testDb.prepare('SELECT id FROM day_assignments WHERE id = ?').get(a.id)).toBeUndefined();
});
it('ASG-SVC-013: reorderAssignments applies positional order, scoped to the day', () => {
const { trip, day, place } = fixture();
const otherDay = createDay(testDb, trip.id);
const a1 = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
const a2 = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
const foreign = createDayAssignment(testDb, otherDay.id, place.id, { order_index: 5 });
svc.reorderAssignments(day.id, [a2.id, a1.id, foreign.id]);
const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
expect(order(a2.id)).toBe(0);
expect(order(a1.id)).toBe(1);
// The day-scoped WHERE leaves another day's assignment untouched.
expect(order(foreign.id)).toBe(5);
});
});
// ── getAssignmentForTrip / moveAssignment ─────────────────────────────────────
describe('getAssignmentForTrip', () => {
it('ASG-SVC-014: returns the raw row for the trip, undefined cross-trip', () => {
const { trip, day, place } = fixture();
const a = createDayAssignment(testDb, day.id, place.id);
expect(svc.getAssignmentForTrip(a.id, trip.id)).toMatchObject({ id: a.id, day_id: day.id });
expect(svc.getAssignmentForTrip(a.id, trip.id + 1)).toBeUndefined();
});
});
describe('moveAssignment', () => {
it('ASG-SVC-015: moves to the new day, re-selects the nested shape, derives oldDayId from the row', () => {
const { trip, day, place } = fixture();
const target = createDay(testDb, trip.id);
const a = createDayAssignment(testDb, day.id, place.id);
const result = svc.moveAssignment(a.id, target.id, 2);
expect(result.assignment).toMatchObject({ id: a.id, day_id: target.id, order_index: 2 });
expect(result.oldDayId).toBe(day.id);
});
it('ASG-SVC-016: nullish orderIndex coerces to 0; explicit 0 stays 0', () => {
const { trip, day, place } = fixture();
const target = createDay(testDb, trip.id);
const a = createDayAssignment(testDb, day.id, place.id, { order_index: 7 });
expect(svc.moveAssignment(a.id, target.id, undefined).assignment!.order_index).toBe(0);
expect(svc.moveAssignment(a.id, day.id, null).assignment!.order_index).toBe(0);
expect(svc.moveAssignment(a.id, target.id, 0).assignment!.order_index).toBe(0);
});
});
// ── participants ──────────────────────────────────────────────────────────────
describe('getParticipants / setParticipants', () => {
it('ASG-SVC-017: setParticipants replaces the list and returns the joined rows', () => {
const { user, trip, day, place } = fixture();
const { user: peer } = createUser(testDb);
addTripMember(testDb, trip.id, peer.id);
const a = createDayAssignment(testDb, day.id, place.id);
svc.setParticipants(a.id, [user.id], trip.id);
const replaced = svc.setParticipants(a.id, [peer.id], trip.id);
expect(replaced).toEqual([{ user_id: peer.id, username: peer.username, avatar: null }]);
expect(svc.getParticipants(a.id)).toEqual(replaced);
});
it('ASG-SVC-018: empty array clears all participants', () => {
const { user, trip, day, place } = fixture();
const a = createDayAssignment(testDb, day.id, place.id);
svc.setParticipants(a.id, [user.id], trip.id);
expect(svc.setParticipants(a.id, [], trip.id)).toEqual([]);
expect(svc.getParticipants(a.id)).toEqual([]);
});
it('ASG-SVC-019: username COALESCEs display_name over username', () => {
const { user, trip, day, place } = fixture();
testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('Fancy Name', user.id);
const a = createDayAssignment(testDb, day.id, place.id);
const rows = svc.setParticipants(a.id, [user.id], trip.id);
expect(rows).toEqual([{ user_id: user.id, username: 'Fancy Name', avatar: null }]);
});
it('ASG-SVC-020: duplicate user ids collapse via INSERT OR IGNORE', () => {
const { user, trip, day, place } = fixture();
const a = createDayAssignment(testDb, day.id, place.id);
const rows = svc.setParticipants(a.id, [user.id, user.id], trip.id);
expect(rows).toHaveLength(1);
});
// Used to assert that an id violating the users FK threw and rolled the delete
// back. It cannot reach the insert any more: the roster filter drops an id that
// is not on the trip, so a list of nothing but strangers is simply an empty
// list, and the delete stands. The rollback itself is still covered — the
// transaction wraps delete and insert together, and ASG-SVC-018 pins that an
// explicit empty list clears.
it('ASG-SVC-028: a list of ids that are not on the trip clears rather than throwing', () => {
const { user, trip, day, place } = fixture();
const a = createDayAssignment(testDb, day.id, place.id);
svc.setParticipants(a.id, [user.id], trip.id);
expect(() => svc.setParticipants(a.id, [999999], trip.id)).not.toThrow();
expect(svc.getParticipants(a.id)).toEqual([]);
});
it('ASG-SVC-029: keeps the trip members and drops the stranger in one call', () => {
const { user, trip, day, place } = fixture();
const { user: member } = createUser(testDb);
const { user: stranger } = createUser(testDb);
addTripMember(testDb, trip.id, member.id);
const a = createDayAssignment(testDb, day.id, place.id);
const rows = svc.setParticipants(a.id, [user.id, stranger.id, member.id], trip.id) as { user_id: number }[];
expect(rows.map(r => r.user_id).sort()).toEqual([user.id, member.id].sort());
expect(JSON.stringify(rows)).not.toContain(stranger.username);
});
});
// ── updateTime / setLegTransportMode ──────────────────────────────────────────
describe('updateTime', () => {
it('ASG-SVC-021: persists both times and re-selects the nested shape', () => {
const { day, place } = fixture();
const a = createDayAssignment(testDb, day.id, place.id);
const updated = svc.updateTime(a.id, '09:00', '11:30');
expect(updated).toMatchObject({ id: a.id, assignment_time: '09:00', assignment_end_time: '11:30' });
});
it('ASG-SVC-022: a truthy place_time auto-sorts the day chronologically (untimed keep relative position)', () => {
const { day, place } = fixture();
const a = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
const b = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
const c = createDayAssignment(testDb, day.id, place.id, { order_index: 2 });
svc.updateTime(c.id, '08:00', null);
const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
expect([order(c.id), order(a.id), order(b.id)]).toEqual([0, 1, 2]);
svc.updateTime(a.id, '07:00', null);
expect([order(a.id), order(c.id), order(b.id)]).toEqual([0, 1, 2]);
});
it('ASG-SVC-023: clearing with null persists but skips the auto-sort (falsy gate)', () => {
const { day, place } = fixture();
const a = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
const b = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
svc.updateTime(b.id, '06:00', null); // sorts b first
const updated = svc.updateTime(b.id, null, null); // clear — no re-sort
expect(updated!.assignment_time).toBeNull();
const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
expect(order(b.id)).toBe(0);
expect(order(a.id)).toBe(1);
});
it('ASG-SVC-027: an empty-string time clears the override like null (and skips the auto-sort)', () => {
const { day, place } = fixture();
const a = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
const b = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
svc.updateTime(b.id, '06:00', '07:00'); // sorts b first
const updated = svc.updateTime(b.id, '', '');
expect(updated!.assignment_time).toBeNull();
expect(updated!.assignment_end_time).toBeNull();
expect(testDb.prepare('SELECT assignment_time FROM day_assignments WHERE id = ?').get(b.id)).toEqual({ assignment_time: null });
const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
expect(order(b.id)).toBe(0);
expect(order(a.id)).toBe(1);
});
it('ASG-SVC-024: a time without ":" sorts last among timed via the 99:99 sentinel', () => {
const { day, place } = fixture();
const a = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
const b = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
svc.updateTime(a.id, 'morning', null); // no colon → '99:99' in the sort
svc.updateTime(b.id, '13:00', null);
const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
expect(order(b.id)).toBe(0);
expect(order(a.id)).toBe(1);
});
});
describe('setLegTransportMode', () => {
it('ASG-SVC-025: sets and clears the leg override (sticky per #1281)', () => {
const { day, place } = fixture();
const a = createDayAssignment(testDb, day.id, place.id);
expect(svc.setLegTransportMode(a.id, 'cycling')!.leg_transport_mode).toBe('cycling');
expect(svc.setLegTransportMode(a.id, null)!.leg_transport_mode).toBeNull();
});
});
// ASG-SVC-026 pinned the deleted assignments.bridge and died with it — the
// same paths are covered on the service above and via places.mcp injection.
@@ -0,0 +1,337 @@
/**
* The layover pairing behind #1535. Pure, so it gets its own file and no DB: the
* whole question is which two reservation_endpoints rows describe one plane change
* spread over two bookings, and every case below is a shape the AirTrail import
* really produces (timed legs, date-only legs, a leg whose booking clock belongs
* to the other airport).
*/
import { describe, it, expect } from 'vitest';
import {
MAX_CLOCKLESS_DAY_GAP,
MAX_LAYOVER_MS,
transferEndpointIds,
type FlightEndpointRow,
} from '../../../src/nest/atlas/transfer-endpoints';
interface Airport {
code: string | null;
lat: number;
lng: number;
}
const BRU: Airport = { code: 'BRU', lat: 50.9014, lng: 4.4844 };
const HEL: Airport = { code: 'HEL', lat: 60.3172, lng: 24.9633 };
const JFK: Airport = { code: 'JFK', lat: 40.6413, lng: -73.7781 };
/** Brussels' other airport, 45 km from BRU: the one a cheap return lands at. */
const CRL: Airport = { code: 'CRL', lat: 50.4592, lng: 4.4538 };
/** Amsterdam, 170 km from Brussels, which is two cities and not one. */
const AMS: Airport = { code: 'AMS', lat: 52.3105, lng: 4.7683 };
const FRA: Airport = { code: 'FRA', lat: 50.0379, lng: 8.5622 };
/** Same airport as HEL, but geocoded instead of imported, so no IATA code. */
const HEL_NO_CODE: Airport = { code: null, lat: 60.3174, lng: 24.9629 };
interface Clock {
date?: string | null;
time?: string | null;
/** The booking's own reservation_time/_end_time, which is all a date-only leg has. */
fallback?: string | null;
}
let nextId = 0;
function endpoint(
reservationId: number,
role: 'from' | 'to' | 'stop',
at: Airport,
clock: Clock = {},
tripId = 1,
): FlightEndpointRow {
return {
id: ++nextId,
reservation_id: reservationId,
trip_id: tripId,
role,
code: at.code,
lat: at.lat,
lng: at.lng,
local_date: clock.date ?? null,
local_time: clock.time ?? null,
fallback_time: clock.fallback ?? null,
};
}
/**
* BRU → HEL as one booking and HEL → JFK as the next, which is what the importer
* writes when the two legs never chained. `arrival`/`departure` are the clocks at
* the hub, the only ones the pairing looks at.
*/
function splitChain(arrival: Clock, departure: Clock, hub: Airport = HEL, hubAgain: Airport = hub) {
const rows = [
endpoint(1, 'from', BRU, { date: '2026-08-01', time: '07:00' }),
endpoint(1, 'to', hub, arrival),
endpoint(2, 'from', hubAgain, departure),
endpoint(2, 'to', JFK, { date: departure.date ?? '2026-08-01', time: '15:00' }),
];
return { rows, hubIds: [rows[1].id, rows[2].id].sort((a, b) => a - b) };
}
const ids = (found: Set<number>) => [...found].sort((a, b) => a - b);
describe('transferEndpointIds', () => {
it('keeps the 24 h window the importers use to merge the legs of one journey', () => {
expect(MAX_LAYOVER_MS).toBe(24 * 3600 * 1000);
expect(MAX_CLOCKLESS_DAY_GAP).toBe(1);
});
it('pairs an arrival and an onward departure at the same airport code', () => {
const { rows, hubIds } = splitChain({ date: '2026-08-01', time: '09:30' }, { date: '2026-08-01', time: '11:00' });
expect(ids(transferEndpointIds(rows))).toEqual(hubIds);
});
it('pairs on the coordinate when neither row carries a code', () => {
const { rows, hubIds } = splitChain(
{ date: '2026-08-01', time: '09:30' },
{ date: '2026-08-01', time: '11:00' },
HEL_NO_CODE,
);
expect(ids(transferEndpointIds(rows))).toEqual(hubIds);
});
it('pairs a coded row with an uncoded one at the same coordinate', () => {
const { rows, hubIds } = splitChain(
{ date: '2026-08-01', time: '09:30' },
{ date: '2026-08-01', time: '11:00' },
HEL,
HEL_NO_CODE,
);
expect(ids(transferEndpointIds(rows))).toEqual(hubIds);
});
it('matches codes case-insensitively', () => {
const { rows, hubIds } = splitChain(
{ date: '2026-08-01', time: '09:30' },
{ date: '2026-08-01', time: '11:00' },
{ code: 'hel', lat: 1, lng: 1 },
{ code: 'HEL', lat: 2, lng: 2 },
);
expect(ids(transferEndpointIds(rows))).toEqual(hubIds);
});
it('pairs a turnaround with no ground time at all and one of exactly 24 h', () => {
for (const departure of [
{ date: '2026-08-01', time: '09:30' },
{ date: '2026-08-02', time: '09:30' },
]) {
const { rows, hubIds } = splitChain({ date: '2026-08-01', time: '09:30' }, departure);
expect(ids(transferEndpointIds(rows))).toEqual(hubIds);
}
});
it('leaves a stay of 24 h and a minute, or a departure before the arrival, counted', () => {
for (const departure of [
{ date: '2026-08-02', time: '09:31' },
{ date: '2026-08-01', time: '09:29' },
]) {
const { rows } = splitChain({ date: '2026-08-01', time: '09:30' }, departure);
expect(transferEndpointIds(rows).size).toBe(0);
}
});
it('falls back to the calendar date when a leg has no clock, same day or the next', () => {
for (const date of ['2026-08-01', '2026-08-02']) {
const { rows, hubIds } = splitChain({ date: '2026-08-01' }, { date });
expect(ids(transferEndpointIds(rows))).toEqual(hubIds);
}
});
it('treats an unreadable clock as no clock and pairs on the date', () => {
const { rows, hubIds } = splitChain({ date: '2026-08-01', time: 'midday' }, { date: '2026-08-01', time: '11:00' });
expect(ids(transferEndpointIds(rows))).toEqual(hubIds);
});
it('keeps a hub the traveler left two days later', () => {
const { rows } = splitChain({ date: '2026-08-01' }, { date: '2026-08-03' });
expect(transferEndpointIds(rows).size).toBe(0);
});
it('keeps a hub whose onward departure has no date at all', () => {
const { rows } = splitChain({ date: '2026-08-01', time: '09:30' }, {});
expect(transferEndpointIds(rows).size).toBe(0);
});
it('reads the date out of the booking column but never its clock', () => {
// A date-only AirTrail flight leaves the arrival endpoint without local parts, and
// reservation_time holds the DEPARTURE airport's local clock, 22:00 in Brussels for
// a flight that landed in Helsinki that morning. Using it as an arrival time would
// make the onward 11:00 departure look like it left before the plane landed.
const { rows, hubIds } = splitChain(
{ fallback: '2026-08-01T22:00' },
{ date: '2026-08-01', time: '11:00' },
);
expect(ids(transferEndpointIds(rows))).toEqual(hubIds);
});
it('never pairs the two ends of one booking', () => {
const rows = [
endpoint(1, 'from', BRU, { date: '2026-08-01', time: '07:00' }),
endpoint(1, 'to', HEL, { date: '2026-08-01', time: '09:30' }),
];
expect(transferEndpointIds(rows).size).toBe(0);
});
it('never pairs across two trips', () => {
const rows = [
endpoint(1, 'from', BRU, { date: '2026-08-01', time: '07:00' }),
endpoint(1, 'to', HEL, { date: '2026-08-01', time: '09:30' }),
endpoint(2, 'from', HEL, { date: '2026-08-01', time: '11:00' }, 2),
endpoint(2, 'to', JFK, { date: '2026-08-01', time: '15:00' }, 2),
];
expect(transferEndpointIds(rows).size).toBe(0);
});
it('never treats a same-day out-and-back as a connection', () => {
// Flown out in the morning, back in the evening: the day was spent in Finland.
const rows = [
endpoint(1, 'from', BRU, { date: '2026-08-01', time: '07:00' }),
endpoint(1, 'to', HEL, { date: '2026-08-01', time: '09:30' }),
endpoint(2, 'from', HEL, { date: '2026-08-01', time: '18:00' }),
endpoint(2, 'to', BRU, { date: '2026-08-01', time: '20:30' }),
];
expect(transferEndpointIds(rows).size).toBe(0);
});
it("never treats an out-and-back into the city's other airport as a connection", () => {
// Flown to Helsinki in the morning, back to Brussels in the evening, but the return
// lands at Charleroi instead of Zaventem. The day was still spent in Finland, and
// the airport keys alone can never see that the two ends are one city.
const rows = [
endpoint(1, 'from', BRU, { date: '2026-08-01', time: '07:00' }),
endpoint(1, 'to', HEL, { date: '2026-08-01', time: '09:30' }),
endpoint(2, 'from', HEL, { date: '2026-08-01', time: '18:00' }),
endpoint(2, 'to', CRL, { date: '2026-08-01', time: '20:30' }),
];
expect(transferEndpointIds(rows).size).toBe(0);
});
it('still pairs a hub between two airports that are their own cities', () => {
// Amsterdam to Frankfurt to Brussels is a real connection, and AMS and BRU are
// 170 km apart, so the radius that catches a sibling airport must not reach here.
const rows = [
endpoint(1, 'from', AMS, { date: '2026-08-01', time: '07:00' }),
endpoint(1, 'to', FRA, { date: '2026-08-01', time: '08:15' }),
endpoint(2, 'from', FRA, { date: '2026-08-01', time: '10:00' }),
endpoint(2, 'to', BRU, { date: '2026-08-01', time: '11:05' }),
];
expect(ids(transferEndpointIds(rows))).toEqual([rows[1].id, rows[2].id]);
});
it('keeps an overnight return through the sibling airport out of the pairing', () => {
// Same shape a night away on business has: 22.5 h on the ground, home into Gatwick
// instead of Heathrow. Still inside the 24 h window, so only the direction says no.
const LHR: Airport = { code: 'LHR', lat: 51.47, lng: -0.4543 };
const LGW: Airport = { code: 'LGW', lat: 51.1537, lng: -0.1821 };
const rows = [
endpoint(1, 'from', LHR, { date: '2026-08-01', time: '06:30' }),
endpoint(1, 'to', HEL, { date: '2026-08-01', time: '09:30' }),
endpoint(2, 'from', HEL, { date: '2026-08-02', time: '08:00' }),
endpoint(2, 'to', LGW, { date: '2026-08-02', time: '09:45' }),
];
expect(transferEndpointIds(rows).size).toBe(0);
});
it('pairs only inside one trip, even where the hub and the clocks would fit', () => {
// Two journeys through Helsinki on one day. The second trip's arrival has no onward
// leg of its own, and the first trip's departure two hours later must not become one.
const rows = [
endpoint(1, 'from', BRU, { date: '2026-08-01', time: '07:00' }),
endpoint(1, 'to', HEL, { date: '2026-08-01', time: '09:30' }),
endpoint(2, 'from', HEL, { date: '2026-08-01', time: '11:00' }),
endpoint(2, 'to', JFK, { date: '2026-08-01', time: '15:00' }),
endpoint(3, 'from', BRU, { date: '2026-08-01', time: '06:00' }, 2),
endpoint(3, 'to', HEL, { date: '2026-08-01', time: '09:00' }, 2),
];
expect(ids(transferEndpointIds(rows))).toEqual([rows[1].id, rows[2].id]);
});
it('pairs across midnight when only one of the two legs carries a clock', () => {
// The scan looks ahead from the arrival's date, not from its instant, because a
// date-only leg is anchored on midnight: landing at 23:50 and leaving on a flight
// the next day is one connection, and so is a dateless landing left at 23:45.
const lateArrival = splitChain({ date: '2026-08-01', time: '23:50' }, { date: '2026-08-02' });
expect(ids(transferEndpointIds(lateArrival.rows))).toEqual(lateArrival.hubIds);
const lateDeparture = splitChain({ date: '2026-08-01' }, { date: '2026-08-02', time: '23:45' });
expect(ids(transferEndpointIds(lateDeparture.rows))).toEqual(lateDeparture.hubIds);
});
it('pairs nothing when neither side has a readable date', () => {
for (const clock of [{}, { fallback: 'sometime in August' }, { date: '01/08/2026' }]) {
const { rows } = splitChain(clock, clock);
expect(transferEndpointIds(rows).size).toBe(0);
}
});
it('pairs nothing when a date passes the shape check but is not a real date', () => {
for (const time of [null, '09:30']) {
const { rows } = splitChain({ date: '2026-13-45', time }, { date: '2026-13-45', time });
expect(transferEndpointIds(rows).size).toBe(0);
}
});
it('pairs an onward leg whose booking never got a second endpoint', () => {
// A leg AirTrail has no coordinates for loses that endpoint, so the onward booking
// has a 'from' and nothing else, which must not read as flying back to the origin.
const rows = [
endpoint(1, 'from', BRU, { date: '2026-08-01', time: '07:00' }),
endpoint(1, 'to', HEL, { date: '2026-08-01', time: '09:30' }),
endpoint(2, 'from', HEL, { date: '2026-08-01', time: '11:00' }),
];
expect(ids(transferEndpointIds(rows))).toEqual([rows[1].id, rows[2].id]);
});
it('ignores a stop row rather than reading it as an arrival', () => {
// The callers filter roles in SQL, but a 'stop' is already handled by #1486 and must
// never become one half of a pair here.
const rows = [
endpoint(1, 'from', BRU, { date: '2026-08-01', time: '07:00' }),
endpoint(1, 'stop', HEL, { date: '2026-08-01', time: '09:30' }),
endpoint(2, 'from', HEL, { date: '2026-08-01', time: '11:00' }),
endpoint(2, 'to', JFK, { date: '2026-08-01', time: '15:00' }),
];
expect(transferEndpointIds(rows).size).toBe(0);
});
it('ignores a row that can be keyed neither by code nor by coordinate', () => {
const { rows } = splitChain(
{ date: '2026-08-01', time: '09:30' },
{ date: '2026-08-01', time: '11:00' },
{ code: null, lat: NaN, lng: NaN },
);
expect(transferEndpointIds(rows).size).toBe(0);
});
it('has nothing to pair with a single endpoint', () => {
expect(transferEndpointIds([endpoint(1, 'to', HEL, { date: '2026-08-01', time: '09:30' })]).size).toBe(0);
});
it('marks only the pair that matches when the same hub is used again later', () => {
// Out via Helsinki on the 1st, home via Helsinki on the 8th, but that time with
// three days in the city, so only the first pass is a plane change.
const rows = [
endpoint(1, 'from', BRU, { date: '2026-08-01', time: '07:00' }),
endpoint(1, 'to', HEL, { date: '2026-08-01', time: '09:30' }),
endpoint(2, 'from', HEL, { date: '2026-08-01', time: '11:00' }),
endpoint(2, 'to', JFK, { date: '2026-08-01', time: '15:00' }),
endpoint(3, 'from', JFK, { date: '2026-08-08', time: '01:00' }),
endpoint(3, 'to', HEL, { date: '2026-08-08', time: '10:00' }),
endpoint(4, 'from', HEL, { date: '2026-08-11', time: '12:00' }),
endpoint(4, 'to', BRU, { date: '2026-08-11', time: '14:30' }),
];
expect(ids(transferEndpointIds(rows))).toEqual([rows[1].id, rows[2].id]);
});
});
@@ -1,7 +1,10 @@
import { describe, it, expect, vi } from 'vitest';
import { HttpException } from '@nestjs/common';
import { HttpException, RequestMethod } from '@nestjs/common';
import type { Response } from 'express';
import { AtlasController } from '../../../src/nest/atlas/atlas.controller';
import { TravelStatsController } from '../../../src/nest/atlas/travel-stats.controller';
import { JwtAuthGuard } from '../../../src/nest/auth/jwt-auth.guard';
import { BucketItemExistsError } from '../../../src/nest/atlas/atlas.service';
import type { AtlasService } from '../../../src/nest/atlas/atlas.service';
import type { User } from '../../../src/types';
@@ -95,15 +98,13 @@ describe('AtlasController (parity with the legacy /api/addons/atlas route)', ()
});
describe('region', () => {
it('400 when name or country_code is missing', () => {
const markRegion = vi.fn();
return thrown(() => makeController({ markRegion }).markRegion(user, 'by', undefined, 'DE')).then((r) =>
expect(r).toEqual({ status: 400, body: { error: 'name and country_code are required' } }));
});
// The legacy 'name and country_code are required' 400 is now produced by
// the global ZodValidationPipe (atlas.dto.ts / markRegionRequestSchema)
// before the handler runs — covered by the e2e suite.
it('marks a region, upper-casing both codes', () => {
const markRegion = vi.fn();
expect(makeController({ markRegion }).markRegion(user, 'by', 'Bavaria', 'de')).toEqual({ success: true });
expect(makeController({ markRegion }).markRegion(user, 'by', { name: 'Bavaria', country_code: 'de' })).toEqual({ success: true });
expect(markRegion).toHaveBeenCalledWith(8, 'BY', 'Bavaria', 'DE');
});
});
@@ -139,6 +140,26 @@ describe('AtlasController (parity with the legacy /api/addons/atlas route)', ()
.toEqual({ item: { id: 1, name: 'Kyoto' } });
});
it('409 when the service refuses a duplicate create (#1898)', () => {
const createBucketItem = vi.fn(() => { throw new BucketItemExistsError(); });
return thrown(() => makeController({ createBucketItem }).createBucketItem(user, { name: 'Japan' })).then((r) =>
expect(r).toEqual({ status: 409, body: { error: 'Already on your bucket list' } }));
});
it('409 when the service refuses a duplicate update (#1898)', () => {
const updateBucketItem = vi.fn(() => { throw new BucketItemExistsError(); });
return thrown(() => makeController({ updateBucketItem }).updateBucketItem(user, '1', { target_date: '2027-05' })).then((r) =>
expect(r).toEqual({ status: 409, body: { error: 'Already on your bucket list' } }));
});
it('lets any other create/update failure through untouched', () => {
const boom = new Error('disk on fire');
const createBucketItem = vi.fn(() => { throw boom; });
expect(() => makeController({ createBucketItem }).createBucketItem(user, { name: 'Japan' })).toThrow(boom);
const updateBucketItem = vi.fn(() => { throw boom; });
expect(() => makeController({ updateBucketItem }).updateBucketItem(user, '1', { name: 'Japan' })).toThrow(boom);
});
it('404 on delete of a missing item', () => {
const deleteBucketItem = vi.fn().mockReturnValue(false);
return thrown(() => makeController({ deleteBucketItem }).deleteBucketItem(user, '9')).then((r) =>
@@ -151,3 +172,49 @@ describe('AtlasController (parity with the legacy /api/addons/atlas route)', ()
});
});
});
// ---------------------------------------------------------------------------
// TravelStatsController — GET /api/auth/travel-stats.
//
// The path lives under /api/auth on purpose (the client calls it there and
// moving it would break); the code sits in atlas/ because getTravelStats reads
// Atlas data. These cases pin both halves: the delegation, and the fact that
// the controller keeps the auth prefix.
// ---------------------------------------------------------------------------
describe('TravelStatsController', () => {
it('ATLAS-TRAVEL-001: delegates to AtlasService.getTravelStats with the caller id', () => {
const getTravelStats = vi.fn().mockReturnValue({ countries: ['JP'], totalTrips: 2 });
const controller = new TravelStatsController({ getTravelStats } as unknown as AtlasService);
expect(controller.travelStats(user)).toEqual({ countries: ['JP'], totalTrips: 2 });
expect(getTravelStats).toHaveBeenCalledWith(8);
});
it('ATLAS-TRAVEL-002: passes the payload through untouched', () => {
const payload = { countries: [], cities: [], coords: [], totalTrips: 0, totalDays: 0, totalPlaces: 0, totalDistanceKm: 0 };
const controller = new TravelStatsController({ getTravelStats: () => payload } as unknown as AtlasService);
expect(controller.travelStats(user)).toBe(payload);
});
it('ATLAS-TRAVEL-003: still answers on /api/auth/travel-stats, so the move is not a breaking change', () => {
expect(Reflect.getMetadata('path', TravelStatsController)).toBe('api/auth');
expect(Reflect.getMetadata('path', TravelStatsController.prototype.travelStats)).toBe('travel-stats');
expect(Reflect.getMetadata('method', TravelStatsController.prototype.travelStats)).toBe(RequestMethod.GET);
});
// No module-registration check here: importing AtlasModule drags AtlasMcp and
// the whole MCP SDK chain into what is otherwise a plain controller test, and
// it fails to resolve when the file runs on its own. PROFILE-014 covers the
// registration better anyway — it calls the route through the full app.
it('ATLAS-TRAVEL-004: keeps the JwtAuthGuard the route had on AuthController', () => {
// Array shape asserted first on purpose: expect(undefined).toContain(SomeClass)
// passes in this vitest version, so the plain form would stop guarding the
// moment the decorator disappeared. Same reason module-providers.ts exists.
const guards = Reflect.getMetadata('__guards__', TravelStatsController) as unknown[] | undefined;
expect(Array.isArray(guards)).toBe(true);
expect(guards).toEqual(expect.arrayContaining([JwtAuthGuard]));
});
});
@@ -0,0 +1,168 @@
/**
* Unit tests for nest/audit/audit-log.logger — AUDIT-LOG-001 through
* AUDIT-LOG-009. The logger is the plain module carved out of the legacy
* services/auditLog.ts; since the quirk-fix pass it has a real severity
* threshold (error < warn < info < debug) against the import-frozen LOG_LEVEL,
* lazy data/logs creation (no import-time mkdir), and console.error fallbacks
* for file-IO failures. It sits inside the src/nest/** coverage gate, so its
* branches are pinned here with fs fully mocked.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('fs', () => {
const mock = {
mkdirSync: vi.fn(),
existsSync: vi.fn(() => false),
statSync: vi.fn(() => ({ size: 0 })),
appendFileSync: vi.fn(),
renameSync: vi.fn(),
};
return { default: mock, ...mock };
});
import fs from 'fs';
import { logInfo, logDebug, logError, logWarn, LOG_LEVEL } from '../../../src/nest/audit/audit-log.logger';
const mocked = vi.mocked(fs);
beforeEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
mocked.existsSync.mockReturnValue(false);
mocked.statSync.mockReturnValue({ size: 0 } as unknown as ReturnType<typeof fs.statSync>);
});
// tests/setup.ts sets LOG_LEVEL=error before the first import, so the statically
// imported helpers run at the most restrictive threshold; the fresh-import cases
// below exercise the other levels.
async function freshLogger(level: string) {
vi.resetModules();
vi.stubEnv('LOG_LEVEL', level);
return import('../../../src/nest/audit/audit-log.logger');
}
describe('severity threshold (frozen at import)', () => {
it('AUDIT-LOG-001: at LOG_LEVEL=error only logError writes (console + file)', () => {
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(LOG_LEVEL).toBe('error');
logInfo('nope');
logWarn('nope');
logDebug('nope');
expect(log).not.toHaveBeenCalled();
expect(warn).not.toHaveBeenCalled();
expect(mocked.appendFileSync).not.toHaveBeenCalled();
logError('boom');
const consoleLine = String(err.mock.calls[0][0]);
expect(consoleLine.startsWith('\x1b[31m[ERROR]\x1b[0m ')).toBe(true);
expect(consoleLine).toMatch(/ \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} boom$/);
expect(String(mocked.appendFileSync.mock.calls[0][1])).toMatch(/^\[ERROR\] \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} boom\n$/);
});
it('AUDIT-LOG-002: at LOG_LEVEL=debug every level logs with its tag', async () => {
const fresh = await freshLogger('debug');
try {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
fresh.logInfo('i');
fresh.logDebug('d');
fresh.logWarn('w');
fresh.logError('e');
expect(log.mock.calls.map((c) => String(c[0]).includes('[INFO]') || String(c[0]).includes('[DEBUG]'))).toEqual([true, true]);
expect(String(warn.mock.calls[0][0])).toContain('[WARN]');
expect(String(err.mock.calls[0][0])).toContain('[ERROR]');
expect(mocked.appendFileSync).toHaveBeenCalledTimes(4);
} finally {
vi.unstubAllEnvs();
vi.resetModules();
}
});
it('AUDIT-LOG-003: at the production default (info) info/warn log, debug does not', async () => {
const fresh = await freshLogger('info');
try {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
fresh.logInfo('visible');
fresh.logDebug('invisible');
fresh.logWarn('visible');
expect(log).toHaveBeenCalledTimes(1);
expect(String(log.mock.calls[0][0])).toContain('[INFO]');
expect(warn).toHaveBeenCalledTimes(1);
} finally {
vi.unstubAllEnvs();
vi.resetModules();
}
});
it('AUDIT-LOG-004: the freeze happens at first import — LOG_LEVEL reflects the env then', async () => {
const fresh = await freshLogger('debug');
try {
expect(fresh.LOG_LEVEL).toBe('debug');
expect(LOG_LEVEL).toBe('error'); // the static import stays frozen
} finally {
vi.unstubAllEnvs();
vi.resetModules();
}
});
});
describe('lazy logs dir + rotation + resilience', () => {
it('AUDIT-LOG-005: data/logs is created lazily on the first write, not at import', async () => {
const fresh = await freshLogger('info');
try {
mocked.mkdirSync.mockClear();
expect(mocked.mkdirSync).not.toHaveBeenCalled();
vi.spyOn(console, 'log').mockImplementation(() => {});
fresh.logInfo('first write');
expect(mocked.mkdirSync).toHaveBeenCalledTimes(1);
fresh.logInfo('second write');
expect(mocked.mkdirSync).toHaveBeenCalledTimes(1); // memoized
} finally {
vi.unstubAllEnvs();
vi.resetModules();
}
});
it('AUDIT-LOG-006: rotates trek.log through .1… in descending order once the cap is hit', () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
mocked.existsSync.mockReturnValue(true);
mocked.statSync.mockReturnValue({ size: 10 * 1024 * 1024 } as unknown as ReturnType<typeof fs.statSync>);
logError('rotate me');
// MAX_LOG_FILES=5 → renames .3→.4, .2→.3, .1→.2, trek.log→.1 (descending).
expect(mocked.renameSync).toHaveBeenCalledTimes(4);
const dsts = mocked.renameSync.mock.calls.map((c) => String(c[1]));
expect(dsts[0].endsWith('trek.log.4')).toBe(true);
expect(dsts[3].endsWith('trek.log.1')).toBe(true);
expect(String(mocked.renameSync.mock.calls[3][0]).endsWith('trek.log')).toBe(true);
});
it('AUDIT-LOG-007: no rotation below the size cap', () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
mocked.existsSync.mockReturnValue(true);
mocked.statSync.mockReturnValue({ size: 10 } as unknown as ReturnType<typeof fs.statSync>);
logError('small');
expect(mocked.renameSync).not.toHaveBeenCalled();
expect(mocked.appendFileSync).toHaveBeenCalledTimes(1);
});
it('AUDIT-LOG-008: file-write failures never throw and leave a console.error trace', () => {
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
mocked.appendFileSync.mockImplementation(() => { throw new Error('disk full'); });
expect(() => logError('still up')).not.toThrow();
// First call is the [ERROR] line itself, second is the fallback trace.
expect(err).toHaveBeenCalledTimes(2);
expect(String(err.mock.calls[1][0])).toBe('[logger] log file write failed: disk full');
});
it('AUDIT-LOG-009: rotation failures are traced and the write still goes through', () => {
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
mocked.existsSync.mockReturnValue(true);
mocked.statSync.mockImplementation(() => { throw new Error('stat broke'); });
expect(() => logError('resilient')).not.toThrow();
expect(String(err.mock.calls[1][0])).toBe('[logger] log rotation failed: stat broke');
expect(mocked.appendFileSync).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,215 @@
/**
* Unit tests for the DI-native audit domain — AUDIT-SVC-001 through
* AUDIT-SVC-017 (001–007 are the getClientIp cases moved 1:1 from the legacy
* tests/unit/services/auditLog.test.ts, which had no case IDs — the IDs are
* introduced with the move; 008–014 cover writeAudit over a real in-memory
* SQLite DB, which the legacy suite never exercised; 015–017 pin the
* audit.bridge delegation). The logger module is mocked (it replaces the old
* suite's fs mock: the import-time mkdir lives there now, and mocking it lets
* the exact log-line formats be asserted).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
logDebug: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
}));
import type { Request } from 'express';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { AuditService } from '../../../src/nest/audit/audit.service';
import { getClientIp } from '../../../src/nest/audit/client-ip';
import { logInfo, logDebug, logError } from '../../../src/nest/audit/audit-log.logger';
const svc = new AuditService(new DatabaseService(testDb));
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
vi.clearAllMocks();
testDb.prepare('DELETE FROM audit_log').run();
testDb.prepare('DELETE FROM users').run();
});
afterAll(() => {
testDb.close();
});
function makeReq(options: {
ip?: string;
xff?: string | string[];
remoteAddress?: string;
} = {}): Request {
return {
ip: options.ip,
headers: {
...(options.xff !== undefined ? { 'x-forwarded-for': options.xff } : {}),
},
socket: { remoteAddress: options.remoteAddress ?? undefined },
} as unknown as Request;
}
// ── getClientIp (pure, moved 1:1) ─────────────────────────────────────────────
describe('getClientIp', () => {
it('AUDIT-SVC-001: returns req.ip, which Express resolved through the trust-proxy hop count', () => {
expect(getClientIp(makeReq({ ip: '1.2.3.4', xff: '9.9.9.9, 1.2.3.4' }))).toBe('1.2.3.4');
});
it('AUDIT-SVC-002: ignores a hand-written X-Forwarded-For — the leftmost entry is whatever the caller typed', () => {
expect(getClientIp(makeReq({ ip: '203.0.113.7', xff: '10.0.0.1' }))).toBe('203.0.113.7');
});
it('AUDIT-SVC-003: ignores an array-valued X-Forwarded-For too', () => {
expect(getClientIp(makeReq({ ip: '203.0.113.7', xff: ['203.0.113.1', '10.0.0.1'] }))).toBe('203.0.113.7');
});
it('AUDIT-SVC-004: trims whitespace from the resolved IP', () => {
expect(getClientIp(makeReq({ ip: ' 192.168.1.1 ' }))).toBe('192.168.1.1');
});
it('AUDIT-SVC-005: falls back to req.socket.remoteAddress when req.ip is unset', () => {
expect(getClientIp(makeReq({ remoteAddress: '172.16.0.1' }))).toBe('172.16.0.1');
});
it('AUDIT-SVC-006: returns null when there is neither a resolved IP nor a socket address', () => {
expect(getClientIp(makeReq({}))).toBeNull();
});
it('AUDIT-SVC-007: returns null for an empty req.ip with no socket address', () => {
const req = {
ip: '',
headers: { 'x-forwarded-for': '203.0.113.9' },
socket: { remoteAddress: undefined },
} as unknown as Request;
expect(getClientIp(req)).toBeNull();
});
});
// ── writeAudit (real DB) ──────────────────────────────────────────────────────
function seedUser(id: number, email: string): void {
testDb.prepare(
"INSERT INTO users (id, username, email, password_hash, role) VALUES (?, ?, ?, 'x', 'user')"
).run(id, `u${id}`, email);
}
describe('writeAudit', () => {
it('AUDIT-SVC-008: inserts the row and logs the labeled summary line', () => {
seedUser(1, 'a@b.c');
svc.writeAudit({ userId: 1, action: 'trip.create', resource: 'trip', details: { title: 'Rome' }, ip: '1.2.3.4' });
const row = testDb.prepare('SELECT user_id, action, resource, details, ip FROM audit_log').get();
expect(row).toEqual({ user_id: 1, action: 'trip.create', resource: 'trip', details: '{"title":"Rome"}', ip: '1.2.3.4' });
expect(logInfo).toHaveBeenCalledWith('a@b.c created trip "Rome" ip=1.2.3.4');
});
it('AUDIT-SVC-009: empty details object stores NULL details and skips the debug fallback', () => {
seedUser(1, 'a@b.c');
svc.writeAudit({ userId: 1, action: 'user.login', details: {}, ip: '1.2.3.4' });
const row = testDb.prepare('SELECT details FROM audit_log').get() as { details: string | null };
expect(row.details).toBeNull();
expect(logDebug).not.toHaveBeenCalled();
});
it('AUDIT-SVC-010: unknown action keeps the raw key; empty-email/zero/null userIds resolve', () => {
seedUser(1, 'a@b.c');
svc.writeAudit({ userId: 1, action: 'custom.thing', ip: '9.9.9.9' });
expect(logInfo).toHaveBeenLastCalledWith('a@b.c custom.thing ip=9.9.9.9');
seedUser(42, ''); // falsy email → the `row?.email || uid:N` fallback
svc.writeAudit({ userId: 42, action: 'user.login', ip: '9.9.9.9' });
expect(logInfo).toHaveBeenLastCalledWith('uid:42 logged in ip=9.9.9.9');
seedUser(0, 'zero@b.c'); // since the quirk fix, a real id 0 resolves via the DB
svc.writeAudit({ userId: 0, action: 'user.login', ip: '9.9.9.9' });
expect(logInfo).toHaveBeenLastCalledWith('zero@b.c logged in ip=9.9.9.9');
svc.writeAudit({ userId: null, action: 'user.login', ip: '9.9.9.9' });
expect(logInfo).toHaveBeenLastCalledWith('anonymous logged in ip=9.9.9.9');
});
it('AUDIT-SVC-019: a trip title with a line break cannot forge a second log line', () => {
seedUser(1, 'a@b.c');
svc.writeAudit({
userId: 1,
action: 'trip.create',
details: { title: 'Rome\nadmin@b.c changed user role' },
ip: '1.2.3.4',
});
const logged = String((logInfo as unknown as { mock: { calls: string[][] } }).mock.calls.at(-1)?.[0]);
expect(logged).not.toContain('\n');
expect(logged).toBe('a@b.c created trip "Rome admin@b.c changed user role" ip=1.2.3.4');
});
it('AUDIT-SVC-011: omitted resource/ip store NULL and the log line ends ip=-', () => {
seedUser(1, 'a@b.c');
svc.writeAudit({ userId: 1, action: 'user.login' });
const row = testDb.prepare('SELECT resource, ip FROM audit_log').get();
expect(row).toEqual({ resource: null, ip: null });
expect(logInfo).toHaveBeenCalledWith('a@b.c logged in ip=-');
});
it('AUDIT-SVC-012: debugDetails wins the debug line; detailsJson is the fallback', () => {
seedUser(1, 'a@b.c');
svc.writeAudit({ userId: 1, action: 'settings.app_update', details: { require_mfa: true }, debugDetails: { raw: 1 } });
expect(logDebug).toHaveBeenLastCalledWith('AUDIT settings.app_update userId=1 {"raw":1}');
svc.writeAudit({ userId: 1, action: 'settings.app_update', details: { require_mfa: true } });
expect(logDebug).toHaveBeenLastCalledWith('AUDIT settings.app_update userId=1 {"require_mfa":true}');
});
it('AUDIT-SVC-013: never throws — a failed insert reduces to a logError line', () => {
testDb.prepare('ALTER TABLE audit_log RENAME TO audit_log_gone').run();
expect(() => svc.writeAudit({ userId: 1, action: 'user.login' })).not.toThrow();
expect(logError).toHaveBeenCalledWith(expect.stringMatching(/^Audit write failed: /));
testDb.prepare('ALTER TABLE audit_log_gone RENAME TO audit_log').run();
});
it('AUDIT-SVC-018: settings.api_keys_update names the changed keys and nothing else (#1939)', () => {
seedUser(1, 'admin@b.c');
svc.writeAudit({
userId: 1,
action: 'settings.api_keys_update',
resource: 'api_keys',
details: { changed: ['maps_api_key', 'unsplash_api_key'] },
ip: '1.2.3.4',
});
expect(logInfo).toHaveBeenLastCalledWith('admin@b.c updated API keys (maps_api_key, unsplash_api_key) ip=1.2.3.4');
// A details blob without the array (or with an empty one) leaves the brief off
// rather than stringifying whatever else is in there.
svc.writeAudit({ userId: 1, action: 'settings.api_keys_update', details: { changed: [] }, ip: '1.2.3.4' });
expect(logInfo).toHaveBeenLastCalledWith('admin@b.c updated API keys ip=1.2.3.4');
svc.writeAudit({ userId: 1, action: 'settings.api_keys_update', details: { other: 'x' }, ip: '1.2.3.4' });
expect(logInfo).toHaveBeenLastCalledWith('admin@b.c updated API keys ip=1.2.3.4');
});
it('AUDIT-SVC-014: buildInfoSummary variants (settings parts, login empty brief)', () => {
seedUser(1, 'a@b.c');
svc.writeAudit({ userId: 1, action: 'settings.app_update', details: { notification_channel: 'smtp', require_mfa: false }, ip: '1.1.1.1' });
expect(logInfo).toHaveBeenLastCalledWith('a@b.c updated settings (channel=smtp, mfa=false) ip=1.1.1.1');
svc.writeAudit({ userId: 1, action: 'user.login', details: { anything: true }, ip: '1.1.1.1' });
expect(logInfo).toHaveBeenLastCalledWith('a@b.c logged in ip=1.1.1.1');
});
});
+63 -52
View File
@@ -2,19 +2,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HttpException } from '@nestjs/common';
import type { Request } from 'express';
vi.mock('../../../src/middleware/auth', () => ({ extractToken: vi.fn(), verifyJwtAndLoadUser: vi.fn() }));
vi.mock('../../../src/services/authService', () => ({ resolveAuthToggles: vi.fn() }));
vi.mock('../../../src/services/cookie', () => ({ setAuthCookie: vi.fn() }));
vi.mock('../../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: vi.fn(() => '1.2.3.4') }));
vi.mock('../../../src/services/passkeyService', () => ({
passkeyRegisterOptions: vi.fn(),
passkeyRegisterVerify: vi.fn(),
passkeyLoginOptions: vi.fn(),
passkeyLoginVerify: vi.fn(),
listPasskeys: vi.fn(),
renamePasskey: vi.fn(),
deletePasskey: vi.fn(),
}));
vi.mock('../../../src/nest/auth/jwt-verify', () => ({ extractToken: vi.fn(), verifyJwtAndLoadUser: vi.fn() }));
vi.mock('../../../src/nest/common/cookie', () => ({ setAuthCookie: vi.fn() }));
vi.mock('../../../src/nest/audit/client-ip', () => ({ getClientIp: vi.fn(() => '1.2.3.4') }));
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logDebug: vi.fn(), logError: vi.fn(), logWarn: vi.fn() }));
import { JwtAuthGuard } from '../../../src/nest/auth/jwt-auth.guard';
import { CookieAuthGuard } from '../../../src/nest/auth/cookie-auth.guard';
@@ -22,13 +13,30 @@ import { OptionalJwtGuard } from '../../../src/nest/auth/optional-jwt.guard';
import { AdminGuard } from '../../../src/nest/auth/admin.guard';
import { PasskeyEnabledGuard } from '../../../src/nest/auth/passkey-enabled.guard';
import { PasskeyController } from '../../../src/nest/auth/passkey.controller';
import { RateLimitService } from '../../../src/nest/auth/rate-limit.service';
import { RateLimitService } from '../../../src/nest/common/rate-limit.service';
// AuditService is constructor-injected since the auditLog DI migration; the
// wrapper keeps the historical construction sites positional.
const writeAudit = vi.fn();
const audit = { writeAudit } as unknown as AuditService;
// PasskeyService is constructor-injected since the passkey DI fold; a stub
// object replaces the old services/passkeyService path mock.
const passkey = {
passkeyRegisterOptions: vi.fn(),
passkeyRegisterVerify: vi.fn(),
passkeyLoginOptions: vi.fn(),
passkeyLoginVerify: vi.fn(),
listPasskeys: vi.fn(),
renamePasskey: vi.fn(),
deletePasskey: vi.fn(),
};
const pc = (limiter: RateLimitService) => new PasskeyController(limiter, audit, passkey as unknown as PasskeyService);
import { CurrentUser } from '../../../src/nest/auth/current-user.decorator';
import { extractToken, verifyJwtAndLoadUser } from '../../../src/middleware/auth';
import { resolveAuthToggles } from '../../../src/services/authService';
import { setAuthCookie } from '../../../src/services/cookie';
import { writeAudit } from '../../../src/services/auditLog';
import * as passkey from '../../../src/services/passkeyService';
import { extractToken, verifyJwtAndLoadUser } from '../../../src/nest/auth/jwt-verify';
import type { AuthService } from '../../../src/nest/auth/auth.service';
import type { PasskeyService } from '../../../src/nest/auth/passkey.service';
import { setAuthCookie } from '../../../src/nest/common/cookie';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import type { User } from '../../../src/types';
const user = { id: 1, username: 'u', role: 'user', email: 'u@example.test' } as User;
@@ -157,15 +165,18 @@ describe('AdminGuard', () => {
});
describe('PasskeyEnabledGuard', () => {
const guard = new PasskeyEnabledGuard();
// The guard injects AuthService since the auth DI fold; a resolveAuthToggles
// stub replaces the old services/authService path mock.
const resolveAuthToggles = vi.fn();
const guard = new PasskeyEnabledGuard({ resolveAuthToggles } as unknown as AuthService);
it('404s when passkey_login is off', () => {
vi.mocked(resolveAuthToggles).mockReturnValue({ passkey_login: false } as ReturnType<typeof resolveAuthToggles>);
resolveAuthToggles.mockReturnValue({ passkey_login: false });
expect(thrown(() => guard.canActivate())).toEqual({ status: 404, body: { error: 'Passkey login is not enabled' } });
});
it('allows when passkey_login is on', () => {
vi.mocked(resolveAuthToggles).mockReturnValue({ passkey_login: true } as ReturnType<typeof resolveAuthToggles>);
resolveAuthToggles.mockReturnValue({ passkey_login: true });
expect(guard.canActivate()).toBe(true);
});
});
@@ -195,53 +206,53 @@ describe('PasskeyController', () => {
function rl(): RateLimitService { return new RateLimitService(); }
it('register/options maps a service error, else returns the options', async () => {
vi.mocked(passkey.passkeyRegisterOptions).mockResolvedValue({ error: 'Incorrect password', status: 401 });
expect(await thrownAsync(() => new PasskeyController(rl()).registerOptions(user, { password: 'x' }, req))).toEqual({ status: 401, body: { error: 'Incorrect password' } });
vi.mocked(passkey.passkeyRegisterOptions).mockResolvedValue({ options: { challenge: 'c' } as never });
expect(await new PasskeyController(rl()).registerOptions(user, { password: 'p' }, req)).toEqual({ challenge: 'c' });
passkey.passkeyRegisterOptions.mockResolvedValue({ error: 'Incorrect password', status: 401 });
expect(await thrownAsync(() => pc(rl()).registerOptions(user, { password: 'x' }, req))).toEqual({ status: 401, body: { error: 'Incorrect password' } });
passkey.passkeyRegisterOptions.mockResolvedValue({ options: { challenge: 'c' } as never });
expect(await pc(rl()).registerOptions(user, { password: 'p' }, req)).toEqual({ challenge: 'c' });
});
it('register/verify maps a service error, else audits and returns the credential', async () => {
vi.mocked(passkey.passkeyRegisterVerify).mockResolvedValue({ error: 'Verification failed', status: 400 } as never);
expect(await thrownAsync(() => new PasskeyController(rl()).registerVerify(user, {}, req))).toEqual({ status: 400, body: { error: 'Verification failed' } });
vi.mocked(passkey.passkeyRegisterVerify).mockResolvedValue({ credential: { id: 'cr' } } as never);
expect(await new PasskeyController(rl()).registerVerify(user, {}, req)).toEqual({ success: true, credential: { id: 'cr' } });
passkey.passkeyRegisterVerify.mockResolvedValue({ error: 'Verification failed', status: 400 } as never);
expect(await thrownAsync(() => pc(rl()).registerVerify(user, {}, req))).toEqual({ status: 400, body: { error: 'Verification failed' } });
passkey.passkeyRegisterVerify.mockResolvedValue({ credential: { id: 'cr' } } as never);
expect(await pc(rl()).registerVerify(user, {}, req)).toEqual({ success: true, credential: { id: 'cr' } });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.passkey_register' }));
});
it('login/options maps a service error, else returns the options', async () => {
vi.mocked(passkey.passkeyLoginOptions).mockResolvedValue({ error: 'Not configured', status: 503 } as never);
expect(await thrownAsync(() => new PasskeyController(rl()).loginOptions(req))).toEqual({ status: 503, body: { error: 'Not configured' } });
vi.mocked(passkey.passkeyLoginOptions).mockResolvedValue({ options: { challenge: 'd' } } as never);
expect(await new PasskeyController(rl()).loginOptions(req)).toEqual({ challenge: 'd' });
passkey.passkeyLoginOptions.mockResolvedValue({ error: 'Not configured', status: 503 } as never);
expect(await thrownAsync(() => pc(rl()).loginOptions(req))).toEqual({ status: 503, body: { error: 'Not configured' } });
passkey.passkeyLoginOptions.mockResolvedValue({ options: { challenge: 'd' } } as never);
expect(await pc(rl()).loginOptions(req)).toEqual({ challenge: 'd' });
});
it('login/verify audits a failure then maps the error, padding latency', async () => {
vi.mocked(passkey.passkeyLoginVerify).mockResolvedValue({ error: 'No match', status: 401, auditAction: 'user.login_fail', auditUserId: null } as never);
expect(await thrownAsync(() => new PasskeyController(rl()).loginVerify({}, req, res))).toEqual({ status: 401, body: { error: 'No match' } });
passkey.passkeyLoginVerify.mockResolvedValue({ error: 'No match', status: 401, auditAction: 'user.login_fail', auditUserId: null } as never);
expect(await thrownAsync(() => pc(rl()).loginVerify({}, req, res))).toEqual({ status: 401, body: { error: 'No match' } });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.login_fail' }));
}, 10000);
it('login/verify sets the session cookie and audits login on success', async () => {
vi.mocked(passkey.passkeyLoginVerify).mockResolvedValue({ token: 'tk', user, auditUserId: 1 } as never);
expect(await new PasskeyController(rl()).loginVerify({}, req, res)).toEqual({ token: 'tk', user });
passkey.passkeyLoginVerify.mockResolvedValue({ token: 'tk', user, auditUserId: 1 } as never);
expect(await pc(rl()).loginVerify({}, req, res)).toEqual({ token: 'tk', user });
expect(setAuthCookie).toHaveBeenCalledWith(res, 'tk', req);
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.login', details: { method: 'passkey' } }));
}, 10000);
it('credentials: list, rename (error + success), delete (error + success)', () => {
vi.mocked(passkey.listPasskeys).mockReturnValue([{ id: 'a' }]);
expect(new PasskeyController(rl()).list(user)).toEqual({ credentials: [{ id: 'a' }] });
passkey.listPasskeys.mockReturnValue([{ id: 'a' }]);
expect(pc(rl()).list(user)).toEqual({ credentials: [{ id: 'a' }] });
vi.mocked(passkey.renamePasskey).mockReturnValue({ error: 'Not found', status: 404 });
expect(thrown(() => new PasskeyController(rl()).rename(user, 'cid', { name: 'x' }))).toEqual({ status: 404, body: { error: 'Not found' } });
vi.mocked(passkey.renamePasskey).mockReturnValue({ success: true });
expect(new PasskeyController(rl()).rename(user, 'cid', { name: 'x' })).toEqual({ success: true });
passkey.renamePasskey.mockReturnValue({ error: 'Not found', status: 404 });
expect(thrown(() => pc(rl()).rename(user, 'cid', { name: 'x' }))).toEqual({ status: 404, body: { error: 'Not found' } });
passkey.renamePasskey.mockReturnValue({ success: true });
expect(pc(rl()).rename(user, 'cid', { name: 'x' })).toEqual({ success: true });
vi.mocked(passkey.deletePasskey).mockReturnValue({ error: 'Incorrect password', status: 401 });
expect(thrown(() => new PasskeyController(rl()).remove(user, 'cid', { password: 'x' }, req))).toEqual({ status: 401, body: { error: 'Incorrect password' } });
vi.mocked(passkey.deletePasskey).mockReturnValue({ success: true });
expect(new PasskeyController(rl()).remove(user, 'cid', { password: 'p' }, req)).toEqual({ success: true });
passkey.deletePasskey.mockReturnValue({ error: 'Incorrect password', status: 401 });
expect(thrown(() => pc(rl()).remove(user, 'cid', { password: 'x' }, req))).toEqual({ status: 401, body: { error: 'Incorrect password' } });
passkey.deletePasskey.mockReturnValue({ success: true });
expect(pc(rl()).remove(user, 'cid', { password: 'p' }, req)).toEqual({ success: true });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.passkey_delete' }));
});
@@ -249,16 +260,16 @@ describe('PasskeyController', () => {
const s = new RateLimitService();
const now = Date.now();
for (let i = 0; i < 5; i++) s.check('mfa', '9.9.9.9', 5, 15 * 60 * 1000, now);
expect(await thrownAsync(() => new PasskeyController(s).registerOptions(user, {}, req))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
expect(await thrownAsync(() => pc(s).registerOptions(user, {}, req))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
const s2 = new RateLimitService();
for (let i = 0; i < 10; i++) s2.check('login', '9.9.9.9', 10, 15 * 60 * 1000, now);
expect(await thrownAsync(() => new PasskeyController(s2).loginOptions(req))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
expect(await thrownAsync(() => pc(s2).loginOptions(req))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
});
it('falls back to the "unknown" rate-limit key when req.ip is absent', async () => {
vi.mocked(passkey.passkeyLoginOptions).mockResolvedValue({ options: { challenge: 'z' } } as never);
passkey.passkeyLoginOptions.mockResolvedValue({ options: { challenge: 'z' } } as never);
const noIp = {} as Request;
expect(await new PasskeyController(rl()).loginOptions(noIp)).toEqual({ challenge: 'z' });
expect(await pc(rl()).loginOptions(noIp)).toEqual({ challenge: 'z' });
});
});
+184 -86
View File
@@ -1,17 +1,23 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { HttpException } from '@nestjs/common';
import type { Request, Response } from 'express';
vi.mock('../../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: vi.fn(() => '1.2.3.4') }));
vi.mock('../../../src/services/demo', () => ({ isDemoEmail: vi.fn(() => false) }));
vi.mock('../../../src/nest/audit/client-ip', () => ({ getClientIp: vi.fn(() => '1.2.3.4') }));
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logDebug: vi.fn(), logError: vi.fn(), logWarn: vi.fn() }));
vi.mock('../../../src/nest/common/demo', () => ({ isDemoEmail: vi.fn(() => false) }));
import { AuthPublicController } from '../../../src/nest/auth/auth-public.controller';
import { AuthController } from '../../../src/nest/auth/auth.controller';
import { RateLimitService } from '../../../src/nest/auth/rate-limit.service';
import type { TokenService } from '../../../src/nest/tokens/token.service';
import type { UserProfileService } from '../../../src/nest/auth/user-profile.service';
import { RateLimitService } from '../../../src/nest/common/rate-limit.service';
import type { AuthService } from '../../../src/nest/auth/auth.service';
import { writeAudit } from '../../../src/services/auditLog';
import { isDemoEmail } from '../../../src/services/demo';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import { isDemoEmail } from '../../../src/nest/common/demo';
import type { User } from '../../../src/types';
import { anyBody } from '../../helpers/dto';
import type { ForgotPasswordDto } from '../../../src/nest/auth/auth.dto';
const user = { id: 1, username: 'u', role: 'user', email: 'u@example.test' } as User;
const req = { ip: '9.9.9.9', headers: {} } as Request;
@@ -22,6 +28,17 @@ function asvc(o: Partial<AuthService> = {}): AuthService {
}
function rl(): RateLimitService { return new RateLimitService(); }
// AuditService is constructor-injected since the auditLog DI migration; the
// wrappers keep the historical construction sites positional.
const writeAudit = vi.fn();
const audit = { writeAudit } as unknown as AuditService;
const apc = (a: AuthService, limiter: RateLimitService) => new AuthPublicController(a, limiter, audit);
// Tokens moved to TokenService; the controller takes it second. Stubbed via a
// third, optional argument so every non-token call site stays as it was.
const storageStub = { put: vi.fn().mockResolvedValue(undefined) } as unknown as import('../../../src/nest/storage/storage.service').StorageService;
const ac = (a: AuthService, limiter: RateLimitService, t: Partial<TokenService> = {}, pr: Partial<UserProfileService> = {}) =>
new AuthController(a, pr as UserProfileService, t as TokenService, limiter, audit, new RuntimeEnvService(), storageStub);
function thrown(fn: () => unknown): { status: number; body: unknown } {
try { fn(); } catch (err) {
expect(err).toBeInstanceOf(HttpException);
@@ -67,17 +84,17 @@ describe('RateLimitService', () => {
describe('AuthPublicController', () => {
it('demo-login maps error, else sets the cookie + returns token/user', () => {
expect(thrown(() => new AuthPublicController(asvc({ demoLogin: vi.fn().mockReturnValue({ error: 'Demo disabled', status: 403 }) } as Partial<AuthService>), rl()).demoLogin(req, res))).toEqual({ status: 403, body: { error: 'Demo disabled' } });
expect(thrown(() => apc(asvc({ demoLogin: vi.fn().mockReturnValue({ error: 'Demo disabled', status: 403 }) } as Partial<AuthService>), rl()).demoLogin(req, res))).toEqual({ status: 403, body: { error: 'Demo disabled' } });
const setAuthCookie = vi.fn();
const c = new AuthPublicController(asvc({ demoLogin: vi.fn().mockReturnValue({ token: 'tk', user }), setAuthCookie } as Partial<AuthService>), rl());
const c = apc(asvc({ demoLogin: vi.fn().mockReturnValue({ token: 'tk', user }), setAuthCookie } as Partial<AuthService>), rl());
expect(c.demoLogin(req, res)).toEqual({ token: 'tk', user });
expect(setAuthCookie).toHaveBeenCalledWith(res, 'tk', req);
});
it('register audits + sets cookie; maps error', () => {
expect(thrown(() => new AuthPublicController(asvc({ registerUser: vi.fn().mockReturnValue({ error: 'Email taken', status: 409 }) } as Partial<AuthService>), rl()).register({}, req, res))).toEqual({ status: 409, body: { error: 'Email taken' } });
expect(thrown(() => apc(asvc({ registerUser: vi.fn().mockReturnValue({ error: 'Email taken', status: 409 }) } as Partial<AuthService>), rl()).register(anyBody(), req, res))).toEqual({ status: 409, body: { error: 'Email taken' } });
const setAuthCookie = vi.fn();
const c = new AuthPublicController(asvc({ registerUser: vi.fn().mockReturnValue({ token: 'tk', user, auditUserId: 1, auditDetails: {} }), setAuthCookie } as Partial<AuthService>), rl());
const c = apc(asvc({ registerUser: vi.fn().mockReturnValue({ token: 'tk', user, auditUserId: 1, auditDetails: {} }), setAuthCookie } as Partial<AuthService>), rl());
expect(c.register({ email: 'a@b.c', password: 'p' }, req, res)).toEqual({ token: 'tk', user });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.register' }));
expect(setAuthCookie).toHaveBeenCalled();
@@ -86,39 +103,39 @@ describe('AuthPublicController', () => {
it('invite 429 when rate-limited', () => {
const s = rl();
s.check('login', '9.9.9.9', 10, 15 * 60 * 1000, Date.now()); // not exhausted yet
const c = new AuthPublicController(asvc({ validateInviteToken: vi.fn().mockReturnValue({ valid: true, max_uses: 1, used_count: 0, expires_at: null }) } as Partial<AuthService>), s);
const c = apc(asvc({ validateInviteToken: vi.fn().mockReturnValue({ valid: true, max_uses: 1, used_count: 0, expires_at: null }) } as Partial<AuthService>), s);
expect(c.invite('tok', req)).toEqual({ valid: true, max_uses: 1, used_count: 0, expires_at: null });
});
it('login: mfa branch, success cookie, error mapping', async () => {
const setAuthCookie = vi.fn();
const mfa = new AuthPublicController(asvc({ loginUser: vi.fn().mockReturnValue({ mfa_required: true, mfa_token: 'mt' }) } as Partial<AuthService>), rl());
expect(await mfa.login({}, req, res)).toEqual({ mfa_required: true, mfa_token: 'mt' });
const ok = new AuthPublicController(asvc({ loginUser: vi.fn().mockReturnValue({ token: 'tk', user, remember: true }), setAuthCookie } as Partial<AuthService>), rl());
expect(await ok.login({}, req, res)).toEqual({ token: 'tk', user });
const mfa = apc(asvc({ loginUser: vi.fn().mockReturnValue({ mfa_required: true, mfa_token: 'mt' }) } as Partial<AuthService>), rl());
expect(await mfa.login(anyBody(), req, res)).toEqual({ mfa_required: true, mfa_token: 'mt' });
const ok = apc(asvc({ loginUser: vi.fn().mockReturnValue({ token: 'tk', user, remember: true }), setAuthCookie } as Partial<AuthService>), rl());
expect(await ok.login(anyBody(), req, res)).toEqual({ token: 'tk', user });
// The "remember me" flag from the service rides through to the cookie service.
expect(setAuthCookie).toHaveBeenCalledWith(res, 'tk', req, true);
const bad = new AuthPublicController(asvc({ loginUser: vi.fn().mockReturnValue({ error: 'Bad creds', status: 401, auditAction: 'user.login_fail' }) } as Partial<AuthService>), rl());
expect(await thrownAsync(() => bad.login({}, req, res))).toEqual({ status: 401, body: { error: 'Bad creds' } });
const bad = apc(asvc({ loginUser: vi.fn().mockReturnValue({ error: 'Bad creds', status: 401, auditAction: 'user.login_fail' }) } as Partial<AuthService>), rl());
expect(await thrownAsync(() => bad.login(anyBody(), req, res))).toEqual({ status: 401, body: { error: 'Bad creds' } });
}, 10000);
it('forgot-password issues a reset email then returns the generic ok', async () => {
const sendPasswordResetEmail = vi.fn().mockResolvedValue({ delivered: true });
const c = new AuthPublicController(asvc({ requestPasswordReset: vi.fn().mockReturnValue({ reason: 'issued', tokenForDelivery: 'rt', userEmail: 'a@b.c', userId: 1 }), sendPasswordResetEmail } as Partial<AuthService>), rl());
const c = apc(asvc({ requestPasswordReset: vi.fn().mockReturnValue({ reason: 'issued', tokenForDelivery: 'rt', userEmail: 'a@b.c', userId: 1 }), sendPasswordResetEmail } as Partial<AuthService>), rl());
expect(await c.forgotPassword({ email: 'a@b.c' }, req)).toEqual({ ok: true });
expect(sendPasswordResetEmail).toHaveBeenCalledWith('a@b.c', 'https://x/reset-password?token=rt', 1);
}, 10000);
it('reset-password: error audits a fail, mfa branch, success', () => {
expect(thrown(() => new AuthPublicController(asvc({ resetPassword: vi.fn().mockReturnValue({ error: 'Invalid token', status: 400 }) } as Partial<AuthService>), rl()).resetPassword({}, req))).toEqual({ status: 400, body: { error: 'Invalid token' } });
expect(thrown(() => apc(asvc({ resetPassword: vi.fn().mockReturnValue({ error: 'Invalid token', status: 400 }) } as Partial<AuthService>), rl()).resetPassword(anyBody(), req))).toEqual({ status: 400, body: { error: 'Invalid token' } });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.password_reset_fail' }));
expect(new AuthPublicController(asvc({ resetPassword: vi.fn().mockReturnValue({ mfa_required: true }) } as Partial<AuthService>), rl()).resetPassword({}, req)).toEqual({ mfa_required: true });
expect(new AuthPublicController(asvc({ resetPassword: vi.fn().mockReturnValue({ userId: 1 }) } as Partial<AuthService>), rl()).resetPassword({}, req)).toEqual({ success: true });
expect(apc(asvc({ resetPassword: vi.fn().mockReturnValue({ mfa_required: true }) } as Partial<AuthService>), rl()).resetPassword(anyBody(), req)).toEqual({ mfa_required: true });
expect(apc(asvc({ resetPassword: vi.fn().mockReturnValue({ userId: 1 }) } as Partial<AuthService>), rl()).resetPassword(anyBody(), req)).toEqual({ success: true });
});
it('app-config forwards the optional user (present and absent)', () => {
const getAppConfig = vi.fn().mockReturnValue({ version: '3' });
const c = new AuthPublicController(asvc({ getAppConfig } as Partial<AuthService>), rl());
const c = apc(asvc({ getAppConfig } as Partial<AuthService>), rl());
expect(c.appConfig({ user } as unknown as Request)).toEqual({ version: '3' });
expect(getAppConfig).toHaveBeenLastCalledWith(user);
expect(c.appConfig({} as Request)).toEqual({ version: '3' });
@@ -126,14 +143,14 @@ describe('AuthPublicController', () => {
});
it('invite maps a service error', () => {
const c = new AuthPublicController(asvc({ validateInviteToken: vi.fn().mockReturnValue({ error: 'Expired', status: 410 }) } as Partial<AuthService>), rl());
const c = apc(asvc({ validateInviteToken: vi.fn().mockReturnValue({ error: 'Expired', status: 410 }) } as Partial<AuthService>), rl());
expect(thrown(() => c.invite('tok', req))).toEqual({ status: 410, body: { error: 'Expired' } });
});
it('login takes the mfa-required branch and never sets a cookie', async () => {
const setAuthCookie = vi.fn();
const c = new AuthPublicController(asvc({ loginUser: vi.fn().mockReturnValue({ mfa_required: true, mfa_token: 'mt', auditAction: 'user.login_mfa' }), setAuthCookie } as Partial<AuthService>), rl());
expect(await c.login({}, req, res)).toEqual({ mfa_required: true, mfa_token: 'mt' });
const c = apc(asvc({ loginUser: vi.fn().mockReturnValue({ mfa_required: true, mfa_token: 'mt', auditAction: 'user.login_mfa' }), setAuthCookie } as Partial<AuthService>), rl());
expect(await c.login(anyBody(), req, res)).toEqual({ mfa_required: true, mfa_token: 'mt' });
expect(setAuthCookie).not.toHaveBeenCalled();
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.login_mfa' }));
}, 10000);
@@ -141,21 +158,21 @@ describe('AuthPublicController', () => {
it('forgot-password: non-issued reason and a delivery failure both still return ok', async () => {
// Non-issued (unknown email / throttled): audits the reason, no email sent.
const sendNever = vi.fn();
const skip = new AuthPublicController(asvc({ requestPasswordReset: vi.fn().mockReturnValue({ reason: 'not_found', userId: null }), sendPasswordResetEmail: sendNever } as Partial<AuthService>), rl());
const skip = apc(asvc({ requestPasswordReset: vi.fn().mockReturnValue({ reason: 'not_found', userId: null }), sendPasswordResetEmail: sendNever } as Partial<AuthService>), rl());
expect(await skip.forgotPassword({ email: 'x@y.z' }, req)).toEqual({ ok: true });
expect(sendNever).not.toHaveBeenCalled();
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.password_reset_request', details: { reason: 'not_found' } }));
// Issued but the mailer throws: swallowed, audited as failed, still ok.
const boom = vi.fn().mockRejectedValue(new Error('smtp'));
const fail = new AuthPublicController(asvc({ requestPasswordReset: vi.fn().mockReturnValue({ reason: 'issued', tokenForDelivery: 'rt', userEmail: 'a@b.c', userId: 1 }), sendPasswordResetEmail: boom } as Partial<AuthService>), rl());
const fail = apc(asvc({ requestPasswordReset: vi.fn().mockReturnValue({ reason: 'issued', tokenForDelivery: 'rt', userEmail: 'a@b.c', userId: 1 }), sendPasswordResetEmail: boom } as Partial<AuthService>), rl());
expect(await fail.forgotPassword({ email: 'a@b.c' }, req)).toEqual({ ok: true });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ details: { delivered: 'failed' } }));
}, 10000);
it('forgot-password ignores a non-string email body', async () => {
const requestPasswordReset = vi.fn().mockReturnValue({ reason: 'not_found', userId: null });
const c = new AuthPublicController(asvc({ requestPasswordReset } as Partial<AuthService>), rl());
expect(await c.forgotPassword({ email: 42 } as { email?: unknown }, req)).toEqual({ ok: true });
const c = apc(asvc({ requestPasswordReset } as Partial<AuthService>), rl());
expect(await c.forgotPassword(anyBody<ForgotPasswordDto>({ email: 42 as unknown as string }), req)).toEqual({ ok: true });
expect(requestPasswordReset).toHaveBeenCalledWith('', expect.any(String));
}, 10000);
@@ -163,77 +180,108 @@ describe('AuthPublicController', () => {
const s = rl();
const now = Date.now();
for (let i = 0; i < 5; i++) s.check('reset', '9.9.9.9', 5, 15 * 60 * 1000, now);
const c = new AuthPublicController(asvc({ resetPassword: vi.fn() } as Partial<AuthService>), s);
expect(thrown(() => c.resetPassword({}, req))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
const c = apc(asvc({ resetPassword: vi.fn() } as Partial<AuthService>), s);
expect(thrown(() => c.resetPassword(anyBody(), req))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
});
it('mfa/verify-login maps a service error', () => {
const c = new AuthPublicController(asvc({ verifyMfaLogin: vi.fn().mockReturnValue({ error: 'Bad code', status: 401 }) } as Partial<AuthService>), rl());
expect(thrown(() => c.verifyMfaLogin({}, req, res))).toEqual({ status: 401, body: { error: 'Bad code' } });
const c = apc(asvc({ verifyMfaLogin: vi.fn().mockReturnValue({ error: 'Bad code', status: 401 }) } as Partial<AuthService>), rl());
expect(thrown(() => c.verifyMfaLogin(anyBody(), req, res))).toEqual({ status: 401, body: { error: 'Bad code' } });
});
it('demo-login + register + invite throw 429 when the login bucket is exhausted', () => {
const s = rl();
const now = Date.now();
for (let i = 0; i < 10; i++) s.check('login', '9.9.9.9', 10, 15 * 60 * 1000, now);
const c = new AuthPublicController(asvc({ registerUser: vi.fn(), validateInviteToken: vi.fn() } as Partial<AuthService>), s);
expect(thrown(() => c.register({}, req, res))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
const c = apc(asvc({ registerUser: vi.fn(), validateInviteToken: vi.fn() } as Partial<AuthService>), s);
expect(thrown(() => c.register(anyBody(), req, res))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
expect(thrown(() => c.invite('t', req))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
});
it('mfa/verify-login sets cookie + audits; logout clears cookie', () => {
const setAuthCookie = vi.fn();
const c = new AuthPublicController(asvc({ verifyMfaLogin: vi.fn().mockReturnValue({ token: 'tk', user, auditUserId: 1 }), setAuthCookie } as Partial<AuthService>), rl());
expect(c.verifyMfaLogin({}, req, res)).toEqual({ token: 'tk', user });
const c = apc(asvc({ verifyMfaLogin: vi.fn().mockReturnValue({ token: 'tk', user, auditUserId: 1 }), setAuthCookie } as Partial<AuthService>), rl());
expect(c.verifyMfaLogin(anyBody(), req, res)).toEqual({ token: 'tk', user });
expect(setAuthCookie).toHaveBeenCalled();
const clearAuthCookie = vi.fn();
expect(new AuthPublicController(asvc({ clearAuthCookie } as Partial<AuthService>), rl()).logout(req, res)).toEqual({ success: true });
expect(apc(asvc({ clearAuthCookie } as Partial<AuthService>), rl()).logout(req, res)).toEqual({ success: true });
expect(clearAuthCookie).toHaveBeenCalledWith(res, req);
});
});
describe('AuthController (authenticated)', () => {
it('GET /me 404 when missing, else returns the loaded user', () => {
expect(thrown(() => new AuthController(asvc({ getCurrentUser: vi.fn().mockReturnValue(undefined) } as Partial<AuthService>), rl()).me(user))).toEqual({ status: 404, body: { error: 'User not found' } });
expect(new AuthController(asvc({ getCurrentUser: vi.fn().mockReturnValue({ id: 1 }) } as Partial<AuthService>), rl()).me(user)).toEqual({ user: { id: 1 } });
expect(thrown(() => ac(asvc({ getCurrentUser: vi.fn().mockReturnValue(undefined) } as Partial<AuthService>), rl()).me(user))).toEqual({ status: 404, body: { error: 'User not found' } });
expect(ac(asvc({ getCurrentUser: vi.fn().mockReturnValue({ id: 1 }) } as Partial<AuthService>), rl()).me(user)).toEqual({ user: { id: 1 } });
});
it('change-password maps error, else audits', () => {
expect(thrown(() => new AuthController(asvc({ changePassword: vi.fn().mockReturnValue({ error: 'Wrong', status: 400 }) } as Partial<AuthService>), rl()).changePassword(user, {}, req))).toEqual({ status: 400, body: { error: 'Wrong' } });
expect(new AuthController(asvc({ changePassword: vi.fn().mockReturnValue({}) } as Partial<AuthService>), rl()).changePassword(user, {}, req)).toEqual({ success: true });
expect(thrown(() => ac(asvc({ changePassword: vi.fn().mockReturnValue({ error: 'Wrong', status: 400 }) } as Partial<AuthService>), rl()).changePassword(user, anyBody(), req, res))).toEqual({ status: 400, body: { error: 'Wrong' } });
expect(ac(asvc({ changePassword: vi.fn().mockReturnValue({}) } as Partial<AuthService>), rl()).changePassword(user, anyBody(), req, res)).toEqual({ success: true });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.password_change' }));
});
it('avatar 403 in demo mode, 400 without a file, else saves', async () => {
process.env.DEMO_MODE = 'true';
vi.mocked(isDemoEmail).mockReturnValue(true);
expect(await thrownAsync(() => new AuthController(asvc(), rl()).avatar(user, { filename: 'a.jpg' } as Express.Multer.File))).toEqual({ status: 403, body: { error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' } });
expect(await thrownAsync(() => ac(asvc(), rl()).avatar(user, { filename: 'a.jpg' } as Express.Multer.File))).toEqual({ status: 403, body: { error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' } });
vi.mocked(isDemoEmail).mockReturnValue(false);
delete process.env.DEMO_MODE;
expect(await thrownAsync(() => new AuthController(asvc(), rl()).avatar(user, undefined))).toEqual({ status: 400, body: { error: 'No image uploaded' } });
expect(await thrownAsync(() => ac(asvc(), rl()).avatar(user, undefined))).toEqual({ status: 400, body: { error: 'No image uploaded' } });
const saveAvatar = vi.fn().mockResolvedValue({ avatar: '/a.jpg' });
expect(await new AuthController(asvc({ saveAvatar } as Partial<AuthService>), rl()).avatar(user, { filename: 'a.jpg' } as Express.Multer.File)).toEqual({ avatar: '/a.jpg' });
expect(await ac(asvc({}), rl(), {}, { saveAvatar }).avatar(user, { filename: 'a.jpg' } as Express.Multer.File)).toEqual({ avatar: '/a.jpg' });
});
it('mfa/setup awaits the QR promise, maps a generation failure to 500', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
const ok = new AuthController(asvc({ setupMfa: vi.fn().mockReturnValue({ secret: 's', otpauth_url: 'o', qrPromise: Promise.resolve('<svg>') }) } as Partial<AuthService>), rl());
const ok = ac(asvc({ setupMfa: vi.fn().mockReturnValue({ secret: 's', otpauth_url: 'o', qrPromise: Promise.resolve('<svg>') }) } as Partial<AuthService>), rl());
expect(await ok.mfaSetup(user)).toEqual({ secret: 's', otpauth_url: 'o', qr_svg: '<svg>' });
const fail = new AuthController(asvc({ setupMfa: vi.fn().mockReturnValue({ secret: 's', otpauth_url: 'o', qrPromise: Promise.reject(new Error('x')) }) } as Partial<AuthService>), rl());
const fail = ac(asvc({ setupMfa: vi.fn().mockReturnValue({ secret: 's', otpauth_url: 'o', qrPromise: Promise.reject(new Error('x')) }) } as Partial<AuthService>), rl());
expect(await thrownAsync(() => fail.mfaSetup(user))).toEqual({ status: 500, body: { error: 'Could not generate QR code' } });
});
it('mfa/enable audits + returns backup codes; mcp-tokens create 201', () => {
const enable = new AuthController(asvc({ enableMfa: vi.fn().mockReturnValue({ mfa_enabled: true, backup_codes: ['a', 'b'] }) } as Partial<AuthService>), rl());
const enable = ac(asvc({ enableMfa: vi.fn().mockReturnValue({ mfa_enabled: true, backup_codes: ['a', 'b'] }) } as Partial<AuthService>), rl());
expect(enable.mfaEnable(user, { code: '123456' }, req)).toEqual({ success: true, mfa_enabled: true, backup_codes: ['a', 'b'] });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.mfa_enable' }));
const tok = new AuthController(asvc({ createMcpToken: vi.fn().mockReturnValue({ token: 'mcp_x' }) } as Partial<AuthService>), rl());
const tok = ac(asvc({}), rl(), { createMcpToken: vi.fn().mockReturnValue({ token: 'mcp_x' }) });
expect(tok.createMcpToken(user, { name: 'CLI' }, req)).toEqual({ token: 'mcp_x' });
});
it('resource-token 503 when unavailable, else returns the token payload', () => {
expect(thrown(() => new AuthController(asvc({ createResourceToken: vi.fn().mockReturnValue(null) } as Partial<AuthService>), rl()).resourceToken(user, {}))).toEqual({ status: 503, body: { error: 'Service unavailable' } });
expect(new AuthController(asvc({ createResourceToken: vi.fn().mockReturnValue({ token: 'rt' }) } as Partial<AuthService>), rl()).resourceToken(user, { purpose: 'download' })).toEqual({ token: 'rt' });
expect(thrown(() => ac(asvc({}), rl(), { createResourceToken: vi.fn().mockReturnValue(null) }).resourceToken(user, {}))).toEqual({ status: 503, body: { error: 'Service unavailable' } });
expect(ac(asvc({}), rl(), { createResourceToken: vi.fn().mockReturnValue({ token: 'rt' }) }).resourceToken(user, { purpose: 'download' })).toEqual({ token: 'rt' });
});
it('ws/resource tokens throttle on their own buckets, so a mint loop cannot drain the store or block login', () => {
const s = rl();
const now = Date.now();
for (let i = 0; i < 120; i++) s.check('ws_token', String(user.id), 120, 15 * 60 * 1000, now);
expect(thrown(() => ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user)))
.toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
// The login bucket is untouched: an exhausted socket loop must not lock the account out.
expect(s.check('login', '9.9.9.9', 5, 15 * 60 * 1000, now)).toBe(true);
const s2 = rl();
for (let i = 0; i < 120; i++) s2.check('resource_token', String(user.id), 120, 15 * 60 * 1000, now);
expect(thrown(() => ac(asvc({}), s2, { createResourceToken: vi.fn().mockReturnValue({ token: 'rt' }) }).resourceToken(user, {})))
.toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
});
it('the ws/resource ceilings are per account, not per address: one heavy user cannot 429 the office', () => {
const s = rl();
const now = Date.now();
const other = { ...user, id: 2 } as User;
// Both users sit behind the same NAT address, and the first one burns its
// whole ceiling.
for (let i = 0; i < 120; i++) {
ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user);
}
expect(thrown(() => ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user)))
.toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
expect(ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws2' }) }).wsToken(other)).toEqual({ token: 'ws2' });
expect(ac(asvc({}), s, { createResourceToken: vi.fn().mockReturnValue({ token: 'rt2' }) }).resourceToken(other, {})).toEqual({ token: 'rt2' });
});
it('rate-limited account ops throw 429 once the bucket is exhausted', () => {
@@ -241,91 +289,141 @@ describe('AuthController (authenticated)', () => {
const now = Date.now();
// exhaust the shared 'login' bucket for this ip (max 5)
for (let i = 0; i < 5; i++) s.check('login', '9.9.9.9', 5, 15 * 60 * 1000, now);
const c = new AuthController(asvc({ changePassword: vi.fn() } as Partial<AuthService>), s);
expect(thrown(() => c.changePassword(user, {}, req))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
const c = ac(asvc({ changePassword: vi.fn() } as Partial<AuthService>), s);
expect(thrown(() => c.changePassword(user, anyBody(), req, res))).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
});
it('change-password refreshes this device cookie when the service returns a token', () => {
const setAuthCookie = vi.fn();
const c = new AuthController(asvc({ changePassword: vi.fn().mockReturnValue({ token: 'tk2' }), setAuthCookie } as Partial<AuthService>), rl());
expect(c.changePassword(user, {}, req, res)).toEqual({ success: true });
expect(setAuthCookie).toHaveBeenCalledWith(res, 'tk2', req);
const c = ac(asvc({ changePassword: vi.fn().mockReturnValue({ token: 'tk2' }), setAuthCookie } as Partial<AuthService>), rl());
expect(c.changePassword(user, anyBody(), req, res)).toEqual({ success: true });
expect(setAuthCookie).toHaveBeenCalledWith(res, 'tk2', req, undefined);
});
it('change-password carries the session cookie remember claim into the service and the re-issued cookie (#1927)', () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const jwt = require('jsonwebtoken');
const remembered = jwt.sign({ id: 1, pv: 0, remember: true }, 'any-secret');
const reqCookie = { ip: '9.9.9.9', headers: {}, cookies: { trek_session: remembered } } as unknown as Request;
const setAuthCookie = vi.fn();
const changePassword = vi.fn().mockReturnValue({ token: 'tk3' });
const c = ac(asvc({ changePassword, setAuthCookie } as Partial<AuthService>), rl());
expect(c.changePassword(user, anyBody(), reqCookie, res)).toEqual({ success: true });
expect(changePassword).toHaveBeenCalledWith(1, 'u@example.test', anyBody(), true);
expect(setAuthCookie).toHaveBeenCalledWith(res, 'tk3', reqCookie, true);
});
it('delete-account maps error, else audits and succeeds', () => {
expect(thrown(() => new AuthController(asvc({ deleteAccount: vi.fn().mockReturnValue({ error: 'Last admin', status: 403 }) } as Partial<AuthService>), rl()).deleteAccount(user, req))).toEqual({ status: 403, body: { error: 'Last admin' } });
expect(new AuthController(asvc({ deleteAccount: vi.fn().mockReturnValue({}) } as Partial<AuthService>), rl()).deleteAccount(user, req)).toEqual({ success: true });
expect(thrown(() => ac(asvc({ deleteAccount: vi.fn().mockReturnValue({ error: 'Last admin', status: 403 }) } as Partial<AuthService>), rl()).deleteAccount(user, req))).toEqual({ status: 403, body: { error: 'Last admin' } });
expect(ac(asvc({ deleteAccount: vi.fn().mockReturnValue({}) } as Partial<AuthService>), rl()).deleteAccount(user, req)).toEqual({ success: true });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.account_delete' }));
});
it('maps-key + api-keys pass straight through to the service', () => {
const updateMapsKey = vi.fn().mockReturnValue({ success: true });
expect(new AuthController(asvc({ updateMapsKey } as Partial<AuthService>), rl()).mapsKey(user, { maps_api_key: 'k' })).toEqual({ success: true });
expect(ac(asvc({}), rl(), {}, { updateMapsKey }).mapsKey(user, { maps_api_key: 'k' }, req)).toEqual({ success: true });
expect(updateMapsKey).toHaveBeenCalledWith(1, 'k');
const updateApiKeys = vi.fn().mockReturnValue({ ok: 1 });
expect(new AuthController(asvc({ updateApiKeys } as Partial<AuthService>), rl()).apiKeys(user, { a: 1 })).toEqual({ ok: 1 });
expect(ac(asvc({}), rl(), {}, { updateApiKeys }).apiKeys(user, anyBody({ a: 1 } as never), req)).toEqual({ ok: 1 });
// No changedKeys from the service (and none in the body): nothing to audit.
expect(writeAudit).not.toHaveBeenCalled();
});
it('api-keys audits one settings.api_keys_update with the changed names only (#1939)', () => {
const updateApiKeys = vi.fn().mockReturnValue({ success: true, user: { id: 1 }, changedKeys: ['maps_api_key'] });
const c = ac(asvc({}), rl(), {}, { updateApiKeys });
// changedKeys is stripped off the response — the client body is unchanged.
expect(c.apiKeys(user, anyBody({ maps_api_key: 'AIza-super-secret' } as never), req)).toEqual({ success: true, user: { id: 1 } });
expect(writeAudit).toHaveBeenCalledTimes(1);
expect(writeAudit).toHaveBeenCalledWith({
userId: 1,
action: 'settings.api_keys_update',
resource: 'api_keys',
ip: '1.2.3.4',
details: { changed: ['maps_api_key'] },
});
// Never the value, not even truncated: details is rendered raw in the panel.
expect(JSON.stringify(writeAudit.mock.calls)).not.toContain('AIza-super-secret');
});
it('maps-key and settings audit the same action; an unchanged save writes nothing', () => {
const mapsC = ac(asvc({}), rl(), {}, { updateMapsKey: vi.fn().mockReturnValue({ success: true, changedKeys: ['maps_api_key'] }) });
mapsC.mapsKey(user, { maps_api_key: 'k' }, req);
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'settings.api_keys_update', details: { changed: ['maps_api_key'] } }));
writeAudit.mockClear();
const setC = ac(asvc({}), rl(), {}, { updateSettings: vi.fn().mockReturnValue({ success: true, user: { id: 1 }, changedKeys: ['unsplash_api_key'] }) });
expect(setC.updateSettings(user, {}, req)).toEqual({ success: true, user: { id: 1 } });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'settings.api_keys_update', details: { changed: ['unsplash_api_key'] } }));
// The test button in the panel saves before every click — an identical value
// must not cost a log line.
writeAudit.mockClear();
ac(asvc({}), rl(), {}, { updateApiKeys: vi.fn().mockReturnValue({ success: true, changedKeys: [] }) })
.apiKeys(user, anyBody({ maps_api_key: 'same' } as never), req);
expect(writeAudit).not.toHaveBeenCalled();
});
it('update-settings + get-settings map errors, else return their payloads', () => {
expect(thrown(() => new AuthController(asvc({ updateSettings: vi.fn().mockReturnValue({ error: 'Bad', status: 400 }) } as Partial<AuthService>), rl()).updateSettings(user, {}))).toEqual({ status: 400, body: { error: 'Bad' } });
expect(new AuthController(asvc({ updateSettings: vi.fn().mockReturnValue({ success: true, user: { id: 1 } }) } as Partial<AuthService>), rl()).updateSettings(user, {})).toEqual({ success: true, user: { id: 1 } });
expect(thrown(() => new AuthController(asvc({ getSettings: vi.fn().mockReturnValue({ error: 'Nope', status: 404 }) } as Partial<AuthService>), rl()).getSettings(user))).toEqual({ status: 404, body: { error: 'Nope' } });
expect(new AuthController(asvc({ getSettings: vi.fn().mockReturnValue({ settings: { theme: 'dark' } }) } as Partial<AuthService>), rl()).getSettings(user)).toEqual({ settings: { theme: 'dark' } });
expect(thrown(() => ac(asvc({}), rl(), {}, { updateSettings: vi.fn().mockReturnValue({ error: 'Bad', status: 400 }) }).updateSettings(user, {}, req))).toEqual({ status: 400, body: { error: 'Bad' } });
expect(ac(asvc({}), rl(), {}, { updateSettings: vi.fn().mockReturnValue({ success: true, user: { id: 1 } }) }).updateSettings(user, {}, req)).toEqual({ success: true, user: { id: 1 } });
expect(thrown(() => ac(asvc({}), rl(), {}, { getSettings: vi.fn().mockReturnValue({ error: 'Nope', status: 404 }) }).getSettings(user))).toEqual({ status: 404, body: { error: 'Nope' } });
expect(ac(asvc({}), rl(), {}, { getSettings: vi.fn().mockReturnValue({ settings: { theme: 'dark' } }) }).getSettings(user)).toEqual({ settings: { theme: 'dark' } });
});
it('delete-avatar + users + travel-stats delegate to the service', async () => {
// travel-stats left with getTravelStats; it is covered by
// atlas.controller.test.ts (TravelStatsController).
it('delete-avatar + users delegate to the service', async () => {
const deleteAvatar = vi.fn().mockResolvedValue({ removed: true });
expect(await new AuthController(asvc({ deleteAvatar } as Partial<AuthService>), rl()).deleteAvatar(user)).toEqual({ removed: true });
expect(await ac(asvc({}), rl(), {}, { deleteAvatar }).deleteAvatar(user)).toEqual({ removed: true });
const listUsers = vi.fn().mockReturnValue([{ id: 1 }]);
expect(new AuthController(asvc({ listUsers } as Partial<AuthService>), rl()).users(user)).toEqual({ users: [{ id: 1 }] });
expect(ac(asvc({}), rl(), {}, { listUsers }).users(user)).toEqual({ users: [{ id: 1 }] });
expect(listUsers).toHaveBeenCalledWith(1);
const getTravelStats = vi.fn().mockReturnValue({ countries: 3 });
expect(new AuthController(asvc({ getTravelStats } as Partial<AuthService>), rl()).travelStats(user)).toEqual({ countries: 3 });
});
it('validate-keys maps error, else returns the maps/weather payload', async () => {
expect(await thrownAsync(() => new AuthController(asvc({ validateKeys: vi.fn().mockResolvedValue({ error: 'fail', status: 502 }) } as Partial<AuthService>), rl()).validateKeys(user))).toEqual({ status: 502, body: { error: 'fail' } });
const ok = new AuthController(asvc({ validateKeys: vi.fn().mockResolvedValue({ maps: true, weather: false, maps_details: { ok: 1 } }) } as Partial<AuthService>), rl());
expect(await thrownAsync(() => ac(asvc({}), rl(), {}, { validateKeys: vi.fn().mockResolvedValue({ error: 'fail', status: 502 }) }).validateKeys(user))).toEqual({ status: 502, body: { error: 'fail' } });
const ok = ac(asvc({}), rl(), {}, { validateKeys: vi.fn().mockResolvedValue({ maps: true, weather: false, maps_details: { ok: 1 } }) });
expect(await ok.validateKeys(user)).toEqual({ maps: true, weather: false, maps_details: { ok: 1 } });
});
it('app-settings get maps error, else returns data; put maps error, else audits', () => {
expect(thrown(() => new AuthController(asvc({ getAppSettings: vi.fn().mockReturnValue({ error: 'denied', status: 403 }) } as Partial<AuthService>), rl()).getAppSettings(user))).toEqual({ status: 403, body: { error: 'denied' } });
expect(new AuthController(asvc({ getAppSettings: vi.fn().mockReturnValue({ data: { x: 1 } }) } as Partial<AuthService>), rl()).getAppSettings(user)).toEqual({ x: 1 });
expect(thrown(() => new AuthController(asvc({ updateAppSettings: vi.fn().mockReturnValue({ error: 'bad', status: 400 }) } as Partial<AuthService>), rl()).updateAppSettings(user, {}, req))).toEqual({ status: 400, body: { error: 'bad' } });
expect(new AuthController(asvc({ updateAppSettings: vi.fn().mockReturnValue({ auditSummary: 's', auditDebugDetails: 'd' }) } as Partial<AuthService>), rl()).updateAppSettings(user, {}, req)).toEqual({ success: true });
expect(thrown(() => ac(asvc({ getAppSettings: vi.fn().mockReturnValue({ error: 'denied', status: 403 }) } as Partial<AuthService>), rl()).getAppSettings(user))).toEqual({ status: 403, body: { error: 'denied' } });
expect(ac(asvc({ getAppSettings: vi.fn().mockReturnValue({ data: { x: 1 } }) } as Partial<AuthService>), rl()).getAppSettings(user)).toEqual({ x: 1 });
expect(thrown(() => ac(asvc({ updateAppSettings: vi.fn().mockReturnValue({ error: 'bad', status: 400 }) } as Partial<AuthService>), rl()).updateAppSettings(user, {}, req))).toEqual({ status: 400, body: { error: 'bad' } });
expect(ac(asvc({ updateAppSettings: vi.fn().mockReturnValue({ auditSummary: 's', auditDebugDetails: 'd' }) } as Partial<AuthService>), rl()).updateAppSettings(user, {}, req)).toEqual({ success: true });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'settings.app_update' }));
});
it('mfa/setup maps a service error before ever awaiting the QR promise', async () => {
const c = new AuthController(asvc({ setupMfa: vi.fn().mockReturnValue({ error: 'already on', status: 409 }) } as Partial<AuthService>), rl());
const c = ac(asvc({ setupMfa: vi.fn().mockReturnValue({ error: 'already on', status: 409 }) } as Partial<AuthService>), rl());
expect(await thrownAsync(() => c.mfaSetup(user))).toEqual({ status: 409, body: { error: 'already on' } });
});
it('mfa/enable + mfa/disable map errors', () => {
expect(thrown(() => new AuthController(asvc({ enableMfa: vi.fn().mockReturnValue({ error: 'Invalid code', status: 400 }) } as Partial<AuthService>), rl()).mfaEnable(user, { code: 'x' }, req))).toEqual({ status: 400, body: { error: 'Invalid code' } });
expect(thrown(() => new AuthController(asvc({ disableMfa: vi.fn().mockReturnValue({ error: 'Wrong', status: 401 }) } as Partial<AuthService>), rl()).mfaDisable(user, {}, req))).toEqual({ status: 401, body: { error: 'Wrong' } });
const ok = new AuthController(asvc({ disableMfa: vi.fn().mockReturnValue({ mfa_enabled: false }) } as Partial<AuthService>), rl());
expect(ok.mfaDisable(user, {}, req)).toEqual({ success: true, mfa_enabled: false });
expect(thrown(() => ac(asvc({ enableMfa: vi.fn().mockReturnValue({ error: 'Invalid code', status: 400 }) } as Partial<AuthService>), rl()).mfaEnable(user, { code: 'x' }, req))).toEqual({ status: 400, body: { error: 'Invalid code' } });
expect(thrown(() => ac(asvc({ disableMfa: vi.fn().mockReturnValue({ error: 'Wrong', status: 401 }) } as Partial<AuthService>), rl()).mfaDisable(user, anyBody(), req))).toEqual({ status: 401, body: { error: 'Wrong' } });
const ok = ac(asvc({ disableMfa: vi.fn().mockReturnValue({ mfa_enabled: false }) } as Partial<AuthService>), rl());
expect(ok.mfaDisable(user, anyBody(), req)).toEqual({ success: true, mfa_enabled: false });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'user.mfa_disable' }));
});
it('mcp-tokens list + create error + delete error/success', () => {
expect(new AuthController(asvc({ listMcpTokens: vi.fn().mockReturnValue([{ id: 't' }]) } as Partial<AuthService>), rl()).listMcpTokens(user)).toEqual({ tokens: [{ id: 't' }] });
expect(thrown(() => new AuthController(asvc({ createMcpToken: vi.fn().mockReturnValue({ error: 'Name taken', status: 409 }) } as Partial<AuthService>), rl()).createMcpToken(user, { name: 'x' }, req))).toEqual({ status: 409, body: { error: 'Name taken' } });
expect(thrown(() => new AuthController(asvc({ deleteMcpToken: vi.fn().mockReturnValue({ error: 'Not found', status: 404 }) } as Partial<AuthService>), rl()).deleteMcpToken(user, 'tid'))).toEqual({ status: 404, body: { error: 'Not found' } });
expect(new AuthController(asvc({ deleteMcpToken: vi.fn().mockReturnValue({}) } as Partial<AuthService>), rl()).deleteMcpToken(user, 'tid')).toEqual({ success: true });
expect(ac(asvc({}), rl(), { listMcpTokens: vi.fn().mockReturnValue([{ id: 't' }]) }).listMcpTokens(user)).toEqual({ tokens: [{ id: 't' }] });
expect(thrown(() => ac(asvc({}), rl(), { createMcpToken: vi.fn().mockReturnValue({ error: 'Name taken', status: 409 }) }).createMcpToken(user, { name: 'x' }, req))).toEqual({ status: 409, body: { error: 'Name taken' } });
expect(thrown(() => ac(asvc({}), rl(), { deleteMcpToken: vi.fn().mockReturnValue({ error: 'Not found', status: 404 }) }).deleteMcpToken(user, 'tid'))).toEqual({ status: 404, body: { error: 'Not found' } });
expect(ac(asvc({}), rl(), { deleteMcpToken: vi.fn().mockReturnValue({}) }).deleteMcpToken(user, 'tid')).toEqual({ success: true });
});
it('ws-token maps error, else returns the token', () => {
expect(thrown(() => new AuthController(asvc({ createWsToken: vi.fn().mockReturnValue({ error: 'down', status: 503 }) } as Partial<AuthService>), rl()).wsToken(user))).toEqual({ status: 503, body: { error: 'down' } });
expect(new AuthController(asvc({ createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) } as Partial<AuthService>), rl()).wsToken(user)).toEqual({ token: 'ws' });
expect(thrown(() => ac(asvc({}), rl(), { createWsToken: vi.fn().mockReturnValue({ error: 'down', status: 503 }) }).wsToken(user))).toEqual({ status: 503, body: { error: 'down' } });
expect(ac(asvc({}), rl(), { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user)).toEqual({ token: 'ws' });
});
it('avatar saves when not in demo mode (env present but email is not a demo email)', async () => {
process.env.DEMO_MODE = 'true';
vi.mocked(isDemoEmail).mockReturnValue(false);
const saveAvatar = vi.fn().mockResolvedValue({ avatar: '/b.png' });
expect(await new AuthController(asvc({ saveAvatar } as Partial<AuthService>), rl()).avatar(user, { filename: 'b.png' } as Express.Multer.File)).toEqual({ avatar: '/b.png' });
expect(await ac(asvc({}), rl(), {}, { saveAvatar }).avatar(user, { filename: 'b.png' } as Express.Multer.File)).toEqual({ avatar: '/b.png' });
});
});
@@ -1,31 +1,31 @@
/**
* Pure-function half of the auth unit suite, moved 1:1 from the legacy
* tests/unit/services/authService.test.ts when the auth backend went
* DI-native (case IDs preserved — SEC-008 secret-omission block). The DB
* half lives in tests/unit/nest/auth.service.test.ts. Only the apiKeyCrypto
* mock survives (auth.helpers imports it for mask_stored_api_key); the
* legacy db/permissions/mcp/scheduler mocks guarded imports the pure module
* no longer has.
*/
import { describe, it, expect, vi } from 'vitest';
vi.mock('../../../src/db/database', () => ({
db: { prepare: () => ({ get: vi.fn(), all: vi.fn(), run: vi.fn() }) },
canAccessTrip: vi.fn(),
}));
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret', ENCRYPTION_KEY: '0'.repeat(64) }));
vi.mock('../../../src/services/mfaCrypto', () => ({ encryptMfaSecret: vi.fn(), decryptMfaSecret: vi.fn() }));
vi.mock('../../../src/services/apiKeyCrypto', () => ({
vi.mock('../../../src/nest/common/crypto/apiKeyCrypto', () => ({
decrypt_api_key: vi.fn((v) => v),
maybe_encrypt_api_key: vi.fn((v) => v),
encrypt_api_key: vi.fn((v) => v),
}));
vi.mock('../../../src/services/permissions', () => ({ getAllPermissions: vi.fn(() => ({})), checkPermission: vi.fn() }));
vi.mock('../../../src/services/ephemeralTokens', () => ({ createEphemeralToken: vi.fn() }));
vi.mock('../../../src/mcp', () => ({ revokeUserSessions: vi.fn() }));
vi.mock('../../../src/scheduler', () => ({ startTripReminders: vi.fn(), buildCronExpression: vi.fn() }));
import {
utcSuffix,
stripUserForClient,
maskKey,
avatarUrl,
normalizeBackupCode,
hashBackupCode,
generateBackupCodes,
parseBackupCodeHashes,
} from '../../../src/services/authService';
} from '../../../src/nest/auth/auth.helpers';
import { avatarUrl } from '../../../src/nest/common/avatarUrl';
import type { User } from '../../../src/types';
// ── utcSuffix ────────────────────────────────────────────────────────────────
File diff suppressed because it is too large Load Diff
@@ -7,7 +7,7 @@ beforeEach(() => {
describe('ephemeralTokens', () => {
async function getModule() {
return import('../../../src/services/ephemeralTokens');
return import('../../../../src/nest/auth/ephemeral-tokens');
}
// AUTH-030 — Resource token creation (single-use)
@@ -0,0 +1,135 @@
/**
* The canonical JWT session check, moved here with the verify itself.
*
* These assertions come from tests/unit/middleware/auth.test.ts, which exercised
* them through the Express `authenticate` middleware — a wrapper that no longer
* exists. They now hit verifyJwtAndLoadUser directly, so a 401 is expressed as
* "returns null" rather than "sets status 401"; the guards own the status codes
* and assert them in auth-guard.test.ts.
*
* The password_version gate gets direct cases here for the first time. It is the
* reason this function exists at all: a reset bumps users.password_version and
* every JWT carrying the prior value has to stop working.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import jwt from 'jsonwebtoken';
vi.mock('../../../../src/db/database', () => ({
db: { prepare: vi.fn(() => ({ get: vi.fn(), all: vi.fn() })) },
}));
vi.mock('../../../../src/config', () => ({ JWT_SECRET: 'test-secret' }));
import { extractToken, verifyJwtAndLoadUser } from '../../../../src/nest/auth/jwt-verify';
import { db } from '../../../../src/db/database';
import type { Request } from 'express';
function makeReq(overrides: {
cookies?: Record<string, string>;
headers?: Record<string, string>;
} = {}): Request {
return {
cookies: overrides.cookies || {},
headers: overrides.headers || {},
} as unknown as Request;
}
/** Stub the single users row the verify reads. */
function userRow(row: Record<string, unknown> | undefined): void {
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => row), all: vi.fn() } as never);
}
afterEach(() => vi.clearAllMocks());
describe('extractToken', () => {
it('returns cookie value when trek_session cookie is set', () => {
expect(extractToken(makeReq({ cookies: { trek_session: 'cookie-token' } }))).toBe('cookie-token');
});
it('returns Bearer token from Authorization header when no cookie', () => {
expect(extractToken(makeReq({ headers: { authorization: 'Bearer header-token' } }))).toBe('header-token');
});
it('prefers cookie over Authorization header when both are present', () => {
const req = makeReq({
cookies: { trek_session: 'cookie-token' },
headers: { authorization: 'Bearer header-token' },
});
expect(extractToken(req)).toBe('cookie-token');
});
it('returns null when neither cookie nor header are present', () => {
expect(extractToken(makeReq())).toBeNull();
});
it('returns null for Authorization header without a token (empty Bearer)', () => {
expect(extractToken(makeReq({ headers: { authorization: 'Bearer ' } }))).toBeNull();
});
it('returns the second word for a non-Bearer scheme — it splits on space, it does not parse', () => {
expect(extractToken(makeReq({ headers: { authorization: 'Basic sometoken' } }))).toBe('sometoken');
});
});
describe('verifyJwtAndLoadUser', () => {
it('AUTH-JWT-001: returns the user for a valid token, without password_version', () => {
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 0 });
const token = jwt.sign({ id: 1 }, 'test-secret', { algorithm: 'HS256' });
expect(verifyJwtAndLoadUser(token)).toEqual({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user' });
});
it('AUTH-JWT-002: returns null for a malformed token', () => {
expect(verifyJwtAndLoadUser('invalid.jwt.token')).toBeNull();
});
it('AUTH-JWT-003: returns null when the user no longer exists', () => {
userRow(undefined);
expect(verifyJwtAndLoadUser(jwt.sign({ id: 99999 }, 'test-secret', { algorithm: 'HS256' }))).toBeNull();
});
it('AUTH-JWT-004: returns null for an expired token', () => {
const expired = jwt.sign({ id: 1, exp: Math.floor(Date.now() / 1000) - 3600 }, 'test-secret', { algorithm: 'HS256' });
expect(verifyJwtAndLoadUser(expired)).toBeNull();
});
it('AUTH-JWT-005: returns null for a token signed with the wrong secret', () => {
expect(verifyJwtAndLoadUser(jwt.sign({ id: 1 }, 'wrong-secret', { algorithm: 'HS256' }))).toBeNull();
});
it('AUTH-JWT-006: rejects a purpose-scoped mfa_login token even when the user is valid', () => {
// Issued after the password check but before TOTP, signed with the same
// secret. It must never authenticate an ordinary request.
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 0 });
const mfaToken = jwt.sign({ id: 1, purpose: 'mfa_login' }, 'test-secret', { algorithm: 'HS256' });
expect(verifyJwtAndLoadUser(mfaToken)).toBeNull();
});
it('AUTH-JWT-007: rejects a token whose password_version predates the user row', () => {
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 2 });
const stale = jwt.sign({ id: 1, pv: 1 }, 'test-secret', { algorithm: 'HS256' });
expect(verifyJwtAndLoadUser(stale)).toBeNull();
});
it('AUTH-JWT-008: accepts a token whose password_version matches', () => {
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 2 });
const current = jwt.sign({ id: 1, pv: 2 }, 'test-secret', { algorithm: 'HS256' });
expect(verifyJwtAndLoadUser(current)).not.toBeNull();
});
it('AUTH-JWT-009: a pre-pv token still works against a never-reset user (both read as 0)', () => {
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: null });
const legacy = jwt.sign({ id: 1 }, 'test-secret', { algorithm: 'HS256' });
expect(verifyJwtAndLoadUser(legacy)).not.toBeNull();
});
it('AUTH-JWT-010: but a pre-pv token stops working once the user has reset', () => {
userRow({ id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 1 });
const legacy = jwt.sign({ id: 1 }, 'test-secret', { algorithm: 'HS256' });
expect(verifyJwtAndLoadUser(legacy)).toBeNull();
});
});
@@ -0,0 +1,277 @@
/**
* Auto-backup settings + retention (moved from tests/unit/scheduler.test.ts
* when the code moved from src/scheduler.ts into the backup domain).
*/
import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
// Prevent fs side effects (creating directories, reading files)
vi.mock('node:fs', () => ({
default: {
existsSync: vi.fn(() => false),
mkdirSync: vi.fn(),
readFileSync: vi.fn(() => '{}'),
writeFileSync: vi.fn(),
readdirSync: vi.fn(() => []),
statSync: vi.fn(() => ({ mtime: new Date(), size: 0 })),
unlinkSync: vi.fn(),
createWriteStream: vi.fn(() => ({ on: vi.fn(), pipe: vi.fn() })),
},
existsSync: vi.fn(() => false),
mkdirSync: vi.fn(),
readFileSync: vi.fn(() => '{}'),
writeFileSync: vi.fn(),
readdirSync: vi.fn(() => []),
statSync: vi.fn(() => ({ mtime: new Date(), size: 0 })),
unlinkSync: vi.fn(),
createWriteStream: vi.fn(() => ({ on: vi.fn(), pipe: vi.fn() })),
}));
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({
logInfo: vi.fn(),
logError: vi.fn(),
}));
import fs from 'node:fs';
import {
buildCronExpression,
cleanupOldBackups,
loadSettings,
saveSettings,
type BackupSettings,
} from '../../../src/nest/backup/auto-backup.settings';
import type { StorageService } from '../../../src/nest/storage/storage.service';
// The settings half still does file I/O; these handles pin the mock functions
// from the factory above to the plain signatures loadSettings/saveSettings use.
// (Retention no longer touches fs — it goes through StorageService.)
const existsSyncMock = fs.existsSync as unknown as Mock<(path: string) => boolean>;
const readFileSyncMock = fs.readFileSync as unknown as Mock<(path: string, enc: string) => string>;
const writeFileSyncMock = fs.writeFileSync as unknown as Mock<(path: string, data: string) => void>;
const mkdirSyncMock = fs.mkdirSync as unknown as Mock<(path: string, opts?: unknown) => void>;
function settings(overrides: Partial<BackupSettings> = {}): BackupSettings {
return {
enabled: true,
interval: 'daily',
keep_days: 7,
hour: 2,
day_of_week: 0,
day_of_month: 1,
...overrides,
};
}
describe('buildCronExpression', () => {
describe('hourly', () => {
it('returns 0 * * * * regardless of hour/dow/dom', () => {
expect(buildCronExpression(settings({ interval: 'hourly', hour: 5, day_of_week: 3, day_of_month: 15 }))).toBe('0 * * * *');
});
});
describe('daily', () => {
it('returns 0 <hour> * * *', () => {
expect(buildCronExpression(settings({ interval: 'daily', hour: 3 }))).toBe('0 3 * * *');
});
it('handles midnight (hour 0)', () => {
expect(buildCronExpression(settings({ interval: 'daily', hour: 0 }))).toBe('0 0 * * *');
});
it('handles last valid hour (23)', () => {
expect(buildCronExpression(settings({ interval: 'daily', hour: 23 }))).toBe('0 23 * * *');
});
it('falls back to hour 2 for invalid hour (24)', () => {
expect(buildCronExpression(settings({ interval: 'daily', hour: 24 }))).toBe('0 2 * * *');
});
it('falls back to hour 2 for negative hour', () => {
expect(buildCronExpression(settings({ interval: 'daily', hour: -1 }))).toBe('0 2 * * *');
});
});
describe('weekly', () => {
it('returns 0 <hour> * * <dow>', () => {
expect(buildCronExpression(settings({ interval: 'weekly', hour: 5, day_of_week: 3 }))).toBe('0 5 * * 3');
});
it('handles Sunday (dow 0)', () => {
expect(buildCronExpression(settings({ interval: 'weekly', hour: 2, day_of_week: 0 }))).toBe('0 2 * * 0');
});
it('handles Saturday (dow 6)', () => {
expect(buildCronExpression(settings({ interval: 'weekly', hour: 2, day_of_week: 6 }))).toBe('0 2 * * 6');
});
it('falls back to dow 0 for invalid day_of_week (7)', () => {
expect(buildCronExpression(settings({ interval: 'weekly', hour: 2, day_of_week: 7 }))).toBe('0 2 * * 0');
});
});
describe('monthly', () => {
it('returns 0 <hour> <dom> * *', () => {
expect(buildCronExpression(settings({ interval: 'monthly', hour: 2, day_of_month: 15 }))).toBe('0 2 15 * *');
});
it('handles day_of_month 1', () => {
expect(buildCronExpression(settings({ interval: 'monthly', hour: 2, day_of_month: 1 }))).toBe('0 2 1 * *');
});
it('handles max valid day_of_month (28)', () => {
expect(buildCronExpression(settings({ interval: 'monthly', hour: 2, day_of_month: 28 }))).toBe('0 2 28 * *');
});
it('falls back to dom 1 for day_of_month 29', () => {
expect(buildCronExpression(settings({ interval: 'monthly', hour: 2, day_of_month: 29 }))).toBe('0 2 1 * *');
});
it('falls back to dom 1 for day_of_month 0', () => {
expect(buildCronExpression(settings({ interval: 'monthly', hour: 2, day_of_month: 0 }))).toBe('0 2 1 * *');
});
});
describe('unknown interval', () => {
it('defaults to daily pattern', () => {
expect(buildCronExpression(settings({ interval: 'unknown', hour: 4 }))).toBe('0 4 * * *');
});
});
});
describe('loadSettings / saveSettings', () => {
beforeEach(() => {
existsSyncMock.mockReset().mockReturnValue(false);
readFileSyncMock.mockReset().mockReturnValue('{}');
writeFileSyncMock.mockReset();
mkdirSyncMock.mockReset();
});
it('returns the defaults when no settings file exists', () => {
expect(loadSettings()).toEqual({ enabled: false, interval: 'daily', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 });
});
it('merges the saved file over the defaults', () => {
existsSyncMock.mockReturnValue(true);
readFileSyncMock.mockReturnValue(JSON.stringify({ enabled: true, interval: 'weekly', hour: 6 }));
expect(loadSettings()).toEqual({ enabled: true, interval: 'weekly', keep_days: 7, hour: 6, day_of_week: 0, day_of_month: 1 });
});
it('falls back to the defaults on a corrupt settings file', () => {
existsSyncMock.mockReturnValue(true);
readFileSyncMock.mockReturnValue('{not json');
expect(loadSettings()).toEqual({ enabled: false, interval: 'daily', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 });
});
it('saveSettings creates the data dir when missing and writes pretty JSON', () => {
const s = settings({ enabled: true, interval: 'weekly' });
saveSettings(s);
expect(mkdirSyncMock).toHaveBeenCalledWith(expect.stringContaining('data'), { recursive: true });
expect(writeFileSyncMock).toHaveBeenCalledWith(
expect.stringContaining('backup-settings.json'),
JSON.stringify(s, null, 2),
);
});
it('saveSettings skips the mkdir when the data dir already exists', () => {
existsSyncMock.mockReturnValue(true);
saveSettings(settings());
expect(mkdirSyncMock).not.toHaveBeenCalled();
});
});
describe('cleanupOldBackups', () => {
const DAY = 24 * 60 * 60 * 1000;
const NOW = new Date('2026-04-27T02:00:00Z').getTime();
function isoFilename(daysAgo: number, prefix: 'auto-backup' | 'backup' = 'auto-backup'): string {
const d = new Date(NOW - daysAgo * DAY);
const stamp = d.toISOString().replace(/[:.]/g, '-').slice(0, 19);
return `${prefix}-${stamp}.zip`;
}
/** Retention runs against the backups category through storage now. */
function storageWith(entries: Array<{ key: string; mtimeMs?: number }>): StorageService {
return {
list: vi.fn(async function* () {
for (const e of entries) yield { size: 0, mtimeMs: NOW, ...e };
}),
delete: vi.fn(async () => {}),
} as unknown as StorageService;
}
const deletedKeys = (s: StorageService) => (s.delete as Mock).mock.calls.map(([, key]) => key as string);
it('never deletes manual backup-*.zip files regardless of age', async () => {
const manual = isoFilename(365 * 5, 'backup');
const storage = storageWith([{ key: manual }, { key: isoFilename(0) }]);
await cleanupOldBackups(storage, 7, NOW);
expect(deletedKeys(storage)).not.toContain(manual);
});
it('keeps auto-backups newer than retention', async () => {
const storage = storageWith([{ key: isoFilename(3) }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).not.toHaveBeenCalled();
});
it('deletes auto-backups older than retention', async () => {
const old = isoFilename(30);
const storage = storageWith([{ key: old }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).toHaveBeenCalledOnce();
expect(storage.delete).toHaveBeenCalledWith('backups', old);
});
it('ages by filename timestamp first: a fresh name survives a bogus epoch mtime (overlayfs regression)', async () => {
// On overlayfs the fs timestamps lie (birthtime 0); the filename stamp is
// authoritative. ObjectStat only carries mtimeMs — set it to epoch and the
// same-day filename must still win.
const storage = storageWith([{ key: isoFilename(0), mtimeMs: 0 }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).not.toHaveBeenCalled();
});
it('malformed filename falls back to mtimeMs: keeps recent file', async () => {
const storage = storageWith([{ key: 'auto-backup-garbage.zip', mtimeMs: NOW - 1 * DAY }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).not.toHaveBeenCalled();
});
it('malformed filename falls back to mtimeMs: deletes stale file', async () => {
const storage = storageWith([{ key: 'auto-backup-garbage.zip', mtimeMs: NOW - 30 * DAY }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).toHaveBeenCalledOnce();
});
it('ignores non-zip files and does not crash', async () => {
const old = isoFilename(30);
const storage = storageWith([{ key: old }, { key: 'notes.txt', mtimeMs: 0 }]);
await cleanupOldBackups(storage, 7, NOW);
expect(deletedKeys(storage)).toEqual([old]);
});
it('ignores nested keys (storage.list recurses; the legacy readdir was single-level)', async () => {
const storage = storageWith([{ key: `restore-123/${isoFilename(30)}`, mtimeMs: 0 }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).not.toHaveBeenCalled();
});
it('swallows storage list errors without throwing', async () => {
const storage = {
list: vi.fn(() => { throw new Error('ENOENT'); }),
delete: vi.fn(async () => {}),
} as unknown as StorageService;
await expect(cleanupOldBackups(storage, 7, NOW)).resolves.toBeUndefined();
});
it('swallows delete failures without throwing (mirror replica or fs error)', async () => {
const storage = storageWith([{ key: isoFilename(30) }]);
(storage.delete as Mock).mockRejectedValue(new Error('EACCES'));
await expect(cleanupOldBackups(storage, 7, NOW)).resolves.toBeUndefined();
});
it('swallows non-Error throws without throwing (string rejection path)', async () => {
const storage = {
list: vi.fn(() => { throw 'nope'; }),
delete: vi.fn(async () => {}),
} as unknown as StorageService;
await expect(cleanupOldBackups(storage, 7, NOW)).resolves.toBeUndefined();
});
});
+103 -58
View File
@@ -2,48 +2,62 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { HttpException } from '@nestjs/common';
import type { Request, Response } from 'express';
vi.mock('../../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: vi.fn(() => '1.2.3.4') }));
// The controller imports the tmp-dir + size cap at module load. The thin
// BackupService wrapper forwards every call straight into this module, so the
// mock also stubs the delegated functions for the wrapper tests below.
vi.mock('../../../src/services/backupService', () => ({
getUploadTmpDir: () => '/tmp',
vi.mock('../../../src/nest/audit/client-ip', () => ({ getClientIp: vi.fn(() => '1.2.3.4') }));
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logDebug: vi.fn(), logError: vi.fn(), logWarn: vi.fn() }));
// The thin BackupService wrapper forwards every call straight into this
// module, so the mock stubs the delegated functions for the wrapper tests
// below (the multer size cap is consumed by backup.module's upload factory).
vi.mock('../../../src/nest/backup/backup.impl', () => ({
MAX_BACKUP_UPLOAD_SIZE: 1024,
BACKUP_RATE_WINDOW: 3600000,
listBackups: vi.fn().mockReturnValue([{ filename: 'svc.zip' }]),
createBackup: vi.fn().mockResolvedValue({ filename: 'svc.zip', size: 5 }),
restoreFromZip: vi.fn().mockResolvedValue({ success: true }),
getAutoSettings: vi.fn().mockReturnValue({ settings: { enabled: false }, timezone: 'UTC' }),
updateAutoSettings: vi.fn().mockReturnValue({ enabled: true, interval: 'daily', keep_days: 7 }),
restoreBackup: vi.fn().mockResolvedValue({ success: true }),
deleteBackup: vi.fn(),
isValidBackupFilename: vi.fn().mockReturnValue(true),
backupFilePath: vi.fn().mockReturnValue('/data/backups/svc.zip'),
backupFileExists: vi.fn().mockReturnValue(true),
sendBackupToResponse: vi.fn().mockResolvedValue(undefined),
checkRateLimit: vi.fn().mockReturnValue(true),
}));
import { BackupController } from '../../../src/nest/backup/backup.controller';
import { StorageNotFoundError } from '../../../src/nest/storage/storage.types';
import { BackupService as RealBackupService } from '../../../src/nest/backup/backup.service';
import { AdminGuard } from '../../../src/nest/auth/admin.guard';
import type { BackupService } from '../../../src/nest/backup/backup.service';
import { writeAudit } from '../../../src/services/auditLog';
import * as backupSvc from '../../../src/services/backupService';
import type { AutoBackupJob } from '../../../src/nest/backup/auto-backup.job';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import * as backupSvc from '../../../src/nest/backup/backup.impl';
import type { User } from '../../../src/types';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
const user = { id: 1, role: 'admin', email: 'a@example.test' } as User;
const req = { ip: '1.2.3.4', headers: {} } as Request;
// AuditService is constructor-injected since the auditLog DI migration; the
// wrapper keeps the historical construction sites positional.
const writeAudit = vi.fn();
const audit = { writeAudit } as unknown as AuditService;
// The auto-settings routes live on AutoBackupJob since the cron moved into the
// backup domain; every other route still goes through BackupService.
function job(o: Partial<AutoBackupJob> = {}): AutoBackupJob {
return { getAutoSettings: vi.fn(), updateAutoSettings: vi.fn(), start: vi.fn(), ...o } as unknown as AutoBackupJob;
}
const bc = (s: BackupService, j: AutoBackupJob = job()) => new BackupController(s, audit, j, { isManaged: () => false } as unknown as RuntimeEnvService);
function svc(o: Partial<BackupService> = {}): BackupService {
return {
listBackups: vi.fn().mockReturnValue([]),
createBackup: vi.fn(),
restoreFromZip: vi.fn(),
restoreBackup: vi.fn(),
getAutoSettings: vi.fn(),
updateAutoSettings: vi.fn(),
deleteBackup: vi.fn(),
isValidBackupFilename: vi.fn().mockReturnValue(true),
backupFilePath: vi.fn().mockReturnValue('/b/x.zip'),
backupFileExists: vi.fn().mockReturnValue(true),
sendBackupToResponse: vi.fn().mockResolvedValue(undefined),
checkRateLimit: vi.fn().mockReturnValue(true),
rateWindow: 3600000,
...o,
@@ -81,75 +95,87 @@ describe('AdminGuard (used by BackupController)', () => {
});
describe('BackupController', () => {
it('GET /list returns backups, 500 on error', () => {
expect(new BackupController(svc({ listBackups: vi.fn().mockReturnValue([{ filename: 'a.zip' }]) } as Partial<BackupService>)).list()).toEqual({ backups: [{ filename: 'a.zip' }] });
expect(thrown(() => new BackupController(svc({ listBackups: vi.fn(() => { throw new Error('io'); }) } as Partial<BackupService>)).list())).toEqual({ status: 500, body: { error: 'Error loading backups' } });
it('GET /list returns backups, 500 on error', async () => {
await expect(bc(svc({ listBackups: vi.fn().mockResolvedValue([{ filename: 'a.zip' }]) } as Partial<BackupService>)).list()).resolves.toEqual({ backups: [{ filename: 'a.zip' }] });
expect(await thrownAsync(() => bc(svc({ listBackups: vi.fn(() => { throw new Error('io'); }) } as Partial<BackupService>)).list())).toEqual({ status: 500, body: { error: 'Error loading backups' } });
});
it('POST /create 429 when rate-limited, else creates + audits', async () => {
expect(await thrownAsync(() => new BackupController(svc({ checkRateLimit: vi.fn().mockReturnValue(false) })).create(user, req))).toEqual({ status: 429, body: { error: 'Too many backup requests. Please try again later.' } });
expect(await thrownAsync(() => bc(svc({ checkRateLimit: vi.fn().mockReturnValue(false) })).create(user, req))).toEqual({ status: 429, body: { error: 'Too many backup requests. Please try again later.' } });
const createBackup = vi.fn().mockResolvedValue({ filename: 'b.zip', size: 10 });
const res = await new BackupController(svc({ createBackup } as Partial<BackupService>)).create(user, req);
const res = await bc(svc({ createBackup } as Partial<BackupService>)).create(user, req);
expect(res).toEqual({ success: true, backup: { filename: 'b.zip', size: 10 } });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'backup.create', resource: 'b.zip' }));
});
it('GET /download 400 invalid / 404 missing, else res.download', () => {
const res = { download: vi.fn() } as unknown as Response;
expect(thrown(() => new BackupController(svc({ isValidBackupFilename: vi.fn().mockReturnValue(false) })).download('x', res))).toEqual({ status: 400, body: { error: 'Invalid filename' } });
expect(thrown(() => new BackupController(svc({ backupFileExists: vi.fn().mockReturnValue(false) })).download('x.zip', res))).toEqual({ status: 404, body: { error: 'Backup not found' } });
new BackupController(svc()).download('x.zip', res);
expect(res.download).toHaveBeenCalledWith('/b/x.zip', 'x.zip');
it('GET /download 400 invalid / 404 missing, else serves through storage', async () => {
const res = {} as unknown as Response;
expect(await thrownAsync(() => bc(svc({ isValidBackupFilename: vi.fn().mockReturnValue(false) })).download('x', res))).toEqual({ status: 400, body: { error: 'Invalid filename' } });
expect(await thrownAsync(() => bc(svc({ backupFileExists: vi.fn().mockResolvedValue(false) })).download('x.zip', res))).toEqual({ status: 404, body: { error: 'Backup not found' } });
const sendBackupToResponse = vi.fn().mockResolvedValue(undefined);
await bc(svc({ sendBackupToResponse } as Partial<BackupService>)).download('x.zip', res);
expect(sendBackupToResponse).toHaveBeenCalledWith('x.zip', res);
});
it('GET /download maps a StorageNotFoundError raced past the pre-check to the same 404', async () => {
const res = {} as unknown as Response;
const sendBackupToResponse = vi.fn().mockRejectedValue(new StorageNotFoundError('x.zip'));
expect(await thrownAsync(() => bc(svc({ sendBackupToResponse } as Partial<BackupService>)).download('x.zip', res))).toEqual({ status: 404, body: { error: 'Backup not found' } });
// A non-miss failure is NOT swallowed into the 404 envelope.
const boom = vi.fn().mockRejectedValue(new Error('io'));
await expect(bc(svc({ sendBackupToResponse: boom } as Partial<BackupService>)).download('x.zip', res)).rejects.toThrow('io');
});
it('POST /restore maps the service status, else audits', async () => {
expect(await thrownAsync(() => new BackupController(svc({ isValidBackupFilename: vi.fn().mockReturnValue(false) })).restore(user, 'x', req))).toEqual({ status: 400, body: { error: 'Invalid filename' } });
expect(await thrownAsync(() => new BackupController(svc({ backupFileExists: vi.fn().mockReturnValue(false) })).restore(user, 'x.zip', req))).toEqual({ status: 404, body: { error: 'Backup not found' } });
expect(await thrownAsync(() => new BackupController(svc({ restoreFromZip: vi.fn().mockResolvedValue({ success: false, status: 422, error: 'bad zip' }) } as Partial<BackupService>)).restore(user, 'x.zip', req))).toEqual({ status: 422, body: { error: 'bad zip' } });
const res = await new BackupController(svc({ restoreFromZip: vi.fn().mockResolvedValue({ success: true }) } as Partial<BackupService>)).restore(user, 'x.zip', req);
expect(await thrownAsync(() => bc(svc({ isValidBackupFilename: vi.fn().mockReturnValue(false) })).restore(user, 'x', req))).toEqual({ status: 400, body: { error: 'Invalid filename' } });
expect(await thrownAsync(() => bc(svc({ backupFileExists: vi.fn().mockReturnValue(false) })).restore(user, 'x.zip', req))).toEqual({ status: 404, body: { error: 'Backup not found' } });
expect(await thrownAsync(() => bc(svc({ restoreBackup: vi.fn().mockResolvedValue({ success: false, status: 422, error: 'bad zip' }) } as Partial<BackupService>)).restore(user, 'x.zip', req))).toEqual({ status: 422, body: { error: 'bad zip' } });
const restoreBackup = vi.fn().mockResolvedValue({ success: true });
const res = await bc(svc({ restoreBackup } as Partial<BackupService>)).restore(user, 'x.zip', req);
expect(res).toEqual({ success: true });
expect(restoreBackup).toHaveBeenCalledWith('x.zip');
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'backup.restore', resource: 'x.zip' }));
});
it('POST /restore falls back to status 400 when the service omits one', async () => {
expect(await thrownAsync(() => new BackupController(svc({ restoreFromZip: vi.fn().mockResolvedValue({ success: false, error: 'nope' }) } as Partial<BackupService>)).restore(user, 'x.zip', req))).toEqual({ status: 400, body: { error: 'nope' } });
expect(await thrownAsync(() => bc(svc({ restoreBackup: vi.fn().mockResolvedValue({ success: false, error: 'nope' }) } as Partial<BackupService>)).restore(user, 'x.zip', req))).toEqual({ status: 400, body: { error: 'nope' } });
});
it('POST /upload-restore 400 without a file, cleans up the tmp file', async () => {
expect(await thrownAsync(() => new BackupController(svc()).uploadRestore(user, undefined, req))).toEqual({ status: 400, body: { error: 'No file uploaded' } });
expect(await thrownAsync(() => bc(svc()).uploadRestore(user, undefined, req))).toEqual({ status: 400, body: { error: 'No file uploaded' } });
});
it('POST /upload-restore success audits + reports', async () => {
const file = { path: '/tmp/does-not-exist-xyz.zip', originalname: 'up.zip' } as Express.Multer.File;
const res = await new BackupController(svc({ restoreFromZip: vi.fn().mockResolvedValue({ success: true }) } as Partial<BackupService>)).uploadRestore(user, file, req);
const res = await bc(svc({ restoreFromZip: vi.fn().mockResolvedValue({ success: true }) } as Partial<BackupService>)).uploadRestore(user, file, req);
expect(res).toEqual({ success: true });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'backup.upload_restore', resource: 'up.zip' }));
});
it('POST /upload-restore maps a failed restore status', async () => {
const file = { path: '/tmp/does-not-exist-xyz.zip', originalname: 'up.zip' } as Express.Multer.File;
expect(await thrownAsync(() => new BackupController(svc({ restoreFromZip: vi.fn().mockResolvedValue({ success: false, status: 422, error: 'bad' }) } as Partial<BackupService>)).uploadRestore(user, file, req))).toEqual({ status: 422, body: { error: 'bad' } });
expect(await thrownAsync(() => bc(svc({ restoreFromZip: vi.fn().mockResolvedValue({ success: false, status: 422, error: 'bad' }) } as Partial<BackupService>)).uploadRestore(user, file, req))).toEqual({ status: 422, body: { error: 'bad' } });
});
it('POST /upload-restore falls back to a default name and maps unexpected errors to 500', async () => {
const file = { path: '/tmp/does-not-exist-xyz.zip', originalname: '' } as Express.Multer.File;
expect(await thrownAsync(() => new BackupController(svc({ restoreFromZip: vi.fn().mockRejectedValue(new Error('boom')) } as Partial<BackupService>)).uploadRestore(user, file, req))).toEqual({ status: 500, body: { error: 'Error restoring backup' } });
expect(await thrownAsync(() => bc(svc({ restoreFromZip: vi.fn().mockRejectedValue(new Error('boom')) } as Partial<BackupService>)).uploadRestore(user, file, req))).toEqual({ status: 500, body: { error: 'Error restoring backup' } });
const ok = { path: '/tmp/does-not-exist-xyz.zip', originalname: '' } as Express.Multer.File;
await new BackupController(svc({ restoreFromZip: vi.fn().mockResolvedValue({ success: true }) } as Partial<BackupService>)).uploadRestore(user, ok, req);
await bc(svc({ restoreFromZip: vi.fn().mockResolvedValue({ success: true }) } as Partial<BackupService>)).uploadRestore(user, ok, req);
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'backup.upload_restore', resource: 'upload.zip' }));
});
it('maps unexpected service errors to 500 (create, restore, auto-settings)', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
expect(await thrownAsync(() => new BackupController(svc({ createBackup: vi.fn().mockRejectedValue(new Error('disk')) } as Partial<BackupService>)).create(user, req))).toEqual({ status: 500, body: { error: 'Error creating backup' } });
expect(await thrownAsync(() => new BackupController(svc({ restoreFromZip: vi.fn().mockRejectedValue(new Error('boom')) } as Partial<BackupService>)).restore(user, 'x.zip', req))).toEqual({ status: 500, body: { error: 'Error restoring backup' } });
expect(thrown(() => new BackupController(svc({ getAutoSettings: vi.fn(() => { throw new Error('io'); }) } as Partial<BackupService>)).autoSettings())).toEqual({ status: 500, body: { error: 'Could not load backup settings' } });
expect(await thrownAsync(() => bc(svc({ createBackup: vi.fn().mockRejectedValue(new Error('disk')) } as Partial<BackupService>)).create(user, req))).toEqual({ status: 500, body: { error: 'Error creating backup' } });
expect(await thrownAsync(() => bc(svc({ restoreBackup: vi.fn().mockRejectedValue(new Error('boom')) } as Partial<BackupService>)).restore(user, 'x.zip', req))).toEqual({ status: 500, body: { error: 'Error restoring backup' } });
expect(thrown(() => bc(svc(), job({ getAutoSettings: vi.fn(() => { throw new Error('io'); }) })).autoSettings())).toEqual({ status: 500, body: { error: 'Could not load backup settings' } });
});
it('PUT /auto-settings maps errors to 500 (with a dev-only detail)', () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
process.env.NODE_ENV = 'development';
const r = thrown(() => new BackupController(svc({ updateAutoSettings: vi.fn(() => { throw new Error('parse fail'); }) } as Partial<BackupService>)).updateAutoSettings(user, {}, req));
const r = thrown(() => bc(svc(), job({ updateAutoSettings: vi.fn(() => { throw new Error('parse fail'); }) })).updateAutoSettings(user, {}, req));
expect(r.status).toBe(500);
expect(r.body).toEqual({ error: 'Could not save auto-backup settings', detail: 'parse fail' });
});
@@ -157,63 +183,64 @@ describe('BackupController', () => {
it('PUT /auto-settings hides the detail in production and stringifies non-Error throws', () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
process.env.NODE_ENV = 'production';
const r = thrown(() => new BackupController(svc({ updateAutoSettings: vi.fn(() => { throw 'plain string'; }) } as Partial<BackupService>)).updateAutoSettings(user, {}, req));
const r = thrown(() => bc(svc(), job({ updateAutoSettings: vi.fn(() => { throw 'plain string'; }) })).updateAutoSettings(user, {}, req));
expect(r.status).toBe(500);
expect(r.body).toEqual({ error: 'Could not save auto-backup settings', detail: undefined });
});
it('PUT /auto-settings tolerates a missing body', () => {
const updateAutoSettings = vi.fn().mockReturnValue({ enabled: false, interval: 'weekly', keep_days: 30 });
new BackupController(svc({ updateAutoSettings } as Partial<BackupService>)).updateAutoSettings(user, undefined as unknown as Record<string, unknown>, req);
bc(svc(), job({ updateAutoSettings })).updateAutoSettings(user, undefined as unknown as Record<string, unknown>, req);
expect(updateAutoSettings).toHaveBeenCalledWith({});
});
it('GET/PUT /auto-settings', () => {
expect(new BackupController(svc({ getAutoSettings: vi.fn().mockReturnValue({ settings: { enabled: true }, timezone: 'UTC' }) } as Partial<BackupService>)).autoSettings()).toEqual({ settings: { enabled: true }, timezone: 'UTC' });
const res = new BackupController(svc({ updateAutoSettings: vi.fn().mockReturnValue({ enabled: true, interval: 'daily', keep_days: 7 }) } as Partial<BackupService>)).updateAutoSettings(user, { enabled: true }, req);
expect(bc(svc(), job({ getAutoSettings: vi.fn().mockReturnValue({ settings: { enabled: true }, timezone: 'UTC' }) as never })).autoSettings()).toEqual({ settings: { enabled: true }, timezone: 'UTC' });
const res = bc(svc(), job({ updateAutoSettings: vi.fn().mockReturnValue({ enabled: true, interval: 'daily', keep_days: 7 }) as never })).updateAutoSettings(user, { enabled: true }, req);
expect(res).toEqual({ settings: { enabled: true, interval: 'daily', keep_days: 7 } });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'backup.auto_settings' }));
});
it('DELETE /:filename 400/404, else deletes + audits', () => {
expect(thrown(() => new BackupController(svc({ isValidBackupFilename: vi.fn().mockReturnValue(false) })).remove(user, 'x', req))).toEqual({ status: 400, body: { error: 'Invalid filename' } });
expect(thrown(() => new BackupController(svc({ backupFileExists: vi.fn().mockReturnValue(false) })).remove(user, 'x.zip', req))).toEqual({ status: 404, body: { error: 'Backup not found' } });
it('DELETE /:filename 400/404, else deletes + audits', async () => {
expect(await thrownAsync(() => bc(svc({ isValidBackupFilename: vi.fn().mockReturnValue(false) })).remove(user, 'x', req))).toEqual({ status: 400, body: { error: 'Invalid filename' } });
expect(await thrownAsync(() => bc(svc({ backupFileExists: vi.fn().mockResolvedValue(false) })).remove(user, 'x.zip', req))).toEqual({ status: 404, body: { error: 'Backup not found' } });
const deleteBackup = vi.fn();
expect(new BackupController(svc({ deleteBackup } as Partial<BackupService>)).remove(user, 'x.zip', req)).toEqual({ success: true });
await expect(bc(svc({ deleteBackup } as Partial<BackupService>)).remove(user, 'x.zip', req)).resolves.toEqual({ success: true });
expect(deleteBackup).toHaveBeenCalledWith('x.zip');
});
});
describe('BackupService (wrapper)', () => {
const wrapper = new RealBackupService();
// The impl module is fully mocked above, so an empty sentinel stands in for
// the injected StorageService — the wrapper's job is passing it through.
const storage = { __sentinel: 'storage' } as unknown as import('../../../src/nest/storage/storage.service').StorageService;
const wrapper = new RealBackupService(storage);
it('forwards every call straight to the legacy backup service', async () => {
expect(wrapper.listBackups()).toEqual([{ filename: 'svc.zip' }]);
expect(backupSvc.listBackups).toHaveBeenCalled();
expect(backupSvc.listBackups).toHaveBeenCalledWith(storage);
await expect(wrapper.createBackup()).resolves.toEqual({ filename: 'svc.zip', size: 5 });
expect(backupSvc.createBackup).toHaveBeenCalled();
await expect(wrapper.restoreFromZip('/tmp/a.zip')).resolves.toEqual({ success: true });
expect(backupSvc.restoreFromZip).toHaveBeenCalledWith('/tmp/a.zip');
expect(backupSvc.restoreFromZip).toHaveBeenCalledWith(storage, '/tmp/a.zip');
expect(wrapper.getAutoSettings()).toEqual({ settings: { enabled: false }, timezone: 'UTC' });
expect(backupSvc.getAutoSettings).toHaveBeenCalled();
expect(wrapper.updateAutoSettings({ enabled: true })).toEqual({ enabled: true, interval: 'daily', keep_days: 7 });
expect(backupSvc.updateAutoSettings).toHaveBeenCalledWith({ enabled: true });
await expect(wrapper.restoreBackup('svc.zip')).resolves.toEqual({ success: true });
expect(backupSvc.restoreBackup).toHaveBeenCalledWith(storage, 'svc.zip');
wrapper.deleteBackup('svc.zip');
expect(backupSvc.deleteBackup).toHaveBeenCalledWith('svc.zip');
expect(backupSvc.deleteBackup).toHaveBeenCalledWith(storage, 'svc.zip');
expect(wrapper.isValidBackupFilename('svc.zip')).toBe(true);
expect(backupSvc.isValidBackupFilename).toHaveBeenCalledWith('svc.zip');
expect(wrapper.backupFilePath('svc.zip')).toBe('/data/backups/svc.zip');
expect(backupSvc.backupFilePath).toHaveBeenCalledWith('svc.zip');
expect(wrapper.backupFileExists('svc.zip')).toBe(true);
expect(backupSvc.backupFileExists).toHaveBeenCalledWith('svc.zip');
expect(backupSvc.backupFileExists).toHaveBeenCalledWith(storage, 'svc.zip');
const fakeRes = {} as Response;
await wrapper.sendBackupToResponse('svc.zip', fakeRes);
expect(backupSvc.sendBackupToResponse).toHaveBeenCalledWith(storage, 'svc.zip', fakeRes);
expect(wrapper.checkRateLimit('ip', 3, 1000)).toBe(true);
expect(backupSvc.checkRateLimit).toHaveBeenCalledWith('ip', 3, 1000);
@@ -229,4 +256,22 @@ describe('BackupModule', () => {
const { BackupModule } = await import('../../../src/nest/backup/backup.module');
expect(new BackupModule()).toBeInstanceOf(BackupModule);
});
it('spools restore uploads to the storage tempDir with the legacy filter and cap', async () => {
// The restore upload is a restore INPUT, not a stored object — it gets no
// category and spools to the driver-agnostic scratch dir (spec Uploads #9).
const { buildBackupUploadOptions } = await import('../../../src/nest/backup/backup.module');
const storage = { tempDir: vi.fn(() => '/data/tmp') } as unknown as import('../../../src/nest/storage/storage.service').StorageService;
const opts = buildBackupUploadOptions(storage);
expect(opts.dest).toBe('/data/tmp');
expect(opts.limits).toEqual({ fileSize: 1024 }); // MAX_BACKUP_UPLOAD_SIZE from the impl mock
const accept = vi.fn();
opts.fileFilter?.(undefined as never, { originalname: 'a.zip' } as Express.Multer.File, accept);
expect(accept).toHaveBeenCalledWith(null, true);
const reject = vi.fn();
opts.fileFilter?.(undefined as never, { originalname: 'a.tar.gz' } as Express.Multer.File, reject);
expect(reject).toHaveBeenCalledWith(expect.objectContaining({ message: 'Only ZIP files allowed' }), false);
});
});
File diff suppressed because it is too large Load Diff
@@ -3,13 +3,16 @@ import { HttpException } from '@nestjs/common';
// Mock the heavy side-effect imports so the service module loads cleanly; the
// preview() path under test only touches the extractor + llmParse deps.
vi.mock('../../../../src/db/database', () => ({ db: { prepare: vi.fn() }, closeDb: () => {}, reinitialize: () => {} }));
vi.mock('../../../../src/db/database', () => ({
db: { prepare: vi.fn() }, closeDb: () => {}, reinitialize: () => {},
// Trip access reaches these through DatabaseService; preview() never calls
// them, but the module-level import has to resolve.
canAccessTrip: vi.fn(), isOwner: () => false, getPlaceWithTags: () => null,
}));
import { db as dbConn } from '../../../../src/db/database';
import { DatabaseService } from '../../../../src/nest/database/database.service';
vi.mock('../../../../src/websocket', () => ({ broadcast: vi.fn() }));
vi.mock('../../../../src/services/permissions', () => ({ checkPermission: vi.fn(() => true) }));
vi.mock('../../../../src/services/tripAccess', () => ({ verifyTripAccess: vi.fn() }));
vi.mock('../../../../src/services/reservationService', () => ({ createReservation: vi.fn() }));
vi.mock('../../../../src/services/placeService', () => ({ createPlace: vi.fn() }));
vi.mock('../../../../src/services/mapsService', () => ({ searchNominatim: vi.fn() }));
const permissionsStub = { checkPermission: vi.fn(() => true) };
import { BookingImportService } from '../../../../src/nest/booking-import/booking-import.service';
@@ -19,7 +22,14 @@ const file = (name = 'a.pdf') => ({ buffer: Buffer.from('x'), originalname: name
function make(opts: { kit?: boolean; ai?: boolean; extract?: any; parse?: any }) {
const extractor = { isAvailable: () => opts.kit ?? false, extract: vi.fn(opts.extract ?? (async () => [])) };
const llmParse = { isAvailable: () => opts.ai ?? false, parse: vi.fn(opts.parse ?? (async () => ({ kiItems: [], warnings: [] }))) };
return { svc: new BookingImportService(extractor as any, llmParse as any), extractor, llmParse };
const reservations = { create: vi.fn() };
// budget/addons/realtime/maps ride the confirm() path only — the preview()
// tests never reach them, so stubs beyond the positional slots aren't needed.
const maps = { searchNominatim: vi.fn() };
// Places became a constructor dep with the place DI fold (was a path mock of
// services/placeService); only confirm() reaches it, so a bare create stub does.
const places = { create: vi.fn() };
return { svc: new BookingImportService(extractor as any, llmParse as any, new DatabaseService(dbConn), reservations as never, permissionsStub as never, undefined as never, undefined as never, undefined as never, maps as never, places as never), extractor, llmParse, reservations, maps, places };
}
beforeEach(() => vi.clearAllMocks());
@@ -77,3 +87,96 @@ describe('BookingImportService.preview', () => {
expect(res.items[0].needs_review).toBe(true);
});
});
/**
* Endpoints that arrive without coordinates (#1969).
*
* kitinerary and the LLM name stations, stops, terminals and rental desks but
* rarely geo-locate them — only airports come with coordinates, from the
* mapper's own table. `reservation_endpoints.lat`/`lng` are NOT NULL, so
* `saveEndpoints` drops anything without them.
*
* The lookup that was meant to fill them in lived in confirm(), which nothing
* calls: both the desktop planner and mobile go preview -> review form ->
* ordinary save. So a named endpoint showed up in the review step's From -> To
* summary and then vanished on save, with nothing logged and nothing shown.
*
* These run against preview(), because that is the path that exists.
*/
describe('BookingImportService.preview endpoint geocoding (#1969)', () => {
const TRAIN_KI = {
'@type': 'TrainReservation',
reservationNumber: 'TR1',
reservationFor: {
trainNumber: 'ICE 597',
departureStation: { name: 'Berlin Hbf' },
arrivalStation: { name: 'München Hbf' },
departureTime: '2026-06-11T08:00:00',
arrivalTime: '2026-06-11T12:00:00',
},
};
const hit = (lat: number, lng: number) => [{ lat, lng, display_name: 'x' }];
it('gives a named station coordinates, so it survives the save', async () => {
const { svc, maps } = make({ kit: true, extract: async () => [TRAIN_KI] });
maps.searchNominatim.mockResolvedValue(hit(52.525, 13.369));
const res = await svc.preview([file()], 'no-ai', 1);
const endpoints = (res.items[0] as { endpoints?: { lat: number | null }[] }).endpoints ?? [];
expect(endpoints.length).toBeGreaterThan(0);
for (const ep of endpoints) expect(ep.lat).not.toBeNull();
});
it('asks the same station only once, however often it appears', async () => {
const { svc, maps } = make({
kit: true,
// Two legs out of and back into the same station.
extract: async () => [TRAIN_KI, TRAIN_KI],
});
maps.searchNominatim.mockResolvedValue(hit(52.525, 13.369));
await svc.preview([file()], 'no-ai', 1);
// Two distinct names across four endpoints — Nominatim allows about one
// request a second on this lane, so repeats have to come from the cache.
expect(maps.searchNominatim).toHaveBeenCalledTimes(2);
});
/*
* The half that made this so hard to notice: the endpoint disappeared without
* a word. It stays on the item now, so the review form can still show and
* edit it, and the preview says what it could not place.
*/
it('keeps an endpoint it cannot place, and says so', async () => {
const { svc, maps } = make({ kit: true, extract: async () => [TRAIN_KI] });
maps.searchNominatim.mockResolvedValue([]);
const res = await svc.preview([file()], 'no-ai', 1);
const endpoints = (res.items[0] as { endpoints?: { name: string }[] }).endpoints ?? [];
expect(endpoints.map(e => e.name)).toContain('Berlin Hbf');
expect(res.warnings.some(w => w.includes('Berlin Hbf'))).toBe(true);
});
it('survives a geocoder that throws, rather than failing the import', async () => {
const { svc, maps } = make({ kit: true, extract: async () => [TRAIN_KI] });
maps.searchNominatim.mockRejectedValue(new Error('nominatim down'));
const res = await svc.preview([file()], 'no-ai', 1);
expect(res.items).toHaveLength(1);
});
it('does not look up an endpoint that already knows where it is', async () => {
const withGeo = {
...TRAIN_KI,
reservationFor: {
...TRAIN_KI.reservationFor,
departureStation: { name: 'Berlin Hbf', geo: { latitude: 52.525, longitude: 13.369 } },
arrivalStation: { name: 'München Hbf', geo: { latitude: 48.140, longitude: 11.558 } },
},
};
const { svc, maps } = make({ kit: true, extract: async () => [withGeo] });
await svc.preview([file()], 'no-ai', 1);
expect(maps.searchNominatim).not.toHaveBeenCalled();
});
});
@@ -4,10 +4,11 @@ const { broadcastToUser } = vi.hoisted(() => ({ broadcastToUser: vi.fn() }));
vi.mock('../../../../src/websocket', () => ({ broadcastToUser }));
import { ImportJobsService } from '../../../../src/nest/booking-import/import-jobs.service';
import { RealtimeService } from '../../../../src/nest/realtime/realtime.service';
type Preview = ReturnType<typeof vi.fn>;
function makeService(preview: Preview) {
return new ImportJobsService({ preview } as never);
return new ImportJobsService({ preview } as never, new RealtimeService());
}
const files = (n: number) => Array.from({ length: n }, (_, i) => ({ originalname: `f${i}.pdf` })) as never;
const eventsFor = (jobId: string) => broadcastToUser.mock.calls.map((c) => c[1]).filter((p) => p.jobId === jobId);
@@ -72,4 +73,31 @@ describe('ImportJobsService', () => {
// B must not start before A finished — the per-user chain serializes them.
expect(order).toEqual(['start:A.pdf', 'end:A.pdf', 'start:B.pdf', 'end:B.pdf']);
});
it('reports a parse failure as an error job rather than losing it', async () => {
// The catch arm had no case: a throw inside the off-request parse would have
// left the job stuck on 'running' and the widget spinning forever.
const preview = vi.fn(async () => { throw new Error('kitinerary exploded'); });
const svc = makeService(preview);
const id = svc.start('7', files(1), 'no-ai', 42);
await vi.waitFor(() => expect(svc.get(id, 42)?.status).toBe('error'));
expect(svc.get(id, 42)?.error).toBe('kitinerary exploded');
expect(eventsFor(id).some((p) => p.message === 'kitinerary exploded')).toBe(true);
});
it('turns a non-Error throw into a readable message', async () => {
const preview = vi.fn(async () => { throw 'just a string'; });
const svc = makeService(preview);
const id = svc.start('7', files(1), 'no-ai', 42);
await vi.waitFor(() => expect(svc.get(id, 42)?.status).toBe('error'));
expect(svc.get(id, 42)?.error).toBe('just a string');
});
it('hides a job from a different user', () => {
const svc = makeService(vi.fn(async () => ({ items: [] })));
const id = svc.start('7', files(1), 'no-ai', 42);
expect(svc.get(id, 99)).toBeUndefined();
});
});
@@ -0,0 +1,126 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
/**
* The binary probe behind `GET /api/health/features`.
*
* It had no test at all, which matters more than the line count suggests: this
* one boolean is what the client reads to decide whether to offer booking import
* at all, and every branch that resolves it is a filesystem lookup that behaves
* differently on the three platforms TREK ships to.
*/
const { existsSync, readdirSync, readEnv, execFileSync, execFile } = vi.hoisted(() => ({
existsSync: vi.fn(),
readdirSync: vi.fn(),
readEnv: vi.fn(),
execFileSync: vi.fn(),
// A plain function, because the service promisifies it at module load.
execFile: vi.fn(),
}));
vi.mock('node:fs', () => ({
existsSync,
readdirSync,
writeFileSync: vi.fn(),
unlinkSync: vi.fn(),
}));
// The last branch of the probe runs the candidate to see whether it works.
// Unmocked, the suite spawns a real process on every machine and comes back
// green-or-red depending on whether the developer happens to have KItinerary
// installed.
vi.mock('node:child_process', () => ({ execFileSync, execFile }));
vi.mock('../../../../src/app-config', () => ({ readEnv }));
import { join } from 'node:path';
import { KitineraryExtractorService } from '../../../../src/nest/booking-import/kitinerary-extractor.service';
// The probe builds candidates with path.join, so the expectations have to as
// well — on Windows the separator is a backslash and a hardcoded '/usr/...'
// string would never match.
const onPath = (dir: string) => join(dir, 'kitinerary-extractor');
function boot(env: { kitineraryExtractorPath?: string; searchPath?: string[] } = {}) {
readEnv.mockReturnValue({ integrations: { searchPath: [], ...env } });
const svc = new KitineraryExtractorService();
svc.onModuleInit();
return svc;
}
beforeEach(() => {
vi.clearAllMocks();
existsSync.mockReturnValue(false);
readdirSync.mockReturnValue([]);
execFileSync.mockImplementation(() => { throw new Error('command not found'); });
});
describe('KitineraryExtractorService binary probe', () => {
it('KIT-EXT-001: takes the configured path when it exists', () => {
existsSync.mockImplementation((p: string) => p === '/opt/kitinerary-extractor');
expect(boot({ kitineraryExtractorPath: '/opt/kitinerary-extractor' }).isAvailable()).toBe(true);
});
it('KIT-EXT-002: an explicitly configured path that is missing disables the feature outright', () => {
// It deliberately does NOT fall through to the search: somebody who set the
// variable meant that binary, and silently using another one would hide the
// typo behind a working feature.
const svc = boot({ kitineraryExtractorPath: '/nope/kitinerary-extractor' });
expect(svc.isAvailable()).toBe(false);
expect(readdirSync).not.toHaveBeenCalled();
});
it('KIT-EXT-003: finds the Debian multiarch location by scanning /usr/lib', () => {
readdirSync.mockReturnValue(['x86_64-linux-gnu'] as never);
existsSync.mockImplementation((p: string) => p.includes('x86_64-linux-gnu'));
expect(boot().isAvailable()).toBe(true);
});
it('KIT-EXT-004: survives a system with no /usr/lib at all', () => {
readdirSync.mockImplementation(() => { throw new Error('ENOENT'); });
expect(boot().isAvailable()).toBe(false);
});
it('KIT-EXT-005: reports unavailable when nothing is found, rather than throwing at boot', () => {
expect(boot().isAvailable()).toBe(false);
});
it('KIT-EXT-006: extracting without a binary fails loudly', async () => {
await expect(boot().extract(Buffer.from(''), 'x.pdf')).rejects.toThrow('not available');
});
it('KIT-EXT-007: falls back to a binary on the search path when nothing is on disk', () => {
existsSync.mockImplementation((p: string) => p === onPath('/usr/local/bin'));
execFileSync.mockReturnValue(Buffer.from(''));
expect(boot({ searchPath: ['/usr/local/bin'] }).isAvailable()).toBe(true);
expect(execFileSync).toHaveBeenCalledWith(
onPath('/usr/local/bin'), ['--version'], expect.objectContaining({ timeout: 3000 }),
);
});
it('KIT-EXT-008: stores the absolute path, never the bare name', async () => {
existsSync.mockImplementation((p: string) => p === onPath('/opt/tools'));
execFileSync.mockReturnValue(Buffer.from(''));
execFile.mockImplementation((_b: string, _a: string[], _o: unknown, cb: (e: null, r: unknown) => void) =>
cb(null, { stdout: '[]', stderr: '' }));
// An unqualified name would be re-resolved through PATH on every extraction,
// so what the probe stores has to be the concrete file it verified.
await boot({ searchPath: ['/opt/tools'] }).extract(Buffer.from(''), 'x.pdf');
expect(execFile).toHaveBeenCalledWith(
onPath('/opt/tools'), [expect.any(String)], expect.anything(), expect.anything(),
);
});
it('KIT-EXT-009: a search-path entry that exists but will not run is skipped', () => {
existsSync.mockReturnValue(true);
execFileSync.mockImplementation((bin: string) => {
if (bin === onPath('/broken')) throw new Error('not executable');
return Buffer.from('');
});
expect(boot({ searchPath: ['/broken', '/good'] }).isAvailable()).toBe(true);
expect(execFileSync).toHaveBeenLastCalledWith(
onPath('/good'), ['--version'], expect.anything(),
);
});
});

Some files were not shown because too many files have changed in this diff Show More