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
+9 -5
View File
@@ -66,7 +66,7 @@ describe('API-DOCS (#1412) — flag-gated OpenAPI surface', () => {
testDb.close();
});
it('DOCS-001 — the kill switch parses the env strictly', () => {
it('DOCS-001 — the kill switch parses the boolean-like env family', () => {
const prev = process.env.TREK_API_DOCS_ENABLED;
try {
process.env.TREK_API_DOCS_ENABLED = 'true';
@@ -75,8 +75,9 @@ describe('API-DOCS (#1412) — flag-gated OpenAPI surface', () => {
expect(apiDocsEnabled()).toBe(true);
process.env.TREK_API_DOCS_ENABLED = 'false';
expect(apiDocsEnabled()).toBe(false);
// '1' counts as truthy since the unified boolean coercion (app-config).
process.env.TREK_API_DOCS_ENABLED = '1';
expect(apiDocsEnabled()).toBe(false);
expect(apiDocsEnabled()).toBe(true);
delete process.env.TREK_API_DOCS_ENABLED;
expect(apiDocsEnabled()).toBe(false);
} finally {
@@ -104,11 +105,14 @@ describe('API-DOCS (#1412) — flag-gated OpenAPI surface', () => {
it('DOCS-004 — Zod request bodies are lifted into the spec (no double annotation)', async () => {
const res = await request(instance).get('/api/docs-json');
// collections create validates with collectionCreateRequestSchema via
// ZodValidationPipe — the enricher must surface its object schema.
// collections create validates with CollectionCreateDto (createZodDto over
// collectionCreateRequestSchema) via the global ZodValidationPipe — the DTO
// metatype must surface as a $ref to a component object schema.
const create = res.body.paths['/api/addons/collections']?.post;
expect(create).toBeDefined();
const schema = create.requestBody?.content?.['application/json']?.schema;
const ref = create.requestBody?.content?.['application/json']?.schema?.$ref as string | undefined;
expect(ref).toMatch(/^#\/components\/schemas\//);
const schema = res.body.components.schemas[ref!.split('/').pop()!];
expect(schema?.type).toBe('object');
expect(schema?.properties?.name).toBeDefined();
});
@@ -0,0 +1,94 @@
/**
* AppConfigModule wired into the real buildApp(): boot-stable registerAs
* snapshots must re-derive on every app build (the env-mutate-then-rebuild
* pattern the integration suite relies on), and RuntimeEnvService must stay
* live within a single app's lifetime.
*/
import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest';
import type { INestApplication } from '@nestjs/common';
const { testDb, dbMock } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
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: () => undefined,
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: () => {},
SESSION_DURATION: '24h',
SESSION_DURATION_MS: 86400000,
SESSION_DURATION_SECONDS: 86400,
DEFAULT_LANGUAGE: 'en',
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { resetTestDb } from '../helpers/test-db';
import { buildApp } from '../../src/bootstrap';
import { httpConfig, RuntimeEnvService } from '../../src/nest/app-config';
import type { ConfigType } from '@nestjs/config';
describe('AppConfigModule in the real buildApp()', () => {
let app: INestApplication | undefined;
let prevForceHttps: string | undefined;
let prevDemo: string | undefined;
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
resetTestDb(testDb);
prevForceHttps = process.env.FORCE_HTTPS;
prevDemo = process.env.DEMO_MODE;
});
afterEach(async () => {
await app?.close();
app = undefined;
if (prevForceHttps === undefined) delete process.env.FORCE_HTTPS;
else process.env.FORCE_HTTPS = prevForceHttps;
if (prevDemo === undefined) delete process.env.DEMO_MODE;
else process.env.DEMO_MODE = prevDemo;
});
it('boot-stable snapshots re-derive per app build (mutate → rebuild → new value)', async () => {
process.env.FORCE_HTTPS = 'true';
app = await buildApp();
let http = app.get<ConfigType<typeof httpConfig>>(httpConfig.KEY);
expect(http.forceHttps).toBe(true);
await app.close();
process.env.FORCE_HTTPS = 'off';
app = await buildApp();
http = app.get<ConfigType<typeof httpConfig>>(httpConfig.KEY);
expect(http.forceHttps).toBe(false);
});
it('a snapshot does NOT move within one app lifetime, RuntimeEnvService does', async () => {
delete process.env.FORCE_HTTPS;
delete process.env.DEMO_MODE;
app = await buildApp();
const http = app.get<ConfigType<typeof httpConfig>>(httpConfig.KEY);
const runtime = app.get(RuntimeEnvService);
process.env.FORCE_HTTPS = 'true';
process.env.DEMO_MODE = 'true';
expect(http.forceHttps).toBe(false); // frozen at build — by design
expect(runtime.isDemoMode()).toBe(true); // live — by design
});
});
@@ -191,6 +191,30 @@ describe('List assignments', () => {
expect(res.body.assignments).toHaveLength(0);
});
it('ASSIGN-003 — the embedded place carries osm_id so the day-plan thumbnail can auto-fetch (#1136)', async () => {
const { user } = createUser(testDb);
const { trip, day, place } = setupAssignmentFixtures(user.id);
testDb.prepare('UPDATE places SET osm_id = ? WHERE id = ?').run('node:42', place.id);
await request(app)
.post(`/api/trips/${trip.id}/days/${day.id}/assignments`)
.set('Cookie', authCookie(user.id))
.send({ place_id: place.id });
const res = await request(app)
.get(`/api/trips/${trip.id}/days/${day.id}/assignments`)
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.assignments[0].place.osm_id).toBe('node:42');
// Also surfaced through the full trip-days bundle (the actual day-plan source).
const daysRes = await request(app)
.get(`/api/trips/${trip.id}/days`)
.set('Cookie', authCookie(user.id));
const embedded = daysRes.body.days.find((d: { id: number }) => d.id === day.id).assignments[0].place;
expect(embedded.osm_id).toBe('node:42');
});
it('ASSIGN-006 — non-member cannot list assignments', async () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
+101 -2
View File
@@ -47,8 +47,9 @@ import { buildApp } from '../../src/bootstrap';
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser } from '../helpers/factories';
import { createUser, createTrip } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
import { getRegionGeo } from '../../src/nest/atlas/atlas-geo';
let nestApp: INestApplication;
let app: Application;
@@ -79,7 +80,13 @@ beforeAll(async () => {
runMigrations(testDb);
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
});
// Warm the admin-1 store here rather than inside ATLAS-013. The first call streams
// the multi-MB bundle through the brace-depth splitter and caches it for the process,
// which costs ~3s on a quiet machine and more when every worker is busy — so whichever
// test hit it first used to pay for it inside its own 5s budget and fail under load.
await getRegionGeo(['ZZ']);
}, 60_000);
beforeEach(() => {
resetTestDb(testDb);
@@ -104,6 +111,30 @@ describe('Atlas stats', () => {
expect(res.body).toHaveProperty('stats');
});
it('ATLAS-014 — a future trip is returned as planned and excluded from totalCountries (#1048)', async () => {
const { user } = createUser(testDb);
// Offsets from today rather than literal dates, so this cannot expire.
const iso = (days: number) => new Date(Date.now() + days * 86_400_000).toISOString().slice(0, 10);
const past = createTrip(testDb, user.id, { title: 'Rome, last month', start_date: iso(-40), end_date: iso(-30) });
const future = createTrip(testDb, user.id, { title: 'Tokyo, next month', start_date: iso(30), end_date: iso(40) });
const insertPlace = testDb.prepare('INSERT INTO places (trip_id, name, address) VALUES (?, ?, ?)');
insertPlace.run(past.id, 'Colosseum', 'Piazza del Colosseo, Rome, Italy');
insertPlace.run(future.id, 'Senso-ji', 'Asakusa, Tokyo, Japan');
const res = await request(app)
.get('/api/addons/atlas/stats')
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
const countries = res.body.countries as { code: string; status: string }[];
expect(countries.find(c => c.code === 'IT')?.status).toBe('visited');
expect(countries.find(c => c.code === 'JP')?.status).toBe('planned');
expect(res.body.stats.totalCountries).toBe(1);
expect(res.body.stats.totalCountriesPlanned).toBe(1);
// The whole point: the map gets more countries than the passport counter shows.
expect(countries.length).toBeGreaterThan(res.body.stats.totalCountries);
});
it('ATLAS-002 — GET /api/atlas/country/:code returns places in country', async () => {
const { user } = createUser(testDb);
@@ -170,6 +201,50 @@ describe('Bucket list', () => {
expect(res.status).toBe(400);
});
it('ATLAS-005 — POST the same item twice returns 409 and keeps one row (#1898)', async () => {
const { user } = createUser(testDb);
const body = { name: 'Japan', country_code: 'JP' };
const first = await request(app)
.post('/api/addons/atlas/bucket-list')
.set('Cookie', authCookie(user.id))
.send(body);
expect(first.status).toBe(201);
const second = await request(app)
.post('/api/addons/atlas/bucket-list')
.set('Cookie', authCookie(user.id))
.send(body);
expect(second.status).toBe(409);
expect(second.body).toEqual({ error: 'Already on your bucket list' });
const list = await request(app)
.get('/api/addons/atlas/bucket-list')
.set('Cookie', authCookie(user.id));
expect(list.body.items).toHaveLength(1);
});
it('ATLAS-005 — POST the same item for another target date is allowed (#1898)', async () => {
const { user } = createUser(testDb);
const undated = await request(app)
.post('/api/addons/atlas/bucket-list')
.set('Cookie', authCookie(user.id))
.send({ name: 'Japan', country_code: 'JP', target_date: null });
expect(undated.status).toBe(201);
const dated = await request(app)
.post('/api/addons/atlas/bucket-list')
.set('Cookie', authCookie(user.id))
.send({ name: 'Japan', country_code: 'JP', target_date: '2027-05' });
expect(dated.status).toBe(201);
const list = await request(app)
.get('/api/addons/atlas/bucket-list')
.set('Cookie', authCookie(user.id));
expect(list.body.items).toHaveLength(2);
});
it('ATLAS-006 — GET /bucket-list returns items', async () => {
const { user } = createUser(testDb);
@@ -202,6 +277,30 @@ describe('Bucket list', () => {
expect(res.body.item.name).toBe('New Name');
});
it('ATLAS-007 — PUT onto an existing wish returns 409 and leaves the row alone (#1898)', async () => {
const { user } = createUser(testDb);
await request(app)
.post('/api/addons/atlas/bucket-list')
.set('Cookie', authCookie(user.id))
.send({ name: 'Japan', country_code: 'JP', target_date: '2027-05' });
const second = await request(app)
.post('/api/addons/atlas/bucket-list')
.set('Cookie', authCookie(user.id))
.send({ name: 'Japan', country_code: 'JP', target_date: '2028-09' });
const res = await request(app)
.put(`/api/addons/atlas/bucket-list/${second.body.item.id}`)
.set('Cookie', authCookie(user.id))
.send({ target_date: '2027-05' });
expect(res.status).toBe(409);
expect(res.body).toEqual({ error: 'Already on your bucket list' });
const list = await request(app)
.get('/api/addons/atlas/bucket-list')
.set('Cookie', authCookie(user.id));
expect(list.body.items.map((i: { target_date: string }) => i.target_date).sort()).toEqual(['2027-05', '2028-09']);
});
it('ATLAS-008 — DELETE /bucket-list/:id removes item', async () => {
const { user } = createUser(testDb);
+1 -1
View File
@@ -554,7 +554,7 @@ describe('Extended auth scenarios', () => {
});
it('AUTH-033 — MFA backup code login succeeds and invalidates the used code', async () => {
const { hashBackupCode, generateBackupCodes } = await import('../../src/services/authService');
const { hashBackupCode, generateBackupCodes } = await import('../../src/nest/auth/auth.helpers');
const { user, password } = createUserWithMfa(testDb);
// Generate and store backup codes on the MFA-enabled user
+44 -33
View File
@@ -48,8 +48,8 @@ vi.mock('../../src/config', () => ({
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
// Mock filesystem-dependent service functions to avoid real disk I/O in tests
vi.mock('../../src/services/backupService', async () => {
const actual = await vi.importActual<typeof import('../../src/services/backupService')>('../../src/services/backupService');
vi.mock('../../src/nest/backup/backup.impl', async () => {
const actual = await vi.importActual<typeof import('../../src/nest/backup/backup.impl')>('../../src/nest/backup/backup.impl');
return {
...actual,
createBackup: vi.fn().mockResolvedValue({
@@ -58,30 +58,34 @@ vi.mock('../../src/services/backupService', async () => {
sizeText: '1.0 KB',
created_at: new Date().toISOString(),
}),
updateAutoSettings: vi.fn().mockReturnValue({
enabled: false,
interval: 'daily',
keep_days: 7,
hour: 2,
day_of_week: 0,
day_of_month: 1,
}),
restoreFromZip: vi.fn().mockResolvedValue({ success: true }),
restoreBackup: vi.fn().mockResolvedValue({ success: true }),
deleteBackup: vi.fn().mockReturnValue(undefined),
backupFileExists: vi.fn().mockReturnValue(false),
backupFilePath: vi.fn().mockReturnValue('/tmp/test-backup.zip'),
// Keep checkRateLimit from actual so rate-limit tests work correctly
checkRateLimit: vi.fn().mockReturnValue(true),
};
});
// The auto-settings routes live on AutoBackupJob now; keep its settings-file
// I/O off the real data/ dir (the scheduling itself is off under the test gate).
vi.mock('../../src/nest/backup/auto-backup.settings', async () => {
const actual = await vi.importActual<typeof import('../../src/nest/backup/auto-backup.settings')>('../../src/nest/backup/auto-backup.settings');
return {
...actual,
loadSettings: vi.fn(() => ({ enabled: false, interval: 'daily', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 })),
saveSettings: vi.fn(),
};
});
import { buildApp } from '../../src/bootstrap';
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createAdmin, createUser } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
import * as backupService from '../../src/services/backupService';
import * as backupService from '../../src/nest/backup/backup.impl';
import { DEFAULT_BACKUPS_ROOT } from '../../src/nest/storage/storage-paths';
import fs from 'fs';
import path from 'path';
import os from 'os';
@@ -197,36 +201,41 @@ describe('Backup security', () => {
// ---------------------------------------------------------------------------
describe('Backup download', () => {
let tmpFile: string;
// Serving goes through the real StorageService now (sendBackupToResponse is
// NOT overridden in the impl mock), so the fixture must live in the real
// backups root. Only this one file is cleaned up — never the whole dir.
const downloadFixture = 'backup-2026-04-06T12-00-00.zip';
const downloadFixturePath = path.join(DEFAULT_BACKUPS_ROOT, downloadFixture);
beforeEach(() => {
// Create a real temporary file that Express can stream back
tmpFile = path.join(os.tmpdir(), `test-backup-${Date.now()}.zip`);
fs.writeFileSync(tmpFile, 'fake zip content');
vi.mocked(backupService.backupFileExists).mockReturnValue(true);
vi.mocked(backupService.backupFilePath).mockReturnValue(tmpFile);
vi.mocked(backupService.backupFileExists).mockResolvedValue(true);
});
afterAll(() => {
try { fs.unlinkSync(tmpFile); } catch {}
try { fs.unlinkSync(downloadFixturePath); } catch {}
});
it('BACKUP-INT-001 — GET /backup/download/:filename returns 200 with content-disposition', async () => {
const { user: admin } = createAdmin(testDb);
const filename = 'backup-2026-04-06T12-00-00.zip';
// (Re)write the fixture immediately before the request that serves it.
fs.mkdirSync(DEFAULT_BACKUPS_ROOT, { recursive: true });
fs.writeFileSync(downloadFixturePath, 'fake zip content');
const res = await request(app)
.get(`/api/backup/download/${filename}`)
.get(`/api/backup/download/${downloadFixture}`)
.set('Cookie', authCookie(admin.id));
expect(res.status).toBe(200);
expect(res.headers['content-disposition']).toMatch(/attachment/i);
expect(res.headers['content-disposition']).toContain(filename);
expect(res.headers['content-disposition']).toContain(downloadFixture);
// superagent has no parser for application/zip, so assert the byte count
// rather than the (unbuffered) body.
expect(res.headers['content-length']).toBe(String('fake zip content'.length));
});
it('BACKUP-INT-002 — GET /backup/download/:filename returns 400 for invalid filename', async () => {
const { user: admin } = createAdmin(testDb);
vi.mocked(backupService.backupFileExists).mockReturnValue(false);
vi.mocked(backupService.backupFileExists).mockResolvedValue(false);
const res = await request(app)
.get('/api/backup/download/not-a-valid-name.tar.gz')
@@ -238,7 +247,7 @@ describe('Backup download', () => {
it('BACKUP-INT-003 — GET /backup/download/:filename returns 404 when file not found', async () => {
const { user: admin } = createAdmin(testDb);
vi.mocked(backupService.backupFileExists).mockReturnValue(false);
vi.mocked(backupService.backupFileExists).mockResolvedValue(false);
const res = await request(app)
.get('/api/backup/download/backup-2026-04-06T12-00-00.zip')
@@ -258,8 +267,8 @@ describe('Backup restore', () => {
const { user: admin } = createAdmin(testDb);
const filename = 'backup-2026-04-06T12-00-00.zip';
vi.mocked(backupService.backupFileExists).mockReturnValue(true);
vi.mocked(backupService.restoreFromZip).mockResolvedValue({ success: true });
vi.mocked(backupService.backupFileExists).mockResolvedValue(true);
vi.mocked(backupService.restoreBackup).mockResolvedValue({ success: true });
const res = await request(app)
.post(`/api/backup/restore/${filename}`)
@@ -267,12 +276,13 @@ describe('Backup restore', () => {
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect(vi.mocked(backupService.restoreBackup)).toHaveBeenCalledWith(expect.anything(), filename);
});
it('BACKUP-INT-005 — POST /backup/restore/:filename returns 404 when backup not found', async () => {
const { user: admin } = createAdmin(testDb);
vi.mocked(backupService.backupFileExists).mockReturnValue(false);
vi.mocked(backupService.backupFileExists).mockResolvedValue(false);
const res = await request(app)
.post('/api/backup/restore/backup-2026-04-06T12-00-00.zip')
@@ -293,12 +303,12 @@ describe('Backup restore', () => {
expect([400, 404]).toContain(res.status);
});
it('BACKUP-INT-007 — POST /backup/restore/:filename returns 400 when restoreFromZip reports failure', async () => {
it('BACKUP-INT-007 — POST /backup/restore/:filename returns 400 when the restore reports failure', async () => {
const { user: admin } = createAdmin(testDb);
const filename = 'backup-2026-04-06T12-00-00.zip';
vi.mocked(backupService.backupFileExists).mockReturnValue(true);
vi.mocked(backupService.restoreFromZip).mockResolvedValue({
vi.mocked(backupService.backupFileExists).mockResolvedValue(true);
vi.mocked(backupService.restoreBackup).mockResolvedValue({
success: false,
error: 'Invalid backup: travel.db not found',
status: 400,
@@ -322,7 +332,7 @@ describe('Backup delete', () => {
const { user: admin } = createAdmin(testDb);
const filename = 'backup-2026-04-06T12-00-00.zip';
vi.mocked(backupService.backupFileExists).mockReturnValue(true);
vi.mocked(backupService.backupFileExists).mockResolvedValue(true);
vi.mocked(backupService.deleteBackup).mockReturnValue(undefined);
const res = await request(app)
@@ -331,13 +341,14 @@ describe('Backup delete', () => {
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect(vi.mocked(backupService.deleteBackup)).toHaveBeenCalledWith(filename);
// First arg is the app's real StorageService (BackupService forwards it).
expect(vi.mocked(backupService.deleteBackup)).toHaveBeenCalledWith(expect.anything(), filename);
});
it('BACKUP-INT-009 — DELETE /backup/:filename returns 404 when not found', async () => {
const { user: admin } = createAdmin(testDb);
vi.mocked(backupService.backupFileExists).mockReturnValue(false);
vi.mocked(backupService.backupFileExists).mockResolvedValue(false);
const res = await request(app)
.delete('/api/backup/backup-2026-04-06T12-00-00.zip')
@@ -0,0 +1,60 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import request from 'supertest';
import type { INestApplication } from '@nestjs/common';
import { buildApp } from '../../src/bootstrap';
/**
* A book is bigger than a form post (#1973).
*
* The API's body ceiling is a hundred kilobytes, which is right for an
* interface of forms and ids and wrong for a photo book. A Studio document is
* sent WHOLE on every autosave, on purpose, and a fortnight's journey passes a
* hundred kilobytes before anybody asks for road geometry: an Iceland book with
* roads measured 101KB against a 100KB limit.
*
* What that produced was not an error anybody could act on. The save failed
* with a 413, the editor said "not saved", and nothing anywhere said why —
* which is the same shape of bug as the mood mark that could not be stored, and
* it deserves the same kind of guard.
*/
describe('the size of a book', () => {
let app: INestApplication;
beforeAll(async () => {
app = await buildApp();
await app.init();
});
afterAll(async () => {
await app?.close();
});
/** A body far past the ordinary ceiling, shaped like a save. */
const bigBody = () => ({
title: 'A long journey',
baseVersion: 1,
document: { version: 1, title: 'A long journey', spreads: [], filler: 'x'.repeat(400_000) },
});
it('takes a document larger than the API-wide limit rather than refusing it', async () => {
const res = await request(app.getHttpServer())
.put('/api/journeys/1/book')
.send(bigBody());
/*
* Unauthenticated, so 401 is the expected answer and the point of the test
* is what it is NOT: a 413 means the body never reached the router, which
* is exactly the failure being guarded against.
*/
expect(res.status).not.toBe(413);
});
it('keeps the tighter limit on every other route', async () => {
const res = await request(app.getHttpServer())
.post('/api/journeys')
.send({ title: 'x'.repeat(400_000) });
expect(res.status).toBe(413);
});
});
@@ -44,6 +44,19 @@ vi.mock('../../src/config', () => ({
DEFAULT_LANGUAGE: 'en',
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
// BOOT-007 boots with NODE_ENV=production, which opens the cron gate — keep the
// registrar inert so a bootstrap test never schedules real jobs or runs boot
// sweeps against the real uploads/data dirs. The gate itself is covered by
// tests/integration/scheduler-gate.test.ts.
vi.mock('../../src/nest/scheduling/cron-registrar.service', () => ({
CronRegistrarService: class {
isEnabled() { return false; }
register() { return false; }
unregister() {}
get jobCount() { return 0; }
onApplicationShutdown() {}
},
}));
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
+11 -3
View File
@@ -63,9 +63,17 @@ beforeAll(async () => {
beforeEach(() => {
resetTestDb(testDb);
resetRateLimits(nestApp);
// GET /budget/settlement reaches ExchangeRatesService.getRates unconditionally
// (budget.service.ts settlement()), and that is a real fetch to
// api.frankfurter.dev with a 10 s abort. Without this stub the suite talks to
// the internet: slow, offline-dependent, and it makes the run take minutes
// longer on a machine that cannot reach it. Fail closed — every assertion here
// is single-currency, so rates never enter the arithmetic.
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); }));
});
afterAll(async () => {
vi.unstubAllGlobals();
await nestApp.close();
testDb.close();
});
@@ -416,7 +424,7 @@ describe('Reorder budget items', () => {
// Restrict budget_edit to trip_owner only
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('perm_budget_edit', 'trip_owner')").run();
const { invalidatePermissionsCache } = await import('../../src/services/permissions');
const { invalidatePermissionsCache } = await import('../../src/nest/permissions/permissions-cache');
invalidatePermissionsCache();
const res = await request(app)
@@ -519,7 +527,7 @@ describe('Budget edit permission enforcement', () => {
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
const { invalidatePermissionsCache } = await import('../../src/services/permissions');
const { invalidatePermissionsCache } = await import('../../src/nest/permissions/permissions-cache');
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('perm_budget_edit', 'trip_owner')").run();
invalidatePermissionsCache();
@@ -540,7 +548,7 @@ describe('Budget edit permission enforcement', () => {
addTripMember(testDb, trip.id, member.id);
createBudgetItem(testDb, trip.id, { name: 'Item', category: 'Transport' });
const { invalidatePermissionsCache } = await import('../../src/services/permissions');
const { invalidatePermissionsCache } = await import('../../src/nest/permissions/permissions-cache');
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('perm_budget_edit', 'trip_owner')").run();
invalidatePermissionsCache();
+128 -14
View File
@@ -48,22 +48,21 @@ vi.mock('../../src/config', () => ({
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
// Partially mock collabService to make fetchLinkPreview controllable
vi.mock('../../src/services/collabService', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/services/collabService')>();
return {
...actual,
fetchLinkPreview: vi.fn().mockResolvedValue({ title: null, description: null, image: null, url: '' }),
};
});
import { buildApp } from '../../src/bootstrap';
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser, createTrip, addTripMember } from '../helpers/factories';
import { authCookie, generateToken } from '../helpers/auth';
import * as collabService from '../../src/services/collabService';
import { CollabService } from '../../src/nest/collab/collab.service';
// Spy on the DI-native service's linkPreview so the SSRF-guarded fetch never
// runs; the rest of CollabService exercises its real SQL through the container.
// The original is kept so the guard cases below can put it back for one call —
// mockRestore would drop the spy for every test declared after them.
const realLinkPreview = CollabService.prototype.linkPreview;
const linkPreviewSpy = vi.spyOn(CollabService.prototype, 'linkPreview')
.mockResolvedValue({ title: null, description: null, image: null, url: '' });
let nestApp: INestApplication;
let app: Application;
@@ -268,6 +267,81 @@ describe('Collab notes', () => {
expect(del.body.success).toBe(true);
});
it('COLLAB-P01 — attachment filename is stored bare (category + name; no files/ prefix)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const create = await request(app)
.post(`/api/trips/${trip.id}/collab/notes`)
.set('Cookie', authCookie(user.id))
.send({ title: 'Bare name' });
const noteId = create.body.note.id;
const upload = await request(app)
.post(`/api/trips/${trip.id}/collab/notes/${noteId}/files`)
.set('Cookie', authCookie(user.id))
.attach('file', FIXTURE_PDF);
expect(upload.status).toBe(201);
const list = await request(app)
.get(`/api/trips/${trip.id}/collab/notes`)
.set('Cookie', authCookie(user.id));
const note = list.body.notes.find((n: any) => n.id === noteId);
expect(note.attachments[0].filename).toMatch(/^[0-9a-f-]{36}\.pdf$/);
expect(note.attachments[0].url).toMatch(/^\/api\/trips\/\d+\/files\/\d+\/download$/);
// The bytes live in uploads/files under the bare name.
expect(fs.existsSync(path.join(uploadsDir, note.attachments[0].filename))).toBe(true);
});
it('COLLAB-P02 — deleting a note file removes its bytes from uploads/files', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const create = await request(app)
.post(`/api/trips/${trip.id}/collab/notes`)
.set('Cookie', authCookie(user.id))
.send({ title: 'Delete file bytes' });
const noteId = create.body.note.id;
const upload = await request(app)
.post(`/api/trips/${trip.id}/collab/notes/${noteId}/files`)
.set('Cookie', authCookie(user.id))
.attach('file', FIXTURE_PDF);
const fileId = upload.body.file.id;
const diskName = path.basename(upload.body.file.filename);
expect(fs.existsSync(path.join(uploadsDir, diskName))).toBe(true);
const del = await request(app)
.delete(`/api/trips/${trip.id}/collab/notes/${noteId}/files/${fileId}`)
.set('Cookie', authCookie(user.id));
expect(del.status).toBe(200);
expect(fs.existsSync(path.join(uploadsDir, diskName))).toBe(false);
});
it('COLLAB-P03 — deleting a note removes its attachments’ bytes from uploads/files', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const create = await request(app)
.post(`/api/trips/${trip.id}/collab/notes`)
.set('Cookie', authCookie(user.id))
.send({ title: 'Delete note bytes' });
const noteId = create.body.note.id;
const upload = await request(app)
.post(`/api/trips/${trip.id}/collab/notes/${noteId}/files`)
.set('Cookie', authCookie(user.id))
.attach('file', FIXTURE_PDF);
const diskName = path.basename(upload.body.file.filename);
expect(fs.existsSync(path.join(uploadsDir, diskName))).toBe(true);
const del = await request(app)
.delete(`/api/trips/${trip.id}/collab/notes/${noteId}`)
.set('Cookie', authCookie(user.id));
expect(del.status).toBe(200);
expect(fs.existsSync(path.join(uploadsDir, diskName))).toBe(false);
});
it('COLLAB-028 — uploaded note file URL uses authenticated download path, not /uploads/', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
@@ -666,11 +740,26 @@ describe('Collab validation', () => {
.send({ question: 'Only one option?', options: ['Option A'] });
expect(res.status).toBe(400);
expect(res.body.error).toMatch(/2 options/i);
// The Zod pipe's standard envelope replaced the bespoke 'At least 2 options
// are required' string when the collab bodies adopted DTOs.
expect(res.body.error).toMatch(/options/i);
});
});
describe('Link preview', () => {
it('COLLAB-025 — GET /collab/link-preview as a non-member returns 404 (trip-access check added post-migration)', async () => {
const { user: owner } = createUser(testDb);
const { user: outsider } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const res = await request(app)
.get(`/api/trips/${trip.id}/collab/link-preview?url=https://example.com`)
.set('Cookie', authCookie(outsider.id));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
});
it('COLLAB-025 — GET /collab/link-preview without url returns 400', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
@@ -687,7 +776,7 @@ describe('Link preview', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
vi.mocked(collabService.fetchLinkPreview).mockResolvedValueOnce({
linkPreviewSpy.mockResolvedValueOnce({
title: 'Example Domain',
description: 'A test page',
image: null,
@@ -706,7 +795,7 @@ describe('Link preview', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
vi.mocked(collabService.fetchLinkPreview).mockResolvedValueOnce({
linkPreviewSpy.mockResolvedValueOnce({
title: null,
description: null,
image: null,
@@ -722,11 +811,36 @@ describe('Link preview', () => {
expect(res.body.error).toBeDefined();
});
// Every case above mocks linkPreview out, so the SSRF guard, the redirect
// refusal and the pinned dispatcher are unproven over HTTP: swapping
// checkSsrf(url, true) for checkSsrf(url) would leave this file green. These
// two put the real implementation back for one call each. No traffic leaves
// the machine — the guard refuses both targets before any fetch.
it.each([
['loopback', 'http://127.0.0.1:9/'],
// The unspecified address routes to loopback when connected to, and used to
// pass the guard: it is not '::1', and it does not start with '0.'.
['the unspecified address', 'http://[::]:9/'],
])('COLLAB-032 — GET /collab/link-preview refuses %s (%s) through the real guard', async (_label, url) => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
linkPreviewSpy.mockImplementationOnce(realLinkPreview);
const res = await request(app)
.get(`/api/trips/${trip.id}/collab/link-preview?url=${encodeURIComponent(url)}`)
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(400);
// One constant reason. The guard knows three, and telling them apart would
// map out the internal DNS of the server one guessed hostname at a time.
expect(res.body).toEqual({ error: 'URL not allowed' });
});
it('COLLAB-027 — GET /collab/link-preview catches thrown errors and returns fallback', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
vi.mocked(collabService.fetchLinkPreview).mockRejectedValueOnce(new Error('Unexpected error'));
linkPreviewSpy.mockRejectedValueOnce(new Error('Unexpected error'));
const res = await request(app)
.get(`/api/trips/${trip.id}/collab/link-preview?url=https://example.com`)
@@ -0,0 +1,156 @@
/**
* Collections upload integration tests (COLL-P01…P05).
*
* Cover + place-image upload parity, written BEFORE the storage-upload swap:
* statuses, bodies, on-disk layout — including the cover filter's plain-Error
* 500 quirk (shared with the trip cover config) and the place-image filter's
* statusCode-400 contract.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
import request from 'supertest';
import type { Application } from 'express';
import type { INestApplication } from '@nestjs/common';
import path from 'path';
import fs from 'fs';
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: () => {},
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: () => {},
SESSION_DURATION: '24h',
SESSION_DURATION_MS: 86400000,
SESSION_DURATION_SECONDS: 86400,
DEFAULT_LANGUAGE: 'en',
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn(), getOnlineUserIds: vi.fn(() => []) }));
import { buildApp } from '../../src/bootstrap';
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
let nestApp: INestApplication;
let app: Application;
const FIXTURE_IMG = path.join(__dirname, '../fixtures/small-image.jpg');
const coversDir = path.join(__dirname, '../../uploads/covers');
const placesDir = path.join(__dirname, '../../uploads/places');
function createCollection(ownerId: number): number {
return Number(testDb.prepare("INSERT INTO collections (owner_id, name) VALUES (?, 'C')").run(ownerId).lastInsertRowid);
}
function createCollectionPlace(collectionId: number, ownerId: number): number {
return Number(testDb.prepare("INSERT INTO collection_places (collection_id, owner_id, name) VALUES (?, ?, 'P')").run(collectionId, ownerId).lastInsertRowid);
}
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
});
beforeEach(() => {
resetTestDb(testDb);
resetRateLimits(nestApp);
// Enable the collections addon (the controller sits behind AddonGuard).
testDb.prepare(
"INSERT OR REPLACE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES ('collections', 'Collections', 'Saved places', 'global', 'Bookmark', 1, 40)"
).run();
});
afterAll(async () => {
await nestApp.close();
testDb.close();
fs.rmSync(coversDir, { recursive: true, force: true });
fs.rmSync(placesDir, { recursive: true, force: true });
});
describe('Collection cover upload', () => {
it('COLL-P01 — cover upload stores /uploads/covers/<uuid> and writes the file', async () => {
const { user } = createUser(testDb);
const collectionId = createCollection(user.id);
const res = await request(app)
.post(`/api/addons/collections/${collectionId}/cover`)
.set('Cookie', authCookie(user.id))
.attach('cover', FIXTURE_IMG, 'cover.png');
expect(res.status).toBe(201);
expect(res.body.cover_image).toMatch(/^\/uploads\/covers\/[0-9a-f-]{36}\.png$/);
const diskName = res.body.cover_image.replace('/uploads/covers/', '');
expect(fs.existsSync(path.join(coversDir, diskName))).toBe(true);
});
it('COLL-P02 — no file → 400 "No image uploaded"', async () => {
const { user } = createUser(testDb);
const collectionId = createCollection(user.id);
const res = await request(app)
.post(`/api/addons/collections/${collectionId}/cover`)
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(400);
expect(res.body.error).toBe('No image uploaded');
});
it('COLL-P03 — non-image cover is 500 (plain-Error filter quirk — pinned, do not "fix")', async () => {
const { user } = createUser(testDb);
const collectionId = createCollection(user.id);
const res = await request(app)
.post(`/api/addons/collections/${collectionId}/cover`)
.set('Cookie', authCookie(user.id))
.attach('cover', Buffer.from('plain text'), { filename: 'doc.txt', contentType: 'text/plain' });
expect(res.status).toBe(500);
});
});
describe('Collection place image upload', () => {
it('COLL-P04 — place image upload stores /uploads/places/<uuid> and writes the file', async () => {
const { user } = createUser(testDb);
const collectionId = createCollection(user.id);
const placeId = createCollectionPlace(collectionId, user.id);
const res = await request(app)
.post(`/api/addons/collections/places/${placeId}/image`)
.set('Cookie', authCookie(user.id))
.attach('image', FIXTURE_IMG, 'photo.jpg');
expect(res.status).toBe(200);
expect(res.body.image_url).toMatch(/^\/uploads\/places\/[0-9a-f-]{36}\.jpg$/);
const diskName = res.body.image_url.replace('/uploads/places/', '');
expect(fs.existsSync(path.join(placesDir, diskName))).toBe(true);
});
it('COLL-P05 — non-image place upload is 400 with the bespoke message', async () => {
const { user } = createUser(testDb);
const collectionId = createCollection(user.id);
const placeId = createCollectionPlace(collectionId, user.id);
const res = await request(app)
.post(`/api/addons/collections/places/${placeId}/image`)
.set('Cookie', authCookie(user.id))
.attach('image', Buffer.from('%PDF-1.4'), { filename: 'doc.pdf', contentType: 'application/pdf' });
expect(res.status).toBe(400);
expect(res.body.error).toBe('Only jpg, png, gif, webp images allowed');
});
});
+10 -2
View File
@@ -1,6 +1,6 @@
/**
* Day reorder + insert integration tests (#589) — exercises the real
* dayService against the real schema. Covers: position renumber, dates pinned
* DaysService against the real schema. Covers: position renumber, dates pinned
* to slots while content rides along by id, booking-date re-stamp, permutation
* validation, the accommodation-inversion guard, and insert (dated + dateless).
*/
@@ -28,7 +28,15 @@ import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { resetTestDb } from '../helpers/test-db';
import { createUser, createTrip, createPlace, createDay, createDayAssignment, createReservation, createDayAccommodation } from '../helpers/factories';
import { reorderDays, insertDay, DayReorderError } from '../../src/services/dayService';
import { DatabaseService } from '../../src/nest/database/database.service';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { DaysService, DayReorderError } from '../../src/nest/days/days.service';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { QueryHelpersService } from '../../src/nest/query-helpers/query-helpers.service';
const svc = new DaysService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb)), new RealtimeService(), new QueryHelpersService(new DatabaseService(testDb)));
const reorderDays = (tripId: number, orderedIds: number[]) => svc.reorder(tripId, orderedIds);
const insertDay = (tripId: number, position?: number) => svc.insert(tripId, position);
let userId: number;
+111
View File
@@ -133,6 +133,57 @@ describe('Upload file', () => {
}
});
it('FILE-P01 — stored filename is a bare uuid name and the bytes land in uploads/files', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const res = await uploadFile(trip.id, user.id, FIXTURE_PDF);
expect(res.status).toBe(201);
expect(res.body.file.filename).toMatch(/^[0-9a-f-]{36}\.pdf$/);
expect(fs.existsSync(path.join(uploadsDir, res.body.file.filename))).toBe(true);
// Nothing left behind in the spool after a successful commit.
const spoolDir = path.join(__dirname, '../../uploads/.tmp');
if (fs.existsSync(spoolDir)) {
expect(fs.readdirSync(spoolDir)).not.toContain(res.body.file.filename);
}
});
it('FILE-P02 — non-video over 50 MB is rejected with no bytes left anywhere', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const BIG = 51 * 1024 * 1024;
// Other suites share the real uploads/ tree when the whole tier runs in
// parallel, so the residue checks key on this upload's unique size rather
// than comparing whole-directory listings.
const bigFilesIn = (dir: string) =>
fs.existsSync(dir)
? fs.readdirSync(dir).filter((f) => {
try { return fs.statSync(path.join(dir, f)).size === BIG; } catch { return false; }
})
: [];
const res = await request(app)
.post(`/api/trips/${trip.id}/files`)
.set('Cookie', authCookie(user.id))
.attach('file', Buffer.alloc(BIG), { filename: 'big.pdf', contentType: 'application/pdf' });
expect(res.status).toBe(400);
expect(res.body.error).toBe('File is too large');
expect(bigFilesIn(uploadsDir)).toEqual([]);
expect(bigFilesIn(path.join(__dirname, '../../uploads/.tmp'))).toEqual([]);
});
it('FILE-P03 — non-ASCII original filenames are preserved (defParamCharset utf8)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const res = await request(app)
.post(`/api/trips/${trip.id}/files`)
.set('Cookie', authCookie(user.id))
.attach('file', Buffer.from('utf8 name test'), { filename: 'résumé.pdf', contentType: 'application/pdf' });
expect(res.status).toBe(201);
expect(res.body.file.original_name).toBe('résumé.pdf');
});
it('FILE-021 — non-member cannot upload file', async () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
@@ -514,4 +565,64 @@ describe('File download', () => {
.set('Cookie', `trek_session=${token}`);
expect(dl.status).toBe(200);
});
it('FILE-P04 — download serves the exact bytes with Content-Type, ETag, and Range support', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const upload = await uploadFile(trip.id, user.id, FIXTURE_PDF);
const fileId = upload.body.file.id;
const fixtureBytes = fs.readFileSync(FIXTURE_PDF);
const dl = await request(app)
.get(`/api/trips/${trip.id}/files/${fileId}/download`)
.set('Cookie', authCookie(user.id));
expect(dl.status).toBe(200);
expect(dl.headers['content-type']).toBe('application/pdf');
expect(dl.headers.etag).toMatch(/^W\/"[0-9a-f]+-[0-9a-f]+"$/);
expect(Buffer.from(dl.body).equals(fixtureBytes)).toBe(true);
const ranged = await request(app)
.get(`/api/trips/${trip.id}/files/${fileId}/download`)
.set('Cookie', authCookie(user.id))
.set('Range', 'bytes=0-3');
expect(ranged.status).toBe(206);
expect(ranged.headers['content-range']).toBe(`bytes 0-3/${fixtureBytes.length}`);
});
it('FILE-P05 — Apple Wallet passes are served inline with the canonical MIME types', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
for (const [ext, mime] of [
['pkpass', 'application/vnd.apple.pkpass'],
['pkpasses', 'application/vnd.apple.pkpasses'],
] as const) {
const upload = await request(app)
.post(`/api/trips/${trip.id}/files`)
.set('Cookie', authCookie(user.id))
.attach('file', Buffer.from('PK-wallet-bytes'), `pass.${ext}`);
expect(upload.status).toBe(201);
const dl = await request(app)
.get(`/api/trips/${trip.id}/files/${upload.body.file.id}/download`)
.set('Cookie', authCookie(user.id));
expect(dl.status).toBe(200);
expect(dl.headers['content-type']).toBe(mime);
expect(dl.headers['content-disposition']).toBe(`inline; filename="pass.${ext}"`);
}
});
it('FILE-P06 — a DB row whose bytes are gone answers 404 File not found', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const upload = await uploadFile(trip.id, user.id, FIXTURE_PDF);
const fileId = upload.body.file.id;
fs.rmSync(path.join(uploadsDir, upload.body.file.filename), { force: true });
const dl = await request(app)
.get(`/api/trips/${trip.id}/files/${fileId}/download`)
.set('Cookie', authCookie(user.id));
expect(dl.status).toBe(404);
expect(dl.body).toEqual({ error: 'File not found' });
});
});
+217 -2
View File
@@ -52,7 +52,6 @@ vi.mock('../../src/config', () => ({
vi.mock('../../src/websocket', () => ({
broadcast: vi.fn(),
broadcastToUser: vi.fn(),
setupWebSocket: vi.fn(),
getOnlineUserIds: vi.fn(() => []),
}));
vi.mock('../../src/services/memories/immichService', () => ({
@@ -73,7 +72,7 @@ import {
addJourneyContributor,
} from '../helpers/factories';
import { authCookie } from '../helpers/auth';
import { invalidatePermissionsCache } from '../../src/services/permissions';
import { invalidatePermissionsCache } from '../../src/nest/permissions/permissions-cache';
let nestApp: INestApplication;
let app: Application;
@@ -418,6 +417,69 @@ describe('Journey share link', () => {
expect(get.body.link.share_map).toBe(false);
});
it('JOURNEY-INT-044 — a contributor cannot read the token, only the owner can', async () => {
const { user: owner } = createUser(testDb);
const { user: helper } = createUser(testDb);
const journey = createJourney(testDb, owner.id);
addJourneyContributor(testDb, journey.id, helper.id, 'editor');
await request(app)
.post(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', authCookie(owner.id))
.send({ share_timeline: true, share_gallery: true, share_map: true });
// The token is the whole credential and it outlives the contributor's
// access, so reading it takes the same owner check create and delete take —
// and it refuses the same way, because a 200 with a null link would tell the
// editor this published journey is unpublished.
const res = await request(app)
.get(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', authCookie(helper.id));
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'Not allowed' });
// The owner still reads the link out of the same route.
const owned = await request(app)
.get(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', authCookie(owner.id));
expect(owned.status).toBe(200);
expect(owned.body.link.token).toBeTruthy();
});
it('JOURNEY-INT-044b — an owner with nothing published still gets 200 and a null link', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const res = await request(app)
.get(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body.link).toBeNull();
});
it('JOURNEY-INT-045 — a flag-only update leaves the other flags alone', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
await request(app)
.post(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', authCookie(user.id))
.send({ share_timeline: true, share_gallery: false, share_map: false, newest_first: true });
await request(app)
.post(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', authCookie(user.id))
.send({ share_timeline: false });
const get = await request(app)
.get(`/api/journeys/${journey.id}/share-link`)
.set('Cookie', authCookie(user.id));
expect(get.body.link.share_timeline).toBe(false);
expect(get.body.link.share_gallery).toBe(false);
expect(get.body.link.share_map).toBe(false);
expect(get.body.link.newest_first).toBe(true);
});
it('JOURNEY-INT-017 — DELETE /api/journeys/:id/share-link deletes the share link', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
@@ -1009,3 +1071,156 @@ describe('Photo upload validation', () => {
expect(res.body.error).toBe('No files uploaded');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Upload parity (JOURNEY-P01…P09) — entry photos, gallery photos, video+poster,
// journey cover. Written BEFORE the storage-upload swap to pin behavior.
// ─────────────────────────────────────────────────────────────────────────────
describe('Journey upload parity', () => {
const fsMod = require('fs') as typeof import('fs');
const pathMod = require('path') as typeof import('path');
const FIXTURE_IMG = pathMod.join(__dirname, '../fixtures/small-image.jpg');
const journeyDir = pathMod.join(__dirname, '../../uploads/journey');
afterAll(() => {
fsMod.rmSync(journeyDir, { recursive: true, force: true });
});
it('JOURNEY-P01 — entry photo upload stores journey/<uuid> with a lowercased extension', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id, { entry_date: '2026-04-01' });
const res = await request(app)
.post(`/api/journeys/entries/${entry.id}/photos`)
.set('Cookie', authCookie(user.id))
.attach('photos', FIXTURE_IMG, 'PHOTO.JPG');
expect(res.status).toBe(201);
expect(res.body.photos).toHaveLength(1);
expect(res.body.photos[0].file_path).toMatch(/^journey\/[0-9a-f-]{36}\.jpg$/);
const diskName = res.body.photos[0].file_path.replace(/^journey\//, '');
expect(fsMod.existsSync(pathMod.join(journeyDir, diskName))).toBe(true);
});
it('JOURNEY-P02 — extensionless originalname falls back to .jpg (wildcard allowlist)', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id, { entry_date: '2026-04-01' });
// The admin allowlist rejects the empty extension before the filename
// fallback can run; the wildcard makes the fallback reachable so it is
// actually pinned here.
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allowed_file_types', '*')").run();
const res = await request(app)
.post(`/api/journeys/entries/${entry.id}/photos`)
.set('Cookie', authCookie(user.id))
.attach('photos', fsMod.readFileSync(FIXTURE_IMG), { filename: 'noext', contentType: 'image/jpeg' });
expect(res.status).toBe(201);
expect(res.body.photos[0].file_path).toMatch(/^journey\/[0-9a-f-]{36}\.jpg$/);
});
it('JOURNEY-P03 — non-image entry upload is rejected 400', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id, { entry_date: '2026-04-01' });
const res = await request(app)
.post(`/api/journeys/entries/${entry.id}/photos`)
.set('Cookie', authCookie(user.id))
.attach('photos', Buffer.from('plain text'), { filename: 'doc.txt', contentType: 'text/plain' });
expect(res.status).toBe(400);
expect(res.body.error).toBe('Only image files are allowed');
});
it('JOURNEY-P04 — gallery photo upload stores journey/<uuid> paths', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const res = await request(app)
.post(`/api/journeys/${journey.id}/gallery/photos`)
.set('Cookie', authCookie(user.id))
.attach('photos', FIXTURE_IMG);
expect(res.status).toBe(201);
expect(res.body.photos.length).toBeGreaterThan(0);
});
it('JOURNEY-P05 — non-contributor gallery upload is 403 and the bytes are taken back off disk', async () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const journey = createJourney(testDb, owner.id);
const before = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
const res = await request(app)
.post(`/api/journeys/${journey.id}/gallery/photos`)
.set('Cookie', authCookie(other.id))
.attach('photos', FIXTURE_IMG);
expect(res.status).toBe(403);
expect(res.body.error).toBe('Not allowed');
// The commit runs before the permission answer is known, so the refusal has
// to delete the object again. Nothing sweeps orphans.
const after = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
expect(after).toBe(before);
});
it('JOURNEY-P06 — video+poster upload: poster is ALWAYS stored as .jpg (stored-XSS pin)', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const res = await request(app)
.post(`/api/journeys/${journey.id}/gallery/video`)
.set('Cookie', authCookie(user.id))
.attach('video', Buffer.from('fake video bytes'), { filename: 'clip.MP4', contentType: 'video/mp4' })
.attach('poster', fsMod.readFileSync(FIXTURE_IMG), { filename: 'poster.png', contentType: 'image/png' });
expect(res.status).toBe(201);
expect(res.body.photos).toHaveLength(1);
expect(res.body.photos[0].file_path).toMatch(/^journey\/[0-9a-f-]{36}\.mp4$/);
expect(res.body.photos[0].thumbnail_path).toMatch(/^journey\/[0-9a-f-]{36}\.jpg$/);
});
it('JOURNEY-P07 — poster-only video upload is 400 with no files left anywhere', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const before = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
const res = await request(app)
.post(`/api/journeys/${journey.id}/gallery/video`)
.set('Cookie', authCookie(user.id))
.attach('poster', fsMod.readFileSync(FIXTURE_IMG), { filename: 'poster.png', contentType: 'image/png' });
expect(res.status).toBe(400);
expect(res.body.error).toBe('No video uploaded');
const after = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
expect(after).toBe(before);
});
it('JOURNEY-P08 — non-contributor video upload is 403 and BOTH files are removed', async () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const journey = createJourney(testDb, owner.id);
const before = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
const res = await request(app)
.post(`/api/journeys/${journey.id}/gallery/video`)
.set('Cookie', authCookie(other.id))
.attach('video', Buffer.from('fake video bytes'), { filename: 'clip.mp4', contentType: 'video/mp4' })
.attach('poster', fsMod.readFileSync(FIXTURE_IMG), { filename: 'poster.png', contentType: 'image/png' });
expect(res.status).toBe(403);
expect(res.body.error).toBe('Not allowed');
const after = fsMod.existsSync(journeyDir) ? fsMod.readdirSync(journeyDir).length : 0;
expect(after).toBe(before);
});
it('JOURNEY-P09 — cover upload stores journey/<uuid> into cover_image', async () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const res = await request(app)
.post(`/api/journeys/${journey.id}/cover`)
.set('Cookie', authCookie(user.id))
.attach('cover', FIXTURE_IMG);
expect(res.status).toBe(200);
expect(res.body.cover_image).toMatch(/^journey\/[0-9a-f-]{36}\.jpg$/);
const diskName = res.body.cover_image.replace(/^journey\//, '');
expect(fsMod.existsSync(pathMod.join(journeyDir, diskName))).toBe(true);
});
});
@@ -0,0 +1,267 @@
/**
* Migration test for incoming_leg_transport_mode on day_assignments, plus
* read-path parity: the field must survive both the single-assignment
* projection and the day-LIST projection.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
import request from 'supertest';
import type { Application } from 'express';
import type { INestApplication } from '@nestjs/common';
const Database = require('better-sqlite3');
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
let testDb: any;
beforeAll(() => {
testDb = new Database(':memory:');
testDb.exec('PRAGMA journal_mode = WAL');
testDb.exec('PRAGMA foreign_keys = ON');
createTables(testDb);
runMigrations(testDb);
});
afterAll(() => {
testDb.close();
});
describe('incoming_leg_transport_mode migration', () => {
it('adds a nullable incoming_leg_transport_mode column to day_assignments', () => {
const cols = testDb.prepare(`PRAGMA table_info(day_assignments)`).all() as { name: string }[];
expect(cols.map(c => c.name)).toContain('incoming_leg_transport_mode');
});
// The case above starts from an empty database and runs every migration, so it
// passes wherever a migration sits in the array.
it('every unreleased migration replays cleanly on a database that is behind', () => {
// What actually has to hold: existing installs replay only the slots above
// their schema_version, and an install may skip releases — so every
// migration that has not shipped yet must be REPLAY-SAFE on a schema where
// it already applied: guard DDL (CREATE ... IF NOT EXISTS, pragma column
// checks before ALTER TABLE) and make data transforms idempotent (WHERE
// guards, UPDATE OR IGNORE). This test rewinds a fully migrated database
// to the last released version and replays everything above it; a slot
// that is not replay-safe throws here.
//
// >>> Appending a migration? Nothing to change here — just write it
// >>> replay-safe; this replay tells you if it is not.
// >>> Cutting a release? Bump RELEASED_VERSION to the version it ships.
const RELEASED_VERSION = 189;
const upgraded = new Database(':memory:');
upgraded.exec('PRAGMA foreign_keys = ON');
createTables(upgraded);
runMigrations(upgraded);
const { version } = upgraded.prepare('SELECT version FROM schema_version').get() as { version: number };
expect(version).toBeGreaterThanOrEqual(RELEASED_VERSION);
upgraded.prepare('UPDATE schema_version SET version = ?').run(RELEASED_VERSION);
runMigrations(upgraded); // a throw = some trailing migration is not replay-safe
expect(upgraded.prepare('SELECT version FROM schema_version').get()).toEqual({ version });
upgraded.close();
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Read-path parity (day-LIST endpoint) — mirrors the harness in
// tests/integration/assignments.test.ts verbatim.
// ─────────────────────────────────────────────────────────────────────────────
const { testDb2, dbMock } = vi.hoisted(() => {
const Database2 = require('better-sqlite3');
const db = new Database2(':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 { testDb2: 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: () => {},
SESSION_DURATION: '24h',
SESSION_DURATION_MS: 86400000,
SESSION_DURATION_SECONDS: 86400,
DEFAULT_LANGUAGE: 'en',
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
import { buildApp } from '../../src/bootstrap';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser, createTrip, createDay, createPlace } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
describe('incoming_leg_transport_mode read-path parity', () => {
let nestApp: INestApplication;
let app: Application;
beforeAll(async () => {
createTables(testDb2);
runMigrations(testDb2);
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
});
beforeEach(() => {
resetTestDb(testDb2);
resetRateLimits(nestApp);
});
afterAll(async () => {
await nestApp.close();
testDb2.close();
});
it('round-trips incoming_leg_transport_mode through the day-LIST endpoint', async () => {
const { user } = createUser(testDb2);
const trip = createTrip(testDb2, user.id);
const day = createDay(testDb2, trip.id, { date: '2025-06-01' });
const place = createPlace(testDb2, trip.id, { name: 'Test Place' });
const create = await request(app)
.post(`/api/trips/${trip.id}/days/${day.id}/assignments`)
.set('Cookie', authCookie(user.id))
.send({ place_id: place.id });
expect(create.status).toBe(201);
const assignmentId = create.body.assignment.id;
testDb2.prepare('UPDATE day_assignments SET incoming_leg_transport_mode = ? WHERE id = ?').run('transit', assignmentId);
const res = await request(app)
.get(`/api/trips/${trip.id}/days`)
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
const foundDay = res.body.days.find((d: any) => d.id === day.id);
const a = foundDay.assignments.find((x: any) => x.id === assignmentId);
expect(a.incoming_leg_transport_mode).toBe('transit');
});
// ───────────────────────────────────────────────────────────────────────────
// Write path — PUT .../transport gains `direction` (outgoing|incoming).
// ───────────────────────────────────────────────────────────────────────────
describe('PUT /assignments/:id/transport direction', () => {
it('defaults to outgoing (back-compat)', async () => {
const { user } = createUser(testDb2);
const trip = createTrip(testDb2, user.id);
const day = createDay(testDb2, trip.id, { date: '2025-06-01' });
const place = createPlace(testDb2, trip.id, { name: 'Test Place' });
const create = await request(app)
.post(`/api/trips/${trip.id}/days/${day.id}/assignments`)
.set('Cookie', authCookie(user.id))
.send({ place_id: place.id });
const assignmentId = create.body.assignment.id;
const res = await request(app)
.put(`/api/trips/${trip.id}/assignments/${assignmentId}/transport`)
.set('Cookie', authCookie(user.id))
.send({ transport_mode: 'cycling' });
expect(res.status).toBe(200);
const row = testDb2.prepare('SELECT leg_transport_mode, incoming_leg_transport_mode FROM day_assignments WHERE id = ?').get(assignmentId);
expect(row.leg_transport_mode).toBe('cycling');
expect(row.incoming_leg_transport_mode).toBeNull();
});
it("direction: 'incoming' writes the incoming column", async () => {
const { user } = createUser(testDb2);
const trip = createTrip(testDb2, user.id);
const day = createDay(testDb2, trip.id, { date: '2025-06-01' });
const place = createPlace(testDb2, trip.id, { name: 'Test Place' });
const create = await request(app)
.post(`/api/trips/${trip.id}/days/${day.id}/assignments`)
.set('Cookie', authCookie(user.id))
.send({ place_id: place.id });
const assignmentId = create.body.assignment.id;
const res = await request(app)
.put(`/api/trips/${trip.id}/assignments/${assignmentId}/transport`)
.set('Cookie', authCookie(user.id))
.send({ transport_mode: 'transit', direction: 'incoming' });
expect(res.status).toBe(200);
const row = testDb2.prepare('SELECT incoming_leg_transport_mode FROM day_assignments WHERE id = ?').get(assignmentId);
expect(row.incoming_leg_transport_mode).toBe('transit');
});
it('rejects an invalid direction with 400', async () => {
const { user } = createUser(testDb2);
const trip = createTrip(testDb2, user.id);
const day = createDay(testDb2, trip.id, { date: '2025-06-01' });
const place = createPlace(testDb2, trip.id, { name: 'Test Place' });
const create = await request(app)
.post(`/api/trips/${trip.id}/days/${day.id}/assignments`)
.set('Cookie', authCookie(user.id))
.send({ place_id: place.id });
const assignmentId = create.body.assignment.id;
const res = await request(app)
.put(`/api/trips/${trip.id}/assignments/${assignmentId}/transport`)
.set('Cookie', authCookie(user.id))
.send({ transport_mode: 'walking', direction: 'sideways' });
expect(res.status).toBe(400);
});
it('outgoing and incoming leg modes on one stop persist independently', async () => {
const { user } = createUser(testDb2);
const trip = createTrip(testDb2, user.id);
const day = createDay(testDb2, trip.id, { date: '2025-06-01' });
const place = createPlace(testDb2, trip.id, { name: 'Test Place' });
const create = await request(app)
.post(`/api/trips/${trip.id}/days/${day.id}/assignments`)
.set('Cookie', authCookie(user.id))
.send({ place_id: place.id });
const assignmentId = create.body.assignment.id;
await request(app)
.put(`/api/trips/${trip.id}/assignments/${assignmentId}/transport`)
.set('Cookie', authCookie(user.id))
.send({ transport_mode: 'cycling' })
.expect(200);
await request(app)
.put(`/api/trips/${trip.id}/assignments/${assignmentId}/transport`)
.set('Cookie', authCookie(user.id))
.send({ transport_mode: 'transit', direction: 'incoming' })
.expect(200);
const row = testDb2.prepare('SELECT leg_transport_mode, incoming_leg_transport_mode FROM day_assignments WHERE id = ?').get(assignmentId);
expect(row.leg_transport_mode).toBe('cycling');
expect(row.incoming_leg_transport_mode).toBe('transit');
const res = await request(app)
.get(`/api/trips/${trip.id}/days`)
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
const foundDay = res.body.days.find((d: any) => d.id === day.id);
const a = foundDay.assignments.find((x: any) => x.id === assignmentId);
expect(a.leg_transport_mode).toBe('cycling');
expect(a.incoming_leg_transport_mode).toBe('transit');
});
});
});
+71 -32
View File
@@ -46,37 +46,46 @@ vi.mock('../../src/config', () => ({
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
// Default mock: resolveGoogleMapsUrl rejects with 400 (SSRF-like behaviour for
// URLs that look internal); individual tests override with mockResolvedValueOnce.
vi.mock('../../src/services/mapsService', () => ({
searchPlaces: vi.fn(),
autocompletePlaces: vi.fn(),
getPlaceDetails: vi.fn(),
getPlacePhoto: vi.fn(),
reverseGeocode: vi.fn(),
resolveGoogleMapsUrl: vi.fn().mockRejectedValue(
Object.assign(new Error('SSRF or invalid URL'), { status: 400 })
),
// Imported at module load by transitService (pulled in via app.module).
buildUserAgent: () => 'TREK-Test-UA',
}));
import { buildApp } from '../../src/bootstrap';
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
import * as mapsService from '../../src/services/mapsService';
import { MapsService } from '../../src/nest/maps/maps.service';
let nestApp: INestApplication;
let app: Application;
// Instance spies on the container's MapsService (permissions-migration
// precedent) — the DI fold made the provider methods the outbound seam.
// Defaults mirror the old module mock: bare resolves, except
// resolveGoogleMapsUrl which rejects with 400 (SSRF-like behaviour for URLs
// that look internal); individual tests override with mockResolvedValueOnce.
let mapsService: {
searchPlaces: ReturnType<typeof vi.spyOn>;
autocompletePlaces: ReturnType<typeof vi.spyOn>;
getPlaceDetails: ReturnType<typeof vi.spyOn>;
getPlacePhoto: ReturnType<typeof vi.spyOn>;
reverseGeocode: ReturnType<typeof vi.spyOn>;
resolveGoogleMapsUrl: ReturnType<typeof vi.spyOn>;
};
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
const maps = nestApp.get(MapsService);
mapsService = {
searchPlaces: vi.spyOn(maps, 'searchPlaces').mockResolvedValue(undefined as never),
autocompletePlaces: vi.spyOn(maps, 'autocompletePlaces').mockResolvedValue(undefined as never),
getPlaceDetails: vi.spyOn(maps, 'getPlaceDetails').mockResolvedValue(undefined as never),
getPlacePhoto: vi.spyOn(maps, 'getPlacePhoto').mockResolvedValue(undefined as never),
reverseGeocode: vi.spyOn(maps, 'reverseGeocode').mockResolvedValue(undefined as never),
resolveGoogleMapsUrl: vi.spyOn(maps, 'resolveGoogleMapsUrl').mockRejectedValue(
Object.assign(new Error('SSRF or invalid URL'), { status: 400 }),
),
};
});
beforeEach(() => {
@@ -161,7 +170,7 @@ describe('Maps SSRF protection', () => {
describe('Maps happy paths (mocked service)', () => {
it('MAPS-002 — POST /maps/search returns results from service', async () => {
const { user } = createUser(testDb);
vi.mocked(mapsService.searchPlaces).mockResolvedValueOnce({
mapsService.searchPlaces.mockResolvedValueOnce({
results: [{ address: 'Paris, France', source: 'nominatim' }],
} as any);
@@ -177,7 +186,7 @@ describe('Maps happy paths (mocked service)', () => {
it('MAPS-003 — GET /maps/details/:placeId returns place details', async () => {
const { user } = createUser(testDb);
vi.mocked(mapsService.getPlaceDetails).mockResolvedValueOnce({
mapsService.getPlaceDetails.mockResolvedValueOnce({
name: 'Eiffel Tower',
address: 'Champ de Mars, Paris',
} as any);
@@ -192,7 +201,7 @@ describe('Maps happy paths (mocked service)', () => {
it('MAPS-004 — GET /maps/place-photo/:placeId returns photo url', async () => {
const { user } = createUser(testDb);
vi.mocked(mapsService.getPlacePhoto).mockResolvedValueOnce({
mapsService.getPlacePhoto.mockResolvedValueOnce({
url: 'https://example.com/photo.jpg',
source: 'wikimedia',
} as any);
@@ -207,7 +216,7 @@ describe('Maps happy paths (mocked service)', () => {
it('MAPS-005 — GET /maps/reverse returns geocoded location', async () => {
const { user } = createUser(testDb);
vi.mocked(mapsService.reverseGeocode).mockResolvedValueOnce({
mapsService.reverseGeocode.mockResolvedValueOnce({
name: 'Eiffel Tower',
address: 'Champ de Mars, Paris',
} as any);
@@ -222,7 +231,7 @@ describe('Maps happy paths (mocked service)', () => {
it('MAPS-008 — POST /maps/resolve-url returns extracted coordinates', async () => {
const { user } = createUser(testDb);
vi.mocked(mapsService.resolveGoogleMapsUrl).mockResolvedValueOnce({
mapsService.resolveGoogleMapsUrl.mockResolvedValueOnce({
lat: 48.8584,
lng: 2.2945,
} as any);
@@ -240,7 +249,7 @@ describe('Maps happy paths (mocked service)', () => {
it('MAPS-002 — search service error propagates correct status', async () => {
const { user } = createUser(testDb);
const err = Object.assign(new Error('No API key'), { status: 503 });
vi.mocked(mapsService.searchPlaces).mockRejectedValueOnce(err);
mapsService.searchPlaces.mockRejectedValueOnce(err);
const res = await request(app)
.post('/api/maps/search')
@@ -252,7 +261,7 @@ describe('Maps happy paths (mocked service)', () => {
it('MAPS-003 — getPlaceDetails error returns 500', async () => {
const { user } = createUser(testDb);
vi.mocked(mapsService.getPlaceDetails).mockRejectedValueOnce(new Error('External API failure'));
mapsService.getPlaceDetails.mockRejectedValueOnce(new Error('External API failure'));
const res = await request(app)
.get('/api/maps/details/some-place-id')
@@ -264,21 +273,49 @@ describe('Maps happy paths (mocked service)', () => {
it('MAPS-004 — getPlacePhoto error with status returns that status', async () => {
const { user } = createUser(testDb);
vi.mocked(mapsService.getPlacePhoto).mockRejectedValueOnce(
Object.assign(new Error('Photo not found'), { status: 404 })
mapsService.getPlacePhoto.mockRejectedValueOnce(
Object.assign(new Error('Photo provider unavailable'), { status: 503 })
);
const res = await request(app)
.get('/api/maps/place-photo/some-place-id?lat=48.8&lng=2.3')
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(404);
expect(res.status).toBe(503);
expect(res.body).toHaveProperty('error');
});
// A photo-less place must answer 200 { photoUrl: null }: one 404 per place turns
// a normal itinerary render into a 404 storm that fail2ban/CrowdSec bans (#1727).
it('MAPS-004b — a place with no photo answers 200 with photoUrl null', async () => {
const { user } = createUser(testDb);
mapsService.getPlacePhoto.mockResolvedValueOnce({ photoUrl: null, attribution: null });
const res = await request(app)
.get('/api/maps/place-photo/node%3A5255005321?lat=36.76&lng=-3.84&name=Nerja')
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body).toEqual({ photoUrl: null, attribution: null });
});
// Places keep the bytes URL in image_url, so an evicted cache entry means one
// request per place on the next trip render — the second half of the same ban
// vector. Nothing to serve is an empty 204, not a 404.
it('MAPS-004c — the bytes proxy answers 204 for a photo that is not cached', async () => {
const { user } = createUser(testDb);
const res = await request(app)
.get('/api/maps/place-photo/ChIJnot-cached/bytes')
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(204);
expect(res.text).toBeFalsy();
});
it('MAPS-005 — reverseGeocode error returns null values', async () => {
const { user } = createUser(testDb);
vi.mocked(mapsService.reverseGeocode).mockRejectedValueOnce(new Error('Geocode failed'));
mapsService.reverseGeocode.mockRejectedValueOnce(new Error('Geocode failed'));
const res = await request(app)
.get('/api/maps/reverse?lat=48.8584&lng=2.2945')
@@ -330,7 +367,7 @@ describe('Maps autocomplete', () => {
it('MAPS-013 — POST /maps/autocomplete returns suggestions from service', async () => {
const { user } = createUser(testDb);
vi.mocked(mapsService.autocompletePlaces).mockResolvedValueOnce({
mapsService.autocompletePlaces.mockResolvedValueOnce({
suggestions: [
{ placeId: 'ChIJ1234', mainText: 'Paris', secondaryText: 'France' },
],
@@ -350,7 +387,7 @@ describe('Maps autocomplete', () => {
it('MAPS-014 — POST /maps/autocomplete passes lang and locationBias to service', async () => {
const { user } = createUser(testDb);
vi.mocked(mapsService.autocompletePlaces).mockResolvedValueOnce({
mapsService.autocompletePlaces.mockResolvedValueOnce({
suggestions: [],
source: 'google',
});
@@ -365,13 +402,14 @@ describe('Maps autocomplete', () => {
'test',
'fr',
{ low: { lat: 48.5, lng: 2.0 }, high: { lat: 49.0, lng: 2.8 } },
undefined,
);
});
it('MAPS-015 — autocomplete service error propagates correct status', async () => {
const { user } = createUser(testDb);
const err = Object.assign(new Error('Rate limited'), { status: 429 });
vi.mocked(mapsService.autocompletePlaces).mockRejectedValueOnce(err);
mapsService.autocompletePlaces.mockRejectedValueOnce(err);
const res = await request(app)
.post('/api/maps/autocomplete')
@@ -384,7 +422,7 @@ describe('Maps autocomplete', () => {
it('MAPS-016 — autocomplete service error without status returns 500', async () => {
const { user } = createUser(testDb);
vi.mocked(mapsService.autocompletePlaces).mockRejectedValueOnce(new Error('Unknown'));
mapsService.autocompletePlaces.mockRejectedValueOnce(new Error('Unknown'));
const res = await request(app)
.post('/api/maps/autocomplete')
@@ -403,6 +441,7 @@ describe('Maps autocomplete', () => {
.send({ input: 'a'.repeat(201) });
expect(res.status).toBe(400);
expect(res.body.error).toMatch(/too long/i);
// Wording pinned in maps.controller.test.ts (see the e2e suite's note).
expect(res.body).toHaveProperty('error');
});
});
+307
View File
@@ -55,6 +55,26 @@ import { generateToken } from '../helpers/auth';
import { createMcpToken } from '../helpers/factories';
import { closeMcpSessions } from '../../src/mcp/index';
import { sessions } from '../../src/mcp/sessionManager';
import { getMcpSafeUrl } from '../../src/app-config';
import { OauthService } from '../../src/nest/oauth/oauth.service';
import { DatabaseService } from '../../src/nest/database/database.service';
import { AddonsService } from '../../src/nest/addons/addons.service';
import { AuditService } from '../../src/nest/audit/audit.service';
const oauthDbs = new DatabaseService(testDb);
const oauthSvc = new OauthService(oauthDbs, new AddonsService(oauthDbs), new AuditService(oauthDbs));
/** Mint a trekoa_ access token for the user via a fresh OAuth client. */
function mintOauthToken(userId: number, audience: string | null): { accessToken: string; clientId: string } {
const created = oauthSvc.createOAuthClient(userId, 'MCP Test Client', ['https://client.example.com/cb'], ['trips:read']);
const clientId = (created.client as { client_id: string }).client_id;
const tokens = oauthSvc.issueTokens(clientId, userId, ['trips:read'], null, audience);
return { accessToken: tokens.access_token, clientId };
}
const MCP_AUDIENCE = `${getMcpSafeUrl().replace(/\/+$/, '')}/mcp`;
const EXPECTED_CHALLENGE =
`Bearer realm="TREK MCP", resource_metadata="${getMcpSafeUrl().replace(/\/+$/, '')}/.well-known/oauth-protected-resource/mcp", error="invalid_token"`;
let nestApp: INestApplication;
let app: Application;
@@ -230,6 +250,43 @@ describe('MCP session management', () => {
expect(sessions.has(firstSessionId)).toBe(false); // the least-recently-active one made room
});
it('MCP-006 — initializes that race past the cap check are trimmed when they register', async () => {
const { user } = createUser(testDb);
testDb.prepare("UPDATE addons SET enabled = 1 WHERE id = 'mcp'").run();
const sessionsForUser = () => [...sessions.values()].filter((s) => s.userId === user.id).length;
// What the race leaves behind: concurrent initializes all read the same
// pre-registration count, all pass the cap check, and all register — so the
// map ends up over the cap. Driving that through supertest depends on how
// the requests interleave, so the state itself is set up instead: four past
// the cap, none of them the newcomer's doing. Each entry is only ever
// counted and evicted, so a stub with closable halves is enough.
// Inside the TTL, or countSessionsForUser skips them and there is nothing
// over the cap to trim.
const stale = Date.now() - 10_000;
for (let i = 0; i < 24; i++) {
sessions.set(`overshoot-${i}`, {
server: { close() {} },
transport: { close() {} },
userId: user.id,
scopes: null,
clientId: null,
isStaticToken: false,
lastActivity: stale + i,
lastClientIp: null,
} as unknown as NonNullable<ReturnType<typeof sessions.get>>);
}
expect(sessionsForUser()).toBe(24);
// The pre-check gives back one; without the trim at registration the other
// four stay in the map — each holding a full McpServer — until the TTL sweep.
const newSessionId = await createSession(user.id);
expect(sessionsForUser()).toBe(20);
expect(sessions.has(newSessionId)).toBe(true);
});
it('MCP — session resumption with valid mcp-session-id', async () => {
const { user } = createUser(testDb);
testDb.prepare("UPDATE addons SET enabled = 1 WHERE id = 'mcp'").run();
@@ -311,6 +368,256 @@ describe('MCP session management', () => {
});
});
describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
const initBody = { jsonrpc: '2.0', method: 'initialize', id: 1, params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1' } } };
async function createSession(token: string): Promise<string> {
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${token}`)
.set('Accept', 'application/json, text/event-stream')
.send(initBody);
expect(res.status).toBe(200);
return res.headers['mcp-session-id'] as string;
}
beforeEach(() => {
testDb.prepare("UPDATE addons SET enabled = 1 WHERE id = 'mcp'").run();
});
it('MCP-P01 — addon off answers 403 with the exact legacy body', async () => {
testDb.prepare("UPDATE addons SET enabled = 0 WHERE id = 'mcp'").run();
const res = await request(app).post('/mcp').send(initBody);
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'MCP is not enabled' });
});
it('MCP-P02 — missing/invalid auth carries the exact WWW-Authenticate challenge', async () => {
const res = await request(app).post('/mcp').send(initBody);
expect(res.status).toBe(401);
expect(res.body).toEqual({ error: 'Access token required' });
expect(res.headers['www-authenticate']).toBe(EXPECTED_CHALLENGE);
});
it('MCP-P03 — a non-Bearer scheme and a schemeless token are both rejected', async () => {
for (const header of ['Basic dXNlcjpwdw==', 'just-a-token']) {
const res = await request(app).post('/mcp').set('Authorization', header).send(initBody);
expect(res.status, header).toBe(401);
}
});
it('MCP-P04 — a trekoa_ token with the wrong audience is rejected with a challenge', async () => {
const { user } = createUser(testDb);
const { accessToken } = mintOauthToken(user.id, 'https://other.example.com/api');
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${accessToken}`)
.send(initBody);
expect(res.status).toBe(401);
expect(res.headers['www-authenticate']).toBe(EXPECTED_CHALLENGE);
});
it('MCP-P05 — a trekoa_ token with the MCP audience authenticates', async () => {
const { user } = createUser(testDb);
const { accessToken } = mintOauthToken(user.id, MCP_AUDIENCE);
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${accessToken}`)
.set('Accept', 'application/json, text/event-stream')
.send(initBody);
expect(res.status).toBe(200);
expect(res.headers['mcp-session-id']).toBeTruthy();
});
it('MCP-P06 — resuming an unknown session answers the exact 404 body', async () => {
const { user } = createUser(testDb);
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${generateToken(user.id)}`)
.set('mcp-session-id', 'no-such-session')
.send({ jsonrpc: '2.0', method: 'tools/list', id: 2 });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Session not found' });
});
it("MCP-P07 — another user's session answers 403 with the challenge and exact body", async () => {
const { user: owner } = createUser(testDb);
const { user: intruder } = createUser(testDb);
const sessionId = await createSession(generateToken(owner.id));
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${generateToken(intruder.id)}`)
.set('mcp-session-id', sessionId)
.send({ jsonrpc: '2.0', method: 'tools/list', id: 2 });
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'Session belongs to a different user' });
expect(res.headers['www-authenticate']).toBe(EXPECTED_CHALLENGE);
});
it('MCP-P08 — a session created via JWT rejects resumption by an OAuth client', async () => {
const { user } = createUser(testDb);
const sessionId = await createSession(generateToken(user.id));
const { accessToken } = mintOauthToken(user.id, MCP_AUDIENCE);
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${accessToken}`)
.set('mcp-session-id', sessionId)
.send({ jsonrpc: '2.0', method: 'tools/list', id: 2 });
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'Session was created with a different OAuth client' });
expect(res.headers['www-authenticate']).toBe(EXPECTED_CHALLENGE);
});
it('MCP-P08b — a narrower token cannot resume a session that was created with wider scopes', async () => {
const { user } = createUser(testDb);
const created = oauthSvc.createOAuthClient(user.id, 'Scope Test Client', ['https://client.example.com/cb'], ['trips:read', 'trips:write']);
const clientId = (created.client as { client_id: string }).client_id;
const wide = oauthSvc.issueTokens(clientId, user.id, ['trips:read', 'trips:write'], null, MCP_AUDIENCE);
const narrow = oauthSvc.issueTokens(clientId, user.id, ['trips:read'], null, MCP_AUDIENCE);
const sessionId = await createSession(wide.access_token);
// The tool surface was registered from the wide set; resuming with the
// narrow one would ride it.
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${narrow.access_token}`)
.set('mcp-session-id', sessionId)
.send({ jsonrpc: '2.0', method: 'tools/list', id: 2 });
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'Session was created with different scopes' });
expect(res.headers['www-authenticate']).toContain('error="insufficient_scope"');
});
it('MCP-P08c — the same scopes in a different order still resume', async () => {
const { user } = createUser(testDb);
const created = oauthSvc.createOAuthClient(user.id, 'Scope Order Client', ['https://client.example.com/cb'], ['trips:read', 'trips:write']);
const clientId = (created.client as { client_id: string }).client_id;
const first = oauthSvc.issueTokens(clientId, user.id, ['trips:read', 'trips:write'], null, MCP_AUDIENCE);
const reordered = oauthSvc.issueTokens(clientId, user.id, ['trips:write', 'trips:read'], null, MCP_AUDIENCE);
const sessionId = await createSession(first.access_token);
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${reordered.access_token}`)
.set('mcp-session-id', sessionId)
.set('Accept', 'application/json, text/event-stream')
.send({ jsonrpc: '2.0', method: 'tools/list', id: 2 });
expect(res.status).toBe(200);
});
it('MCP-P09 — a static-token session carries the deprecation notice on the first tool call only', async () => {
const { user } = createUser(testDb);
const { rawToken } = createMcpToken(testDb, user.id);
const sessionId = await createSession(rawToken);
const callBody = { jsonrpc: '2.0', method: 'tools/call', id: 3, params: { name: 'list_trips', arguments: {} } };
const first = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${rawToken}`)
.set('mcp-session-id', sessionId)
.set('Accept', 'application/json, text/event-stream')
.send(callBody);
expect(first.status).toBe(200);
expect(first.text).toContain('Deprecated authentication');
const second = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${rawToken}`)
.set('mcp-session-id', sessionId)
.set('Accept', 'application/json, text/event-stream')
.send({ ...callBody, id: 4 });
expect(second.status).toBe(200);
expect(second.text).not.toContain('Deprecated authentication');
});
it('MCP-P13 — an authorized tools/call writes exactly one mcp.tool_call audit row', async () => {
const { user } = createUser(testDb);
const { accessToken, clientId } = mintOauthToken(user.id, MCP_AUDIENCE);
const sessionId = await createSession(accessToken);
testDb.prepare("DELETE FROM audit_log WHERE action = 'mcp.tool_call'").run();
const call = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${accessToken}`)
.set('mcp-session-id', sessionId)
.set('Accept', 'application/json, text/event-stream')
.send({ jsonrpc: '2.0', method: 'tools/call', id: 3, params: { name: 'list_trips', arguments: {} } });
expect(call.status).toBe(200);
const rows = testDb.prepare(
"SELECT user_id, action, resource, details FROM audit_log WHERE action = 'mcp.tool_call'",
).all() as Array<{ user_id: number; action: string; resource: string; details: string }>;
expect(rows).toHaveLength(1);
expect(rows[0].user_id).toBe(user.id);
expect(rows[0].resource).toBe('list_trips');
expect(JSON.parse(rows[0].details)).toEqual({ clientId });
});
it('MCP-P14 — tools/list and resource reads write no mcp.tool_call rows', async () => {
const { user } = createUser(testDb);
const token = generateToken(user.id);
const sessionId = await createSession(token);
testDb.prepare("DELETE FROM audit_log WHERE action = 'mcp.tool_call'").run();
const list = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${token}`)
.set('mcp-session-id', sessionId)
.set('Accept', 'application/json, text/event-stream')
.send({ jsonrpc: '2.0', method: 'tools/list', id: 2, params: {} });
expect(list.status).toBe(200);
const read = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${token}`)
.set('mcp-session-id', sessionId)
.set('Accept', 'application/json, text/event-stream')
.send({ jsonrpc: '2.0', method: 'resources/list', id: 3, params: {} });
expect(read.status).toBe(200);
const rows = testDb.prepare("SELECT id FROM audit_log WHERE action = 'mcp.tool_call'").all();
expect(rows).toHaveLength(0);
});
it('MCP-P10 — /mcp bodies stay raw: an initialize payload over the global 100kb cap succeeds', async () => {
const { user } = createUser(testDb);
const big = {
...initBody,
params: { ...initBody.params, clientInfo: { name: 'x'.repeat(150 * 1024), version: '1' } },
};
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${generateToken(user.id)}`)
.set('Accept', 'application/json, text/event-stream')
.send(big);
expect(res.status).toBe(200);
expect(res.headers['mcp-session-id']).toBeTruthy();
});
it('MCP-P11 — the global 100kb JSON cap still guards every other route', async () => {
const res = await request(app)
.post('/api/auth/login')
.set('Content-Type', 'application/json')
.send(JSON.stringify({ username: 'x'.repeat(150 * 1024), password: 'y' }));
expect(res.status).toBe(413);
});
it('MCP-P12 — malformed JSON on /mcp gets the SDK JSON-RPC parse error, not body-parser 400', async () => {
const { user } = createUser(testDb);
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${generateToken(user.id)}`)
.set('Accept', 'application/json, text/event-stream')
.set('Content-Type', 'application/json')
.send('{ this is not json');
expect(res.status).toBe(400);
expect(res.body.jsonrpc).toBe('2.0');
expect(res.body.error.code).toBe(-32700);
});
});
describe('MCP rate limiting', () => {
it('MCP-005 — requests below limit succeed', async () => {
const { user } = createUser(testDb);
@@ -56,7 +56,7 @@ const { testDb, dbMock, immichState } = vi.hoisted(() => {
* the legacy one. Both must be filtered out of the picker (#1474).
*/
const DEFAULT_ALBUM_ASSETS = [
{ id: 'asset-sync-1', type: 'IMAGE', fileCreatedAt: '2024-06-01T10:00:00.000Z', exifInfo: { city: 'Paris', country: 'France' } },
{ id: 'asset-sync-1', type: 'IMAGE', fileCreatedAt: '2024-06-01T10:00:00.000Z', exifInfo: { city: 'Paris', country: 'France', latitude: 48.8584, longitude: 2.2945 } },
{ id: 'asset-sync-2', type: 'VIDEO', fileCreatedAt: '2024-06-02T10:00:00.000Z', exifInfo: { city: 'Lyon', country: 'France' } },
{ id: 'asset-hidden', type: 'VIDEO', fileCreatedAt: '2024-06-03T10:00:00.000Z', visibility: 'hidden' },
{ id: 'asset-legacy-hidden', type: 'VIDEO', fileCreatedAt: '2024-06-04T10:00:00.000Z', isVisible: false },
@@ -123,7 +123,7 @@ vi.mock('../../src/utils/ssrfGuard', async () => {
json: () => Promise.resolve({
assets: {
items: [
{ id: 'asset-search-1', fileCreatedAt: '2024-06-01T10:00:00.000Z', exifInfo: { city: 'Paris', country: 'France' } },
{ id: 'asset-search-1', fileCreatedAt: '2024-06-01T10:00:00.000Z', exifInfo: { city: 'Paris', country: 'France', latitude: 48.8566, longitude: 2.3522 } },
],
},
}),
@@ -347,8 +347,9 @@ describe('Immich browse and search', () => {
expect(res.status).toBe(200);
expect(Array.isArray(res.body.assets)).toBe(true);
expect(res.body.assets[0]).toMatchObject({ id: 'asset-search-1', city: 'Paris', country: 'France' });
expect(res.body.assets[0]).toMatchObject({ id: 'asset-search-1', city: 'Paris', country: 'France', lat: 48.8566, lng: 2.3522 });
expect(typeof res.body.hasMore).toBe('boolean');
expect(immichState.searchCalls[0]).toMatchObject({ withExif: true });
});
it('IMMICH-043 — POST /search when upstream throws returns 502', async () => {
@@ -589,6 +590,23 @@ describe('Immich album photos', () => {
expect(res.body.assets[1].mediaType).toBe('video');
});
// #1614 — the album mapping used to drop lat/lng even though the search path
// kept them, so a photo picked from an album could never reach a map.
it('IMMICH-064b — album photos carry their capture coordinates, and tolerate their absence', async () => {
const { user } = createUser(testDb);
setImmichCredentials(testDb, user.id, 'https://immich.example.com', 'test-api-key');
const res = await request(app)
.get(`${IMMICH}/albums/album-uuid-1/photos`)
.set('Cookie', authCookie(user.id));
expect(res.body.assets[0]).toMatchObject({ lat: 48.8584, lng: 2.2945 });
// The second fixture asset has no coordinates; it must come back null, not undefined
// or a half pair.
expect(res.body.assets[1].lat).toBeNull();
expect(res.body.assets[1].lng).toBeNull();
});
it('IMMICH-065 — album photos are fetched via search/metadata with albumIds and withExif', async () => {
const { user } = createUser(testDb);
setImmichCredentials(testDb, user.id, 'https://immich.example.com', 'test-api-key');
@@ -8,7 +8,7 @@
*
* No real HTTP calls are made.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
import request from 'supertest';
import type { Application } from 'express';
import type { INestApplication } from '@nestjs/common';
@@ -704,7 +704,7 @@ describe('Synology auth checks', () => {
// ── Album sync ────────────────────────────────────────────────────────────────
import { addAlbumLink } from '../helpers/factories';
import { encrypt_api_key } from '../../src/services/apiKeyCrypto';
import { encrypt_api_key } from '../../src/nest/common/crypto/apiKeyCrypto';
describe('Synology syncSynologyAlbumLink', () => {
it('SYNO-050 — POST sync happy path: trip owner with album link saves photos to DB', async () => {
@@ -977,7 +977,7 @@ describe('Synology searchSynologyPhotos date range', () => {
thumbnail: { cache_key: '201_abc' },
address: { city: 'Kyoto', country: 'Japan', state: 'Kyoto' },
exif: {},
gps: {},
gps: { latitude: 35.0116, longitude: 135.7681 },
resolution: { width: 4000, height: 3000 },
orientation: 1,
description: null,
@@ -997,6 +997,7 @@ describe('Synology searchSynologyPhotos date range', () => {
expect(res.status).toBe(200);
expect(Array.isArray(res.body.assets)).toBe(true);
expect(res.body.assets[0]).toMatchObject({ lat: 35.0116, lng: 135.7681 });
// Verify date parameters were forwarded in the Synology API request body
expect(capturedBody).not.toBeNull();
@@ -1006,6 +1007,9 @@ describe('Synology searchSynologyPhotos date range', () => {
expect(Number(startTime)).toBeGreaterThan(0);
expect(endTime).toBeDefined();
expect(Number(endTime)).toBeGreaterThan(Number(startTime));
const additional = JSON.parse(capturedBody!.get('additional') || '[]') as string[];
expect(additional).toContain('gps');
});
it('SYNO-071 — POST /search without date range omits start_time and end_time', async () => {
@@ -1182,8 +1186,16 @@ describe('Synology SSRF blocked error handling', () => {
// ── Passphrase persistence fixes ─────────────────────────────────────────────
import { getOrCreateTrekPhoto, deleteTrekPhotoIfOrphan } from '../../src/services/memories/photoResolverService';
import { decrypt_api_key } from '../../src/services/apiKeyCrypto';
import { TrekPhotosRepository } from '../../src/nest/photos/trek-photos.repository';
import { DatabaseService } from '../../src/nest/database/database.service';
import { db as trekDb } from '../../src/db/database';
// Was photos.bridge, which existed for consumers outside the container and had
// none left. The repository is what it delegated to.
const trekPhotos = new TrekPhotosRepository(new DatabaseService(trekDb));
const getOrCreateTrekPhoto = (...a: Parameters<TrekPhotosRepository['getOrCreate']>) => trekPhotos.getOrCreate(...a);
const deleteTrekPhotoIfOrphan = (id: number) => trekPhotos.deleteIfOrphan(id);
import { decrypt_api_key } from '../../src/nest/common/crypto/apiKeyCrypto';
describe('trek_photos passphrase healing (SYNO-090)', () => {
it('SYNO-090 — getOrCreateTrekPhoto overwrites an existing bad passphrase when a new one is supplied', () => {
@@ -248,6 +248,42 @@ describe('Unified photo management', () => {
expect(row).toBeUndefined();
});
it('UNIFIED-009a — DELETE photos is held to the body contract, and still takes a numeric string', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
addTripPhoto(testDb, trip.id, user.id, 'asset-contract', 'immich');
const trekRef = testDb.prepare(`
SELECT tp.photo_id FROM trip_photos tp
JOIN trek_photos tkp ON tkp.id = tp.photo_id
WHERE tp.trip_id = ? AND tkp.asset_id = ?
`).get(trip.id, 'asset-contract') as any;
// A DELETE that reads a body validates it like any other write, so a
// photo_id that is neither a number nor a string never reaches the handler.
const bad = await request(app)
.delete(photosUrl(trip.id))
.set('Cookie', authCookie(user.id))
.send({ photo_id: { id: trekRef.photo_id } });
expect(bad.status).toBe(400);
expect(bad.body.error).toContain('photo_id');
// The contract is deliberately loose about the type, because the client has
// always been free to send the id as a string.
const ok = await request(app)
.delete(photosUrl(trip.id))
.set('Cookie', authCookie(user.id))
.send({ photo_id: String(trekRef.photo_id) });
expect(ok.status).toBe(200);
const row = testDb.prepare(`
SELECT tp.* FROM trip_photos tp
JOIN trek_photos tkp ON tkp.id = tp.photo_id
WHERE tkp.asset_id = ?
`).get('asset-contract');
expect(row).toBeUndefined();
});
it('UNIFIED-010 — DELETE photos on non-member trip returns 404', async () => {
const { user: owner } = createUser(testDb);
const { user: stranger } = createUser(testDb);
+21
View File
@@ -145,3 +145,24 @@ describe('Force HTTPS redirect', () => {
});
});
describe('Request body ceiling', () => {
// The Express shell set '100kb' and stopped when the Nest instance took over
// parsing, which left the limit implicit. This pins it, so it cannot drift
// back to a framework default without somebody noticing.
it('MISC-009 — a body over 100kb is refused with 413', async () => {
const res = await request(app)
.post('/api/auth/login')
.set('Content-Type', 'application/json')
.send({ email: 'a@b.c', password: 'x'.repeat(200 * 1024) });
expect(res.status).toBe(413);
});
it('MISC-010 — a body under it still reaches the handler', async () => {
const res = await request(app)
.post('/api/auth/login')
.set('Content-Type', 'application/json')
.send({ email: 'a@b.c', password: 'x'.repeat(1024) });
expect(res.status).not.toBe(413);
});
});
+21 -9
View File
@@ -45,13 +45,18 @@ vi.mock('../../src/config', () => ({
DEFAULT_LANGUAGE: 'en',
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
vi.mock('../../src/services/notifications', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/services/notifications')>();
return {
...actual,
testSmtp: vi.fn().mockResolvedValue({ success: true }),
testWebhook: vi.fn().mockResolvedValue({ success: true }),
};
// The two test-send endpoints must not reach a real SMTP server or URL. Since
// the fold they are provider methods, so they are stubbed on the prototype
// rather than by module path — everything else in the domain stays real.
vi.mock('../../src/nest/notifications/mailer/mailer.service', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/nest/notifications/mailer/mailer.service')>();
actual.MailerService.prototype.testSmtp = vi.fn().mockResolvedValue({ success: true });
return actual;
});
vi.mock('../../src/nest/notifications/transports/webhook.service', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/nest/notifications/transports/webhook.service')>();
actual.WebhookService.prototype.testWebhook = vi.fn().mockResolvedValue({ success: true });
return actual;
});
import { buildApp } from '../../src/bootstrap';
@@ -95,10 +100,13 @@ describe('Notification preferences', () => {
it('NOTIF-001 — PUT /api/notifications/preferences updates settings', async () => {
const { user } = createUser(testDb);
// The DTO ratchet enforces the matrix shape the client actually sends
// ({ event: { channel: enabled } }); the pre-matrix flat notify_* body
// this case used to send is rejected by the pipe now.
const res = await request(app)
.put('/api/notifications/preferences')
.set('Cookie', authCookie(user.id))
.send({ notify_trip_invite: true, notify_booking_change: false });
.send({ trip_invite: { email: true }, booking_change: { email: false } });
expect(res.status).toBe(200);
expect(res.body).toHaveProperty('preferences');
});
@@ -310,9 +318,13 @@ describe('Notification test endpoints', () => {
it('NOTIF-005 — POST /api/notifications/test-smtp requires admin', async () => {
const { user } = createUser(testDb);
// Send the empty JSON body the client sends ({ email: undefined } →
// {}): a completely body-less POST has no content-type, so the DTO pipe
// rejects it before the admin gate since the ratchet.
const res = await request(app)
.post('/api/notifications/test-smtp')
.set('Cookie', authCookie(user.id));
.set('Cookie', authCookie(user.id))
.send({});
// Non-admin gets 403
expect(res.status).toBe(403);
});
@@ -0,0 +1,289 @@
/**
* HTTP-level tests for GET /oauth/authorize — the MCP SDK authorizationHandler
* wrapping TREK's OAuthServerProvider. Written as byte-level parity oracles for
* the MCP/OAuth mount migration: they must pass identically while the handler
* is mounted pre-init AND after it moves behind the Nest container.
*
* This was the one platform surface with no HTTP coverage at all —
* trekOAuthProvider.authorize and trekClientsStore.getClient run for the first
* time under test here.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
import request from 'supertest';
import type { Application } from 'express';
import type { INestApplication } from '@nestjs/common';
import crypto from 'crypto';
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: () => undefined,
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: () => {},
SESSION_DURATION: '24h',
SESSION_DURATION_MS: 86400000,
SESSION_DURATION_SECONDS: 86400,
DEFAULT_LANGUAGE: 'en',
}));
vi.mock('../../src/app-config', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/app-config')>();
return { ...actual, getMcpSafeUrl: () => 'https://trek.example.com' };
});
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
vi.mock('../../src/mcp/sessionManager', () => ({ revokeUserSessions: vi.fn(), revokeUserSessionsForClient: vi.fn(), sessions: new Map() }));
import { buildApp } from '../../src/bootstrap';
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser } from '../helpers/factories';
import { OauthService } from '../../src/nest/oauth/oauth.service';
import { DatabaseService } from '../../src/nest/database/database.service';
import { AddonsService } from '../../src/nest/addons/addons.service';
import { AuditService } from '../../src/nest/audit/audit.service';
// The consent controller writes pending codes through the container instance;
// the SDK-mounted authorize path reads them back. The map is module-scoped in
// oauth.pending-codes.ts, so a hand-built service instance shares it — the
// same single-instance property the full auth-code loop below proves end-to-end.
const oauthDbs = new DatabaseService(testDb);
const containerSideOauth = new OauthService(oauthDbs, new AddonsService(oauthDbs), new AuditService(oauthDbs));
let nestApp: INestApplication;
let app: Application;
function makePkce() {
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
return { verifier, challenge };
}
function setMcpEnabled(enabled: boolean) {
testDb.prepare(
"INSERT OR REPLACE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES ('mcp', 'MCP', 'AI assistant integration', 'integration', 'Terminal', ?, 12)"
).run(enabled ? 1 : 0);
}
/** DCR-register a public client and return its client_id. */
async function registerClient(redirectUri = 'https://client.example.com/cb', scope = 'trips:read'): Promise<string> {
const res = await request(app)
.post('/oauth/register')
.set('Content-Type', 'application/json')
.send({ redirect_uris: [redirectUri], token_endpoint_auth_method: 'none', scope });
expect(res.status).toBe(201);
return res.body.client_id as string;
}
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
});
beforeEach(() => {
resetTestDb(testDb);
resetRateLimits(nestApp);
setMcpEnabled(true);
});
afterAll(async () => {
await nestApp.close();
testDb.close();
});
describe('GET /oauth/authorize — SDK authorizationHandler over trekOAuthProvider', () => {
it('AUTHZ-001 — happy path 302-redirects to the SPA consent page with the exact forwarded params', async () => {
const clientId = await registerClient();
const { challenge } = makePkce();
const res = await request(app).get('/oauth/authorize').query({
response_type: 'code',
client_id: clientId,
redirect_uri: 'https://client.example.com/cb',
scope: 'trips:read',
state: 'st4te',
code_challenge: challenge,
code_challenge_method: 'S256',
resource: 'https://trek.example.com/mcp',
});
expect(res.status).toBe(302);
const expected = new URLSearchParams({
client_id: clientId,
redirect_uri: 'https://client.example.com/cb',
scope: 'trips:read',
code_challenge: challenge,
code_challenge_method: 'S256',
state: 'st4te',
resource: 'https://trek.example.com/mcp',
});
expect(res.headers.location).toBe(`https://trek.example.com/oauth/consent?${expected.toString()}`);
});
it('AUTHZ-002 — omitted resource defaults to the MCP endpoint and still reaches consent', async () => {
const clientId = await registerClient();
const { challenge } = makePkce();
const res = await request(app).get('/oauth/authorize').query({
response_type: 'code',
client_id: clientId,
redirect_uri: 'https://client.example.com/cb',
scope: 'trips:read',
code_challenge: challenge,
code_challenge_method: 'S256',
});
expect(res.status).toBe(302);
const loc = new URL(res.headers.location);
expect(`${loc.origin}${loc.pathname}`).toBe('https://trek.example.com/oauth/consent');
expect(loc.searchParams.get('client_id')).toBe(clientId);
// No resource param was sent, so none is forwarded.
expect(loc.searchParams.get('resource')).toBeNull();
expect(loc.searchParams.get('state')).toBeNull();
});
it('AUTHZ-003 — wrong resource 302-redirects back to the client with invalid_target', async () => {
const clientId = await registerClient();
const { challenge } = makePkce();
const res = await request(app).get('/oauth/authorize').query({
response_type: 'code',
client_id: clientId,
redirect_uri: 'https://client.example.com/cb',
scope: 'trips:read',
state: 'xyz',
code_challenge: challenge,
code_challenge_method: 'S256',
resource: 'https://evil.example.com/other',
});
expect(res.status).toBe(302);
const loc = new URL(res.headers.location);
expect(`${loc.origin}${loc.pathname}`).toBe('https://client.example.com/cb');
expect(loc.searchParams.get('error')).toBe('invalid_target');
expect(loc.searchParams.get('error_description')).toBe('Requested resource must be the TREK MCP endpoint');
expect(loc.searchParams.get('state')).toBe('xyz');
});
it('AUTHZ-004 — unknown client_id is a 400 invalid_client, no redirect', async () => {
const { challenge } = makePkce();
const res = await request(app).get('/oauth/authorize').query({
response_type: 'code',
client_id: 'does-not-exist',
redirect_uri: 'https://client.example.com/cb',
scope: 'trips:read',
code_challenge: challenge,
code_challenge_method: 'S256',
});
expect(res.status).toBe(400);
expect(res.body.error).toBe('invalid_client');
});
it('AUTHZ-005 — unregistered redirect_uri is a 400 invalid_request, no redirect', async () => {
const clientId = await registerClient();
const { challenge } = makePkce();
const res = await request(app).get('/oauth/authorize').query({
response_type: 'code',
client_id: clientId,
redirect_uri: 'https://attacker.example.com/cb',
scope: 'trips:read',
code_challenge: challenge,
code_challenge_method: 'S256',
});
expect(res.status).toBe(400);
expect(res.body.error).toBe('invalid_request');
});
it('AUTHZ-006 — missing code_challenge redirects back to the client with invalid_request', async () => {
const clientId = await registerClient();
const res = await request(app).get('/oauth/authorize').query({
response_type: 'code',
client_id: clientId,
redirect_uri: 'https://client.example.com/cb',
scope: 'trips:read',
});
expect(res.status).toBe(302);
const loc = new URL(res.headers.location);
expect(`${loc.origin}${loc.pathname}`).toBe('https://client.example.com/cb');
expect(loc.searchParams.get('error')).toBe('invalid_request');
});
it('AUTHZ-007 — MCP addon off: authorize and register both 404 with empty bodies', async () => {
setMcpEnabled(false);
const authz = await request(app).get('/oauth/authorize').query({ client_id: 'x' });
expect(authz.status).toBe(404);
expect(authz.text).toBe('');
const reg = await request(app)
.post('/oauth/register')
.set('Content-Type', 'application/json')
.send({ redirect_uris: ['https://client.example.com/cb'], token_endpoint_auth_method: 'none' });
expect(reg.status).toBe(404);
expect(reg.text).toBe('');
});
it('AUTHZ-008 — full loop: register → authorize → consent-written code → token exchange', async () => {
const { user } = createUser(testDb);
const clientId = await registerClient();
const { verifier, challenge } = makePkce();
// 1. authorize forwards to consent
const authz = await request(app).get('/oauth/authorize').query({
response_type: 'code',
client_id: clientId,
redirect_uri: 'https://client.example.com/cb',
scope: 'trips:read',
code_challenge: challenge,
code_challenge_method: 'S256',
resource: 'https://trek.example.com/mcp',
});
expect(authz.status).toBe(302);
// 2. the consent controller writes the code through the container
// singleton; the module-scoped pending-code map is what lets the
// SDK-side exchange see it.
const code = containerSideOauth.createAuthCode({
clientId,
userId: user.id,
redirectUri: 'https://client.example.com/cb',
scopes: ['trips:read'],
resource: 'https://trek.example.com/mcp',
codeChallenge: challenge,
codeChallengeMethod: 'S256',
});
expect(code).toBeTruthy();
// 3. token exchange through the public token endpoint
const token = await request(app).post('/oauth/token').send({
grant_type: 'authorization_code',
client_id: clientId,
code,
redirect_uri: 'https://client.example.com/cb',
code_verifier: verifier,
resource: 'https://trek.example.com/mcp',
});
expect(token.status).toBe(200);
expect(token.body.access_token).toMatch(/^trekoa_/);
expect(token.body.token_type).toBe('Bearer');
expect(token.body.scope).toBe('trips:read');
});
});
+193 -20
View File
@@ -44,17 +44,8 @@ vi.mock('../../src/config', () => ({
DEFAULT_LANGUAGE: 'en',
}));
const { isAddonEnabledMock } = vi.hoisted(() => {
const isAddonEnabledMock = vi.fn().mockReturnValue(true);
return { isAddonEnabledMock };
});
vi.mock('../../src/services/adminService', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/services/adminService')>();
return { ...actual, isAddonEnabled: isAddonEnabledMock };
});
vi.mock('../../src/services/notifications', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/services/notifications')>();
vi.mock('../../src/app-config', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/app-config')>();
return { ...actual, getMcpSafeUrl: () => 'https://trek.example.com' };
});
@@ -67,7 +58,22 @@ import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
import { createOAuthClient, createAuthCode, getUserByAccessToken } from '../../src/services/oauthService';
import { ALL_SCOPES } from '../../src/mcp/scopes';
import { OauthService } from '../../src/nest/oauth/oauth.service';
import { DatabaseService } from '../../src/nest/database/database.service';
import { AddonsService } from '../../src/nest/addons/addons.service';
import { AuditService } from '../../src/nest/audit/audit.service';
// In production the consent controller writes pending codes through the
// container instance and the SDK routes read them back through the same
// injected singleton. These tests write codes the way the consent controller
// does: through a service instance. The pending-code map is module-scoped in
// oauth.pending-codes.ts, so the routes under test see every code written here.
const oauthDbs = new DatabaseService(testDb);
const containerSideOauth = new OauthService(oauthDbs, new AddonsService(oauthDbs), new AuditService(oauthDbs));
const createAuthCode = containerSideOauth.createAuthCode.bind(containerSideOauth);
const createOAuthClient = containerSideOauth.createOAuthClient.bind(containerSideOauth);
const getUserByAccessToken = containerSideOauth.getUserByAccessToken.bind(containerSideOauth);
let nestApp: INestApplication;
let app: Application;
@@ -79,13 +85,11 @@ function makePkce() {
return { verifier, challenge };
}
// A7: under the unified Nest app the adminService mock only reaches the directly
// imported isAddonEnabled (OauthService.mcpEnabled); oauthService.ts reads the
// addon state through its own import that the Nest module graph loads unmocked,
// so it falls back to the real DB row. Drive BOTH so the MCP-enabled state is
// consistent across mcpEnabled() AND validateAuthorizeRequest()/token/revoke.
// Since the admin-1 extraction, both OauthService (injected AddonsService) and
// the legacy oauthService (addons.bridge) resolve the MCP addon from the real
// addons row, so driving the DB row keeps mcpEnabled() AND
// validateAuthorizeRequest()/token/revoke consistent from one source.
function setMcpEnabled(enabled: boolean) {
isAddonEnabledMock.mockReturnValue(enabled);
testDb.prepare(
"INSERT OR REPLACE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES ('mcp', 'MCP', 'AI assistant integration', 'integration', 'Terminal', ?, 12)"
).run(enabled ? 1 : 0);
@@ -161,6 +165,87 @@ describe('DCR scope optional — ChatGPT compatibility (issue #959 bug 2)', () =
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Platform/discovery parity pins — byte-level oracles for the MCP/OAuth mount
// migration (these must pass identically before AND after the routes move
// behind the Nest container).
// ─────────────────────────────────────────────────────────────────────────────
describe('platform/discovery parity pins', () => {
it('PLAT-PIN-001 — GET /api/health returns the exact probe body + Cache-Control', async () => {
const res = await request(app).get('/api/health');
expect(res.status).toBe(200);
expect(res.headers['cache-control']).toBe('no-store, must-revalidate');
expect(res.body).toEqual({ status: 'ok' });
});
it('PLAT-PIN-002 — openid-configuration is the AS metadata plus userinfo_endpoint, exactly', async () => {
const res = await request(app).get('/.well-known/openid-configuration');
expect(res.status).toBe(200);
expect(res.body).toEqual({
issuer: 'https://trek.example.com',
authorization_endpoint: 'https://trek.example.com/oauth/authorize',
token_endpoint: 'https://trek.example.com/oauth/token',
revocation_endpoint: 'https://trek.example.com/oauth/revoke',
registration_endpoint: 'https://trek.example.com/oauth/register',
response_types_supported: ['code'],
grant_types_supported: ['authorization_code', 'refresh_token', 'client_credentials'],
code_challenge_methods_supported: ['S256'],
token_endpoint_auth_methods_supported: ['client_secret_post', 'none'],
scopes_supported: ALL_SCOPES,
userinfo_endpoint: 'https://trek.example.com/oauth/userinfo',
});
});
it('PLAT-PIN-003 — flat oauth-protected-resource is the exact 5-key RFC 9728 document', async () => {
const res = await request(app).get('/.well-known/oauth-protected-resource');
expect(res.status).toBe(200);
expect(res.body).toEqual({
resource: 'https://trek.example.com/mcp',
authorization_servers: ['https://trek.example.com'],
bearer_methods_supported: ['header'],
scopes_supported: ALL_SCOPES,
resource_name: 'TREK MCP',
});
});
it('PLAT-PIN-004 — every /.well-known/* path 404s with an EMPTY body when MCP is disabled', async () => {
setMcpEnabled(false);
for (const path of [
'/.well-known/openid-configuration',
'/.well-known/oauth-protected-resource',
'/.well-known/oauth-authorization-server',
]) {
const res = await request(app).get(path);
expect(res.status, path).toBe(404);
expect(res.text, path).toBe('');
}
});
it('PLAT-PIN-005 — an unhandled /.well-known path gets the JSON 404, never SPA HTML', async () => {
const res = await request(app).get('/.well-known/does-not-exist');
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'not_found' });
});
it('PLAT-PIN-006 — /.well-known/ (trailing slash) also gets the JSON 404', async () => {
const res = await request(app).get('/.well-known/');
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'not_found' });
});
it('PLAT-PIN-007 — bare /.well-known falls through to the router 404 envelope', async () => {
const res = await request(app).get('/.well-known');
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Cannot GET /.well-known' });
});
it('PLAT-PIN-008 — /oauth/consent responses carry the relaxed COOP header', async () => {
const res = await request(app).get('/oauth/consent');
expect(res.headers['cross-origin-opener-policy']).toBe('unsafe-none');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// POST /oauth/token — authorization_code grant
// ─────────────────────────────────────────────────────────────────────────────
@@ -223,6 +308,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
// Try to use it with client2
@@ -252,6 +338,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
const res = await request(app)
@@ -280,6 +367,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
const res = await request(app)
@@ -308,6 +396,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
const res = await request(app)
@@ -336,6 +425,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
const res = await request(app)
@@ -398,6 +488,7 @@ describe('POST /oauth/token — refresh_token grant', () => {
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
// Exchange code for tokens
@@ -489,6 +580,7 @@ describe('POST /oauth/revoke', () => {
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
const tokenRes = await request(app)
@@ -728,22 +820,44 @@ describe('POST /api/oauth/authorize', () => {
it('OAUTH-030 — user denied returns redirect with error=access_denied', async () => {
const { user } = createUser(testDb);
const r = createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
const res = await request(app)
.post('/api/oauth/authorize')
.set('Cookie', authCookie(user.id))
.send({
approved: false,
client_id: 'any',
client_id: r.client!.client_id,
redirect_uri: 'https://app.example.com/cb',
scope: 'trips:read',
code_challenge: 'c',
code_challenge: challenge,
code_challenge_method: 'S256',
});
expect(res.status).toBe(200);
expect(res.body.redirect).toContain('error=access_denied');
});
it('OAUTH-030b — a denial for an unregistered redirect_uri is refused, not redirected', async () => {
const { user } = createUser(testDb);
const r = createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
const res = await request(app)
.post('/api/oauth/authorize')
.set('Cookie', authCookie(user.id))
.send({
approved: false,
client_id: r.client!.client_id,
redirect_uri: 'https://attacker.example.com/cb',
scope: 'trips:read',
code_challenge: challenge,
code_challenge_method: 'S256',
});
expect(res.status).toBe(400);
expect(res.body.error).toBe('invalid_redirect_uri');
});
it('OAUTH-031 — invalid params returns 400', async () => {
const { user } = createUser(testDb);
const { challenge } = makePkce();
@@ -909,6 +1023,7 @@ describe('Sessions — /api/oauth/sessions', () => {
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
// Get a token so there's a session to revoke
@@ -1017,6 +1132,7 @@ describe('H1 — PKCE format validation', () => {
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
// Submit a valid-looking but wrong-format verifier (too short)
@@ -1074,6 +1190,7 @@ describe('H5 — All invalid_grant cases return identical response body', () =>
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
// Bad code
@@ -1094,6 +1211,7 @@ describe('H5 — All invalid_grant cases return identical response body', () =>
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
const res2 = await request(app).post('/oauth/token').send({
grant_type: 'authorization_code',
@@ -1207,6 +1325,17 @@ describe('M7 — Cookie-only auth on privileged OAuth endpoints', () => {
});
describe('C3 — Refresh token replay detection', () => {
/**
* Push a rotation out of the concurrency grace window (#1007) so a replay
* below still describes theft — a token used minutes later — rather than two
* clients refreshing at the same moment.
*/
function agePastGrace(rawRefreshToken: string) {
const hash = crypto.createHash('sha256').update(rawRefreshToken).digest('hex');
const old = new Date(Date.now() - 5 * 60 * 1000).toISOString().replace('T', ' ').slice(0, 19);
testDb.prepare('UPDATE oauth_tokens SET revoked_at = ? WHERE refresh_token_hash = ?').run(old, hash);
}
it('OAUTH-SEC-012 — replaying a rotated (old) refresh token returns invalid_grant', async () => {
const { user } = createUser(testDb);
const r = createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
@@ -1219,6 +1348,7 @@ describe('C3 — Refresh token replay detection', () => {
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
// Get initial tokens
@@ -1243,6 +1373,7 @@ describe('C3 — Refresh token replay detection', () => {
expect(t2.status).toBe(200);
// Replay the original (now rotated/revoked) refresh token — must be rejected
agePastGrace(originalRefreshToken);
const t3 = await request(app).post('/oauth/token').send({
grant_type: 'refresh_token',
client_id: r.client!.client_id,
@@ -1253,6 +1384,46 @@ describe('C3 — Refresh token replay detection', () => {
expect(t3.body.error).toBe('invalid_grant');
});
it('OAUTH-SEC-012b — two clients refreshing the same token at once both keep working (#1007)', async () => {
const { user } = createUser(testDb);
const r = createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
const code = createAuthCode({
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
const t1 = await request(app).post('/oauth/token').send({
grant_type: 'authorization_code',
client_id: r.client!.client_id,
client_secret: r.client!.client_secret,
code,
redirect_uri: 'https://app.example.com/cb',
code_verifier: verifier,
});
const shared = t1.body.refresh_token;
const refresh = () => request(app).post('/oauth/token').send({
grant_type: 'refresh_token',
client_id: r.client!.client_id,
client_secret: r.client!.client_secret,
refresh_token: shared,
});
// The second MCP session posts the token its sibling has just spent.
const first = await refresh();
const second = await refresh();
expect(first.status).toBe(200);
expect(second.status).toBe(200);
expect(second.body.refresh_token).not.toBe(first.body.refresh_token);
});
it('OAUTH-SEC-013 — replaying old token also invalidates the new chain', async () => {
const { user } = createUser(testDb);
const r = createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
@@ -1265,6 +1436,7 @@ describe('C3 — Refresh token replay detection', () => {
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
const t1 = await request(app).post('/oauth/token').send({
@@ -1287,6 +1459,7 @@ describe('C3 — Refresh token replay detection', () => {
const newRefreshToken = t2.body.refresh_token;
// Replay original — triggers chain revocation
agePastGrace(originalRefreshToken);
await request(app).post('/oauth/token').send({
grant_type: 'refresh_token',
client_id: r.client!.client_id,
+94 -34
View File
@@ -1,8 +1,11 @@
/**
* OIDC integration tests — OIDC-001 through OIDC-010.
* OIDC integration tests — OIDC-001 through OIDC-014.
* Covers /api/auth/oidc/login, /callback, /exchange.
* HTTP calls (discover, exchangeCodeForToken, getUserInfo) are mocked.
* State management, auth codes, and findOrCreateUser run against the real test DB.
* HTTP calls (discover, exchangeCodeForToken, getUserInfo, verifyIdToken) are
* stubbed with vi.spyOn on the container's OidcService instance (the domain is
* DI-native since the oidc fold — a services/oidcService path mock would
* silently miss). State management, auth codes, and findOrCreateUser run for
* real on that same instance against the real test DB.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
import request from 'supertest';
@@ -38,37 +41,20 @@ vi.mock('../../src/config', () => ({
SESSION_DURATION: '24h',
SESSION_DURATION_MS: 86400000,
SESSION_DURATION_SECONDS: 86400,
SESSION_DURATION_REMEMBER: '30d',
SESSION_DURATION_REMEMBER_MS: 2592000000,
SESSION_DURATION_REMEMBER_SECONDS: 2592000,
DEFAULT_LANGUAGE: 'en',
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
// ── Mock only the HTTP-calling functions from oidcService ────────────────────
vi.mock('../../src/services/oidcService', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/services/oidcService')>();
return {
...actual,
discover: vi.fn(),
exchangeCodeForToken: vi.fn(),
getUserInfo: vi.fn(),
// Bypass real JWKS fetch + signature verification in tests. Callers
// that exercise the security of verifyIdToken should unit-test the
// function directly instead; integration tests here focus on the
// callback flow, not the crypto.
verifyIdToken: vi.fn(),
};
});
import type { MockInstance } from 'vitest';
import { buildApp } from '../../src/bootstrap';
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser } from '../helpers/factories';
import * as oidcService from '../../src/services/oidcService';
const mockDiscover = vi.mocked(oidcService.discover);
const mockExchangeCode = vi.mocked(oidcService.exchangeCodeForToken);
const mockGetUserInfo = vi.mocked(oidcService.getUserInfo);
const mockVerifyIdToken = vi.mocked(oidcService.verifyIdToken);
import { OidcService } from '../../src/nest/oidc/oidc.service';
const MOCK_DISCOVERY_DOC = {
authorization_endpoint: 'https://oidc.example.com/auth',
@@ -78,12 +64,29 @@ const MOCK_DISCOVERY_DOC = {
let nestApp: INestApplication;
let app: Application;
let oidcSvc: OidcService;
let mockDiscover: MockInstance<OidcService['discover']>;
let mockExchangeCode: MockInstance<OidcService['exchangeCodeForToken']>;
let mockGetUserInfo: MockInstance<OidcService['getUserInfo']>;
let mockVerifyIdToken: MockInstance<OidcService['verifyIdToken']>;
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
// Stub only the HTTP-calling methods on the container's OidcService — the
// default implementation resolves undefined so an unexpected call fails the
// flow (matching the old vi.fn() mocks) instead of hitting the network.
// Bypasses real JWKS fetch + signature verification: callers that exercise
// the security of verifyIdToken unit-test the method directly; integration
// tests here focus on the callback flow, not the crypto. State management,
// auth codes, and findOrCreateUser run for real on this same instance.
oidcSvc = nestApp.get(OidcService);
mockDiscover = vi.spyOn(oidcSvc, 'discover').mockImplementation(async () => undefined as never);
mockExchangeCode = vi.spyOn(oidcSvc, 'exchangeCodeForToken').mockImplementation(async () => undefined as never);
mockGetUserInfo = vi.spyOn(oidcSvc, 'getUserInfo').mockImplementation(async () => undefined as never);
mockVerifyIdToken = vi.spyOn(oidcSvc, 'verifyIdToken').mockImplementation(async () => undefined as never);
});
beforeEach(() => {
@@ -169,7 +172,7 @@ describe('GET /api/auth/oidc/callback', () => {
});
// Create a valid state token
const { state } = oidcService.createState('http://localhost:3001/api/auth/oidc/callback');
const { state } = oidcSvc.createState('http://localhost:3001/api/auth/oidc/callback');
const res = await request(app).get(`/api/auth/oidc/callback?code=authcode123&state=${state}`).set('Cookie', `trek_oidc_state=${state}`);
@@ -187,7 +190,7 @@ describe('GET /api/auth/oidc/callback', () => {
name: 'New User',
});
const { state } = oidcService.createState('http://localhost:3001/api/auth/oidc/callback');
const { state } = oidcSvc.createState('http://localhost:3001/api/auth/oidc/callback');
const res = await request(app).get(`/api/auth/oidc/callback?code=code999&state=${state}`).set('Cookie', `trek_oidc_state=${state}`);
@@ -224,7 +227,7 @@ describe('GET /api/auth/oidc/callback', () => {
mockDiscover.mockResolvedValueOnce(MOCK_DISCOVERY_DOC);
mockExchangeCode.mockResolvedValueOnce({ _ok: false, _status: 400 });
const { state } = oidcService.createState('http://localhost:3001/api/auth/oidc/callback');
const { state } = oidcSvc.createState('http://localhost:3001/api/auth/oidc/callback');
const res = await request(app).get(`/api/auth/oidc/callback?code=badcode&state=${state}`).set('Cookie', `trek_oidc_state=${state}`);
@@ -236,7 +239,7 @@ describe('GET /api/auth/oidc/callback', () => {
mockDiscover.mockResolvedValueOnce(MOCK_DISCOVERY_DOC);
mockExchangeCode.mockResolvedValueOnce({ access_token: 'tok', _ok: true, _status: 200 }); // no id_token
const { state } = oidcService.createState('http://localhost:3001/api/auth/oidc/callback');
const { state } = oidcSvc.createState('http://localhost:3001/api/auth/oidc/callback');
const res = await request(app).get(`/api/auth/oidc/callback?code=anycode&state=${state}`).set('Cookie', `trek_oidc_state=${state}`);
@@ -249,7 +252,7 @@ describe('GET /api/auth/oidc/callback', () => {
mockExchangeCode.mockResolvedValueOnce({ access_token: 'tok', id_token: 'bad.id.token', _ok: true, _status: 200 });
mockVerifyIdToken.mockResolvedValueOnce({ ok: false, error: 'signature_or_claim_mismatch: invalid signature' });
const { state } = oidcService.createState('http://localhost:3001/api/auth/oidc/callback');
const { state } = oidcSvc.createState('http://localhost:3001/api/auth/oidc/callback');
const res = await request(app).get(`/api/auth/oidc/callback?code=anycode&state=${state}`).set('Cookie', `trek_oidc_state=${state}`);
@@ -267,7 +270,7 @@ describe('GET /api/auth/oidc/callback', () => {
name: 'Alice',
});
const { state } = oidcService.createState('http://localhost:3001/api/auth/oidc/callback');
const { state } = oidcSvc.createState('http://localhost:3001/api/auth/oidc/callback');
const res = await request(app).get(`/api/auth/oidc/callback?code=anycode&state=${state}`).set('Cookie', `trek_oidc_state=${state}`);
@@ -290,7 +293,7 @@ describe('GET /api/auth/oidc/callback', () => {
name: 'Blocked',
});
const { state } = oidcService.createState('http://localhost:3001/api/auth/oidc/callback');
const { state } = oidcSvc.createState('http://localhost:3001/api/auth/oidc/callback');
const res = await request(app).get(`/api/auth/oidc/callback?code=anycode&state=${state}`).set('Cookie', `trek_oidc_state=${state}`);
@@ -304,7 +307,7 @@ describe('GET /api/auth/oidc/callback', () => {
describe('GET /api/auth/oidc/exchange', () => {
it('OIDC-011: valid auth code returns JWT and sets cookie', async () => {
const fakeToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.test.sig';
const code = oidcService.createAuthCode(fakeToken);
const code = oidcSvc.createAuthCode(fakeToken);
const res = await request(app).get(`/api/auth/oidc/exchange?code=${code}`);
@@ -331,7 +334,7 @@ describe('GET /api/auth/oidc/exchange', () => {
it('OIDC-014: auth code is single-use (second use returns 400)', async () => {
const fakeToken = 'test.token.here';
const code = oidcService.createAuthCode(fakeToken);
const code = oidcSvc.createAuthCode(fakeToken);
// First use: success
const res1 = await request(app).get(`/api/auth/oidc/exchange?code=${code}`);
@@ -342,3 +345,60 @@ describe('GET /api/auth/oidc/exchange', () => {
expect(res2.status).toBe(400);
});
});
// ── remember-me across the full flow (#1927) ─────────────────────────────────
describe('OIDC remember-me (#1927)', () => {
// Runs the real /login → /callback → /exchange chain, following the state the
// controller minted, and returns the exchange response for cookie assertions.
async function runFlow(loginQuery: string, sub: string, email: string) {
mockDiscover.mockResolvedValue(MOCK_DISCOVERY_DOC);
mockExchangeCode.mockResolvedValue({ access_token: 'tok', id_token: 'fake.id.token', _ok: true, _status: 200 });
mockVerifyIdToken.mockResolvedValue({ ok: true, claims: { sub } });
mockGetUserInfo.mockResolvedValue({ sub, email, name: 'Flow User' });
const login = await request(app).get(`/api/auth/oidc/login${loginQuery}`);
expect(login.status).toBe(302);
const state = new URL(login.headers.location!).searchParams.get('state')!;
const cb = await request(app)
.get(`/api/auth/oidc/callback?code=anycode&state=${state}`)
.set('Cookie', `trek_oidc_state=${state}`);
expect(cb.status).toBe(302);
const oidcCode = new URL(cb.headers.location!, 'http://localhost').searchParams.get('oidc_code')!;
expect(oidcCode).toBeTruthy();
return request(app).get(`/api/auth/oidc/exchange?code=${oidcCode}`);
}
function sessionCookie(res: request.Response): string {
const cookies = Array.isArray(res.headers['set-cookie']) ? res.headers['set-cookie'] : [res.headers['set-cookie']];
return cookies.filter((c: string) => c.startsWith('trek_session=')).pop()!;
}
it('OIDC-015: remember=1 issues a 30d JWT and a Max-Age=2592000 cookie', async () => {
const res = await runFlow('?remember=1', 'sub-rm-1', 'rm1@example.com');
expect(res.status).toBe(200);
expect(sessionCookie(res)).toContain('Max-Age=2592000');
const jwt = require('jsonwebtoken');
const decoded = jwt.decode(res.body.token) as { iat: number; exp: number };
expect(decoded.exp - decoded.iat).toBe(2592000);
});
it('OIDC-016: remember=0 issues a browser-session cookie (no Max-Age) with the default JWT', async () => {
const res = await runFlow('?remember=0', 'sub-rm-0', 'rm0@example.com');
expect(res.status).toBe(200);
const cookie = sessionCookie(res);
expect(cookie).not.toContain('Max-Age=');
expect(cookie).not.toContain('Expires=');
const jwt = require('jsonwebtoken');
const decoded = jwt.decode(res.body.token) as { iat: number; exp: number };
expect(decoded.exp - decoded.iat).toBe(86400);
});
it('OIDC-017: no remember param keeps the historical 24h persistent cookie', async () => {
const res = await runFlow('', 'sub-rm-abs', 'rmabs@example.com');
expect(res.status).toBe(200);
expect(sessionCookie(res)).toContain('Max-Age=86400');
});
});
+8 -1
View File
@@ -257,7 +257,14 @@ describe('Three-tier packing sharing (#858)', () => {
addTripMember(testDb, trip.id, member.id);
const created = await request(app).post(`/api/trips/${trip.id}/packing`).set('Cookie', authCookie(owner.id)).send({ name: 'Tent', visibility: 'personal' });
const denied = await request(app).put(`/api/trips/${trip.id}/packing/${created.body.item.id}/sharing`).set('Cookie', authCookie(member.id)).send({ visibility: 'common' });
// A member who cannot see the item at all gets 404, not 403: answering 403
// would confirm that the id exists (GHSA-vh2h-288v-ggch).
const hidden = await request(app).put(`/api/trips/${trip.id}/packing/${created.body.item.id}/sharing`).set('Cookie', authCookie(member.id)).send({ visibility: 'common' });
expect(hidden.status).toBe(404);
// An item the member CAN see but does not own still answers 403.
const shared = await request(app).post(`/api/trips/${trip.id}/packing`).set('Cookie', authCookie(owner.id)).send({ name: 'Stove', visibility: 'common' });
const denied = await request(app).put(`/api/trips/${trip.id}/packing/${shared.body.item.id}/sharing`).set('Cookie', authCookie(member.id)).send({ visibility: 'personal' });
expect(denied.status).toBe(403);
});
});
+70 -22
View File
@@ -7,7 +7,7 @@
* - PLACE-014: reordering within a day is tested in assignments.test.ts
* - PLACE-019: GPX bulk import tested here using the test fixture
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll, type MockInstance } from 'vitest';
import request from 'supertest';
import type { Application } from 'express';
import type { INestApplication } from '@nestjs/common';
@@ -48,14 +48,6 @@ vi.mock('../../src/config', () => ({
DEFAULT_LANGUAGE: 'en',
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
vi.mock('../../src/services/placeService', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/services/placeService')>();
return {
...actual,
importGoogleList: vi.fn(),
searchPlaceImage: vi.fn(),
};
});
import { buildApp } from '../../src/bootstrap';
import { createTables } from '../../src/db/schema';
@@ -63,11 +55,17 @@ import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser, createAdmin, createTrip, createPlace, addTripMember } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
import * as placeService from '../../src/services/placeService';
import { invalidatePermissionsCache } from '../../src/services/permissions';
import { PlacesService } from '../../src/nest/places/places.service';
import { invalidatePermissionsCache } from '../../src/nest/permissions/permissions-cache';
let nestApp: INestApplication;
let app: Application;
// Since the place DI fold the two outbound-I/O paths are stubbed as spies on the
// container's PlacesService singleton (permissions precedent) instead of a path
// mock of the deleted services/placeService. Bare spies keep the real
// implementation, so only the *Once overrides below change behaviour.
let importGoogleList: MockInstance;
let searchPlaceImage: MockInstance;
const GPX_FIXTURE = path.join(__dirname, '../fixtures/test.gpx');
const KML_FIXTURE = path.join(__dirname, '../fixtures/test.kml');
const KML_NESTED_FIXTURE = path.join(__dirname, '../fixtures/test-nested.kml');
@@ -85,6 +83,10 @@ beforeEach(() => {
resetTestDb(testDb);
resetRateLimits(nestApp);
invalidatePermissionsCache();
// Re-attached per test: one describe below calls vi.restoreAllMocks() in its
// afterEach, which would otherwise strip these for every later test.
importGoogleList = vi.spyOn(nestApp.get(PlacesService), 'importGoogleList');
searchPlaceImage = vi.spyOn(nestApp.get(PlacesService), 'searchImage');
});
afterAll(async () => {
@@ -547,7 +549,7 @@ describe('Naver list import', () => {
})
.mockResolvedValueOnce({
ok: true,
json: async () => ({
text: async () => JSON.stringify({
folder: { name: 'Seoul Food', bookmarkCount: 22 },
bookmarkList: [
{ name: 'SINSAJEON', px: 127.0226195, py: 37.5186363, memo: null, address: 'Sinsa-dong Seoul' },
@@ -557,7 +559,7 @@ describe('Naver list import', () => {
})
.mockResolvedValueOnce({
ok: true,
json: async () => ({
text: async () => JSON.stringify({
folder: { name: 'Seoul Food', bookmarkCount: 22 },
bookmarkList: [
{ name: 'WAIKIKI MARKET', px: 126.8886523, py: 37.5589079, memo: null, address: 'Mapo-gu Seoul' },
@@ -631,7 +633,7 @@ describe('Naver list import', () => {
const fetchMock = vi.fn().mockResolvedValueOnce({
ok: true,
json: async () => ({ folder: { name: 'Empty List', bookmarkCount: 0 }, bookmarkList: [] }),
text: async () => JSON.stringify({ folder: { name: 'Empty List', bookmarkCount: 0 }, bookmarkList: [] }),
});
vi.stubGlobal('fetch', fetchMock);
@@ -654,7 +656,7 @@ describe('Naver list import', () => {
const fetchMock = vi.fn().mockResolvedValueOnce({
ok: true,
json: async () => ({
text: async () => JSON.stringify({
folder: { name: 'No Coords', bookmarkCount: 2 },
bookmarkList: [
{ name: 'Place A', px: undefined, py: undefined },
@@ -683,7 +685,7 @@ describe('Naver list import', () => {
const fetchMock = vi.fn().mockResolvedValueOnce({
ok: true,
json: async () => ({
text: async () => JSON.stringify({
folder: { name: 'Seoul', bookmarkCount: 1 },
bookmarkList: [{ name: 'Gyeongbokgung', px: 126.9770, py: 37.5796, memo: null, address: 'Sejongno Seoul' }],
}),
@@ -894,7 +896,7 @@ describe('Google Maps list import', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
vi.mocked(placeService.importGoogleList).mockResolvedValueOnce({
importGoogleList.mockResolvedValueOnce({
places: [{ id: 1, name: 'Mocked Place' } as any],
listName: 'My List',
} as any);
@@ -912,7 +914,7 @@ describe('Google Maps list import', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
vi.mocked(placeService.importGoogleList).mockResolvedValueOnce({
importGoogleList.mockResolvedValueOnce({
error: 'Invalid list URL',
status: 422,
} as any);
@@ -929,7 +931,7 @@ describe('Google Maps list import', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
vi.mocked(placeService.importGoogleList).mockRejectedValueOnce(new Error('Network failure'));
importGoogleList.mockRejectedValueOnce(new Error('Network failure'));
const res = await request(app)
.post(`/api/trips/${trip.id}/places/import/google-list`)
@@ -949,7 +951,7 @@ describe('Place image search', () => {
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Louvre' });
vi.mocked(placeService.searchPlaceImage).mockResolvedValueOnce({
searchPlaceImage.mockResolvedValueOnce({
photos: [{ url: 'https://example.com/photo.jpg' }],
} as any);
@@ -965,7 +967,7 @@ describe('Place image search', () => {
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Tower' });
vi.mocked(placeService.searchPlaceImage).mockResolvedValueOnce({
searchPlaceImage.mockResolvedValueOnce({
error: 'No images found',
status: 404,
} as any);
@@ -982,7 +984,7 @@ describe('Place image search', () => {
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Bridge' });
vi.mocked(placeService.searchPlaceImage).mockRejectedValueOnce(new Error('Unsplash down'));
searchPlaceImage.mockRejectedValueOnce(new Error('Unsplash down'));
const res = await request(app)
.get(`/api/trips/${trip.id}/places/${place.id}/image`)
@@ -1025,3 +1027,49 @@ describe('Delete place — not found', () => {
expect(res.status).toBe(404);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Custom place image upload (#1136)
// ─────────────────────────────────────────────────────────────────────────────
describe('Custom place image upload', () => {
const FIXTURE_JPEG = path.join(__dirname, '../fixtures/small-image.jpg');
const FIXTURE_PDF = path.join(__dirname, '../fixtures/test.pdf');
it('PLACE-026 — POST /:id/image stores the upload, then PUT image_url:null clears it', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Snap' });
const res = await request(app)
.post(`/api/trips/${trip.id}/places/${place.id}/image`)
.set('Cookie', authCookie(user.id))
.attach('image', FIXTURE_JPEG);
expect(res.status).toBe(200);
expect(res.body.place.image_url).toMatch(/^\/uploads\/places\/[0-9a-f-]{36}\./);
// The bytes land at the final uploads/places path under the bare uuid name.
const fsMod = require('fs') as typeof import('fs');
const pathMod = require('path') as typeof import('path');
const diskName = res.body.place.image_url.replace('/uploads/places/', '');
expect(fsMod.existsSync(pathMod.join(__dirname, '../../uploads/places', diskName))).toBe(true);
const cleared = await request(app)
.put(`/api/trips/${trip.id}/places/${place.id}`)
.set('Cookie', authCookie(user.id))
.send({ image_url: null });
expect(cleared.status).toBe(200);
expect(cleared.body.place.image_url).toBeNull();
});
it('PLACE-027 — uploading a non-image (PDF) is rejected', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Snap' });
const res = await request(app)
.post(`/api/trips/${trip.id}/places/${place.id}/image`)
.set('Cookie', authCookie(user.id))
.attach('image', FIXTURE_PDF);
expect(res.status).toBe(400);
});
});
@@ -0,0 +1,142 @@
/**
* Boot-order regression (#plugins): the RPC registry must be scanned before the
* runtime auto-activates the plugins an admin had enabled.
*
* The bug this pins: PluginRuntimeService booted enabled plugins from
* onModuleInit, and Nest fires same-module onModuleInit hooks in providers-array
* declaration order — where the runtime service is listed BEFORE
* PluginRpcRegistryService. Each boot activation builds its PluginRpcHost
* synchronously (bindInto snapshots the registry at construction), so every host
* was bound from a STILL-EMPTY registry: the plugin's first RPC on activation
* (typically ctx.db.migrate in onLoad) came back PERMISSION_DENIED and the plugin
* landed in error state on every cold boot, until an admin deactivated and
* reactivated it by hand. The fix moves the boot reconcile to
* onApplicationBootstrap, which Nest guarantees runs after EVERY module's
* onModuleInit — so this suite assembles a real Nest module mirroring the
* production declaration order (runtime provider first, registry scan later) and
* asserts the plugin still comes up clean.
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Test } from '@nestjs/testing';
import type { TestingModule } from '@nestjs/testing';
const { testDb } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec(`CREATE TABLE plugins (
id TEXT PRIMARY KEY, status TEXT, enabled INTEGER DEFAULT 0, version TEXT, api_version INTEGER DEFAULT 1, permissions TEXT DEFAULT '[]', operator_egress INTEGER DEFAULT 0, granted_permissions TEXT DEFAULT '',
config TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', capabilities TEXT DEFAULT '{}', last_error TEXT, updated_at TEXT,
trek_range TEXT DEFAULT '>=3.0.0',
source_repo TEXT, author_pubkey TEXT, update_block_code TEXT, update_block_detail TEXT, update_block_version TEXT);
CREATE TABLE plugin_error_log (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, level TEXT, message TEXT, ts TEXT);
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER);
CREATE TABLE settings (user_id INTEGER, key TEXT, value TEXT);
CREATE TABLE plugin_entity_metadata (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, entity_type TEXT, entity_id INTEGER, key TEXT, value TEXT, updated_at TEXT);
CREATE TABLE plugin_user_config (plugin_id TEXT, user_id INTEGER, field_key TEXT, value TEXT, PRIMARY KEY (plugin_id, user_id, field_key));
CREATE TABLE plugin_meta_migrations (plugin_id TEXT, migration_id TEXT, PRIMARY KEY (plugin_id, migration_id));
CREATE TABLE plugin_capability_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, acting_user_id INTEGER, method TEXT, resource TEXT, code TEXT, ts TEXT, prev_hash TEXT, hash TEXT);
CREATE TABLE plugin_scheduled_tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT NOT NULL, name TEXT NOT NULL, due_at INTEGER NOT NULL, payload TEXT NOT NULL DEFAULT 'null', every_ms INTEGER, created_at TEXT DEFAULT (datetime('now')), UNIQUE(plugin_id, name));
CREATE TABLE plugin_user_erasure_queue (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT NOT NULL, user_id INTEGER NOT NULL, created_at TEXT DEFAULT (datetime('now')), UNIQUE(plugin_id, user_id));
CREATE TABLE addons (id TEXT PRIMARY KEY, enabled INTEGER DEFAULT 0);
CREATE TABLE audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
user_id INTEGER, action TEXT NOT NULL, resource TEXT, details TEXT, ip TEXT);`);
return { testDb: db };
});
vi.mock('../../../src/db/database', () => ({ db: testDb, canAccessTrip: () => undefined }));
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
import { db as dbConn } from '../../../src/db/database';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { AuditService } from '../../../src/nest/audit/audit.service';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
import { PluginRpcHostFactory } from '../../../src/nest/plugins/host/plugin-rpc-host.factory';
import { PluginRpcRegistry } from '../../../src/nest/plugins/host/rpc-kit/registry';
import type { PluginRpcRegistryService } from '../../../src/nest/plugins/host/rpc-kit/registry.service';
import { DbRpc } from '../../../src/nest/plugins/host/rpc/db.rpc';
let codeRoot: string;
let dataRoot: string;
let mod: TestingModule;
beforeAll(() => {
codeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'trekplug-boot-code-'));
dataRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'trekplug-boot-data-'));
process.env.TREK_PLUGINS_DIR = codeRoot;
process.env.TREK_PLUGINS_DATA_DIR = dataRoot;
process.env.TREK_PLUGINS_ENABLED = 'true';
// The exact shape the bug bit: a plugin that runs its own-db migration as the
// first thing its onLoad does — what every db-backed plugin's activation looks like.
const dir = path.join(codeRoot, 'migrator', 'server');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, 'index.js'),
`module.exports = { async onLoad(ctx) { await ctx.db.migrate('001', 'CREATE TABLE t (n INTEGER)'); } };`,
);
// The row a container recreate leaves behind: enabled, already consented to
// db:own. Seeded 'inactive' (not the 'active' a real shutdown leaves) so the
// poll below only terminates on a status the THIS-boot supervisor wrote.
testDb
.prepare("INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config) VALUES ('migrator','inactive',1,'[\"db:own\"]','[\"db:own\"]','{}')")
.run();
});
afterAll(async () => {
await mod?.close();
delete process.env.TREK_PLUGINS_DIR;
delete process.env.TREK_PLUGINS_DATA_DIR;
delete process.env.TREK_PLUGINS_ENABLED;
fs.rmSync(codeRoot, { recursive: true, force: true });
fs.rmSync(dataRoot, { recursive: true, force: true });
});
describe('plugin boot vs registry scan ordering', () => {
it('BOOT-REG-001 a plugin enabled before a restart activates cleanly even though the registry scan runs in a LATER provider\'s onModuleInit', async () => {
const dbs = new DatabaseService(dbConn);
const userSettings = new PluginUserSettingsService(dbs);
// Empty at construction — exactly what PluginRpcRegistryService is before its
// own onModuleInit scan has run.
const registry = new PluginRpcRegistry();
const hostFactory = new PluginRpcHostFactory(dbs, registry as unknown as PluginRpcRegistryService);
mod = await Test.createTestingModule({
providers: [
// Mirrors plugins-runtime.module.ts: the runtime service is DECLARED BEFORE
// the provider that populates the registry, so Nest fires its onModuleInit
// (if it had one) first. The boot reconcile must therefore not live there.
{
provide: PluginRuntimeService,
useFactory: () => new PluginRuntimeService(dbs, new AuditService(dbs), new AddonsService(dbs), userSettings, undefined, hostFactory),
},
{
provide: 'REGISTRY_SCAN',
useFactory: () => ({
onModuleInit() {
registry.register(new DbRpc(userSettings));
},
}),
},
],
}).compile();
await mod.init();
// Boot activation is fire-and-forget; wait for the supervisor to settle the row.
const runtime = mod.get(PluginRuntimeService);
let row = { status: 'starting', last_error: null as string | null };
for (let i = 0; i < 100; i++) {
row = testDb.prepare("SELECT status, last_error FROM plugins WHERE id='migrator'").get() as typeof row;
if (row.status === 'active' || row.status === 'error') break;
await new Promise((r) => setTimeout(r, 50));
}
expect(row.last_error).toBeNull();
expect(row.status).toBe('active');
expect(runtime.isActive('migrator')).toBe(true);
});
});
@@ -27,9 +27,12 @@ const { testDb } = vi.hoisted(() => {
return { testDb: db };
});
vi.mock('../../../src/db/database', () => ({ db: testDb, canAccessTrip: () => undefined }));
import { db as dbConn } from '../../../src/db/database';
import { DatabaseService } from '../../../src/nest/database/database.service';
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import { createPluginRuntime } from '../../helpers/plugin-host';
let codeRoot: string;
let dataRoot: string;
@@ -58,7 +61,7 @@ beforeAll(() => {
process.env.TREK_PLUGINS_DATA_DIR = dataRoot;
process.env.TREK_PLUGINS_ENABLED = 'true';
process.env.TREK_PLUGINS_DEV_LINK = '1';
runtime = new PluginRuntimeService();
runtime = createPluginRuntime(new DatabaseService(dbConn));
});
afterAll(async () => {
@@ -12,7 +12,7 @@ const { testDb } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec(`CREATE TABLE plugins (
id TEXT PRIMARY KEY, status TEXT, enabled INTEGER DEFAULT 0, version TEXT, permissions TEXT DEFAULT '[]', operator_egress INTEGER DEFAULT 0, granted_permissions TEXT DEFAULT '',
id TEXT PRIMARY KEY, status TEXT, enabled INTEGER DEFAULT 0, version TEXT, api_version INTEGER DEFAULT 1, permissions TEXT DEFAULT '[]', operator_egress INTEGER DEFAULT 0, granted_permissions TEXT DEFAULT '',
config TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', capabilities TEXT DEFAULT '{}', last_error TEXT, updated_at TEXT,
-- Activation refuses a plugin that declares no TREK range, so the fixtures default to a
-- satisfied one: these tests are about permissions/dependencies, and every row would
@@ -43,9 +43,12 @@ const { testDb } = vi.hoisted(() => {
return { testDb: db };
});
vi.mock('../../../src/db/database', () => ({ db: testDb, canAccessTrip: () => undefined }));
import { db as dbConn } from '../../../src/db/database';
import { DatabaseService } from '../../../src/nest/database/database.service';
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
import { PluginRuntimeService, PluginDependencyError } from '../../../src/nest/plugins/plugin-runtime.service';
import { createPluginRuntime } from '../../helpers/plugin-host';
import { DependencyCycleError } from '../../../src/nest/plugins/dependencies';
let codeRoot: string;
@@ -77,7 +80,7 @@ beforeAll(() => {
);
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('counter','active','[\"db:own\"]','{}')").run();
runtime = new PluginRuntimeService();
runtime = createPluginRuntime(new DatabaseService(dbConn));
});
afterAll(async () => {
@@ -145,9 +148,9 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
// first activate is covered by the 'counter' happy-path test above.)
});
it('onModuleInit is a no-op when the runtime is disabled', () => {
it('onApplicationBootstrap is a no-op when the runtime is disabled', () => {
process.env.TREK_PLUGINS_ENABLED = 'false';
expect(() => new PluginRuntimeService().onModuleInit()).not.toThrow();
expect(() => createPluginRuntime(new DatabaseService(dbConn)).onApplicationBootstrap()).not.toThrow();
process.env.TREK_PLUGINS_ENABLED = 'true';
});
@@ -170,7 +173,7 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
fs.mkdirSync(path.join(codeRoot, 'messy', 'server'), { recursive: true });
fs.writeFileSync(path.join(codeRoot, 'messy', 'server', 'index.js'), 'module.exports = { async onLoad() {} };');
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('messy','inactive','not-json','not-json')").run();
const rt = new PluginRuntimeService();
const rt = createPluginRuntime(new DatabaseService(dbConn));
await rt.activate('messy'); // must not throw despite the garbage JSON
expect(rt.isActive('messy')).toBe(true);
await rt.deactivate('messy');
@@ -243,33 +246,33 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='counter' AND user_id=9").get()).toMatchObject({ c: 0 });
});
it('onModuleInit boots every ENABLED plugin — even one left in error state', async () => {
it('onApplicationBootstrap boots every ENABLED plugin — even one left in error state', async () => {
fs.mkdirSync(path.join(codeRoot, 'booter', 'server'), { recursive: true });
fs.writeFileSync(path.join(codeRoot, 'booter', 'server', 'index.js'), 'module.exports = { async onLoad() {} };');
// status='error' from a previous crash, but enabled=1 → must still boot
testDb.prepare("INSERT INTO plugins (id, status, enabled, granted_permissions, config) VALUES ('booter','error',1,'[]','{}')").run();
const rt = new PluginRuntimeService();
rt.onModuleInit(); // fire-and-forget spawn
const rt = createPluginRuntime(new DatabaseService(dbConn));
rt.onApplicationBootstrap(); // fire-and-forget spawn
for (let i = 0; i < 40 && !rt.isActive('booter'); i++) await new Promise((r) => setTimeout(r, 50));
expect(rt.isActive('booter')).toBe(true);
await rt.deactivate('booter');
});
it('onModuleInit does NOT boot a disabled plugin', async () => {
it('onApplicationBootstrap does NOT boot a disabled plugin', async () => {
fs.mkdirSync(path.join(codeRoot, 'sleeper', 'server'), { recursive: true });
fs.writeFileSync(path.join(codeRoot, 'sleeper', 'server', 'index.js'), 'module.exports = { async onLoad() {} };');
testDb.prepare("INSERT INTO plugins (id, status, enabled, granted_permissions, config) VALUES ('sleeper','inactive',0,'[]','{}')").run();
const rt = new PluginRuntimeService();
rt.onModuleInit();
const rt = createPluginRuntime(new DatabaseService(dbConn));
rt.onApplicationBootstrap();
await new Promise((r) => setTimeout(r, 300));
expect(rt.isActive('sleeper')).toBe(false);
});
it('outboundHostsOf extracts declared http:outbound hosts', () => {
testDb.prepare("INSERT INTO plugins (id, status, granted_permissions, config) VALUES ('net','inactive','[\"db:own\",\"http:outbound:api.x.com\",\"http:outbound:*.y.com\"]','{}')").run();
const rt = new PluginRuntimeService();
const rt = createPluginRuntime(new DatabaseService(dbConn));
expect(rt.outboundHostsOf('net')).toEqual(['api.x.com', '*.y.com']);
expect(rt.outboundHostsOf('missing')).toEqual([]);
});
@@ -291,7 +294,7 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
testDb.prepare("INSERT INTO plugin_scheduled_tasks (plugin_id, name, due_at) VALUES ('gone', 'poll', 0)").run();
testDb.prepare("INSERT INTO plugin_user_erasure_queue (plugin_id, user_id) VALUES ('gone', 7)").run();
await new PluginRuntimeService().uninstall('gone', true);
await createPluginRuntime(new DatabaseService(dbConn)).uninstall('gone', true);
expect(fs.existsSync(path.join(codeRoot, 'gone'))).toBe(false);
expect(testDb.prepare("SELECT COUNT(*) c FROM plugins WHERE id='gone'").get()).toMatchObject({ c: 0 });
@@ -310,7 +313,7 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
// a deleted user's erasure is still pending for this plugin
testDb.prepare("INSERT INTO plugin_user_erasure_queue (plugin_id, user_id) VALUES ('keepdata', 42)").run();
await new PluginRuntimeService().uninstall('keepdata', false); // keep the plugin's data
await createPluginRuntime(new DatabaseService(dbConn)).uninstall('keepdata', false); // keep the plugin's data
// the plugin row is gone, but the erasure obligation is retained — a reinstall of the
// same id will drain it and finally honour the deletion, instead of silently keeping
@@ -325,12 +328,12 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
"module.exports = { async onLoad() { await fetch('https://blocked.example/x'); } };");
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('nettry','inactive','[]','{}')").run();
// no http:outbound granted -> egress guard blocks all outbound -> onLoad throws
await expect(new PluginRuntimeService().activate('nettry')).rejects.toThrow(/egress/);
await new PluginRuntimeService().deactivate('nettry').catch(() => {});
await expect(createPluginRuntime(new DatabaseService(dbConn)).activate('nettry')).rejects.toThrow(/egress/);
await createPluginRuntime(new DatabaseService(dbConn)).deactivate('nettry').catch(() => {});
});
it('onModuleDestroy tears down cleanly', async () => {
await expect(new PluginRuntimeService().onModuleDestroy()).resolves.toBeUndefined();
await expect(createPluginRuntime(new DatabaseService(dbConn)).onModuleDestroy()).resolves.toBeUndefined();
});
});
@@ -352,7 +355,7 @@ describe('PluginRuntimeService.update (re-consent gate)', () => {
it('restarts transparently when the new version requests no new permissions', async () => {
seed('upd-same', 1, ['db:own'], ['db:own']);
const rt = new PluginRuntimeService(fakeRegistry(() => {})); // declared perms unchanged
const rt = createPluginRuntime(new DatabaseService(dbConn), fakeRegistry(() => {})); // declared perms unchanged
await rt.activate('upd-same');
const res = await rt.update('upd-same');
expect(res).toMatchObject({ activated: true, newPermissions: [], newEgress: [] });
@@ -362,7 +365,8 @@ describe('PluginRuntimeService.update (re-consent gate)', () => {
it('leaves the plugin inactive and reports the delta when new rights are requested', async () => {
seed('upd-wider', 1, ['db:own'], ['db:own']);
const rt = new PluginRuntimeService(
const rt = createPluginRuntime(
new DatabaseService(dbConn),
fakeRegistry(() => {
testDb.prepare("UPDATE plugins SET permissions = ? WHERE id = 'upd-wider'")
.run(JSON.stringify(['db:own', 'db:read:trips', 'http:outbound:api.new.com']));
@@ -379,17 +383,17 @@ describe('PluginRuntimeService.update (re-consent gate)', () => {
it('a disabled plugin stays disabled even with no new permissions', async () => {
seed('upd-off', 0, ['db:own'], ['db:own']);
const res = await new PluginRuntimeService(fakeRegistry(() => {})).update('upd-off');
const res = await createPluginRuntime(new DatabaseService(dbConn), fakeRegistry(() => {})).update('upd-off');
expect(res).toMatchObject({ activated: false, newPermissions: [], newEgress: [] });
});
it('throws for an unknown plugin id', async () => {
await expect(new PluginRuntimeService(fakeRegistry(() => {})).update('ghost-upd')).rejects.toThrow(/not found/);
await expect(createPluginRuntime(new DatabaseService(dbConn), fakeRegistry(() => {})).update('ghost-upd')).rejects.toThrow(/not found/);
});
it('throws if no registry service is wired', async () => {
seed('upd-noreg', 0, ['db:own'], ['db:own']);
await expect(new PluginRuntimeService().update('upd-noreg')).rejects.toThrow(/registry service unavailable/);
await expect(createPluginRuntime(new DatabaseService(dbConn)).update('upd-noreg')).rejects.toThrow(/registry service unavailable/);
});
});
@@ -556,7 +560,7 @@ describe('PluginRuntimeService.retrust', () => {
it('re-pins AND installs in one call: the new key is pinned, the version moved, the block gone', async () => {
seed('rt-ok', 'OLDKEY');
const registry = registryFor('rt-ok');
const rt = new PluginRuntimeService(registry);
const rt = createPluginRuntime(new DatabaseService(dbConn), registry);
await rt.activate('rt-ok');
await rt.retrust('rt-ok', '2.0.0', 'NEWKEY', { userId: 1, ip: '10.0.0.1' });
@@ -601,7 +605,7 @@ describe('PluginRuntimeService.retrust', () => {
seed('rt-no', 'OLDKEY');
const registry = registryFor('rt-no');
vi.mocked(registry.assertRetrustable).mockRejectedValue(new Error('nothing to re-trust'));
const rt = new PluginRuntimeService(registry);
const rt = createPluginRuntime(new DatabaseService(dbConn), registry);
await expect(rt.retrust('rt-no', '2.0.0', 'NEWKEY', { userId: 1 })).rejects.toThrow(/nothing to re-trust/);
@@ -627,7 +631,7 @@ describe('PluginRuntimeService.retrust', () => {
// exactly the "quietly stops updating" failure the block exists to prevent.
it('activate does NOT clear a recorded update block', async () => {
seed('rt-act', 'OLDKEY');
const rt = new PluginRuntimeService(registryFor('rt-act'));
const rt = createPluginRuntime(new DatabaseService(dbConn), registryFor('rt-act'));
await rt.deactivate('rt-act');
await rt.activate('rt-act');
@@ -663,7 +667,7 @@ describe('TREK host-version gating', () => {
it('refuses to activate a plugin this TREK has outgrown, and says so with a code', async () => {
process.env.APP_VERSION = '4.0.0';
seedRanged('outgrown', '>=3.2.0 <4.0.0');
const err = await new PluginRuntimeService().activate('outgrown').catch((e) => e);
const err = await createPluginRuntime(new DatabaseService(dbConn)).activate('outgrown').catch((e) => e);
expect(err).toBeInstanceOf(PluginDependencyError);
expect(err).toMatchObject({ code: 'TREK_VERSION_INCOMPATIBLE' });
expect(err.detail).toMatchObject({ trekRange: '>=3.2.0 <4.0.0', hostVersion: '4.0.0' });
@@ -675,14 +679,14 @@ describe('TREK host-version gating', () => {
it('refuses a plugin that never declared a range at all', async () => {
process.env.APP_VERSION = '3.3.0';
seedRanged('undeclared', null);
await expect(new PluginRuntimeService().activate('undeclared')).rejects.toMatchObject({ code: 'TREK_VERSION_UNKNOWN' });
await expect(createPluginRuntime(new DatabaseService(dbConn)).activate('undeclared')).rejects.toMatchObject({ code: 'TREK_VERSION_UNKNOWN' });
cleanup('undeclared');
});
it('activates normally when the range admits the host', async () => {
process.env.APP_VERSION = '3.3.0';
seedRanged('fits', '>=3.2.0 <4.0.0');
const rt = new PluginRuntimeService();
const rt = createPluginRuntime(new DatabaseService(dbConn));
await rt.activate('fits');
expect(rt.isActive('fits')).toBe(true);
await rt.deactivate('fits');
@@ -696,8 +700,8 @@ describe('TREK host-version gating', () => {
// panel showing a green, running plugin that does not exist.
process.env.APP_VERSION = '4.0.0';
seedRanged('boot-broken', '>=3.2.0 <4.0.0', 1);
const rt = new PluginRuntimeService();
expect(() => rt.onModuleInit()).not.toThrow();
const rt = createPluginRuntime(new DatabaseService(dbConn));
expect(() => rt.onApplicationBootstrap()).not.toThrow();
for (let i = 0; i < 40; i++) {
const row = testDb.prepare("SELECT enabled FROM plugins WHERE id='boot-broken'").get() as { enabled: number };
if (row.enabled === 0) break;
@@ -714,7 +718,43 @@ describe('TREK host-version gating', () => {
fs.mkdirSync(path.join(codeRoot, 'both-wrong', 'server'), { recursive: true });
fs.writeFileSync(path.join(codeRoot, 'both-wrong', 'server', 'index.js'), 'module.exports = {};');
testDb.prepare("INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config, trek_range) VALUES ('both-wrong','inactive',0,'[\"db:own\"]','[]','{}','>=3.2.0 <4.0.0')").run();
await expect(new PluginRuntimeService().activate('both-wrong')).rejects.toMatchObject({ code: 'TREK_VERSION_INCOMPATIBLE' });
await expect(createPluginRuntime(new DatabaseService(dbConn)).activate('both-wrong')).rejects.toMatchObject({ code: 'TREK_VERSION_INCOMPATIBLE' });
cleanup('both-wrong');
});
});
/**
* The activation gate also refuses a plugin whose manifest `apiVersion` is newer than
* what this TREK's plugin-API surface supports (`PLUGIN_API_VERSION`) — mirrors the
* TREK-version gate above, just for the plugin-API surface instead of the host version.
*/
describe('plugin-API version gating', () => {
const seedApi = (id: string, apiVersion: number) => {
fs.mkdirSync(path.join(codeRoot, id, 'server'), { recursive: true });
fs.writeFileSync(path.join(codeRoot, id, 'server', 'index.js'), 'module.exports = { async onLoad() {} };');
testDb
.prepare(
"INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config, trek_range, api_version) VALUES (?, 'inactive', 0, '[]', '[]', '{}', '>=3.0.0', ?)",
)
.run(id, apiVersion);
};
const cleanup = (...ids: string[]) => { for (const id of ids) testDb.prepare('DELETE FROM plugins WHERE id = ?').run(id); };
it('refuses to activate a plugin whose apiVersion this TREK does not support', async () => {
seedApi('future-api', 2);
const err = await createPluginRuntime(new DatabaseService(dbConn)).activate('future-api').catch((e) => e);
expect(err).toBeInstanceOf(PluginDependencyError);
expect(err).toMatchObject({ code: 'API_VERSION_INCOMPATIBLE' });
expect(err.message).toBe('plugin requires plugin-API v2; this TREK supports v1');
cleanup('future-api');
});
it('activates normally when apiVersion is within what this TREK supports', async () => {
seedApi('current-api', 1);
const rt = createPluginRuntime(new DatabaseService(dbConn));
await rt.activate('current-api');
expect(rt.isActive('current-api')).toBe(true);
await rt.deactivate('current-api');
cleanup('current-api');
});
});
@@ -23,14 +23,17 @@ const { testDb } = vi.hoisted(() => {
CREATE TABLE plugins (id TEXT PRIMARY KEY, name TEXT, description TEXT, type TEXT, icon TEXT, version TEXT,
api_version INTEGER, min_trek_version TEXT, trek_range TEXT, permissions TEXT, capabilities TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', operator_egress INTEGER DEFAULT 0, granted_permissions TEXT, status TEXT, enabled INTEGER DEFAULT 0, config TEXT,
source_repo TEXT, source_commit TEXT, sha256 TEXT, reviewed_at TEXT, author_pubkey TEXT, updated_at TEXT,
update_block_code TEXT, update_block_detail TEXT, update_block_version TEXT);
update_block_code TEXT, update_block_detail TEXT, update_block_version TEXT, update_hold INTEGER NOT NULL DEFAULT 0);
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, label TEXT, input_type TEXT, placeholder TEXT, hint TEXT, required INTEGER, secret INTEGER, scope TEXT, options TEXT, oauth_config TEXT, sort_order INTEGER);
CREATE TABLE plugin_error_log (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, level TEXT, message TEXT, ts TEXT);`);
return { testDb: db };
});
vi.mock('../../../src/db/database', () => ({ db: testDb, canAccessTrip: () => undefined }));
import { db as dbConn } from '../../../src/db/database';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { PluginRegistryService, RegistryError, __clearRegistryCacheForTests } from '../../../src/nest/plugins/registry/registry.service';
import type { ManifestPreview } from '../../../src/nest/plugins/registry/registry.service';
// ── tiny tar.gz builder (wraps the plugin in a codeload-style top dir) ────────
function tarHeader(name: string, size: number, typeflag = '0'): Buffer {
@@ -86,7 +89,7 @@ beforeEach(() => {
testDb.exec('DELETE FROM plugins; DELETE FROM plugin_settings_fields; DELETE FROM plugin_error_log');
__clearRegistryCacheForTests();
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => REGISTRY }) as unknown as Response));
svc = new PluginRegistryService();
svc = new PluginRegistryService(new DatabaseService(dbConn));
});
afterEach(() => {
vi.unstubAllGlobals();
@@ -179,6 +182,27 @@ describe('PluginRegistryService', () => {
});
});
it('detail carries the UI-facing capabilities, so the review sheet can chip a tab takeover', async () => {
safeDownload.mockResolvedValue({
bytes: Buffer.from(JSON.stringify({
id: 'flight-tracker', permissions: [], egress: [],
capabilities: { widget: { slot: 'hero' }, tripPage: { replaces: ['places'], position: 3 }, settingsUi: true },
})),
sha256: 'unused',
});
const d = (await svc.detail('flight-tracker')) as { manifest: ManifestPreview };
expect(d.manifest.capabilities).toEqual({ widget: { slot: 'hero' }, tripPage: { replaces: ['places'] } });
});
it('detail leaves capabilities empty when the manifest declares none', async () => {
safeDownload.mockResolvedValue({
bytes: Buffer.from(JSON.stringify({ id: 'flight-tracker', permissions: [], capabilities: { widget: {} } })),
sha256: 'unused',
});
const d = (await svc.detail('flight-tracker')) as { manifest: ManifestPreview };
expect(d.manifest.capabilities).toEqual({ widget: {} });
});
it('detail soft-fails the manifest fetch (registry metadata still renders)', async () => {
safeDownload.mockRejectedValue(new Error('offline'));
const d = await svc.detail('flight-tracker');
@@ -233,10 +257,127 @@ describe('PluginRegistryService', () => {
await expect(svc.detail('ghost')).rejects.toThrow(RegistryError);
});
// The per-plugin update hold: a DELIBERATE non-latest install excludes the plugin from
// the update banner until the admin resumes updates or lands back on the newest
// compatible version. Dependency resolution pins versions too, but never deliberately —
// the `explicit` flag is what separates the two.
describe('recomputeUpdateHold', () => {
const twoVersions = {
schemaVersion: 1,
plugins: [
{
id: 'flight-tracker', name: 'Flight', author: 'Acme', description: 'flights', repo: 'acme/trek-flight', type: 'widget',
versions: [
{ version: '2.0.0', gitTag: 'v2.0.0', commitSha: 'b'.repeat(40), downloadUrl: 'https://x/2', sha256: '2'.repeat(64) },
{ version: '1.0.0', gitTag: 'v1.0.0', commitSha: 'd'.repeat(40), downloadUrl: 'https://x/1', sha256: '0'.repeat(64) },
],
},
],
};
const seedRow = (hold = 0) =>
testDb.prepare("INSERT INTO plugins (id, status, enabled, update_hold) VALUES ('flight-tracker','inactive',0,?)").run(hold);
const holdInDb = () =>
(testDb.prepare("SELECT update_hold FROM plugins WHERE id='flight-tracker'").get() as { update_hold: number }).update_hold;
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => twoVersions }) as unknown as Response));
__clearRegistryCacheForTests();
});
it('holds when the admin explicitly picked an older version', async () => {
seedRow();
await expect(svc.recomputeUpdateHold('flight-tracker', '1.0.0', true)).resolves.toBe(true);
expect(holdInDb()).toBe(1);
});
it('does not hold when the explicit pick IS the newest compatible version', async () => {
seedRow(1);
await expect(svc.recomputeUpdateHold('flight-tracker', '2.0.0', true)).resolves.toBe(false);
expect(holdInDb()).toBe(0);
});
// The comparison is against the newest version THIS TREK can run, not the newest
// published one. Both fixtures above leave `trek` unset, so every version is
// compatible and the two readings agree; only a version this host must skip tells
// them apart. Getting it wrong stamps a hold on an admin who picked the best
// available version, and the row silently leaves the banner and "Update all".
it('does not hold when a newer version exists but this TREK cannot run it', async () => {
const withIncompatibleNewest = {
schemaVersion: 1,
plugins: [
{
...twoVersions.plugins[0],
versions: [
{ version: '3.0.0', gitTag: 'v3.0.0', commitSha: 'c'.repeat(40), downloadUrl: 'https://x/3', sha256: '3'.repeat(64), trek: '>=4.0.0' },
...twoVersions.plugins[0].versions,
],
},
],
};
process.env.APP_VERSION = '3.3.0';
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => withIncompatibleNewest }) as unknown as Response));
__clearRegistryCacheForTests();
try {
seedRow(1);
await expect(svc.recomputeUpdateHold('flight-tracker', '2.0.0', true)).resolves.toBe(false);
expect(holdInDb()).toBe(0);
} finally {
delete process.env.APP_VERSION;
}
});
it('a non-deliberate update clears a stale hold', async () => {
seedRow(1);
await expect(svc.recomputeUpdateHold('flight-tracker', '2.0.0', false)).resolves.toBe(false);
expect(holdInDb()).toBe(0);
});
it('an unresolvable registry never sets a hold', async () => {
seedRow();
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); }));
__clearRegistryCacheForTests();
await expect(svc.recomputeUpdateHold('flight-tracker', '1.0.0', true)).resolves.toBe(false);
expect(holdInDb()).toBe(0);
});
});
// The version picker's data: every published version, each with its OWN server-computed
// compat verdict — the client has no semver and must never re-derive range logic.
it('detail lists every published version with its own compat verdict', async () => {
process.env.APP_VERSION = '3.3.0';
const multi = {
schemaVersion: 1,
plugins: [
{
id: 'flight-tracker', name: 'Flight', author: 'Acme', description: 'flights', repo: 'acme/trek-flight',
type: 'widget', authorPublicKey: 'K'.repeat(44),
versions: [
{ version: '2.0.0', gitTag: 'v2.0.0', commitSha: 'b'.repeat(40), downloadUrl: 'https://x/2', sha256: '2'.repeat(64), trek: '>=4.0.0', publishedAt: '2026-08-01', size: 2048, signature: 'sig2' },
{ version: '1.5.0', gitTag: 'v1.5.0', commitSha: 'c'.repeat(40), downloadUrl: 'https://x/15', sha256: '1'.repeat(64), trek: '>=3.0.0 <4.0.0', publishedAt: '2026-07-01', size: 1024 },
{ version: '1.0.0', gitTag: 'v1.0.0', commitSha: 'd'.repeat(40), downloadUrl: 'https://x/1', sha256: '0'.repeat(64), minTrekVersion: '3.0.0' },
],
},
],
};
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => multi }) as unknown as Response));
__clearRegistryCacheForTests();
try {
const d = (await svc.detail('flight-tracker')) as { versions: unknown };
expect(d.versions).toEqual([
{ version: '2.0.0', publishedAt: '2026-08-01', size: 2048, signed: true, trek: '>=4.0.0', compatible: false },
{ version: '1.5.0', publishedAt: '2026-07-01', size: 1024, signed: false, trek: '>=3.0.0 <4.0.0', compatible: true },
// A legacy entry composes its requirement from the min/max bounds it has.
{ version: '1.0.0', publishedAt: null, size: null, signed: false, trek: '>=3.0.0', compatible: true },
]);
} finally {
delete process.env.APP_VERSION;
}
});
it('fetchRegistry soft-fails to an empty registry on a cold cache', async () => {
__clearRegistryCacheForTests();
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); }));
expect((await new PluginRegistryService().fetchRegistry()).plugins).toEqual([]);
expect((await new PluginRegistryService(new DatabaseService(dbConn)).fetchRegistry()).plugins).toEqual([]);
});
it('installs a pinned version end to end (verify -> extract -> register inactive)', async () => {
@@ -800,6 +941,14 @@ describe('TREK-version gating on install', () => {
const bytes = makeArtifact({ id: 'my-upload', name: 'Up', version: '1.0.0', type: 'integration', trek: undefined });
expect(() => svc.stageUpload(bytes)).toThrow(/missing "trek"/);
});
it('refuses an uploaded archive declaring apiVersion 2 (this TREK only speaks plugin-API v1), and writes nothing to the plugin code dir', () => {
// trek range is satisfiable on its own — parseManifest's apiVersion check must
// fire (and stop the upload) before assertHostCompatible is ever reached.
const bytes = makeArtifact({ id: 'my-upload', name: 'Up', version: '1.0.0', type: 'integration', apiVersion: 2 });
expect(() => svc.stageUpload(bytes)).toThrow('plugin requires plugin-API v2; this TREK supports v1');
expect(fs.existsSync(path.join(codeRoot, 'my-upload'))).toBe(false);
});
});
it('installWithDependencies installs the version it RESOLVED, not versions[0]', async () => {
@@ -14,6 +14,17 @@ import path from 'node:path';
import { PluginSupervisor, type SupervisorHooks, type SupervisorTuning } from '../../../src/nest/plugins/supervisor/plugin-supervisor';
import { PluginRpcHost, type HostDeps } from '../../../src/nest/plugins/host/rpc-host';
import { PluginDataDb } from '../../../src/nest/plugins/host/plugin-data.service';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import { DbRpc } from '../../../src/nest/plugins/host/rpc/db.rpc';
import type { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
/**
* DbRpc also carries `settings.get`, which needs the per-user settings store. No
* fixture below calls it, and none of these plugins has a stored setting anyway, so
* the stub is the one read DbRpc makes, typed off the real signature and answering
* "nothing stored" exactly as the real service would.
*/
const stubUserSettings: Pick<PluginUserSettingsService, 'readOne'> = { readOne: () => undefined };
let codeRoot: string;
let dataRoot: string;
@@ -31,12 +42,12 @@ function makeSupervisor(events: Array<{ topic: string; data: unknown }>, tuning:
const createRpcHost = (id: string, granted: ReadonlySet<string>): PluginRpcHost => {
const deps: HostDeps = {
data: new PluginDataDb(id),
db: { prepare: () => ({ all: () => [], get: () => null }) },
canAccessTrip: () => undefined,
broadcastToTrip: (tripId, event, payload) => broadcasts.push({ tripId, event, payload }),
broadcastToUser: () => {},
callPlugin: async () => undefined,
emitPluginEvent: (event, payload) => broadcasts.push({ id, event, payload }),
};
return new PluginRpcHost(id, granted, deps);
// Only db.* is exercised from a child here; the rest of the surface has its own
// unit suites and would drag every domain service into this integration test.
return new PluginRpcHost(id, granted, deps, createTestPluginRegistry([new DbRpc(stubUserSettings as PluginUserSettingsService)]));
};
const hooks: SupervisorHooks = {
onEvent: (_id, topic, data) => events.push({ topic, data }),
+26
View File
@@ -108,6 +108,32 @@ describe('Avatar', () => {
expect(typeof res.body.avatar_url).toBe('string');
});
it('PROFILE-P01 — avatar bytes land at uploads/avatars under a bare uuid name', async () => {
const fsMod = require('fs') as typeof import('fs');
const pathMod = require('path') as typeof import('path');
const avatarsDir = pathMod.join(__dirname, '../../uploads/avatars');
const { user } = createUser(testDb);
const res = await request(app)
.post('/api/auth/avatar')
.set('Cookie', authCookie(user.id))
.attach('avatar', FIXTURE_JPEG);
expect(res.status).toBe(200);
const first = pathMod.basename(res.body.avatar_url);
expect(first).toMatch(/^[0-9a-f-]{36}\.jpg$/);
expect(fsMod.existsSync(pathMod.join(avatarsDir, first))).toBe(true);
// Re-upload removes the previous file (saveAvatar's cleanup branch).
const second = await request(app)
.post('/api/auth/avatar')
.set('Cookie', authCookie(user.id))
.attach('avatar', FIXTURE_JPEG);
expect(second.status).toBe(200);
const secondName = pathMod.basename(second.body.avatar_url);
expect(fsMod.existsSync(pathMod.join(avatarsDir, secondName))).toBe(true);
expect(fsMod.existsSync(pathMod.join(avatarsDir, first))).toBe(false);
});
it('PROFILE-003 — uploading non-image (PDF) is rejected', async () => {
const { user } = createUser(testDb);
const res = await request(app)
@@ -0,0 +1,80 @@
/**
* SCHED-GATE — the no-timers-in-the-harness regression test. buildApp() is
* shared with every integration/e2e suite, and job providers register their
* crons from onApplicationBootstrap, which app.init() fires on every boot.
* This proves the CronRegistrarService NODE_ENV=test gate holds: a full
* harness boot registers zero cron jobs, intervals or timeouts, and closing
* the app leaves nothing behind. If this ever goes red, some job bypassed the
* registrar (or used a @Cron decorator) and every suite is now running real
* timers.
*/
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
import type { INestApplication } from '@nestjs/common';
const { testDb, dbMock } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
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: () => undefined,
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: () => {},
SESSION_DURATION: '24h',
SESSION_DURATION_MS: 86400000,
SESSION_DURATION_SECONDS: 86400,
DEFAULT_LANGUAGE: 'en',
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
import { SchedulerRegistry } from '@nestjs/schedule';
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { CronRegistrarService } from '../../src/nest/scheduling/cron-registrar.service';
import { buildApp } from '../../src/bootstrap';
describe('SCHED-GATE — the harness boots without scheduling anything', () => {
let app: INestApplication;
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
app = await buildApp();
});
afterAll(() => {
testDb.close();
});
it('SCHED-GATE-001 — the registrar reports the test gate closed', () => {
expect(app.get(CronRegistrarService).isEnabled()).toBe(false);
});
it('SCHED-GATE-002 — a full app boot registers zero cron jobs, intervals and timeouts', () => {
const registry = app.get(SchedulerRegistry);
expect(registry.getCronJobs().size).toBe(0);
expect(registry.getIntervals()).toHaveLength(0);
expect(registry.getTimeouts()).toHaveLength(0);
expect(app.get(CronRegistrarService).jobCount).toBe(0);
});
it('SCHED-GATE-003 — app.close() leaves the registrar empty (shutdown parity)', async () => {
const registrar = app.get(CronRegistrarService);
await app.close();
expect(registrar.jobCount).toBe(0);
});
});
+34 -2
View File
@@ -136,6 +136,35 @@ describe('API key encryption', () => {
expect(row.openweather_api_key).toMatch(/^enc:v1:/);
});
it('SEC-008 — saving keys audits the names and never the values (#1939)', async () => {
const { user } = createUser(testDb);
const save = () =>
request(app)
.put('/api/auth/me/api-keys')
.set('Cookie', authCookie(user.id))
.send({ openweather_api_key: 'test-api-key-12345' });
const first = await save();
expect(first.status).toBe(200);
// changedKeys is internal: the client body is what it always was.
expect(first.body).not.toHaveProperty('changedKeys');
const rows = () =>
testDb
.prepare("SELECT details FROM audit_log WHERE action = 'settings.api_keys_update'")
.all() as { details: string | null }[];
expect(rows()).toHaveLength(1);
expect(rows()[0].details).toContain('openweather_api_key');
expect(rows()[0].details).not.toContain('test-api-key-12345');
// The same value again writes no second row. This is the real test of the
// cleartext comparison: encryption uses a random IV, so the stored blob
// differs on every save even when the key does not.
await save();
expect(rows()).toHaveLength(1);
});
it('SEC-008 — GET /api/auth/me does not return plaintext API key', async () => {
const { user } = createUser(testDb);
await request(app)
@@ -192,7 +221,10 @@ describe('File download path traversal', () => {
const res = await request(app)
.get(`/api/trips/${trip.id}/files/${fileId}/download`)
.set(authHeader(user.id));
// resolveFilePath strips traversal via path.basename; normalized file does not exist in uploads
expect(res.status).not.toBe(200);
// path.basename() strips traversal in the download controller; the normalized
// name does not exist in uploads, so the answer is the same 404 a missing file
// gets. Pinned exactly: a 500 from a thrown guard would also be "not 200".
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'File not found' });
});
});
+116 -16
View File
@@ -49,8 +49,29 @@ import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser, createTrip, addTripMember, createDay, createPlace, createDayAssignment, createDayNote } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
import * as placePhotoCache from '../../src/services/placePhotoCache';
import { PlacePhotoCacheService } from '../../src/nest/place-photos/place-photo-cache.service';
import { DatabaseService } from '../../src/nest/database/database.service';
import { db as sharedDb } from '../../src/db/database';
import { LocalDriver } from '../../src/nest/storage/drivers/local.driver';
import { StorageService } from '../../src/nest/storage/storage.service';
import type { StorageRegistryService, ResolvedCategory } from '../../src/nest/storage/storage-registry.service';
import { DEFAULT_UPLOADS_ROOT, GLOBAL_TEMP_DIR } from '../../src/nest/storage/storage-paths';
// A real instance over the same connection the app uses — these cases write a
// cache entry and then read it back through the HTTP route, so the stub
// storage must be rooted where the app's registry serves 'photos-google'
// from (mode A: uploads/photos/google).
const uploadsDriver = new LocalDriver({ id: 'share-test-local', root: DEFAULT_UPLOADS_ROOT });
uploadsDriver.init({ ensurePrefixes: ['photos/google/'], cleanSpool: false });
const testStorage = new StorageService({
resolve: (): ResolvedCategory => ({ driver: uploadsDriver, keyPrefix: 'photos/google/', backendName: 'share-test-local' }),
tempDir: () => GLOBAL_TEMP_DIR,
replicaFailures: () => [],
} as unknown as StorageRegistryService);
const placePhotoCache = new PlacePhotoCacheService(new DatabaseService(sharedDb), testStorage);
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
let nestApp: INestApplication;
let app: Application;
@@ -261,6 +282,58 @@ describe('Shared trip access', () => {
.send({});
expect(res.status).toBe(404);
});
it('SHARE-026 — a plain member cannot read the share token', async () => {
// Reading the link hands out the credential for the anonymous /api/shared
// page, which outlives the membership that was used to fetch it. Under the
// default policy share_manage stays with the owner.
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
await request(app).post(`/api/trips/${trip.id}/share-link`).set('Cookie', authCookie(owner.id)).send({});
const res = await request(app).get(`/api/trips/${trip.id}/share-link`).set('Cookie', authCookie(member.id));
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'No permission' });
});
it('SHARE-027 — the owner still reads it, and a non-member still gets 404 rather than 403', async () => {
const { user: owner } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
await request(app).post(`/api/trips/${trip.id}/share-link`).set('Cookie', authCookie(owner.id)).send({});
const mine = await request(app).get(`/api/trips/${trip.id}/share-link`).set('Cookie', authCookie(owner.id));
expect(mine.status).toBe(200);
expect(mine.body.token).toBeTruthy();
// 404, not 403: a stranger must not learn that the trip id exists.
const theirs = await request(app).get(`/api/trips/${trip.id}/share-link`).set('Cookie', authCookie(stranger.id));
expect(theirs.status).toBe(404);
});
it('SHARE-028 — a member may read it once the instance lowers share_manage to trip_member', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
await request(app).post(`/api/trips/${trip.id}/share-link`).set('Cookie', authCookie(owner.id)).send({});
const { invalidatePermissionsCache } = await import('../../src/nest/permissions/permissions-cache');
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('perm_share_manage', 'trip_member')").run();
invalidatePermissionsCache();
try {
const res = await request(app).get(`/api/trips/${trip.id}/share-link`).set('Cookie', authCookie(member.id));
expect(res.status).toBe(200);
expect(res.body.token).toBeTruthy();
} finally {
// Module-scoped cache: leaving it set would decide the next file's tests.
testDb.prepare("DELETE FROM app_settings WHERE key = 'perm_share_manage'").run();
invalidatePermissionsCache();
}
});
});
describe('Shared trip — day assignments and notes', () => {
@@ -451,6 +524,27 @@ describe('Shared trip — display currency (issue #1361)', () => {
});
});
describe('Shared trip: CARTO tile key (issue #2054)', () => {
it('SHARE-029: the payload carries the owner\'s carto_api_key, behind it the admin instance default', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare("INSERT INTO app_settings (key, value) VALUES ('default_user_setting_carto_api_key', 'instance-key')").run();
const { body: { token } } = await request(app)
.post(`/api/trips/${trip.id}/share-link`)
.set('Cookie', authCookie(user.id))
.send({ share_map: true });
const inherited = await request(app).get(`/api/shared/${token}`);
expect(inherited.status).toBe(200);
expect(inherited.body.cartoApiKey).toBe('instance-key');
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'carto_api_key', 'owner-key')").run(user.id);
const own = await request(app).get(`/api/shared/${token}`);
expect(own.body.cartoApiKey).toBe('owner-key');
});
});
describe('Shared trip — place photos in shared links (issue #1100)', () => {
const PLACE_ID = 'ChIJsharedPhoto1100';
const PROXY_URL = `/api/maps/place-photo/${encodeURIComponent(PLACE_ID)}/bytes`;
@@ -502,8 +596,8 @@ describe('Shared trip — place photos in shared links (issue #1100)', () => {
it('SHARE-018 — public proxy streams cached bytes for a valid token + place (no cookie)', async () => {
const { token } = await setupSharedPlaceWithPhoto();
const cached = await placePhotoCache.put(PLACE_ID, photoBytes, null);
cachedFilePath = cached.filePath;
await placePhotoCache.put(PLACE_ID, photoBytes, null);
cachedFilePath = path.join(DEFAULT_UPLOADS_ROOT, 'photos/google', `${crypto.createHash('sha1').update(PLACE_ID).digest('hex')}.jpg`);
const res = await request(app).get(`/api/shared/${token}/place-photo/${encodeURIComponent(PLACE_ID)}/bytes`);
expect(res.status).toBe(200);
@@ -511,24 +605,30 @@ describe('Shared trip — place photos in shared links (issue #1100)', () => {
expect(Buffer.from(res.body)).toEqual(photoBytes);
});
it('SHARE-019 — public proxy 404s for a placeId not in the shared trip', async () => {
// Every miss shape answers the same empty 204 (fix: mirrors the maps proxy,
// #1727 extended to shared pages). The service still collapses "not in
// trip" / "bad token" / "map disabled" into one indistinguishable null, so
// no authorization detail leaks through the status change.
it('SHARE-019 — public proxy answers an empty 204 for a placeId not in the shared trip', async () => {
const { token } = await setupSharedPlaceWithPhoto();
const res = await request(app).get(`/api/shared/${token}/place-photo/ChIJnotInTrip/bytes`);
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Photo not cached' });
expect(res.status).toBe(204);
expect(res.headers['cache-control']).toBe('no-store');
expect(res.text ?? '').toBe('');
});
it('SHARE-020 — public proxy 404s for an invalid token', async () => {
it('SHARE-020 — public proxy answers an empty 204 for an invalid token', async () => {
await setupSharedPlaceWithPhoto();
const res = await request(app).get(`/api/shared/bad-token/place-photo/${encodeURIComponent(PLACE_ID)}/bytes`);
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Photo not cached' });
expect(res.status).toBe(204);
expect(res.headers['cache-control']).toBe('no-store');
expect(res.text ?? '').toBe('');
});
// Regression — GHSA-9hc8 sibling: place photos are part of the map/itinerary,
// so the proxy must 404 when the owner disabled the map, even with a valid
// token + cached bytes.
it('SHARE-025 — public place-photo proxy 404s when share_map=false', async () => {
// so the proxy must stream nothing when the owner disabled the map, even
// with a valid token + cached bytes.
it('SHARE-025 — public place-photo proxy streams nothing when share_map=false', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Hidden Photo Place' });
@@ -537,11 +637,11 @@ describe('Shared trip — place photos in shared links (issue #1100)', () => {
.post(`/api/trips/${trip.id}/share-link`)
.set('Cookie', authCookie(user.id))
.send({ share_map: false });
const cached = await placePhotoCache.put(PLACE_ID, photoBytes, null);
cachedFilePath = cached.filePath;
await placePhotoCache.put(PLACE_ID, photoBytes, null);
cachedFilePath = path.join(DEFAULT_UPLOADS_ROOT, 'photos/google', `${crypto.createHash('sha1').update(PLACE_ID).digest('hex')}.jpg`);
const res = await request(app).get(`/api/shared/${token}/place-photo/${encodeURIComponent(PLACE_ID)}/bytes`);
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Photo not cached' });
expect(res.status).toBe(204);
expect(res.text ?? '').toBe('');
});
});
@@ -0,0 +1,122 @@
/**
* Task C6 (audit #4, major) — a restored archive carries its OWN
* `app_settings` storage.* rows, which can name a different category
* assignment than the pre-restore install. Before this fix,
* `restoreFromZip` never reloaded the storage registry after reopening the
* DB, so uploads rehydration ran against the STALE pre-restore driver/
* category map — files landed on the wrong backend.
*
* `backup.impl.test.ts` (BACKUP-045f / BACKUP-061f) pins the *ordering*
* inside `restoreFromZip` with a stubbed StorageService: reinitialize() →
* storage.reloadConfig() → rehydration, and that reload is skipped when
* reopen fails. This test pins the other half — that `reloadConfig()`
* genuinely causes a changed category assignment to take effect for real
* byte placement — using the REAL StorageRegistryService/StorageService/
* DatabaseService trio (same pattern as storage-registry.service.test.ts),
* with two real LocalDriver backends over real tmp directories, so the
* category under test ('files', reassigned between nas-a/nas-b) never
* touches a production path. Note: registry construction itself still
* mkdirs the built-in uploads-local/backups-local roots (server/uploads,
* server/data/backups) as an unconditional side effect of onModuleInit() —
* accepted precedent from storage-registry.service.test.ts, harmless (mkdir
* -p on an existing dir), and orthogonal to what this test actually exercises.
*/
import { describe, it, expect, beforeAll, afterEach } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
// eslint-disable-next-line @typescript-eslint/no-require-imports
const Database = require('better-sqlite3');
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { DatabaseService } from '../../src/nest/database/database.service';
import type { RuntimeEnvService } from '../../src/nest/app-config/runtime-env.service';
import { StorageEventsService } from '../../src/nest/storage/storage-events.service';
import { BACKENDS_KEY, CATEGORIES_KEY, StorageRegistryService } from '../../src/nest/storage/storage-registry.service';
import { StorageService } from '../../src/nest/storage/storage.service';
const testDb = new Database(':memory:');
testDb.exec('PRAGMA journal_mode = WAL');
testDb.exec('PRAGMA foreign_keys = ON');
const db = new DatabaseService(testDb);
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
const tmpDirs: string[] = [];
function makeTmpDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-restore-reload-'));
tmpDirs.push(dir);
return dir;
}
function envStub(): RuntimeEnvService {
return { env: () => ({ paths: {} }) } as unknown as RuntimeEnvService;
}
function setSetting(key: string, value: unknown): void {
testDb
.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)')
.run(key, JSON.stringify(value));
}
afterEach(() => {
while (tmpDirs.length) fs.rmSync(tmpDirs.pop()!, { recursive: true, force: true });
testDb.prepare("DELETE FROM app_settings WHERE key LIKE 'storage.%'").run();
});
describe('C6 — restore reloads the storage registry (audit #4)', () => {
it("reloadConfig() picks up the restored archive's category assignment before any byte is rehydrated", async () => {
const rootA = makeTmpDir();
const rootB = makeTmpDir();
// Pre-restore world: 'files' resolves to backend nas-a.
setSetting(BACKENDS_KEY, [
{ name: 'nas-a', type: 'local', options: { root: rootA } },
{ name: 'nas-b', type: 'local', options: { root: rootB } },
]);
setSetting(CATEGORIES_KEY, { files: 'nas-a' });
const registry = new StorageRegistryService(db, envStub(), new StorageEventsService());
registry.onModuleInit();
const storage = new StorageService(registry);
expect(registry.resolve('files').backendName).toBe('nas-a');
// A pre-restore object lives under nas-a.
const preSrc = path.join(makeTmpDir(), 'old.txt');
fs.writeFileSync(preSrc, 'pre-restore bytes');
await storage.put('files', 'old.txt', { tmpPath: preSrc });
expect(fs.existsSync(path.join(rootA, 'files', 'old.txt'))).toBe(true);
// Simulate what restoreFromZip's DB swap + reinitialize() actually does in
// production: the restored archive's travel.db is now live, and IT names a
// different backend for 'files' (an admin on the source install pointed
// 'files' at a different backend before taking that backup).
setSetting(CATEGORIES_KEY, { files: 'nas-b' });
// Audit #4, pre-fix: the registry is still holding the pre-restore driver
// map at this point — resolve() is stale until something calls reload().
expect(registry.resolve('files').backendName).toBe('nas-a');
// The fix under test: StorageService.reloadConfig(), the narrow passthrough
// restoreFromZip now calls right after reinitialize() and right before
// rehydration (see backup.impl.ts).
storage.reloadConfig();
expect(registry.resolve('files').backendName).toBe('nas-b');
// Rehydration (the same storage.put({ tmpPath }) shape backup.impl.ts's
// rehydrateUploads uses for every extracted upload entry) now lands under
// the RESTORED config's backend, never the stale pre-restore one.
const restoredSrc = path.join(makeTmpDir(), 'restored.txt');
fs.writeFileSync(restoredSrc, 'restored bytes');
await storage.put('files', 'restored.txt', { tmpPath: restoredSrc });
expect(fs.existsSync(path.join(rootB, 'files', 'restored.txt'))).toBe(true);
expect(fs.existsSync(path.join(rootA, 'files', 'restored.txt'))).toBe(false);
});
});
@@ -0,0 +1,347 @@
/**
* Real-socket repro for the audit's open question ("does a client abort
* mid-download take the process down?") — task C3. Everything else touching
* this fix is exercised at the unit level (storage.service.test.ts,
* maps.controller.test.ts, share.controller.test.ts, exception-filter.test.ts)
* against mocked streams; this suite is the one place a *real* TCP client
* destroys a *real* connection mid-transfer, so the sendFile ECONNABORTED
* path and the pipeline() premature-close path are proven against actual
* socket/eos semantics, not a mock's approximation of them.
*
* A bare express() + http.Server wraps StorageService directly — no need to
* boot the full Nest app for this, since sendToResponse is the one place
* every byte-serving caller (files-download, journey-public,
* photo-resolver, trek-photo-cache, backup, /uploads/photos) funnels
* through, per storage.service.ts's own docblock.
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
import express from 'express';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Readable } from 'node:stream';
import { LocalDriver } from '../../src/nest/storage/drivers/local.driver';
import type { StorageRegistryService, ResolvedCategory } from '../../src/nest/storage/storage-registry.service';
import { StorageService } from '../../src/nest/storage/storage.service';
import type { ObjectStat, StorageDriver } from '../../src/nest/storage/storage.types';
/** Trickles chunks on a timer so a real client has time to abort mid-stream
* regardless of machine/CI speed — the S3-network-latency stand-in. */
class SlowReadable extends Readable {
private sent = 0;
private destroyedFlag = false;
constructor(private readonly totalChunks = 40) {
super();
}
override _read(): void {
if (this.sent >= this.totalChunks) {
this.push(null);
return;
}
this.sent++;
setTimeout(() => this.push(Buffer.alloc(2048, 'x')), 5);
}
override _destroy(err: Error | null, cb: (err: Error | null) => void): void {
this.destroyedFlag = true;
cb(err);
}
get wasDestroyed(): boolean {
return this.destroyedFlag;
}
}
/** Fails before ever pushing a byte — the S3-SDK-network-blip stand-in: a
* source error with NO client involved at all, before any header has gone
* out. Used to prove a pre-header failure still rejects (the caller's
* miss/error contract must run), even when the failure carries a code that
* looks abort-like (ECONNRESET). */
class FailingBeforeFirstByteReadable extends Readable {
override _read(): void {
process.nextTick(() => this.destroy(Object.assign(new Error('simulated S3 network blip'), { code: 'ECONNRESET' })));
}
}
function makeRemoteFixture(): { storage: StorageService; lastStream: () => SlowReadable | undefined } {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-abort-'));
let last: SlowReadable | undefined;
const stat: ObjectStat = { key: 'remote.bin', size: 40 * 2048, mtimeMs: 1 };
const driver: StorageDriver = {
id: 'stub-remote-abort',
put: async () => undefined,
getStream: async () => {
last = new SlowReadable();
return { stream: last, stat };
},
stat: async () => stat,
delete: async () => undefined,
list: async function* () {
yield* [] as ObjectStat[];
},
};
const registry = {
resolve: (): ResolvedCategory => ({ driver, keyPrefix: '', backendName: 'stub-remote-abort' }),
tempDir: () => tmpDir,
replicaFailures: () => [],
} as unknown as StorageRegistryService;
return { storage: new StorageService(registry), lastStream: () => last };
}
function makeFailingRemoteFixture(): { storage: StorageService } {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-abort-fail-'));
const stat: ObjectStat = { key: 'remote.bin', size: 40 * 2048, mtimeMs: 1 };
const driver: StorageDriver = {
id: 'stub-remote-fail',
put: async () => undefined,
getStream: async () => ({ stream: new FailingBeforeFirstByteReadable(), stat }),
stat: async () => stat,
delete: async () => undefined,
list: async function* () {
yield* [] as ObjectStat[];
},
};
const registry = {
resolve: (): ResolvedCategory => ({ driver, keyPrefix: '', backendName: 'stub-remote-fail' }),
tempDir: () => tmpDir,
replicaFailures: () => [],
} as unknown as StorageRegistryService;
return { storage: new StorageService(registry) };
}
function makeLocalFixture(): { storage: StorageService; root: string } {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-abort-local-'));
const driver = new LocalDriver({ id: 'stub-local-abort', root });
driver.init({ cleanSpool: true });
const registry = {
resolve: (): ResolvedCategory => ({ driver, keyPrefix: '', backendName: 'stub-local-abort' }),
tempDir: () => root,
replicaFailures: () => [],
} as unknown as StorageRegistryService;
return { storage: new StorageService(registry), root };
}
describe('storage stream abort — real socket (C3 repro)', () => {
let unhandled: unknown[] = [];
const onUnhandled = (err: unknown) => unhandled.push(err);
beforeEach(() => {
unhandled = [];
process.on('unhandledRejection', onUnhandled);
});
afterEach(() => {
process.off('unhandledRejection', onUnhandled);
});
describe('remote (pipeline) branch', () => {
let server: http.Server;
let baseUrl: string;
let fx: ReturnType<typeof makeRemoteFixture>;
let outcome: { settled: 'resolved' | 'rejected' | 'pending'; error?: unknown };
beforeAll(async () => {
fx = makeRemoteFixture();
const app = express();
app.get('/slow', (_req, res) => {
outcome = { settled: 'pending' };
fx.storage
.sendToResponse('files', 'remote.bin', res)
.then(() => {
outcome = { settled: 'resolved' };
})
.catch((error: unknown) => {
outcome = { settled: 'rejected', error };
});
});
server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, resolve));
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
it('resolves cleanly (no 500, no unhandled rejection) and destroys the source stream (no S3 socket leak)', async () => {
await new Promise<void>((resolve, reject) => {
const req = http.get(`${baseUrl}/slow`, (res) => {
res.once('data', () => {
// Abort mid-transfer: headers + at least one chunk are already
// on the wire, the SlowReadable is still trickling out the rest.
req.destroy();
});
res.on('error', () => {}); // expected once we destroy the socket
});
req.on('error', () => {}); // ECONNRESET after our own destroy — expected
req.on('close', () => resolve());
setTimeout(() => reject(new Error('timed out waiting for the aborted request to close')), 5000);
});
// Give the server's pipeline() rejection handler a tick to settle and
// the source's _destroy to run.
await new Promise((resolve) => setTimeout(resolve, 50));
expect(outcome.settled).toBe('resolved'); // swallowed, not a 500/rejection
expect(outcome.error).toBeUndefined();
expect(fx.lastStream()?.wasDestroyed).toBe(true); // the leak fix
expect(unhandled).toEqual([]); // the audit's "does it take the process down" question
// The process/server is still alive and serving — prove it with one
// more full, un-aborted request.
const finalBody: string = await new Promise((resolve, reject) => {
http
.get(`${baseUrl}/slow`, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
res.on('error', reject);
})
.on('error', reject);
});
expect(finalBody.length).toBe(40 * 2048);
}, 10000);
});
// CRITICAL regression case (task C3 review): a source failure BEFORE any
// byte reaches the client — no client abort involved at all — must still
// reject sendToResponse over a real connection, so the route's own
// miss/error handling actually runs instead of silently answering a
// truncated 200 with an empty body.
//
// Note on what's actually observable here: node:stream/promises'
// `pipeline()` destroys EVERY stream in the pipeline on any single
// failure — including the destination (`res`) — as part of its own
// cleanup, confirmed empirically (`dst.destroyed === true` by the time
// pipeline's rejection is caught, even for a purely source-side, pre-any-
// write error). So a caller's own fallback write attempted from its catch
// block (`res.status(502).json(...)`) is reliably a safe, silent no-op —
// Node's OutgoingMessage swallows writes after destroy rather than
// throwing — not a delivered response body. What this test can and does
// pin: the promise REJECTS (the miss/error contract genuinely runs,
// instead of being silently swallowed as if it were a client abort), that
// safe no-op write doesn't crash the process or the request, and the
// server survives to serve the next, unrelated request correctly.
describe('remote (pipeline) branch — pre-header source failure', () => {
let server: http.Server;
let baseUrl: string;
let outcome: { settled: 'resolved' | 'rejected' | 'pending'; error?: unknown };
beforeAll(async () => {
const fx = makeFailingRemoteFixture();
const app = express();
app.get('/broken', (_req, res) => {
outcome = { settled: 'pending' };
fx.storage
.sendToResponse('files', 'remote.bin', res)
.then(() => {
outcome = { settled: 'resolved' };
})
.catch((error: unknown) => {
outcome = { settled: 'rejected', error };
// The caller's own miss/error contract: prove it actually RUNS
// (as opposed to sendToResponse silently resolving and this
// branch never executing at all) — even though, per the note
// above, the write itself is a no-op onto an already-destroyed
// response.
if (!res.headersSent) res.status(502).json({ error: 'upstream failure' });
});
});
app.get('/ok', (_req, res) => res.status(200).json({ ok: true }));
server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, resolve));
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
it('rejects (the miss/error contract genuinely fires) instead of silently resolving as a fake empty success', async () => {
// The connection ends one way or another (a delivered body, or the
// destroyed-response no-op surfacing as a raw close) — either way,
// within the timeout, proving the server isn't stuck.
await new Promise<void>((resolve, reject) => {
const req = http.get(`${baseUrl}/broken`, (res) => {
res.resume();
res.on('end', () => resolve());
res.on('error', () => resolve()); // a destroyed-response close is expected here
});
req.on('error', () => resolve()); // socket hang up is expected here too
setTimeout(() => reject(new Error('timed out — the server got stuck')), 5000);
});
expect(outcome.settled).toBe('rejected'); // NOT silently swallowed as a client abort
expect((outcome.error as { code?: string } | undefined)?.code).toBe('ECONNRESET');
expect(unhandled).toEqual([]);
// The process/server survived and correctly serves an unrelated,
// ordinary request afterward — the real "did this take the process
// down" proof.
const ok: { status: number; body: unknown } = await new Promise((resolve, reject) => {
http
.get(`${baseUrl}/ok`, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('end', () => resolve({ status: res.statusCode ?? 0, body: JSON.parse(Buffer.concat(chunks).toString('utf8')) }));
res.on('error', reject);
})
.on('error', reject);
});
expect(ok).toEqual({ status: 200, body: { ok: true } });
}, 10000);
});
describe('local (res.sendFile) branch', () => {
let server: http.Server;
let baseUrl: string;
let fx: ReturnType<typeof makeLocalFixture>;
let outcome: { settled: 'resolved' | 'rejected' | 'pending'; error?: unknown };
beforeAll(async () => {
fx = makeLocalFixture();
// A large-enough file that writing it to the socket isn't instantaneous.
await fx.storage.put('files', 'big.bin', Readable.from(Buffer.alloc(20 * 1024 * 1024, 'y')));
const app = express();
app.get('/big', (_req, res) => {
outcome = { settled: 'pending' };
fx.storage
.sendToResponse('files', 'big.bin', res)
.then(() => {
outcome = { settled: 'resolved' };
})
.catch((error: unknown) => {
outcome = { settled: 'rejected', error };
});
});
server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, resolve));
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
it('resolves cleanly (no 500, no unhandled rejection) when the client aborts mid-download', async () => {
await new Promise<void>((resolve, reject) => {
const req = http.get(`${baseUrl}/big`, (res) => {
res.once('data', () => {
req.destroy();
});
res.on('error', () => {});
});
req.on('error', () => {});
req.on('close', () => resolve());
setTimeout(() => reject(new Error('timed out waiting for the aborted request to close')), 5000);
});
await new Promise((resolve) => setTimeout(resolve, 50));
expect(outcome.settled).toBe('resolved');
expect(outcome.error).toBeUndefined();
expect(unhandled).toEqual([]);
}, 10000);
});
});
+1 -1
View File
@@ -44,7 +44,7 @@ import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser, createTrip, addTripMember } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
import { invalidatePermissionsCache } from '../../src/services/permissions';
import { invalidatePermissionsCache } from '../../src/nest/permissions/permissions-cache';
let nestApp: INestApplication;
let app: Application;
+120 -4
View File
@@ -57,7 +57,7 @@ import { runMigrations } from '../../src/db/migrations';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser, createAdmin, createTrip, addTripMember, createPlace, createReservation, createTag, createDayAccommodation, createBudgetItem, createPackingItem, createDayNote, createDayAssignment } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
import { invalidatePermissionsCache } from '../../src/services/permissions';
import { invalidatePermissionsCache } from '../../src/nest/permissions/permissions-cache';
let nestApp: INestApplication;
let app: Application;
@@ -527,7 +527,7 @@ describe('Delete trip', () => {
expect(getRes.status).toBe(404);
});
it('TRIP-019 — Regular user cannot delete another users trip → 403', async () => {
it('TRIP-019 — Regular user cannot delete another users trip → 404', async () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id, { title: "Owner's Trip" });
@@ -536,8 +536,10 @@ describe('Delete trip', () => {
.delete(`/api/trips/${trip.id}`)
.set('Cookie', authCookie(other.id));
// getTripOwner finds the trip (it exists); checkPermission fails for non-members → 403
expect(res.status).toBe(403);
// 404, not 403: someone with no access at all must not be able to tell an
// existing trip from a missing one by walking sequential ids. A member who
// simply lacks trip_delete still gets 403 — see the case below.
expect(res.status).toBe(404);
// Trip still exists
const tripInDb = testDb.prepare('SELECT id FROM trips WHERE id = ?').get(trip.id);
@@ -1032,6 +1034,24 @@ describe('ICS export', () => {
const res = await request(app).get(`/api/trips/${trip.id}/export.ics`);
expect(res.status).toBe(401);
});
it('TRIP-025b — the trip payload never carries feed_token, not even for the owner', async () => {
// feed_token is the sole credential for the anonymous ICS feed. TRIP_SELECT
// reads `t.*`, so without the blanking it ships in every trip response and
// gating /feed/token on share_manage would achieve nothing: any member
// could read the value straight out of GET /api/trips/:id.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip' });
testDb.prepare('UPDATE trips SET feed_token = ? WHERE id = ?').run('secret-feed-token', trip.id);
const one = await request(app).get(`/api/trips/${trip.id}`).set('Cookie', authCookie(user.id));
expect(one.status).toBe(200);
expect(one.body.trip.feed_token ?? null).toBeNull();
expect(JSON.stringify(one.body)).not.toContain('secret-feed-token');
const list = await request(app).get('/api/trips').set('Cookie', authCookie(user.id));
expect(JSON.stringify(list.body)).not.toContain('secret-feed-token');
});
});
// ─────────────────────────────────────────────────────────────────────────────
@@ -1245,4 +1265,100 @@ describe('Trip bundle', () => {
expect(res.status).toBe(401);
});
it('BUNDLE-006 — packingItems are scoped to the viewer: another member\'s private item stays out (#858)', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(trip.id, member.id);
testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, sort_order) VALUES (?, ?, 0, 0)').run(trip.id, 'Tent');
testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, sort_order, is_private, owner_id) VALUES (?, ?, 0, 1, 1, ?)').run(trip.id, 'Secret gift', owner.id);
const ownerView = await request(app).get(`/api/trips/${trip.id}/bundle`).set('Cookie', authCookie(owner.id));
expect(ownerView.body.packingItems.map((i: { name: string }) => i.name).sort()).toEqual(['Secret gift', 'Tent']);
const memberView = await request(app).get(`/api/trips/${trip.id}/bundle`).set('Cookie', authCookie(member.id));
expect(memberView.body.packingItems.map((i: { name: string }) => i.name)).toEqual(['Tent']);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Cover upload parity (TRIP-P01…P05) — written BEFORE the storage-upload swap.
// ─────────────────────────────────────────────────────────────────────────────
describe('Trip cover upload parity', () => {
const fsMod = require('fs') as typeof import('fs');
const pathMod = require('path') as typeof import('path');
const FIXTURE_IMG = pathMod.join(__dirname, '../fixtures/small-image.jpg');
const coversDir = pathMod.join(__dirname, '../../uploads/covers');
afterAll(() => {
fsMod.rmSync(coversDir, { recursive: true, force: true });
});
it('TRIP-P01 — cover upload returns /uploads/covers/<uuid> and writes the file', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const res = await request(app)
.post(`/api/trips/${trip.id}/cover`)
.set('Cookie', authCookie(user.id))
.attach('cover', FIXTURE_IMG, 'cover.png');
expect(res.status).toBe(201);
expect(res.body.cover_image).toMatch(/^\/uploads\/covers\/[0-9a-f-]{36}\.png$/);
const diskName = res.body.cover_image.replace('/uploads/covers/', '');
expect(fsMod.existsSync(pathMod.join(coversDir, diskName))).toBe(true);
});
it('TRIP-P02 — re-upload deletes the previous cover file', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const first = await request(app)
.post(`/api/trips/${trip.id}/cover`)
.set('Cookie', authCookie(user.id))
.attach('cover', FIXTURE_IMG, 'one.jpg');
const firstName = first.body.cover_image.replace('/uploads/covers/', '');
expect(fsMod.existsSync(pathMod.join(coversDir, firstName))).toBe(true);
const second = await request(app)
.post(`/api/trips/${trip.id}/cover`)
.set('Cookie', authCookie(user.id))
.attach('cover', FIXTURE_IMG, 'two.jpg');
expect(second.status).toBe(201);
expect(fsMod.existsSync(pathMod.join(coversDir, firstName))).toBe(false);
});
it('TRIP-P03 — no file → 400 "No image uploaded"', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const res = await request(app)
.post(`/api/trips/${trip.id}/cover`)
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(400);
expect(res.body.error).toBe('No image uploaded');
});
it('TRIP-P04 — non-image upload is 500 (plain-Error filter quirk — pinned, do not "fix")', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const res = await request(app)
.post(`/api/trips/${trip.id}/cover`)
.set('Cookie', authCookie(user.id))
.attach('cover', Buffer.from('plain text'), { filename: 'doc.txt', contentType: 'text/plain' });
expect(res.status).toBe(500);
});
it('TRIP-P05 — unknown trip → 404 "Trip not found"', async () => {
const { user } = createUser(testDb);
const res = await request(app)
.post('/api/trips/999999/cover')
.set('Cookie', authCookie(user.id))
.attach('cover', FIXTURE_IMG);
expect(res.status).toBe(404);
expect(res.body.error).toBe('Trip not found');
});
});
@@ -0,0 +1,304 @@
/**
* /uploads static-mount parity tests (UPLOADS-P01…P24).
*
* Written BEFORE the storage slice-3 swap of the four express.static mounts
* (avatars / covers / journey / places) for a storage-backed handler on the
* same URLs. P01–P21 pin today's express.static behavior — ETag /
* Last-Modified / conditional-GET / Range / HEAD, miss-falls-through to the
* Nest 404 envelope — and must stay green across the swap. P22–P24 are the
* approved deliberate deltas (D1–D3 in the slice-3 plan): RED against
* express.static, green against the storage handler.
*
* These routes are unauthenticated BY DESIGN (audit SEC-M9): server-chosen
* UUIDv4 filenames; gating them would break share-link trip cards, journey
* public pages, and email-embedded avatars. No auth setup here is deliberate.
*/
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
import request from 'supertest';
import type { Application } from 'express';
import type { INestApplication } from '@nestjs/common';
import path from 'path';
import fs from 'fs';
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: () => {},
canAccessTrip: () => undefined,
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: () => {},
SESSION_DURATION: '24h',
SESSION_DURATION_MS: 86400000,
SESSION_DURATION_SECONDS: 86400,
DEFAULT_LANGUAGE: 'en',
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn(), getOnlineUserIds: vi.fn(() => []) }));
import { buildApp } from '../../src/bootstrap';
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
let nestApp: INestApplication;
let app: Application;
const uploadsDir = path.join(__dirname, '../../uploads');
// 8 known bytes (the PNG magic) so Content-Length / Range math is exact.
const BYTES = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const NAME = 'uploads-static-parity.png';
// Every path this suite creates, for targeted afterAll cleanup — the uploads
// tree is shared with other integration workers, so no directory-wide rm of
// the category dirs themselves.
const created: string[] = [];
function writeFixture(rel: string, bytes: Buffer = BYTES): void {
const abs = path.join(uploadsDir, rel);
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, bytes);
created.push(abs);
}
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
// Written AFTER buildApp(): LocalDriver init ensures + realpaths the
// category dirs at boot.
writeFixture(`avatars/${NAME}`);
writeFixture(`covers/${NAME}`);
writeFixture(`journey/thumbs/uploads-static-parity.jpg`);
writeFixture(`places/${NAME}`);
writeFixture('avatars/.uploads-static-parity-hidden');
writeFixture('avatars/.tmp/uploads-static-parity-spooled.bin');
fs.mkdirSync(path.join(uploadsDir, 'journey/parity-subdir'), { recursive: true });
});
afterAll(async () => {
await nestApp.close();
testDb.close();
for (const abs of created) fs.rmSync(abs, { force: true });
fs.rmSync(path.join(uploadsDir, 'avatars/.tmp'), { recursive: true, force: true });
fs.rmSync(path.join(uploadsDir, 'journey/parity-subdir'), { recursive: true, force: true });
});
describe('/uploads static parity — hit headers and bytes', () => {
it('UPLOADS-P01 — GET hit: 200 with express.static header set', async () => {
const res = await request(app).get(`/uploads/avatars/${NAME}`);
expect(res.status).toBe(200);
expect(res.body.equals ? res.body.equals(BYTES) : Buffer.from(res.body).equals(BYTES)).toBe(true);
expect(res.headers.etag).toMatch(/^W\/"[0-9a-f]+-[0-9a-f]+"$/);
expect(res.headers['last-modified']).toBeDefined();
expect(res.headers['cache-control']).toBe('public, max-age=0');
expect(res.headers['accept-ranges']).toBe('bytes');
expect(res.headers['content-type']).toBe('image/png');
expect(res.headers['content-length']).toBe('8');
});
it('UPLOADS-P02 — HEAD hit: 200, same headers, empty body', async () => {
const res = await request(app).head(`/uploads/avatars/${NAME}`);
expect(res.status).toBe(200);
expect(res.headers.etag).toMatch(/^W\/"[0-9a-f]+-[0-9a-f]+"$/);
expect(res.headers['content-length']).toBe('8');
expect(res.headers['content-type']).toBe('image/png');
expect(res.text ?? '').toBe('');
});
it('UPLOADS-P19 — query string is ignored', async () => {
const res = await request(app).get(`/uploads/avatars/${NAME}?x=1`);
expect(res.status).toBe(200);
expect(res.headers['content-length']).toBe('8');
});
it('UPLOADS-P20 — doubled leading slash still serves', async () => {
const res = await request(app).get(`/uploads/avatars//${NAME}`);
expect(res.status).toBe(200);
expect(res.headers['content-length']).toBe('8');
});
});
describe('/uploads static parity — conditional GET', () => {
it('UPLOADS-P03 — If-None-Match with the current ETag → 304', async () => {
const first = await request(app).get(`/uploads/avatars/${NAME}`);
const res = await request(app).get(`/uploads/avatars/${NAME}`).set('If-None-Match', first.headers.etag);
expect(res.status).toBe(304);
expect(res.headers.etag).toBe(first.headers.etag);
expect(res.text ?? '').toBe('');
});
it('UPLOADS-P04 — If-Modified-Since with the current Last-Modified → 304', async () => {
const first = await request(app).get(`/uploads/avatars/${NAME}`);
const res = await request(app)
.get(`/uploads/avatars/${NAME}`)
.set('If-Modified-Since', first.headers['last-modified']);
expect(res.status).toBe(304);
});
it('UPLOADS-P05 — stale If-None-Match → 200 full', async () => {
const res = await request(app).get(`/uploads/avatars/${NAME}`).set('If-None-Match', 'W/"0-0"');
expect(res.status).toBe(200);
expect(res.headers['content-length']).toBe('8');
});
it('UPLOADS-P06 — If-Match mismatch → 412', async () => {
const res = await request(app).get(`/uploads/avatars/${NAME}`).set('If-Match', '"mismatch"');
expect(res.status).toBe(412);
});
});
describe('/uploads static parity — Range', () => {
it('UPLOADS-P07 — single satisfiable range → 206 with Content-Range', async () => {
const res = await request(app).get(`/uploads/avatars/${NAME}`).set('Range', 'bytes=0-3');
expect(res.status).toBe(206);
expect(res.headers['content-range']).toBe('bytes 0-3/8');
expect(res.headers['content-length']).toBe('4');
expect(Buffer.from(res.body).equals(BYTES.subarray(0, 4))).toBe(true);
});
it('UPLOADS-P08 — unsatisfiable range → 416 with Content-Range */size', async () => {
const res = await request(app).get(`/uploads/avatars/${NAME}`).set('Range', 'bytes=999-');
expect(res.status).toBe(416);
expect(res.headers['content-range']).toBe('bytes */8');
});
it('UPLOADS-P09 — multi-range is ignored → 200 full', async () => {
const res = await request(app).get(`/uploads/avatars/${NAME}`).set('Range', 'bytes=0-0,4-5');
expect(res.status).toBe(200);
expect(res.headers['content-length']).toBe('8');
});
it('UPLOADS-P10 — non-bytes range unit is ignored → 200 full', async () => {
const res = await request(app).get(`/uploads/avatars/${NAME}`).set('Range', 'apples=0-1');
expect(res.status).toBe(200);
});
it('UPLOADS-P11 — stale If-Range drops the range → 200 full', async () => {
const res = await request(app)
.get(`/uploads/avatars/${NAME}`)
.set('Range', 'bytes=0-3')
.set('If-Range', 'W/"0-0"');
expect(res.status).toBe(200);
expect(res.headers['content-length']).toBe('8');
});
it('UPLOADS-P12 — fresh If-Range honors the range → 206', async () => {
const first = await request(app).get(`/uploads/avatars/${NAME}`);
const res = await request(app)
.get(`/uploads/avatars/${NAME}`)
.set('Range', 'bytes=0-3')
.set('If-Range', first.headers.etag);
expect(res.status).toBe(206);
});
});
describe('/uploads static parity — miss falls through to the Nest 404 envelope', () => {
it('UPLOADS-P13 — GET miss → Nest envelope, not a bespoke 404', async () => {
const res = await request(app).get('/uploads/avatars/nope.png');
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Cannot GET /uploads/avatars/nope.png' });
});
it('UPLOADS-P14 — HEAD miss → 404, empty body', async () => {
const res = await request(app).head('/uploads/avatars/nope.png');
expect(res.status).toBe(404);
expect(res.text ?? '').toBe('');
});
it('UPLOADS-P15 — POST to a hit URL falls through (no 405)', async () => {
const res = await request(app).post(`/uploads/avatars/${NAME}`);
expect(res.status).toBe(404);
expect(res.body.error).toBe(`Cannot POST /uploads/avatars/${NAME}`);
});
it('UPLOADS-P16 — malformed percent-encoding falls through', async () => {
const res = await request(app).get('/uploads/avatars/%ZZ');
expect(res.status).toBe(404);
expect(res.body.error).toMatch(/^Cannot GET /);
});
it('UPLOADS-P17 — traversal shapes fall through, raw and encoded', async () => {
const raw = await request(app).get('/uploads/avatars/../covers/x.png');
expect(raw.status).toBe(404);
const encoded = await request(app).get('/uploads/avatars/..%2Fcovers%2Fx.png');
expect(encoded.status).toBe(404);
});
it('UPLOADS-P18 — dotfile basename falls through', async () => {
const res = await request(app).get('/uploads/avatars/.uploads-static-parity-hidden');
expect(res.status).toBe(404);
expect(res.body.error).toBe('Cannot GET /uploads/avatars/.uploads-static-parity-hidden');
});
});
describe('/uploads static parity — all four mounts', () => {
it('UPLOADS-P21 — covers/journey(nested)/places each serve a hit and 404 a miss', async () => {
// Fixtures are (re)written immediately before each request: other suites
// rm their whole category dir in afterAll (collections/trips → covers,
// collections → places, journey.test → journey), so a beforeAll-written
// file can vanish mid-run when the tier runs in parallel workers.
writeFixture(`covers/${NAME}`);
const coverHit = await request(app).get(`/uploads/covers/${NAME}`);
expect(coverHit.status).toBe(200);
const coverMiss = await request(app).get('/uploads/covers/nope.png');
expect(coverMiss.status).toBe(404);
expect(coverMiss.body.error).toBe('Cannot GET /uploads/covers/nope.png');
// Nested name — journey thumbs live at journey/thumbs/<hash>.jpg and are
// served through the same mount; pins multi-segment storage keys.
writeFixture('journey/thumbs/uploads-static-parity.jpg');
const journeyHit = await request(app).get('/uploads/journey/thumbs/uploads-static-parity.jpg');
expect(journeyHit.status).toBe(200);
expect(journeyHit.headers['content-type']).toBe('image/jpeg');
const journeyMiss = await request(app).get('/uploads/journey/thumbs/nope.jpg');
expect(journeyMiss.status).toBe(404);
writeFixture(`places/${NAME}`);
const placeHit = await request(app).get(`/uploads/places/${NAME}`);
expect(placeHit.status).toBe(200);
const placeMiss = await request(app).get('/uploads/places/nope.png');
expect(placeMiss.status).toBe(404);
});
});
describe('/uploads static — approved deliberate deltas (RED against express.static)', () => {
// D3 (slice-3 plan): send's legacy dotfiles mode only ignores dot BASENAMES,
// so a file under a dot-directory is servable today. Central storage key
// validation rejects every dot segment — the spec's ".tmp must remain
// unservable" pin.
it('UPLOADS-P22 — a file under a dot-directory is NOT servable', async () => {
const res = await request(app).get('/uploads/avatars/.tmp/uploads-static-parity-spooled.bin');
expect(res.status).toBe(404);
expect(res.body.error).toBe('Cannot GET /uploads/avatars/.tmp/uploads-static-parity-spooled.bin');
});
// D1/D2: express.static answers directory URLs with a 301 trailing-slash
// redirect (and an index.html lookup on the slashed form). The storage
// handler treats both as a plain miss.
it('UPLOADS-P23 — mount root (with and without slash) is a miss', async () => {
const bare = await request(app).get('/uploads/avatars');
expect(bare.status).toBe(404);
expect(bare.body.error).toBe('Cannot GET /uploads/avatars');
const slashed = await request(app).get('/uploads/avatars/');
expect(slashed.status).toBe(404);
});
it('UPLOADS-P24 — a real subdirectory URL is a miss, not a redirect', async () => {
const res = await request(app).get('/uploads/journey/parity-subdir');
expect(res.status).toBe(404);
expect(res.body.error).toBe('Cannot GET /uploads/journey/parity-subdir');
});
});
+141 -12
View File
@@ -51,15 +51,13 @@ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
]),
}));
// Mock vacayService.getCountries to avoid real HTTP call to nager.at
vi.mock('../../src/services/vacayService', async () => {
const actual = await vi.importActual<typeof import('../../src/services/vacayService')>('../../src/services/vacayService');
return {
...actual,
getCountries: vi.fn().mockResolvedValue({
data: [{ countryCode: 'DE', name: 'Germany' }, { countryCode: 'FR', name: 'France' }],
}),
};
import { VacayService } from '../../src/nest/vacay/vacay.service';
// Stub VacayService.getCountries to avoid a real HTTP call to nager.at (the
// legacy path-level partial mock; the service is DI-native now, so spy on the
// prototype instead).
vi.spyOn(VacayService.prototype, 'getCountries').mockResolvedValue({
data: [{ countryCode: 'DE', name: 'Germany' }, { countryCode: 'FR', name: 'France' }],
});
import { buildApp } from '../../src/bootstrap';
@@ -189,17 +187,18 @@ describe('Vacay entries', () => {
expect(res.status).toBe(200);
});
it('VACAY-004 — POST /api/addons/vacay/entries/toggle on weekend is allowed (no server-side weekend blocking)', async () => {
it('VACAY-004 — POST /api/addons/vacay/entries/toggle on a weekend is rejected when block_weekends is on', async () => {
const { user } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(user.id));
await request(app).post('/api/addons/vacay/years').set('Cookie', authCookie(user.id)).send({ year: 2025 });
// 2025-06-21 is a Saturday — server does not block weekends; client-side only
// 2025-06-21 is a Saturday and plans default to block_weekends = 1 (I-02)
const res = await request(app)
.post('/api/addons/vacay/entries/toggle')
.set('Cookie', authCookie(user.id))
.send({ date: '2025-06-21', year: 2025, type: 'vacation' });
expect(res.status).toBe(200);
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Weekend days are blocked on this plan' });
});
it('VACAY-006 — GET /api/addons/vacay/entries/:year returns vacation entries', async () => {
@@ -538,3 +537,133 @@ describe('Vacay toggle entry for plan member', () => {
expect(res.status).toBe(200);
});
});
describe('Vacay read-only calendar shares', () => {
it('VACAY-039 — POST /shares shares the calendar with another user', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
const res = await request(app)
.post('/api/addons/vacay/shares')
.set('Cookie', authCookie(a.id))
.send({ user_id: b.id });
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
});
it('VACAY-040 — GET /shares lists the share as outgoing for A and incoming for B', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const aRes = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(a.id));
expect(aRes.status).toBe(200);
expect(aRes.body.outgoing).toHaveLength(1);
expect(aRes.body.outgoing[0].user_id).toBe(b.id);
expect(aRes.body.incoming).toHaveLength(0);
const bRes = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
expect(bRes.status).toBe(200);
expect(bRes.body.incoming).toHaveLength(1);
expect(bRes.body.incoming[0].owner_id).toBe(a.id);
expect(bRes.body.incoming[0].hidden).toBe(false);
expect(bRes.body.outgoing).toHaveLength(0);
});
it('VACAY-041 — GET /shares/calendars/:year exposes A entries and company holidays to B', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/years').set('Cookie', authCookie(a.id)).send({ year: 2025 });
await request(app).put('/api/addons/vacay/plan').set('Cookie', authCookie(a.id)).send({ company_holidays_enabled: true });
await request(app).post('/api/addons/vacay/entries/toggle').set('Cookie', authCookie(a.id)).send({ date: '2025-06-16' });
await request(app).post('/api/addons/vacay/entries/company-holiday').set('Cookie', authCookie(a.id)).send({ date: '2025-12-25', note: 'Christmas' });
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const res = await request(app)
.get('/api/addons/vacay/shares/calendars/2025')
.set('Cookie', authCookie(b.id));
expect(res.status).toBe(200);
expect(res.body.calendars).toHaveLength(1);
const cal = res.body.calendars[0];
expect(cal.owner_id).toBe(a.id);
expect(cal.entries.map((e: { date: string }) => e.date)).toContain('2025-06-16');
expect(cal.companyHolidays.map((h: { date: string }) => h.date)).toContain('2025-12-25');
});
it('VACAY-042 — PUT /shares/:id lets B hide the shared calendar', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const list = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
const shareId = list.body.incoming[0].id;
const res = await request(app)
.put(`/api/addons/vacay/shares/${shareId}`)
.set('Cookie', authCookie(b.id))
.send({ hidden: true });
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
const after = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
expect(after.body.incoming[0].hidden).toBe(true);
});
it('VACAY-043 — DELETE /shares/:id lets B remove the share', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const list = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
const shareId = list.body.incoming[0].id;
const res = await request(app)
.delete(`/api/addons/vacay/shares/${shareId}`)
.set('Cookie', authCookie(b.id));
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
const bAfter = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
expect(bAfter.body.incoming).toHaveLength(0);
const aAfter = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(a.id));
expect(aAfter.body.outgoing).toHaveLength(0);
});
it('VACAY-044 — PUT/DELETE on a foreign share id returns 404', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
const { user: c } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const list = await request(app).get('/api/addons/vacay/shares').set('Cookie', authCookie(b.id));
const shareId = list.body.incoming[0].id;
const put = await request(app)
.put(`/api/addons/vacay/shares/${shareId}`)
.set('Cookie', authCookie(c.id))
.send({ hidden: true });
expect(put.status).toBe(404);
const del = await request(app)
.delete(`/api/addons/vacay/shares/${shareId}`)
.set('Cookie', authCookie(c.id));
expect(del.status).toBe(404);
});
it('VACAY-045 — sharing with the same user twice returns 400', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await request(app).get('/api/addons/vacay/plan').set('Cookie', authCookie(a.id));
await request(app).post('/api/addons/vacay/shares').set('Cookie', authCookie(a.id)).send({ user_id: b.id });
const res = await request(app)
.post('/api/addons/vacay/shares')
.set('Cookie', authCookie(a.id))
.send({ user_id: b.id });
expect(res.status).toBe(400);
expect(res.body.error).toBe('Already shared');
});
});