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
@@ -1,725 +0,0 @@
/**
* Unit tests for adminService — ADMIN-SVC-001 through ADMIN-SVC-050.
* Uses a real in-memory SQLite DB. Focuses on validation/error branches
* that the integration tests don't exercise.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/services/apiKeyCrypto', () => ({
encrypt_api_key: (v: string) => v,
decrypt_api_key: (v: string) => v,
maybe_encrypt_api_key: (v: string) => v,
}));
vi.mock('../../../src/mcp', () => ({
revokeUserSessions: vi.fn(),
}));
vi.mock('../../../src/demo/demo-reset', () => ({
saveBaseline: vi.fn(),
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createAdmin, createInviteToken } from '../../helpers/factories';
import {
listUsers,
createUser as svcCreateUser,
updateUser,
deleteUser,
getStats,
getPermissions,
savePermissions,
getAuditLog,
listInvites,
createInvite,
deleteInvite,
getBagTracking,
updateBagTracking,
listPackingTemplates,
createPackingTemplate,
updatePackingTemplate,
deletePackingTemplate,
createTemplateCategory,
updateTemplateCategory,
deleteTemplateCategory,
getPackingTemplate,
createTemplateItem,
updateTemplateItem,
deleteTemplateItem,
getOidcSettings,
updateOidcSettings,
saveDemoBaseline,
getGithubReleases,
checkVersion,
listAddons,
updateAddon,
updateCollabFeatures,
listMcpTokens,
deleteMcpToken,
} from '../../../src/services/adminService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ── listUsers ─────────────────────────────────────────────────────────────────
describe('listUsers', () => {
it('ADMIN-SVC-001 — returns all users with online:false', () => {
createUser(testDb);
createUser(testDb);
const users = listUsers() as any[];
expect(users.length).toBeGreaterThanOrEqual(2);
expect(users.every((u: any) => u.online === false)).toBe(true);
});
});
// ── createUser ────────────────────────────────────────────────────────────────
describe('createUser (service)', () => {
it('ADMIN-SVC-002 — creates a user successfully', () => {
const result = svcCreateUser({ username: 'newuser', email: 'new@test.com', password: 'ValidPass1!' }) as any;
expect(result.user).toBeDefined();
expect(result.user.email).toBe('new@test.com');
});
it('ADMIN-SVC-003 — returns 400 when username is missing', () => {
const result = svcCreateUser({ username: '', email: 'x@x.com', password: 'ValidPass1!' }) as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-004 — returns 400 for invalid role', () => {
const result = svcCreateUser({ username: 'u1', email: 'u1@test.com', password: 'ValidPass1!', role: 'superuser' }) as any;
expect(result.status).toBe(400);
expect(result.error).toMatch(/invalid role/i);
});
it('ADMIN-SVC-005 — returns 409 for duplicate username', () => {
createUser(testDb);
const { user } = createUser(testDb);
const result = svcCreateUser({ username: user.username, email: 'unique@test.com', password: 'ValidPass1!' }) as any;
expect(result.status).toBe(409);
});
it('ADMIN-SVC-006 — returns 409 for duplicate email', () => {
const { user } = createUser(testDb);
const result = svcCreateUser({ username: 'uniqueuser', email: user.email, password: 'ValidPass1!' }) as any;
expect(result.status).toBe(409);
});
it('ADMIN-SVC-007 — returns 400 for weak password', () => {
const result = svcCreateUser({ username: 'weakpwuser', email: 'weakpw@test.com', password: 'short' }) as any;
expect(result.status).toBe(400);
});
});
// ── updateUser ────────────────────────────────────────────────────────────────
describe('updateUser', () => {
it('ADMIN-SVC-008 — updates username successfully', () => {
const { user } = createUser(testDb);
const result = updateUser(String(user.id), { username: 'updatedname' }) as any;
expect(result.user).toBeDefined();
expect(result.user.username).toBe('updatedname');
});
it('ADMIN-SVC-009 — returns 404 for non-existent user', () => {
const result = updateUser('99999', { username: 'ghost' }) as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-010 — returns 400 for invalid role', () => {
const { user } = createUser(testDb);
const result = updateUser(String(user.id), { role: 'superadmin' }) as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-011 — returns 409 when username is taken', () => {
const { user: u1 } = createUser(testDb);
const { user: u2 } = createUser(testDb);
const result = updateUser(String(u2.id), { username: u1.username }) as any;
expect(result.status).toBe(409);
});
it('ADMIN-SVC-012 — returns 409 when email is taken', () => {
const { user: u1 } = createUser(testDb);
const { user: u2 } = createUser(testDb);
const result = updateUser(String(u2.id), { email: u1.email }) as any;
expect(result.status).toBe(409);
});
it('ADMIN-SVC-013 — returns 400 for weak password', () => {
const { user } = createUser(testDb);
const result = updateUser(String(user.id), { password: 'weak' }) as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-014 — tracks changed fields in result', () => {
const { user } = createUser(testDb);
const result = updateUser(String(user.id), { username: 'newname', role: 'admin' }) as any;
expect(result.changed).toContain('username');
expect(result.changed).toContain('role');
});
});
// ── deleteUser ────────────────────────────────────────────────────────────────
describe('deleteUser', () => {
it('ADMIN-SVC-015 — deletes user successfully', () => {
const { user: admin } = createAdmin(testDb);
const { user } = createUser(testDb);
const result = deleteUser(String(user.id), admin.id) as any;
expect(result.email).toBe(user.email);
});
it('ADMIN-SVC-016 — returns 400 when deleting own account', () => {
const { user: admin } = createAdmin(testDb);
const result = deleteUser(String(admin.id), admin.id) as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-017 — returns 404 for non-existent user', () => {
const { user: admin } = createAdmin(testDb);
const result = deleteUser('99999', admin.id) as any;
expect(result.status).toBe(404);
});
});
// ── getStats ──────────────────────────────────────────────────────────────────
describe('getStats', () => {
it('ADMIN-SVC-018 — returns numeric counts for all stats', () => {
const stats = getStats() as any;
expect(typeof stats.totalUsers).toBe('number');
expect(typeof stats.totalTrips).toBe('number');
expect(typeof stats.totalPlaces).toBe('number');
expect(typeof stats.totalFiles).toBe('number');
});
});
// ── getPermissions / savePermissions ─────────────────────────────────────────
describe('Permissions', () => {
it('ADMIN-SVC-019 — getPermissions returns an array of actions', () => {
const result = getPermissions() as any;
expect(Array.isArray(result.permissions)).toBe(true);
expect(result.permissions.length).toBeGreaterThan(0);
});
it('ADMIN-SVC-020 — savePermissions persists a permission change', () => {
savePermissions({ trip_create: 'admin' });
const result = getPermissions() as any;
const perm = result.permissions.find((p: any) => p.key === 'trip_create');
expect(perm.level).toBe('admin');
});
});
// ── getAuditLog ───────────────────────────────────────────────────────────────
describe('getAuditLog', () => {
it('ADMIN-SVC-021 — returns entries array with total', () => {
const result = getAuditLog({}) as any;
expect(Array.isArray(result.entries)).toBe(true);
expect(typeof result.total).toBe('number');
expect(result.limit).toBe(100);
expect(result.offset).toBe(0);
});
it('ADMIN-SVC-022 — respects limit and offset params', () => {
const result = getAuditLog({ limit: '10', offset: '0' }) as any;
expect(result.limit).toBe(10);
expect(result.offset).toBe(0);
});
it('ADMIN-SVC-023 — caps limit at 500', () => {
const result = getAuditLog({ limit: '9999' }) as any;
expect(result.limit).toBe(500);
});
});
// ── Invites ───────────────────────────────────────────────────────────────────
describe('Invites', () => {
it('ADMIN-SVC-024 — createInvite returns invite with token', () => {
const { user: admin } = createAdmin(testDb);
const result = createInvite(admin.id, { max_uses: 5 }) as any;
expect(result.invite.token).toBeDefined();
expect(result.invite.max_uses).toBe(5);
});
it('ADMIN-SVC-025 — createInvite defaults to 1 use', () => {
const { user: admin } = createAdmin(testDb);
const result = createInvite(admin.id, {}) as any;
expect(result.uses).toBe(1);
});
it('ADMIN-SVC-026 — listInvites returns array', () => {
const { user: admin } = createAdmin(testDb);
createInvite(admin.id, {});
const invites = listInvites() as any[];
expect(invites.length).toBeGreaterThanOrEqual(1);
});
it('ADMIN-SVC-027 — deleteInvite removes invite', () => {
const { user: admin } = createAdmin(testDb);
const invite = createInviteToken(testDb, { created_by: admin.id }) as any;
const result = deleteInvite(String(invite.id)) as any;
expect(result.error).toBeUndefined();
const check = testDb.prepare('SELECT id FROM invite_tokens WHERE id = ?').get(invite.id);
expect(check).toBeUndefined();
});
it('ADMIN-SVC-028 — deleteInvite returns 404 for non-existent invite', () => {
const result = deleteInvite('99999') as any;
expect(result.status).toBe(404);
});
});
// ── Bag tracking ──────────────────────────────────────────────────────────────
describe('Bag tracking', () => {
it('ADMIN-SVC-029 — getBagTracking returns enabled state', () => {
const result = getBagTracking() as any;
expect(typeof result.enabled).toBe('boolean');
});
it('ADMIN-SVC-030 — updateBagTracking persists the value', () => {
updateBagTracking(true);
expect((getBagTracking() as any).enabled).toBe(true);
updateBagTracking(false);
expect((getBagTracking() as any).enabled).toBe(false);
});
});
// ── Packing templates ─────────────────────────────────────────────────────────
describe('Packing templates', () => {
it('ADMIN-SVC-031 — createPackingTemplate returns template', () => {
const { user: admin } = createAdmin(testDb);
const result = createPackingTemplate('Beach Trip', admin.id) as any;
expect(result.template.name).toBe('Beach Trip');
});
it('ADMIN-SVC-032 — createPackingTemplate returns 400 for empty name', () => {
const { user: admin } = createAdmin(testDb);
const result = createPackingTemplate('', admin.id) as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-033 — listPackingTemplates returns array', () => {
const { user: admin } = createAdmin(testDb);
createPackingTemplate('Template A', admin.id);
const templates = listPackingTemplates() as any[];
expect(templates.length).toBeGreaterThanOrEqual(1);
});
it('ADMIN-SVC-034 — updatePackingTemplate updates name', () => {
const { user: admin } = createAdmin(testDb);
const created = createPackingTemplate('Old Name', admin.id) as any;
const result = updatePackingTemplate(String(created.template.id), { name: 'New Name' }) as any;
expect(result.template.name).toBe('New Name');
});
it('ADMIN-SVC-035 — updatePackingTemplate returns 404 for non-existent', () => {
const result = updatePackingTemplate('99999', { name: 'Ghost' }) as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-036 — deletePackingTemplate removes template', () => {
const { user: admin } = createAdmin(testDb);
const created = createPackingTemplate('To Delete', admin.id) as any;
const result = deletePackingTemplate(String(created.template.id)) as any;
expect(result.name).toBe('To Delete');
});
it('ADMIN-SVC-037 — deletePackingTemplate returns 404 for non-existent', () => {
const result = deletePackingTemplate('99999') as any;
expect(result.status).toBe(404);
});
});
// ── Template categories ───────────────────────────────────────────────────────
describe('Template categories', () => {
it('ADMIN-SVC-038 — createTemplateCategory creates a category', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const result = createTemplateCategory(String(tpl.template.id), 'Clothing') as any;
expect(result.category.name).toBe('Clothing');
});
it('ADMIN-SVC-039 — createTemplateCategory returns 400 for empty name', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const result = createTemplateCategory(String(tpl.template.id), '') as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-040 — createTemplateCategory returns 404 for missing template', () => {
const result = createTemplateCategory('99999', 'Clothing') as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-041 — updateTemplateCategory updates name', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Old') as any;
const result = updateTemplateCategory(String(tpl.template.id), String(cat.category.id), { name: 'New' }) as any;
expect(result.category.name).toBe('New');
});
it('ADMIN-SVC-042 — updateTemplateCategory returns 404 for missing category', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const result = updateTemplateCategory(String(tpl.template.id), '99999', { name: 'X' }) as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-043 — deleteTemplateCategory removes category', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Remove Me') as any;
const result = deleteTemplateCategory(String(tpl.template.id), String(cat.category.id)) as any;
expect(result.error).toBeUndefined();
});
it('ADMIN-SVC-044 — deleteTemplateCategory returns 404 for missing', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const result = deleteTemplateCategory(String(tpl.template.id), '99999') as any;
expect(result.status).toBe(404);
});
});
// ── getAuditLog — JSON details parsing ───────────────────────────────────────
describe('getAuditLog — JSON details', () => {
it('ADMIN-SVC-045 — parses JSON details when present', () => {
const { user } = createUser(testDb);
testDb.prepare('INSERT INTO audit_log (user_id, action, details) VALUES (?, ?, ?)').run(
user.id, 'test_action', JSON.stringify({ key: 'val' })
);
const result = getAuditLog({}) as any;
expect(result.entries.length).toBeGreaterThanOrEqual(1);
const entry = result.entries.find((e: any) => e.action === 'test_action');
expect(entry).toBeDefined();
expect(entry.details).toEqual({ key: 'val' });
});
it('ADMIN-SVC-046 — handles invalid JSON gracefully with _parse_error flag', () => {
const { user } = createUser(testDb);
testDb.prepare('INSERT INTO audit_log (user_id, action, details) VALUES (?, ?, ?)').run(
user.id, 'bad_json_action', 'not-valid-json{'
);
const result = getAuditLog({}) as any;
const entry = result.entries.find((e: any) => e.action === 'bad_json_action');
expect(entry).toBeDefined();
expect(entry.details).toEqual({ _parse_error: true });
});
});
// ── OIDC Settings ─────────────────────────────────────────────────────────────
describe('OIDC Settings', () => {
it('ADMIN-SVC-047 — getOidcSettings returns default empty values when no OIDC configured', () => {
const result = getOidcSettings() as any;
expect(result.issuer).toBe('');
expect(result.client_id).toBe('');
expect(result.oidc_only).toBe(false);
expect(result.client_secret_set).toBe(false);
expect(result.display_name).toBe('');
expect(result.discovery_url).toBe('');
});
it('ADMIN-SVC-048 — updateOidcSettings persists issuer and client_id, then getOidcSettings returns them', () => {
updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
const result = getOidcSettings() as any;
expect(result.issuer).toBe('https://auth.example.com');
expect(result.client_id).toBe('my-client');
});
it('ADMIN-SVC-049 — updateOidcSettings does not write oidc_only (replaced by granular toggles)', () => {
updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
const result = getOidcSettings() as any;
// oidc_only is no longer managed by updateOidcSettings; use password_login/oidc_login toggles
expect(result.oidc_only).toBe(false);
});
});
// ── saveDemoBaseline ──────────────────────────────────────────────────────────
describe('saveDemoBaseline', () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it('ADMIN-SVC-050 — returns 404 when DEMO_MODE is not "true"', () => {
vi.stubEnv('DEMO_MODE', 'false');
const result = saveDemoBaseline() as any;
expect(result.status).toBe(404);
expect(result.error).toBeDefined();
});
it('ADMIN-SVC-051 — returns a defined result object when DEMO_MODE is "true"', () => {
// saveDemoBaseline() uses a dynamic CJS require() whose mock cannot be
// intercepted via vi.mock in this test environment (tsx runtime + CJS loader).
// The function either succeeds (message) or falls through the catch to a
// 500 error. Either way the result must be a defined, non-null object.
vi.stubEnv('DEMO_MODE', 'true');
const result = saveDemoBaseline() as any;
expect(result).toBeDefined();
expect(typeof result).toBe('object');
// The 404 branch must NOT be taken — DEMO_MODE is "true".
expect(result.status).not.toBe(404);
});
});
// ── getGithubReleases ─────────────────────────────────────────────────────────
describe('getGithubReleases', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('ADMIN-SVC-052 — returns empty array when fetch fails', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network error')));
const result = await getGithubReleases();
expect(Array.isArray(result)).toBe(true);
expect(result).toHaveLength(0);
});
it('ADMIN-SVC-053 — returns releases array when fetch succeeds', async () => {
const mockReleases = [
{ id: 1, tag_name: 'v3.0.0', name: 'Release 3.0.0', html_url: 'https://github.com/example/releases/tag/v3.0.0' },
{ id: 2, tag_name: 'v2.9.9', name: 'Release 2.9.9', html_url: 'https://github.com/example/releases/tag/v2.9.9' },
];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => mockReleases,
}));
const result = await getGithubReleases();
expect(Array.isArray(result)).toBe(true);
expect(result).toHaveLength(2);
expect((result as any[])[0].tag_name).toBe('v3.0.0');
});
});
// ── checkVersion ──────────────────────────────────────────────────────────────
describe('checkVersion', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('ADMIN-SVC-054 — returns update_available:false when fetch fails', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network error')));
const result = await checkVersion() as any;
expect(result.update_available).toBe(false);
expect(result.current).toBeDefined();
expect(result.latest).toBeDefined();
});
it('ADMIN-SVC-055 — returns update_available:true when latest version is greater than current', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ tag_name: 'v999.0.0', html_url: 'https://github.com/example/releases/tag/v999.0.0' }),
}));
const result = await checkVersion() as any;
expect(result.update_available).toBe(true);
expect(result.latest).toBe('999.0.0');
expect(result.release_url).toBe('https://github.com/example/releases/tag/v999.0.0');
});
});
// ── getPackingTemplate ────────────────────────────────────────────────────────
describe('getPackingTemplate', () => {
it('ADMIN-SVC-056 — returns template with categories and items when template exists', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Full Template', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Clothing') as any;
createTemplateItem(String(tpl.template.id), String(cat.category.id), 'T-Shirt');
const result = getPackingTemplate(String(tpl.template.id)) as any;
expect(result.template).toBeDefined();
expect(result.template.name).toBe('Full Template');
expect(Array.isArray(result.categories)).toBe(true);
expect(result.categories.length).toBeGreaterThanOrEqual(1);
expect(Array.isArray(result.items)).toBe(true);
expect(result.items.length).toBeGreaterThanOrEqual(1);
expect(result.items[0].name).toBe('T-Shirt');
});
it('ADMIN-SVC-057 — returns 404 for non-existent template', () => {
const result = getPackingTemplate('99999') as any;
expect(result.status).toBe(404);
expect(result.error).toBeDefined();
});
});
// ── Template items ────────────────────────────────────────────────────────────
describe('Template items', () => {
it('ADMIN-SVC-058 — createTemplateItem returns item with name', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any;
const result = createTemplateItem(String(tpl.template.id), String(cat.category.id), 'Backpack') as any;
expect(result.item).toBeDefined();
expect(result.item.name).toBe('Backpack');
});
it('ADMIN-SVC-059 — createTemplateItem returns 400 for empty name', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any;
const result = createTemplateItem(String(tpl.template.id), String(cat.category.id), '') as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-060 — createTemplateItem returns 404 for non-existent category', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const result = createTemplateItem(String(tpl.template.id), '99999', 'Item') as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-061 — updateTemplateItem updates name', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any;
const item = createTemplateItem(String(tpl.template.id), String(cat.category.id), 'Old Item') as any;
const result = updateTemplateItem(String(item.item.id), { name: 'New Item' }) as any;
expect(result.item.name).toBe('New Item');
});
it('ADMIN-SVC-062 — updateTemplateItem returns 404 for non-existent item', () => {
const result = updateTemplateItem('99999', { name: 'Ghost' }) as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-063 — deleteTemplateItem removes item', () => {
const { user: admin } = createAdmin(testDb);
const tpl = createPackingTemplate('Tpl', admin.id) as any;
const cat = createTemplateCategory(String(tpl.template.id), 'Gear') as any;
const item = createTemplateItem(String(tpl.template.id), String(cat.category.id), 'To Delete') as any;
const result = deleteTemplateItem(String(item.item.id)) as any;
expect(result.error).toBeUndefined();
const check = testDb.prepare('SELECT id FROM packing_template_items WHERE id = ?').get(item.item.id);
expect(check).toBeUndefined();
});
it('ADMIN-SVC-064 — deleteTemplateItem returns 404 for non-existent item', () => {
const result = deleteTemplateItem('99999') as any;
expect(result.status).toBe(404);
});
});
// ── listAddons ────────────────────────────────────────────────────────────────
describe('listAddons', () => {
it('ADMIN-SVC-065 — listAddons returns array containing seeded addon entries', () => {
const result = listAddons() as any[];
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBeGreaterThan(0);
const addonIds = result.map((a: any) => a.id);
expect(addonIds).toContain('packing');
expect(addonIds).toContain('budget');
});
});
// ── updateAddon ───────────────────────────────────────────────────────────────
describe('updateAddon', () => {
it('ADMIN-SVC-066 — updateAddon enables and disables a seeded addon', () => {
const disabled = updateAddon('mcp', { enabled: false }) as any;
expect(disabled.addon).toBeDefined();
expect(disabled.addon.enabled).toBe(false);
const enabled = updateAddon('mcp', { enabled: true }) as any;
expect(enabled.addon.enabled).toBe(true);
});
it('ADMIN-SVC-067 — updateAddon returns 404 for unknown addon id', () => {
const result = updateAddon('nonexistent-addon-xyz', { enabled: true }) as any;
expect(result.status).toBe(404);
expect(result.error).toBeDefined();
});
it('ADMIN-SVC-069 — mcpAffected only fires on a real enabled-flip of an MCP-relevant addon (#1414)', () => {
updateAddon('packing', { enabled: true });
// no-op save (enabled already true) → sessions survive
expect((updateAddon('packing', { enabled: true }) as any).mcpAffected).toBe(false);
// config-only save → sessions survive
expect((updateAddon('packing', { config: { foo: 'bar' } }) as any).mcpAffected).toBe(false);
// real flip of an MCP-relevant addon → invalidate
expect((updateAddon('packing', { enabled: false }) as any).mcpAffected).toBe(true);
expect((updateAddon('packing', { enabled: true }) as any).mcpAffected).toBe(true);
// real flip of an addon with no MCP surface → sessions survive
const docsFlip = updateAddon('documents', { enabled: false }) as any;
if (!docsFlip.error) expect(docsFlip.mcpAffected).toBe(false);
});
});
describe('updateCollabFeatures', () => {
it('ADMIN-SVC-070 — reports whether a flag actually flipped (#1414)', () => {
const first = updateCollabFeatures({ chat: false });
expect(first.changed).toBe(true);
expect(first.features.chat).toBe(false);
// identical save → no change, MCP sessions must survive
const second = updateCollabFeatures({ chat: false });
expect(second.changed).toBe(false);
const third = updateCollabFeatures({ chat: true });
expect(third.changed).toBe(true);
});
});
// ── MCP Tokens ────────────────────────────────────────────────────────────────
describe('MCP Tokens', () => {
it('ADMIN-SVC-068 — listMcpTokens returns empty array initially', () => {
const result = listMcpTokens() as any[];
expect(Array.isArray(result)).toBe(true);
expect(result).toHaveLength(0);
});
it('ADMIN-SVC-069 — deleteMcpToken returns 404 for non-existent token', () => {
const result = deleteMcpToken('99999') as any;
expect(result.status).toBe(404);
expect(result.error).toBeDefined();
});
});
@@ -8,20 +8,52 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
* doesn't actually chain.
*/
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
vi.mock('../../../src/services/airtrail/airtrailService', () => ({
getAirtrailCredentials: vi.fn(() => ({ baseUrl: 'https://at.example', apiKey: 'k', allowInsecureTls: false })),
}));
vi.mock('../../../src/services/airtrail/airtrailClient', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../../src/services/airtrail/airtrailClient')>();
return { ...actual, listFlights: vi.fn() };
});
import { db } from '../../../src/db/database';
import { createUser, createTrip } from '../../helpers/factories';
import { listFlights } from '../../../src/services/airtrail/airtrailClient';
import type { AirtrailAirport, AirtrailFlightRaw } from '../../../src/services/airtrail/airtrailClient';
import { importAirtrailFlights } from '../../../src/services/airtrail/airtrailImport';
import type { AirtrailAirport, AirtrailFlightRaw } from '../../../src/nest/integrations/airtrail.client';
import { AirtrailImportService } from '../../../src/nest/integrations/airtrail-import.service';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { BudgetService } from '../../../src/nest/budget/budget.service';
import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service';
import { ReservationsService } from '../../../src/nest/reservations/reservations.service';
import { ReservationsReadRepository } from '../../../src/nest/reservations/reservations-read.repository';
import type { AirtrailClient } from '../../../src/nest/integrations/airtrail.client';
import type { AirtrailService } from '../../../src/nest/integrations/airtrail.service';
import { notificationsStub } from '../../helpers/notifications';
// The client and the per-user credentials are the only stubs; the reservation
// writes go through the real service against the real test DB, as before. They
// were module mocks until the fold made them injected collaborators.
const listFlights = vi.fn();
const broadcast = vi.fn();
function makeImportService(): AirtrailImportService {
const dbs = () => new DatabaseService(db);
const permissions = new PermissionsService(dbs());
const realtime = { broadcast } as unknown as RealtimeService;
return new AirtrailImportService(
dbs(),
realtime,
new ReservationsService(
dbs(),
permissions,
new BudgetService(dbs(), permissions, new ExchangeRatesService(), realtime),
realtime,
notificationsStub(),
new ReservationsReadRepository(dbs()),
),
{ listFlights } as unknown as AirtrailClient,
{
getAirtrailCredentials: () => ({ baseUrl: 'https://at.example', apiKey: 'k', allowInsecureTls: false }),
} as unknown as AirtrailService,
);
}
const importAirtrailFlights = (
...args: Parameters<AirtrailImportService['importAirtrailFlights']>
) => makeImportService().importAirtrailFlights(...args);
const BRU: AirtrailAirport = { id: 1, icao: 'EBBR', iata: 'BRU', name: 'Brussels', lat: 50.9014, lon: 4.4844, tz: 'Europe/Brussels', country: 'BE' };
const HEL: AirtrailAirport = { id: 2, icao: 'EFHK', iata: 'HEL', name: 'Helsinki-Vantaa', lat: 60.3172, lon: 24.9633, tz: 'Europe/Helsinki', country: 'FI' };
@@ -93,7 +125,7 @@ beforeEach(() => {
describe('importAirtrailFlights connection joining (#1535)', () => {
it('imports a connection chain as ONE multi-leg reservation, detached from live sync', async () => {
(listFlights as any).mockResolvedValue([legBruHel(), legHelJfk()]);
listFlights.mockResolvedValue([legBruHel(), legHelJfk()]);
// Deliberately unordered — the server orders the chain by departure itself.
const result = await importAirtrailFlights(tripId, userId, ['101', '102'], undefined, [['102', '101']]);
@@ -131,7 +163,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => {
departure: '2026-08-02T07:00:00.000+00:00',
arrival: '2026-08-02T15:00:00.000+00:00',
};
(listFlights as any).mockResolvedValue([legBruHel(), overnightLeg2]);
listFlights.mockResolvedValue([legBruHel(), overnightLeg2]);
await importAirtrailFlights(tripId, userId, ['101', '102'], undefined, [['101', '102']]);
const [r] = tripReservations(tripId);
@@ -152,7 +184,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => {
arrival: '2026-08-01T21:30:00.000+00:00',
flightNumber: 'AY1503',
};
(listFlights as any).mockResolvedValue([legBruHel(), returnFlight]);
listFlights.mockResolvedValue([legBruHel(), returnFlight]);
const result = await importAirtrailFlights(tripId, userId, ['101', '104'], undefined, [['101', '104']]);
expect([...result.imported].sort()).toEqual(['101', '104']);
@@ -160,7 +192,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => {
});
it('skips every member of a joined booking on a later import attempt', async () => {
(listFlights as any).mockResolvedValue([legBruHel(), legHelJfk()]);
listFlights.mockResolvedValue([legBruHel(), legHelJfk()]);
await importAirtrailFlights(tripId, userId, ['101', '102'], undefined, [['101', '102']]);
// Only leg 2 carries no external_id of its own — it must still be recognized
@@ -172,13 +204,13 @@ describe('importAirtrailFlights connection joining (#1535)', () => {
});
it('recognizes a joined leg imported by another member via its per-leg signature', async () => {
(listFlights as any).mockResolvedValue([legBruHel(), legHelJfk()]);
listFlights.mockResolvedValue([legBruHel(), legHelJfk()]);
await importAirtrailFlights(tripId, userId, ['101', '102'], undefined, [['101', '102']]);
// The same physical HEL→JFK flight from another member's AirTrail carries a
// different id there — the flight-number@date signature must catch it.
const { user: other } = createUser(db);
(listFlights as any).mockResolvedValue([{ ...legHelJfk(), id: 999 }]);
listFlights.mockResolvedValue([{ ...legHelJfk(), id: 999 }]);
const result = await importAirtrailFlights(tripId, other.id, ['999'], undefined);
expect(result.imported).toEqual([]);
expect(result.skipped).toEqual([{ flightId: '999', reason: 'already-in-trip', detail: expect.any(String) }]);
@@ -186,7 +218,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => {
});
it('falls back to individual imports when the requested join does not chain', async () => {
(listFlights as any).mockResolvedValue([legBruHel(), legLhrJfk()]);
listFlights.mockResolvedValue([legBruHel(), legLhrJfk()]);
const result = await importAirtrailFlights(tripId, userId, ['101', '103'], undefined, [['101', '103']]);
expect([...result.imported].sort()).toEqual(['101', '103']);
@@ -201,7 +233,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => {
it('falls back to individual imports when the layover exceeds 24 h', async () => {
const lateLeg2 = { ...legHelJfk(), departure: '2026-08-03T11:00:00.000+00:00', arrival: '2026-08-03T19:00:00.000+00:00', date: '2026-08-03' };
(listFlights as any).mockResolvedValue([legBruHel(), lateLeg2]);
listFlights.mockResolvedValue([legBruHel(), lateLeg2]);
const result = await importAirtrailFlights(tripId, userId, ['101', '102'], undefined, [['101', '102']]);
expect([...result.imported].sort()).toEqual(['101', '102']);
@@ -209,7 +241,7 @@ describe('importAirtrailFlights connection joining (#1535)', () => {
});
it('imports singles exactly as before when no join is requested', async () => {
(listFlights as any).mockResolvedValue([legBruHel()]);
listFlights.mockResolvedValue([legBruHel()]);
const result = await importAirtrailFlights(tripId, userId, ['101'], undefined);
expect(result.imported).toEqual(['101']);
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import { canonicalHash, mapFlightToReservation, mapFlightsToMultiLegReservation, normalizeFlight } from '../../../src/services/airtrail/airtrailMapper';
import type { AirtrailFlightRaw } from '../../../src/services/airtrail/airtrailClient';
import { canonicalHash, mapFlightToReservation, mapFlightsToMultiLegReservation, normalizeFlight } from '../../../src/nest/integrations/airtrail.mapper';
import type { AirtrailFlightRaw } from '../../../src/nest/integrations/airtrail.client';
function airport(over: Partial<AirtrailFlightRaw['from']> = {}): NonNullable<AirtrailFlightRaw['from']> {
return {
@@ -309,3 +309,68 @@ describe('airtrailMapper.mapFlightsToMultiLegReservation (#1535)', () => {
expect(mapFlightsToMultiLegReservation([flight()])).toEqual(mapFlightToReservation(flight()));
});
});
// AirTrail 3.12.0 renamed the passenger list from `seats` to `passengers` and
// moved flightReason from the flight onto each passenger, with no alias either
// way (#1931). The shapes below are the ones a real 3.12.0 and a real 3.11.1
// return: each sends its own key and null for the other.
describe('airtrailMapper — AirTrail 3.12.0 passengers', () => {
const newShape = (over: Partial<AirtrailFlightRaw> = {}) =>
flight({
seats: null as never,
flightReason: null,
passengers: [{ userId: 'u1', guestName: null, seat: 'window', seatNumber: '12A', seatClass: 'economy', flightReason: 'business' }],
...over,
});
it('reads the seat off passengers', () => {
expect(mapFlightToReservation(newShape()).metadata.seat).toBe('12A');
});
it('reads the seat class off passengers', () => {
expect(normalizeFlight(newShape()).seatClass).toBe('economy');
});
it('takes the flight reason off the passenger now that the flight has none', () => {
expect(mapFlightToReservation(newShape()).metadata.flight_reason).toBe('business');
});
it('prefers the entry belonging to the key owner over a co-passenger', () => {
const m = mapFlightToReservation(newShape({
passengers: [
{ userId: null, guestName: 'Plus One', seat: null, seatNumber: '30C', seatClass: null },
{ userId: 'u1', guestName: null, seat: 'window', seatNumber: '12A', seatClass: 'economy' },
],
}));
expect(m.metadata.seat).toBe('12A');
});
it('still reads the old shape, so an older instance keeps working', () => {
const m = mapFlightToReservation(flight());
expect(m.metadata.seat).toBe('12A');
expect(m.metadata.flight_reason).toBe('leisure');
});
it('carries the per-leg seat through the multi-leg mapping', () => {
const legs = mapFlightsToMultiLegReservation([
newShape({ id: 1 }),
newShape({ id: 2, passengers: [{ userId: 'u1', guestName: null, seat: null, seatNumber: '3F', seatClass: null }] }),
]).metadata.legs as any[];
expect(legs.map(l => l.seat)).toEqual(['12A', '3F']);
});
// The snapshot hash decides whether a pull re-imports a flight. Feeding it from
// either shape under the same key keeps an unchanged old-shape flight hashing
// exactly as before, so upgrading TREK must not re-sync every flight.
it('leaves the hash of an unchanged old-shape flight alone', () => {
// Pinned to what the pre-#1931 snapshot produced for this fixture. If this
// ever has to be re-pinned, every existing AirTrail flight re-syncs once.
expect(canonicalHash(flight())).toBe('81d00fb3b22dffa5575221f73c959f5762e50e20e9c5cf7ecc5a485a1845b358');
});
it('hashes the new shape as the same flight as the old one', () => {
const asOld = flight({ flightReason: 'business' });
const asNew = newShape();
expect(canonicalHash(asNew)).toBe(canonicalHash(asOld));
});
});
@@ -1,6 +1,13 @@
import { describe, it, expect } from 'vitest';
import { buildSavePayload } from '../../../src/services/airtrail/airtrailSync';
import type { AirtrailAirport, AirtrailFlightRaw } from '../../../src/services/airtrail/airtrailClient';
import { buildSavePayload } from '../../../src/nest/integrations/airtrail-sync.service';
import type { AirtrailAirport, AirtrailFlightRaw, AirtrailSavePayload } from '../../../src/nest/integrations/airtrail.client';
/**
* buildSavePayload spreads the raw flight, so the body also carries the
* AirTrail-owned keys the save type deliberately leaves unmodelled (terminal,
* gate, actual times, customFields, track). Read those through this view.
*/
type SavePayloadWithPassthrough = AirtrailSavePayload & Record<string, unknown>;
function airport(over: Partial<AirtrailAirport> = {}): AirtrailAirport {
return {
@@ -125,7 +132,7 @@ describe('airtrailSync.buildSavePayload', () => {
metadata: JSON.stringify({ airline: 'BAW', flight_number: 'BA999', seat: '3C' }),
}),
existingFlight(),
);
) as SavePayloadWithPassthrough | null;
expect(payload).toMatchObject({
id: 42,
from: 'JFK',
@@ -176,3 +183,64 @@ describe('airtrailSync.buildSavePayload', () => {
expect(payload).toBeNull();
});
});
// AirTrail 3.12.0 renamed the passenger list from `seats` to `passengers`, with
// no alias on the save endpoint either (#1931). Neither schema is strict, so the
// payload carries both names and each version keeps the one it knows.
describe('airtrailSync.buildSavePayload — AirTrail 3.12.0 passengers', () => {
const newShape = (over: Partial<AirtrailFlightRaw> & Record<string, unknown> = {}) =>
existingFlight({
seats: undefined,
flightReason: undefined,
passengers: [{ userId: 'u1', guestName: null, seat: 'window', seatNumber: '12A', seatClass: 'economy', flightReason: 'leisure' }],
...over,
});
const own = (list: unknown) => (list as Array<{ userId: string | null }>).find(s => s.userId);
it('sends the manifest under both names', () => {
const payload = buildSavePayload(reservation(), newShape()) as SavePayloadWithPassthrough;
expect(payload.passengers).toEqual(payload.seats);
expect(own(payload.passengers)).toMatchObject({ seatNumber: '12A', seatClass: 'economy' });
});
it('reads the existing manifest off passengers and pushes the TREK seat onto it', () => {
const res = reservation({ metadata: JSON.stringify({ seat: '22F' }) });
const payload = buildSavePayload(res, newShape()) as SavePayloadWithPassthrough;
expect(own(payload.passengers)).toMatchObject({ seatNumber: '22F' });
expect(own(payload.seats)).toMatchObject({ seatNumber: '22F' });
// A co-passenger's seat is not TREK's to touch.
const withGuest = buildSavePayload(res, newShape({
passengers: [
{ userId: null, guestName: 'Plus One', seat: null, seatNumber: '30C', seatClass: null },
{ userId: 'u1', guestName: null, seat: 'window', seatNumber: '12A', seatClass: 'economy' },
],
})) as SavePayloadWithPassthrough;
const guest = (withGuest.passengers as Array<{ guestName: string | null; seatNumber: string | null }>).find(s => s.guestName);
expect(guest?.seatNumber).toBe('30C');
});
it('writes the flight reason both on the flight and on the passenger', () => {
const payload = buildSavePayload(reservation(), newShape()) as SavePayloadWithPassthrough;
expect(payload.flightReason).toBe('leisure');
expect(own(payload.passengers)).toMatchObject({ flightReason: 'leisure' });
});
it('recovers the reason from the passenger when the flight no longer carries one', () => {
const res = reservation({ metadata: JSON.stringify({ seat: '12A' }) });
const payload = buildSavePayload(res, newShape()) as SavePayloadWithPassthrough;
expect(payload.flightReason).toBe('leisure');
});
it('still fills the manifest from the old shape', () => {
const payload = buildSavePayload(reservation(), existingFlight()) as SavePayloadWithPassthrough;
expect(own(payload.passengers)).toMatchObject({ seatNumber: '12A' });
expect(own(payload.seats)).toMatchObject({ seatNumber: '12A' });
});
it('falls back to the key-owner placeholder when the flight has no manifest at all', () => {
const payload = buildSavePayload(reservation(), newShape({ passengers: [] })) as SavePayloadWithPassthrough;
expect(payload.passengers).toHaveLength(1);
expect(own(payload.passengers)).toMatchObject({ userId: '<USER_ID>', seatNumber: '12A' });
});
});
@@ -2,66 +2,99 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
/**
* The #1240 write gate: pushReservationToAirtrail must NOT write to AirTrail unless
* the flight's owner has opted in (airtrail_write_enabled). Collaborators are mocked
* the flight's owner has opted in (airtrail_write_enabled). Collaborators are stubbed
* so the test exercises just the gate + payload wiring.
*
* They used to be module mocks over free functions. The fold made them injected
* services, so the stubs go through the constructor now — which is the point:
* the collaborators are visible in the signature instead of resolved by path.
* Only the mapper stays a module mock, because it stayed free functions.
*/
vi.mock('../../../src/db/database', () => ({ db: { prepare: vi.fn() } }));
vi.mock('../../../src/services/adminService', () => ({ isAddonEnabled: vi.fn(() => true) }));
vi.mock('../../../src/services/auditLog', () => ({ logError: vi.fn(), logInfo: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
vi.mock('../../../src/services/reservationService', () => ({
getReservation: vi.fn(),
getReservationWithJoins: vi.fn(),
updateReservation: vi.fn(),
}));
vi.mock('../../../src/services/airtrail/airtrailClient', () => ({
AirtrailAuthError: class AirtrailAuthError extends Error {},
getFlight: vi.fn(),
listFlights: vi.fn(),
saveFlight: vi.fn(),
}));
vi.mock('../../../src/services/airtrail/airtrailMapper', () => ({
vi.mock('../../../src/nest/integrations/airtrail.mapper', () => ({
canonicalHash: vi.fn(() => 'hash'),
mapFlightToReservation: vi.fn(() => ({})),
entityCode: (e: any) => e?.icao || e?.iata || null,
}));
vi.mock('../../../src/services/airtrail/airtrailService', () => ({
isAirtrailWriteEnabled: vi.fn(),
getAirtrailCredentials: vi.fn(),
}));
import { pushReservationToAirtrail, runAirtrailSyncForUser } from '../../../src/services/airtrail/airtrailSync';
import { db } from '../../../src/db/database';
import { getReservation, getReservationWithJoins, updateReservation } from '../../../src/services/reservationService';
import { getFlight, listFlights, saveFlight } from '../../../src/services/airtrail/airtrailClient';
import { isAirtrailWriteEnabled, getAirtrailCredentials } from '../../../src/services/airtrail/airtrailService';
import { AirtrailLinkService } from '../../../src/nest/integrations/airtrail-link.service';
import { AirtrailAuthError } from '../../../src/nest/integrations/airtrail.client';
import type { DatabaseService } from '../../../src/nest/database/database.service';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { AirtrailSyncService } from '../../../src/nest/integrations/airtrail-sync.service';
import type { ReservationsService } from '../../../src/nest/reservations/reservations.service';
import type { ReservationsReadRepository } from '../../../src/nest/reservations/reservations-read.repository';
import type { AirtrailClient } from '../../../src/nest/integrations/airtrail.client';
import type { AirtrailService } from '../../../src/nest/integrations/airtrail.service';
const linkedRow = { id: 5, trip_id: 9, external_id: '42', external_owner_user_id: 7, sync_enabled: 1 };
const runSpy = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
// Route db reads: global sync setting, the linked reservation row and the
// endpoint count the multi-leg guard checks (#1535) — two = plain from/to.
(db.prepare as any).mockImplementation((sql: string) => ({
get: () => {
if (sql.includes('app_settings')) return { value: 'true' };
if (sql.includes('FROM reservation_endpoints')) return { n: 2 };
if (sql.includes('FROM reservations')) return { ...linkedRow };
return undefined;
},
run: (...args: any[]) => {
const runSpy = vi.fn();
const getFlight = vi.fn();
const listFlights = vi.fn();
const saveFlight = vi.fn();
const getReservation = vi.fn();
const getReservationWithJoins = vi.fn();
const updateReservation = vi.fn();
const isAirtrailWriteEnabled = vi.fn();
const getAirtrailCredentials = vi.fn();
/** Routes reads by SQL, exactly as the old db.prepare stub did. */
let dbGet: (sql: string) => unknown;
let dbAll: (sql: string) => unknown[];
function makeServices(): { link: AirtrailLinkService; sync: AirtrailSyncService } {
const db = {
get: (sql: string) => dbGet(sql),
all: (sql: string) => dbAll(sql),
run: (sql: string, ...args: unknown[]) => {
runSpy(sql, args);
return {};
},
all: () => [],
}));
(getAirtrailCredentials as any).mockReturnValue({ baseUrl: 'https://at.example', apiKey: 'k', allowInsecureTls: false });
} as unknown as DatabaseService;
const client = { getFlight, listFlights, saveFlight } as unknown as AirtrailClient;
const airtrail = { isAirtrailWriteEnabled, getAirtrailCredentials } as unknown as AirtrailService;
// The push and the shared link lifecycle live on AirtrailLinkService since the
// core/pull split (which retired airtrail.bridge); the pull delegates to it.
const link = new AirtrailLinkService(
db,
{ broadcast: vi.fn() } as unknown as RealtimeService,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
{ getReservationWithJoins } as unknown as ReservationsReadRepository,
client,
airtrail,
);
const sync = new AirtrailSyncService(
db,
link,
{ getReservation, update: updateReservation } as unknown as ReservationsService,
client,
airtrail,
);
return { link, sync };
}
let svc: { link: AirtrailLinkService; sync: AirtrailSyncService };
beforeEach(() => {
vi.clearAllMocks();
// Global sync setting, the linked reservation row and the endpoint count the
// multi-leg guard checks (#1535) — two = plain from/to.
dbGet = (sql: string) => {
if (sql.includes('app_settings')) return { value: 'true' };
if (sql.includes('FROM reservation_endpoints')) return { n: 2 };
if (sql.includes('FROM reservations')) return { ...linkedRow };
return undefined;
};
dbAll = () => [];
svc = makeServices();
getAirtrailCredentials.mockReturnValue({ baseUrl: 'https://at.example', apiKey: 'k', allowInsecureTls: false });
// GET returns AirTrail-owned detail TREK doesn't model — must survive the writeback.
(getFlight as any).mockResolvedValue({ id: 42, from: { iata: 'JFK' }, to: { iata: 'LHR' }, seats: [], departureTerminal: '7' });
(saveFlight as any).mockResolvedValue({ id: 42 });
(getReservationWithJoins as any).mockReturnValue({
getFlight.mockResolvedValue({ id: 42, from: { iata: 'JFK' }, to: { iata: 'LHR' }, seats: [], departureTerminal: '7' });
saveFlight.mockResolvedValue({ id: 42 });
getReservationWithJoins.mockReturnValue({
external_id: '42',
reservation_time: '2021-09-01T19:00',
reservation_end_time: '2021-09-02T08:00',
@@ -76,101 +109,117 @@ beforeEach(() => {
describe('pushReservationToAirtrail write gate (#1240)', () => {
it('does nothing — and does not detach — when the owner has not opted in', async () => {
(isAirtrailWriteEnabled as any).mockReturnValue(false);
await pushReservationToAirtrail(5, 9);
isAirtrailWriteEnabled.mockReturnValue(false);
await svc.link.pushReservationToAirtrail(5, 9);
expect(getFlight).not.toHaveBeenCalled();
expect(saveFlight).not.toHaveBeenCalled();
expect(runSpy).not.toHaveBeenCalled(); // no detach, no hash write — pure no-op
});
it('writes back, preserving AirTrail-owned fields, when the owner has opted in', async () => {
(isAirtrailWriteEnabled as any).mockReturnValue(true);
await pushReservationToAirtrail(5, 9);
isAirtrailWriteEnabled.mockReturnValue(true);
await svc.link.pushReservationToAirtrail(5, 9);
expect(saveFlight).toHaveBeenCalledTimes(1);
const payload = (saveFlight as any).mock.calls[0][1];
const payload = saveFlight.mock.calls[0][1] as Record<string, unknown>;
expect(payload.departureTerminal).toBe('7'); // spread preserved the unmanaged field
expect(payload.from).toBe('JFK'); // TREK-managed field still applied as a code
});
it('#1535 detaches instead of pushing when the reservation grew extra stops', async () => {
(isAirtrailWriteEnabled as any).mockReturnValue(true);
(db.prepare as any).mockImplementation((sql: string) => ({
get: () => {
if (sql.includes('app_settings')) return { value: 'true' };
if (sql.includes('FROM reservation_endpoints')) return { n: 3 }; // from + stop + to
if (sql.includes('FROM reservations')) return { ...linkedRow };
return undefined;
},
run: (...args: any[]) => {
runSpy(sql, args);
return {};
},
all: () => [],
}));
await pushReservationToAirtrail(5, 9);
isAirtrailWriteEnabled.mockReturnValue(true);
dbGet = (sql: string) => {
if (sql.includes('app_settings')) return { value: 'true' };
if (sql.includes('FROM reservation_endpoints')) return { n: 3 }; // from + stop + to
if (sql.includes('FROM reservations')) return { ...linkedRow };
return undefined;
};
await svc.link.pushReservationToAirtrail(5, 9);
// Pushing would rewrite the single AirTrail flight to span the whole route.
expect(saveFlight).not.toHaveBeenCalled();
expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]);
});
it('#1535 detaches on metadata.legs even when the endpoint count is not available', async () => {
(isAirtrailWriteEnabled as any).mockReturnValue(true);
(getReservationWithJoins as any).mockReturnValue({
isAirtrailWriteEnabled.mockReturnValue(true);
getReservationWithJoins.mockReturnValue({
external_id: '42',
reservation_time: '2021-09-01T19:00',
metadata: JSON.stringify({ legs: [{ from: 'BRU', to: 'HEL' }, { from: 'HEL', to: 'JFK' }] }),
endpoints: [],
});
await pushReservationToAirtrail(5, 9);
await svc.link.pushReservationToAirtrail(5, 9);
expect(saveFlight).not.toHaveBeenCalled();
expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]);
});
it('detaches when the owner key stopped working, rather than retrying forever', async () => {
isAirtrailWriteEnabled.mockReturnValue(true);
getFlight.mockRejectedValue(new AirtrailAuthError('invalid key'));
await svc.link.pushReservationToAirtrail(5, 9);
expect(saveFlight).not.toHaveBeenCalled();
expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]);
});
it('detaches when the flight is gone from AirTrail — the same as a remote delete', async () => {
isAirtrailWriteEnabled.mockReturnValue(true);
getFlight.mockResolvedValue(null);
await svc.link.pushReservationToAirtrail(5, 9);
expect(saveFlight).not.toHaveBeenCalled();
expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]);
});
});
describe('inbound sync multi-leg guard (#1535)', () => {
function withLinkedRow(endpointCount: number) {
dbGet = (sql: string) => {
if (sql.includes('app_settings')) return { value: 'true' };
if (sql.includes('FROM reservation_endpoints')) return { n: endpointCount };
return undefined;
};
dbAll = (sql: string) =>
sql.includes('sync_enabled = 1') ? [{ id: 5, trip_id: 9, external_id: '42', external_hash: 'stale' }] : [];
svc = makeServices();
}
it('detaches instead of flattening when a linked reservation grew extra stops locally', async () => {
// A remote change is pending (stored hash differs from canonicalHash's
// 'hash'), but the local reservation has become multi-leg — applying the
// single-flight shape would flatten the layover chain.
(db.prepare as any).mockImplementation((sql: string) => ({
get: () => {
if (sql.includes('app_settings')) return { value: 'true' };
if (sql.includes('FROM reservation_endpoints')) return { n: 3 };
return undefined;
},
all: () => (sql.includes('sync_enabled = 1') ? [{ id: 5, trip_id: 9, external_id: '42', external_hash: 'stale' }] : []),
run: (...args: any[]) => {
runSpy(sql, args);
return {};
},
}));
(listFlights as any).mockResolvedValue([{ id: 42 }]);
(getReservation as any).mockReturnValue({ id: 5, metadata: JSON.stringify({}) });
withLinkedRow(3);
listFlights.mockResolvedValue([{ id: 42 }]);
getReservation.mockReturnValue({ id: 5, metadata: JSON.stringify({}) });
const { changed } = await runAirtrailSyncForUser(7);
const { changed } = await svc.sync.runAirtrailSyncForUser(7);
expect(updateReservation).not.toHaveBeenCalled();
expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]);
expect(changed).toBe(1);
});
it('still applies a remote change to a plain single-leg reservation', async () => {
(db.prepare as any).mockImplementation((sql: string) => ({
get: () => {
if (sql.includes('app_settings')) return { value: 'true' };
if (sql.includes('FROM reservation_endpoints')) return { n: 2 };
return undefined;
},
all: () => (sql.includes('sync_enabled = 1') ? [{ id: 5, trip_id: 9, external_id: '42', external_hash: 'stale' }] : []),
run: (...args: any[]) => {
runSpy(sql, args);
return {};
},
}));
(listFlights as any).mockResolvedValue([{ id: 42 }]);
(getReservation as any).mockReturnValue({ id: 5, metadata: JSON.stringify({}) });
withLinkedRow(2);
listFlights.mockResolvedValue([{ id: 42 }]);
getReservation.mockReturnValue({ id: 5, metadata: JSON.stringify({}) });
await runAirtrailSyncForUser(7);
await svc.sync.runAirtrailSyncForUser(7);
expect(updateReservation).toHaveBeenCalledTimes(1);
expect(runSpy).not.toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), expect.anything());
});
it('detaches a flight that vanished from AirTrail, keeping the TREK row', async () => {
withLinkedRow(2);
listFlights.mockResolvedValue([]); // the linked id is no longer there
const { changed } = await svc.sync.runAirtrailSyncForUser(7);
expect(updateReservation).not.toHaveBeenCalled();
expect(runSpy).toHaveBeenCalledWith(expect.stringContaining('sync_enabled = 0'), [5]);
expect(changed).toBe(1);
});
it('leaves a disconnected owner alone rather than detaching their rows', async () => {
withLinkedRow(2);
getAirtrailCredentials.mockReturnValue(null);
const { changed } = await svc.sync.runAirtrailSyncForUser(7);
expect(listFlights).not.toHaveBeenCalled();
expect(runSpy).not.toHaveBeenCalled();
expect(changed).toBe(0);
});
});
@@ -8,11 +8,21 @@ vi.mock('../../../src/utils/ssrfGuard', () => ({
import { db } from '../../../src/db/database';
import { createUser } from '../../helpers/factories';
import {
getConnectionSettings,
isAirtrailWriteEnabled,
saveSettings,
} from '../../../src/services/airtrail/airtrailService';
import { AirtrailService } from '../../../src/nest/integrations/airtrail.service';
import { AirtrailClient } from '../../../src/nest/integrations/airtrail.client';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { AuditService } from '../../../src/nest/database/../audit/audit.service';
// The free functions became methods with the airtrail fold; same SQL, same
// behaviour, one instance over the same db handle.
const svc = new AirtrailService(
new DatabaseService(db),
new AuditService(new DatabaseService(db)),
new AirtrailClient(),
);
const getConnectionSettings = svc.getConnectionSettings.bind(svc);
const isAirtrailWriteEnabled = svc.isAirtrailWriteEnabled.bind(svc);
const saveSettings = svc.saveSettings.bind(svc);
describe('airtrail writeback opt-in persistence (#1240)', () => {
it('defaults the writeback opt-in to off for a new user', () => {
@@ -7,7 +7,12 @@ vi.mock('../../../src/config', () => ({
updateJwtSecret: () => {},
}));
import { encrypt_api_key, decrypt_api_key, maybe_encrypt_api_key } from '../../../src/services/apiKeyCrypto';
import {
encrypt_api_key,
decrypt_api_key,
maybe_encrypt_api_key,
is_encrypted_api_key,
} from '../../../src/nest/common/crypto/apiKeyCrypto';
describe('apiKeyCrypto', () => {
const PLAINTEXT_KEY = 'my-secret-api-key-12345';
@@ -76,4 +81,15 @@ describe('apiKeyCrypto', () => {
expect(result).toBe(encrypted);
});
});
describe('is_encrypted_api_key', () => {
it('is true exactly for enc:v1: envelopes', () => {
expect(is_encrypted_api_key(encrypt_api_key('s'))).toBe(true);
expect(is_encrypted_api_key('enc:v1:AAAA')).toBe(true);
expect(is_encrypted_api_key('plaintext')).toBe(false);
expect(is_encrypted_api_key('')).toBe(false);
expect(is_encrypted_api_key(null)).toBe(false);
expect(is_encrypted_api_key(42)).toBe(false);
});
});
});
@@ -51,4 +51,31 @@ describe('Atlas admin1 region bundle (#1217)', () => {
expect(new Set(f.map(r => r.properties.iso_3166_2)).size).toBe(f.length);
}
});
/*
* geoBoundaries' GBR ADM1 is the four constituent countries, so a bundle built
* from it has no polygon below "England" — a London borough marked as visited
* has nothing to light up, and every English place reports "England" (#1974).
* The builder ships GB at ADM2 for exactly that reason.
*
* This is the guard that would have caught it when it landed in 3.1.0: four
* features for a whole country is not a region layer, it is a country layer
* with extra steps.
*/
it('ATLAS-BUNDLE-004 — Great Britain ships below the constituent-country level (#1974)', () => {
const gb = regions('GB');
expect(gb.length, 'GB must ship counties and boroughs, not the four nations').toBeGreaterThan(50);
expect(new Set(gb.map(r => r.properties.iso_3166_2)).size, 'GB region codes must be unique').toBe(gb.length);
});
it('ATLAS-BUNDLE-005 — the London boroughs are in it (#1974)', () => {
const names = new Set(
(features as unknown as { properties: { iso_a2: string | null; name?: string } }[])
.filter(f => f.properties.iso_a2 === 'GB')
.map(f => (f.properties.name || '').toLowerCase()),
);
for (const borough of ['camden', 'westminster', 'hackney', 'islington']) {
expect(names.has(borough), `${borough} should be a region of its own`).toBe(true);
}
});
});
File diff suppressed because it is too large Load Diff
@@ -1,70 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
// Prevent file I/O side effects at module load time
vi.mock('fs', () => ({
default: {
mkdirSync: vi.fn(),
existsSync: vi.fn(() => false),
statSync: vi.fn(() => ({ size: 0 })),
appendFileSync: vi.fn(),
renameSync: vi.fn(),
},
mkdirSync: vi.fn(),
existsSync: vi.fn(() => false),
statSync: vi.fn(() => ({ size: 0 })),
appendFileSync: vi.fn(),
renameSync: vi.fn(),
}));
vi.mock('../../../src/db/database', () => ({
db: { prepare: () => ({ get: vi.fn(), run: vi.fn() }) },
}));
import { getClientIp } from '../../../src/services/auditLog';
import type { Request } from 'express';
function makeReq(options: {
xff?: string | string[];
remoteAddress?: string;
} = {}): Request {
return {
headers: {
...(options.xff !== undefined ? { 'x-forwarded-for': options.xff } : {}),
},
socket: { remoteAddress: options.remoteAddress ?? undefined },
} as unknown as Request;
}
describe('getClientIp', () => {
it('returns first IP from comma-separated X-Forwarded-For string', () => {
expect(getClientIp(makeReq({ xff: '1.2.3.4, 5.6.7.8, 9.10.11.12' }))).toBe('1.2.3.4');
});
it('returns single IP when X-Forwarded-For has no comma', () => {
expect(getClientIp(makeReq({ xff: '10.0.0.1' }))).toBe('10.0.0.1');
});
it('returns first element when X-Forwarded-For is an array', () => {
expect(getClientIp(makeReq({ xff: ['203.0.113.1', '10.0.0.1'] }))).toBe('203.0.113.1');
});
it('trims whitespace from extracted IP', () => {
expect(getClientIp(makeReq({ xff: ' 192.168.1.1 , 10.0.0.1' }))).toBe('192.168.1.1');
});
it('falls back to req.socket.remoteAddress when no X-Forwarded-For', () => {
expect(getClientIp(makeReq({ remoteAddress: '172.16.0.1' }))).toBe('172.16.0.1');
});
it('returns null when no forwarded header and no socket address', () => {
expect(getClientIp(makeReq({}))).toBeNull();
});
it('returns null for empty string X-Forwarded-For', () => {
const req = {
headers: { 'x-forwarded-for': '' },
socket: { remoteAddress: undefined },
} as unknown as Request;
expect(getClientIp(req)).toBeNull();
});
});
@@ -1,299 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('../../../src/db/database', () => ({
db: { prepare: () => ({ get: vi.fn(), all: vi.fn(), run: vi.fn() }) },
canAccessTrip: vi.fn(),
}));
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret', ENCRYPTION_KEY: '0'.repeat(64) }));
vi.mock('../../../src/services/mfaCrypto', () => ({ encryptMfaSecret: vi.fn(), decryptMfaSecret: vi.fn() }));
vi.mock('../../../src/services/apiKeyCrypto', () => ({
decrypt_api_key: vi.fn((v) => v),
maybe_encrypt_api_key: vi.fn((v) => v),
encrypt_api_key: vi.fn((v) => v),
}));
vi.mock('../../../src/services/permissions', () => ({ getAllPermissions: vi.fn(() => ({})), checkPermission: vi.fn() }));
vi.mock('../../../src/services/ephemeralTokens', () => ({ createEphemeralToken: vi.fn() }));
vi.mock('../../../src/mcp', () => ({ revokeUserSessions: vi.fn() }));
vi.mock('../../../src/scheduler', () => ({ startTripReminders: vi.fn(), buildCronExpression: vi.fn() }));
import {
utcSuffix,
stripUserForClient,
maskKey,
avatarUrl,
normalizeBackupCode,
hashBackupCode,
generateBackupCodes,
parseBackupCodeHashes,
} from '../../../src/services/authService';
import type { User } from '../../../src/types';
// ── utcSuffix ────────────────────────────────────────────────────────────────
describe('utcSuffix', () => {
it('returns null for null', () => {
expect(utcSuffix(null)).toBeNull();
});
it('returns null for undefined', () => {
expect(utcSuffix(undefined)).toBeNull();
});
it('returns null for empty string', () => {
expect(utcSuffix('')).toBeNull();
});
it('returns timestamp unchanged when already ending with Z', () => {
expect(utcSuffix('2024-01-01T12:00:00Z')).toBe('2024-01-01T12:00:00Z');
});
it('replaces space with T and appends Z for SQLite-style datetime', () => {
expect(utcSuffix('2024-01-01 12:00:00')).toBe('2024-01-01T12:00:00Z');
});
it('appends Z when T is present but Z is missing', () => {
expect(utcSuffix('2024-06-15T08:30:00')).toBe('2024-06-15T08:30:00Z');
});
});
// ── stripUserForClient ───────────────────────────────────────────────────────
function makeUser(overrides: Partial<User> = {}): User {
return {
id: 1,
username: 'alice',
email: 'alice@example.com',
role: 'user',
password_hash: 'supersecret',
maps_api_key: 'maps-key',
openweather_api_key: 'weather-key',
unsplash_api_key: 'unsplash-key',
mfa_secret: 'totpsecret',
mfa_backup_codes: '["hash1","hash2"]',
mfa_enabled: 0,
must_change_password: 0,
avatar: null,
created_at: '2024-01-01 00:00:00',
updated_at: '2024-06-01 00:00:00',
last_login: null,
...overrides,
} as unknown as User;
}
describe('stripUserForClient', () => {
it('SEC-008: omits password_hash', () => {
const result = stripUserForClient(makeUser());
expect(result).not.toHaveProperty('password_hash');
});
it('SEC-008: omits maps_api_key', () => {
const result = stripUserForClient(makeUser());
expect(result).not.toHaveProperty('maps_api_key');
});
it('SEC-008: omits openweather_api_key', () => {
const result = stripUserForClient(makeUser());
expect(result).not.toHaveProperty('openweather_api_key');
});
it('SEC-008: omits unsplash_api_key', () => {
const result = stripUserForClient(makeUser());
expect(result).not.toHaveProperty('unsplash_api_key');
});
it('SEC-008: omits mfa_secret', () => {
const result = stripUserForClient(makeUser());
expect(result).not.toHaveProperty('mfa_secret');
});
it('SEC-008: omits mfa_backup_codes', () => {
const result = stripUserForClient(makeUser());
expect(result).not.toHaveProperty('mfa_backup_codes');
});
it('preserves non-sensitive fields', () => {
const result = stripUserForClient(makeUser({ username: 'alice', email: 'alice@example.com', role: 'user' }));
expect(result.id).toBe(1);
expect(result.username).toBe('alice');
expect(result.email).toBe('alice@example.com');
expect(result.role).toBe('user');
});
it('normalizes mfa_enabled integer 1 to true', () => {
const result = stripUserForClient(makeUser({ mfa_enabled: 1 } as any));
expect(result.mfa_enabled).toBe(true);
});
it('normalizes mfa_enabled integer 0 to false', () => {
const result = stripUserForClient(makeUser({ mfa_enabled: 0 } as any));
expect(result.mfa_enabled).toBe(false);
});
it('normalizes mfa_enabled boolean true to true', () => {
const result = stripUserForClient(makeUser({ mfa_enabled: true } as any));
expect(result.mfa_enabled).toBe(true);
});
it('normalizes must_change_password integer 1 to true', () => {
const result = stripUserForClient(makeUser({ must_change_password: 1 } as any));
expect(result.must_change_password).toBe(true);
});
it('normalizes must_change_password integer 0 to false', () => {
const result = stripUserForClient(makeUser({ must_change_password: 0 } as any));
expect(result.must_change_password).toBe(false);
});
it('converts created_at through utcSuffix', () => {
const result = stripUserForClient(makeUser({ created_at: '2024-01-01 00:00:00' }));
expect(result.created_at).toBe('2024-01-01T00:00:00Z');
});
it('converts updated_at through utcSuffix', () => {
const result = stripUserForClient(makeUser({ updated_at: '2024-06-01 12:00:00' }));
expect(result.updated_at).toBe('2024-06-01T12:00:00Z');
});
it('passes null last_login through as null', () => {
const result = stripUserForClient(makeUser({ last_login: null }));
expect(result.last_login).toBeNull();
});
});
// ── maskKey ──────────────────────────────────────────────────────────────────
describe('maskKey', () => {
it('returns null for null', () => {
expect(maskKey(null)).toBeNull();
});
it('returns null for undefined', () => {
expect(maskKey(undefined)).toBeNull();
});
it('returns null for empty string', () => {
expect(maskKey('')).toBeNull();
});
it('returns -------- for keys with 8 or fewer characters', () => {
expect(maskKey('abcd1234')).toBe('--------');
expect(maskKey('short')).toBe('--------');
expect(maskKey('a')).toBe('--------');
});
it('returns ---- + last 4 chars for keys longer than 8 characters', () => {
expect(maskKey('abcdefghijkl')).toBe('----ijkl');
expect(maskKey('sk-test-12345678')).toBe('----5678');
});
});
// ── avatarUrl ────────────────────────────────────────────────────────────────
describe('avatarUrl', () => {
it('returns /uploads/avatars/<filename> when avatar is set', () => {
expect(avatarUrl({ avatar: 'photo.jpg' })).toBe('/uploads/avatars/photo.jpg');
});
it('returns null when avatar is null', () => {
expect(avatarUrl({ avatar: null })).toBeNull();
});
it('returns null when avatar is undefined', () => {
expect(avatarUrl({})).toBeNull();
});
});
// ── normalizeBackupCode ──────────────────────────────────────────────────────
describe('normalizeBackupCode', () => {
it('uppercases the input', () => {
expect(normalizeBackupCode('abcd1234')).toBe('ABCD1234');
});
it('strips non-alphanumeric characters', () => {
expect(normalizeBackupCode('AB-CD 12!34')).toBe('ABCD1234');
});
it('handles code with dashes (normal backup code format)', () => {
expect(normalizeBackupCode('A1B2-C3D4')).toBe('A1B2C3D4');
});
it('returns empty string for empty input', () => {
expect(normalizeBackupCode('')).toBe('');
});
});
// ── hashBackupCode ───────────────────────────────────────────────────────────
describe('hashBackupCode', () => {
it('returns a 64-character hex string', () => {
const hash = hashBackupCode('A1B2-C3D4');
expect(hash).toMatch(/^[0-9a-f]{64}$/);
});
it('is deterministic: same input always produces same output', () => {
expect(hashBackupCode('A1B2-C3D4')).toBe(hashBackupCode('A1B2-C3D4'));
});
it('normalizes before hashing: dashed and plain form produce the same hash', () => {
expect(hashBackupCode('A1B2-C3D4')).toBe(hashBackupCode('a1b2c3d4'));
});
});
// ── generateBackupCodes ──────────────────────────────────────────────────────
describe('generateBackupCodes', () => {
it('returns 10 codes by default', () => {
const codes = generateBackupCodes();
expect(codes).toHaveLength(10);
});
it('respects a custom count', () => {
expect(generateBackupCodes(5)).toHaveLength(5);
expect(generateBackupCodes(20)).toHaveLength(20);
});
it('each code matches the XXXX-XXXX uppercase hex pattern', () => {
const codes = generateBackupCodes();
for (const code of codes) {
expect(code).toMatch(/^[0-9A-F]{4}-[0-9A-F]{4}$/);
}
});
it('generates no duplicate codes', () => {
const codes = generateBackupCodes(10);
expect(new Set(codes).size).toBe(10);
});
});
// ── parseBackupCodeHashes ────────────────────────────────────────────────────
describe('parseBackupCodeHashes', () => {
it('returns [] for null', () => {
expect(parseBackupCodeHashes(null)).toEqual([]);
});
it('returns [] for undefined', () => {
expect(parseBackupCodeHashes(undefined)).toEqual([]);
});
it('returns [] for empty string', () => {
expect(parseBackupCodeHashes('')).toEqual([]);
});
it('returns [] for invalid JSON', () => {
expect(parseBackupCodeHashes('not-json')).toEqual([]);
});
it('returns [] for JSON that is not an array', () => {
expect(parseBackupCodeHashes('{"key":"value"}')).toEqual([]);
});
it('filters out non-string entries', () => {
expect(parseBackupCodeHashes('[1, "abc", null, true]')).toEqual(['abc']);
});
it('returns all strings from a valid JSON string array', () => {
expect(parseBackupCodeHashes('["hash1","hash2","hash3"]')).toEqual(['hash1', 'hash2', 'hash3']);
});
});
@@ -1,803 +0,0 @@
/**
* authServiceDb.test.ts
*
* DB-centric unit tests for authService.ts using a real in-memory SQLite database.
* Pure function tests live in authService.test.ts (stub DB); this file covers
* functions that require actual DB queries to exercise their logic.
*/
// ---------------------------------------------------------------------------
// vi.hoisted: build the real in-memory DB and the module mock before any import
// ---------------------------------------------------------------------------
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-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
SESSION_DURATION_SECONDS: 86400,
updateJwtSecret: () => {},
}));
vi.mock('../../../src/services/mfaCrypto', () => ({
encryptMfaSecret: vi.fn((s) => `enc:${s}`),
decryptMfaSecret: vi.fn((s: string) => s.replace('enc:', '')),
}));
vi.mock('../../../src/services/apiKeyCrypto', () => ({
decrypt_api_key: vi.fn((v) => v),
maybe_encrypt_api_key: vi.fn((v) => v),
mask_stored_api_key: vi.fn((v: string | null | undefined) => (v ? '••••••••' : null)),
encrypt_api_key: vi.fn((v) => v),
}));
vi.mock('../../../src/services/permissions', () => ({
getAllPermissions: vi.fn(() => ({})),
checkPermission: vi.fn(),
}));
vi.mock('../../../src/services/ephemeralTokens', () => ({ createEphemeralToken: vi.fn() }));
vi.mock('../../../src/mcp', () => ({ revokeUserSessions: vi.fn() }));
vi.mock('../../../src/scheduler', () => ({
startTripReminders: vi.fn(),
buildCronExpression: vi.fn(),
loadSettings: vi.fn(() => ({ enabled: false })),
VALID_INTERVALS: ['daily', 'weekly', 'monthly'],
}));
// ---------------------------------------------------------------------------
// Imports (after mocks)
// ---------------------------------------------------------------------------
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createAdmin, createInviteToken, createTrip, createReservation } from '../../helpers/factories';
import {
updateSettings,
updateApiKeys,
getSettings,
listUsers,
getAppSettings,
validateKeys,
isOidcOnlyMode,
resolveAuthToggles,
setupMfa,
enableMfa,
disableMfa,
validateInviteToken,
registerUser,
loginUser,
requestPasswordReset,
changePassword,
verifyMfaLogin,
createMcpToken,
deleteMcpToken,
generateToken,
getTravelStats,
} from '../../../src/services/authService';
import { unmarkCountryVisited } from '../../../src/services/atlasService';
import { verifyJwtAndLoadUser } from '../../../src/middleware/auth';
// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => resetTestDb(testDb));
afterAll(() => testDb.close());
// ---------------------------------------------------------------------------
// requestPasswordReset — OIDC/SSO accounts (#1129)
// ---------------------------------------------------------------------------
describe('requestPasswordReset — OIDC/SSO accounts', () => {
it('AUTH-DB-PR1: refuses a reset for an OIDC-linked account that has a (random) password hash', () => {
const { user } = createUser(testDb);
// OIDC users are created with a random bcrypt hash, so password_hash is set —
// the old guard keyed off a missing hash and therefore let the reset through.
testDb.prepare('UPDATE users SET oidc_sub = ?, oidc_issuer = ? WHERE id = ?')
.run('sub-1129', 'https://idp.example', user.id);
const result = requestPasswordReset(user.email, null);
expect(result.reason).toBe('oidc_only');
expect(result.tokenForDelivery).toBeNull();
const { n } = testDb.prepare('SELECT COUNT(*) AS n FROM password_reset_tokens WHERE user_id = ?')
.get(user.id) as { n: number };
expect(n).toBe(0);
});
it('AUTH-DB-PR2: still issues a reset for a normal local (non-SSO) account', () => {
const { user } = createUser(testDb);
const result = requestPasswordReset(user.email, null);
expect(result.reason).toBe('issued');
expect(result.tokenForDelivery).toBeTruthy();
});
});
// ---------------------------------------------------------------------------
// updateSettings
// ---------------------------------------------------------------------------
describe('updateSettings', () => {
it('AUTH-DB-001: updates username successfully', () => {
const { user } = createUser(testDb);
const result = updateSettings(user.id, { username: 'newname' });
expect(result.success).toBe(true);
expect(result.user?.username).toBe('newname');
});
it('AUTH-DB-002: returns 400 when username is too short (< 2 chars)', () => {
const { user } = createUser(testDb);
const result = updateSettings(user.id, { username: 'x' });
expect(result.status).toBe(400);
expect(result.error).toMatch(/between 2 and 50/i);
});
it('AUTH-DB-003: returns 400 when username has invalid characters (spaces)', () => {
const { user } = createUser(testDb);
const result = updateSettings(user.id, { username: 'bad name' });
expect(result.status).toBe(400);
expect(result.error).toMatch(/only contain/i);
});
it('AUTH-DB-004: returns 409 when username is already taken by another user', () => {
const { user: user1 } = createUser(testDb, { username: 'alice' });
const { user: user2 } = createUser(testDb, { username: 'bob' });
const result = updateSettings(user2.id, { username: user1.username });
expect(result.status).toBe(409);
expect(result.error).toMatch(/already taken/i);
});
it('AUTH-DB-005: updates email successfully', () => {
const { user } = createUser(testDb);
const result = updateSettings(user.id, { email: 'new@example.com' });
expect(result.success).toBe(true);
expect(result.user?.email).toBe('new@example.com');
});
it('AUTH-DB-006: returns 400 for invalid email format', () => {
const { user } = createUser(testDb);
const result = updateSettings(user.id, { email: 'not-an-email' });
expect(result.status).toBe(400);
expect(result.error).toMatch(/invalid email/i);
});
it('AUTH-DB-007: returns 409 when email is already taken by another user', () => {
const { user: user1 } = createUser(testDb, { email: 'taken@example.com' });
const { user: user2 } = createUser(testDb);
const result = updateSettings(user2.id, { email: user1.email });
expect(result.status).toBe(409);
expect(result.error).toMatch(/already taken/i);
});
it('AUTH-DB-008: returns success with no field changes when empty body is passed', () => {
const { user } = createUser(testDb);
const result = updateSettings(user.id, {});
expect(result.success).toBe(true);
});
});
// ---------------------------------------------------------------------------
// getSettings
// ---------------------------------------------------------------------------
describe('getSettings', () => {
it('AUTH-DB-009: returns 403 for non-admin user', () => {
const { user } = createUser(testDb);
const result = getSettings(user.id);
expect(result.status).toBe(403);
expect(result.error).toMatch(/admin/i);
});
it('AUTH-DB-010: returns maps_api_key and openweather_api_key for admin', () => {
const { user } = createAdmin(testDb);
testDb
.prepare('UPDATE users SET maps_api_key = ?, openweather_api_key = ? WHERE id = ?')
.run('maps-key-value', 'weather-key-value', user.id);
const result = getSettings(user.id);
expect(result.status).toBeUndefined();
expect(result.settings).toBeDefined();
expect(result.settings).toHaveProperty('maps_api_key');
expect(result.settings).toHaveProperty('openweather_api_key');
});
it('AUTH-DB-010b: round-trips unsplash_api_key through updateApiKeys — masked to the client, readable via getSettings', () => {
const { user } = createAdmin(testDb);
const result = updateApiKeys(user.id, { unsplash_api_key: 'unsplash-secret-key' });
// Returned to the client masked, never in plaintext.
expect(result.user.unsplash_api_key).toBe('-----key');
// getSettings returns the stored key to the admin.
expect(getSettings(user.id).settings?.unsplash_api_key).toBe('unsplash-secret-key');
});
});
// ---------------------------------------------------------------------------
// listUsers
// ---------------------------------------------------------------------------
describe('listUsers', () => {
it('AUTH-DB-011: returns all users except self, sorted by username', () => {
const { user: self } = createUser(testDb, { username: 'zzself' });
createUser(testDb, { username: 'alice' });
createUser(testDb, { username: 'charlie' });
createUser(testDb, { username: 'bob' });
const result = listUsers(self.id);
expect(result).toHaveLength(3);
const names = result.map((u) => u.username);
expect(names).toEqual([...names].sort());
expect(names).not.toContain('zzself');
});
it('AUTH-DB-012: returns empty array when only one user exists', () => {
const { user } = createUser(testDb);
const result = listUsers(user.id);
expect(result).toHaveLength(0);
});
});
// ---------------------------------------------------------------------------
// getAppSettings
// ---------------------------------------------------------------------------
describe('getAppSettings', () => {
it('AUTH-DB-013: returns 403 for non-admin', () => {
const { user } = createUser(testDb);
const result = getAppSettings(user.id);
expect(result.status).toBe(403);
expect(result.error).toMatch(/admin/i);
});
it('AUTH-DB-014: returns settings object for admin with known key allow_registration', () => {
const { user } = createAdmin(testDb);
testDb
.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'true')")
.run();
const result = getAppSettings(user.id);
expect(result.status).toBeUndefined();
expect(result.data).toBeDefined();
expect(result.data).toHaveProperty('allow_registration', 'true');
});
});
// ---------------------------------------------------------------------------
// validateKeys
// ---------------------------------------------------------------------------
describe('validateKeys', () => {
it('AUTH-DB-015: returns 403 for non-admin', async () => {
const { user } = createUser(testDb);
const result = await validateKeys(user.id);
expect(result.status).toBe(403);
expect(result.error).toMatch(/admin/i);
expect(result.maps).toBe(false);
expect(result.weather).toBe(false);
});
it('AUTH-DB-016: returns { maps: false, weather: false } when no API keys are stored', async () => {
const { user } = createAdmin(testDb);
const result = await validateKeys(user.id);
expect(result.maps).toBe(false);
expect(result.weather).toBe(false);
expect(result.maps_details).toBeNull();
});
it('AUTH-DB-017: returns { maps: true } when fetch returns 200', async () => {
const { user } = createAdmin(testDb);
testDb.prepare('UPDATE users SET maps_api_key = ? WHERE id = ?').run('test-key', user.id);
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValueOnce({
status: 200,
statusText: 'OK',
text: async () => '',
} as Response);
const result = await validateKeys(user.id);
expect(result.maps).toBe(true);
expect(result.maps_details?.ok).toBe(true);
fetchSpy.mockRestore();
});
it('AUTH-DB-018: returns { maps: false } when fetch throws a network error', async () => {
const { user } = createAdmin(testDb);
testDb.prepare('UPDATE users SET maps_api_key = ? WHERE id = ?').run('test-key', user.id);
const fetchSpy = vi
.spyOn(global, 'fetch')
.mockRejectedValueOnce(new Error('Network failure'));
const result = await validateKeys(user.id);
expect(result.maps).toBe(false);
expect(result.maps_details?.error_status).toBe('FETCH_ERROR');
expect(result.maps_details?.error_message).toBe('Network failure');
fetchSpy.mockRestore();
});
});
// ---------------------------------------------------------------------------
// isOidcOnlyMode
// ---------------------------------------------------------------------------
describe('isOidcOnlyMode', () => {
it('AUTH-DB-019: returns false when OIDC_ONLY env var is not set', () => {
vi.stubEnv('OIDC_ONLY', '');
expect(isOidcOnlyMode()).toBe(false);
vi.unstubAllEnvs();
});
it('AUTH-DB-020: returns false when OIDC_ONLY=true but no OIDC_ISSUER configured', () => {
vi.stubEnv('OIDC_ONLY', 'true');
vi.stubEnv('OIDC_ISSUER', '');
vi.stubEnv('OIDC_CLIENT_ID', '');
expect(isOidcOnlyMode()).toBe(false);
vi.unstubAllEnvs();
});
it('AUTH-DB-021: returns true when OIDC_ONLY=true AND OIDC_ISSUER AND OIDC_CLIENT_ID are set', () => {
vi.stubEnv('OIDC_ONLY', 'true');
vi.stubEnv('OIDC_ISSUER', 'https://sso.example.com');
vi.stubEnv('OIDC_CLIENT_ID', 'trek-client');
expect(isOidcOnlyMode()).toBe(true);
vi.unstubAllEnvs();
});
});
// ---------------------------------------------------------------------------
// resolveAuthToggles
// ---------------------------------------------------------------------------
describe('resolveAuthToggles', () => {
afterEach(() => {
vi.unstubAllEnvs();
testDb.prepare("DELETE FROM app_settings WHERE key IN ('password_login','password_registration','oidc_login','oidc_registration','oidc_only','allow_registration')").run();
});
it('AUTH-DB-022a: returns all true by default (no DB keys, no env override)', () => {
vi.stubEnv('OIDC_ONLY', '');
const t = resolveAuthToggles();
expect(t.password_login).toBe(true);
expect(t.password_registration).toBe(true);
expect(t.oidc_login).toBe(true);
expect(t.oidc_registration).toBe(true);
});
it('AUTH-DB-022b: legacy — OIDC_ONLY=true with OIDC configured disables password_login and password_registration', () => {
vi.stubEnv('OIDC_ONLY', 'true');
vi.stubEnv('OIDC_ISSUER', 'https://sso.example.com');
vi.stubEnv('OIDC_CLIENT_ID', 'trek-client');
const t = resolveAuthToggles();
expect(t.password_login).toBe(false);
expect(t.password_registration).toBe(false);
expect(t.oidc_login).toBe(true);
expect(t.oidc_registration).toBe(true);
});
it('AUTH-DB-022c: legacy — allow_registration=false disables both password and oidc registration', () => {
vi.stubEnv('OIDC_ONLY', '');
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'false')").run();
const t = resolveAuthToggles();
expect(t.password_login).toBe(true);
expect(t.password_registration).toBe(false);
expect(t.oidc_login).toBe(true);
expect(t.oidc_registration).toBe(false);
});
it('AUTH-DB-022d: new granular keys take precedence over legacy keys', () => {
vi.stubEnv('OIDC_ONLY', '');
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'false')").run();
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('password_registration', 'true')").run();
const t = resolveAuthToggles();
// New key present → use new keys, allow_registration ignored
expect(t.password_registration).toBe(true);
expect(t.oidc_registration).toBe(true); // defaults to true when key not set
});
it('AUTH-DB-022e: OIDC_ONLY env var overrides new granular keys for password toggles', () => {
vi.stubEnv('OIDC_ONLY', 'true');
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('password_login', 'true')").run();
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('password_registration', 'true')").run();
const t = resolveAuthToggles();
// OIDC_ONLY forces password toggles off even when DB says true
expect(t.password_login).toBe(false);
expect(t.password_registration).toBe(false);
});
it('AUTH-DB-022f: individual granular keys can be set independently', () => {
vi.stubEnv('OIDC_ONLY', '');
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('password_login', 'true')").run();
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('password_registration', 'false')").run();
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_login', 'true')").run();
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_registration', 'false')").run();
const t = resolveAuthToggles();
expect(t.password_login).toBe(true);
expect(t.password_registration).toBe(false);
expect(t.oidc_login).toBe(true);
expect(t.oidc_registration).toBe(false);
});
});
// ---------------------------------------------------------------------------
// setupMfa
// ---------------------------------------------------------------------------
describe('setupMfa', () => {
it('AUTH-DB-022: returns 403 in demo mode for demo@nomad.app', () => {
vi.stubEnv('DEMO_MODE', 'true');
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
const result = setupMfa(user.id, 'demo@nomad.app');
expect(result.status).toBe(403);
expect(result.error).toMatch(/demo mode/i);
vi.unstubAllEnvs();
});
it('AUTH-DB-023: returns 400 when MFA is already enabled', () => {
const { user } = createUser(testDb);
testDb.prepare('UPDATE users SET mfa_enabled = 1 WHERE id = ?').run(user.id);
const result = setupMfa(user.id, user.email);
expect(result.status).toBe(400);
expect(result.error).toMatch(/already enabled/i);
});
it('AUTH-DB-024: returns secret and otpauth_url when MFA setup starts successfully', () => {
const { user } = createUser(testDb);
const result = setupMfa(user.id, user.email);
expect(result.error).toBeUndefined();
expect(typeof result.secret).toBe('string');
expect(result.secret!.length).toBeGreaterThan(0);
expect(typeof result.otpauth_url).toBe('string');
expect(result.otpauth_url).toMatch(/^otpauth:\/\/totp\//);
expect(result.qrPromise).toBeInstanceOf(Promise);
});
});
// ---------------------------------------------------------------------------
// enableMfa
// ---------------------------------------------------------------------------
describe('enableMfa', () => {
it('AUTH-DB-025: returns 400 when no verification code is provided', () => {
const { user } = createUser(testDb);
const result = enableMfa(user.id, undefined);
expect(result.status).toBe(400);
expect(result.error).toMatch(/code is required/i);
});
it('AUTH-DB-026: returns 400 when there is no pending MFA setup', () => {
const { user } = createUser(testDb);
// No setupMfa called first, so no pending entry exists
const result = enableMfa(user.id, '123456');
expect(result.status).toBe(400);
expect(result.error).toMatch(/no mfa setup in progress/i);
});
});
// ---------------------------------------------------------------------------
// disableMfa
// ---------------------------------------------------------------------------
describe('disableMfa', () => {
it('AUTH-DB-027: returns 403 in demo mode for demo@nomad.app', () => {
vi.stubEnv('DEMO_MODE', 'true');
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
const result = disableMfa(user.id, 'demo@nomad.app', {
password: 'password123',
code: '000000',
});
expect(result.status).toBe(403);
expect(result.error).toMatch(/demo mode/i);
vi.unstubAllEnvs();
});
it('AUTH-DB-028: returns 400 when password or code is missing', () => {
const { user } = createUser(testDb);
const missingCode = disableMfa(user.id, user.email, { password: 'pass', code: undefined });
expect(missingCode.status).toBe(400);
expect(missingCode.error).toMatch(/password and authenticator code/i);
const missingPassword = disableMfa(user.id, user.email, { password: undefined, code: '123456' });
expect(missingPassword.status).toBe(400);
expect(missingPassword.error).toMatch(/password and authenticator code/i);
});
it('AUTH-DB-029: returns 400 when MFA is not enabled on the account', () => {
const { user } = createUser(testDb);
// mfa_enabled defaults to 0 / not set
const result = disableMfa(user.id, user.email, { password: 'password123', code: '000000' });
expect(result.status).toBe(400);
expect(result.error).toMatch(/not enabled/i);
});
});
// ---------------------------------------------------------------------------
// validateInviteToken
// ---------------------------------------------------------------------------
describe('validateInviteToken', () => {
it('AUTH-DB-030: returns 404 for unknown token', () => {
const result = validateInviteToken('no-such-token');
expect(result.status).toBe(404);
});
it('AUTH-DB-031: returns 410 when max_uses exceeded', () => {
// createInviteToken with used_count already at max
const invite = createInviteToken(testDb, { max_uses: 1 });
// manually set used_count = 1 to simulate exhaustion
testDb.prepare('UPDATE invite_tokens SET used_count = 1 WHERE id = ?').run(invite.id);
const result = validateInviteToken(invite.token);
expect(result.status).toBe(410);
});
it('AUTH-DB-032: returns 410 when expired', () => {
const invite = createInviteToken(testDb, { expires_at: '2000-01-01T00:00:00.000Z' });
const result = validateInviteToken(invite.token);
expect(result.status).toBe(410);
});
});
// ---------------------------------------------------------------------------
// registerUser — OIDC-only / registration-disabled
// ---------------------------------------------------------------------------
describe('registerUser — OIDC-only / registration-disabled', () => {
it('AUTH-DB-033: returns 403 when oidc_only=true and not first user', () => {
createUser(testDb); // ensure userCount > 0
testDb.prepare("INSERT INTO app_settings (key, value) VALUES ('oidc_only', 'true')").run();
testDb.prepare("INSERT INTO app_settings (key, value) VALUES ('oidc_issuer', 'https://x')").run();
testDb.prepare("INSERT INTO app_settings (key, value) VALUES ('oidc_client_id', 'id')").run();
const result = registerUser({ username: 'u', email: 'new@x.com', password: 'Secure123!' });
expect(result.status).toBe(403);
expect(result.error).toMatch(/password registration is disabled/i);
});
it('AUTH-DB-034: returns 403 when registration is disabled and no invite', () => {
createUser(testDb); // ensure userCount > 0
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'false')").run();
const result = registerUser({ username: 'u2', email: 'n2@x.com', password: 'Secure123!' });
expect(result.status).toBe(403);
});
});
// ---------------------------------------------------------------------------
// loginUser — OIDC-only mode
// ---------------------------------------------------------------------------
describe('loginUser — OIDC-only mode', () => {
it('AUTH-DB-035: returns 403 when oidc_only=true', () => {
const { user, password } = createUser(testDb);
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_only', 'true')").run();
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_issuer', 'https://x')").run();
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_client_id', 'id')").run();
const result = loginUser({ email: user.email, password });
expect(result.status).toBe(403);
});
});
// ---------------------------------------------------------------------------
// changePassword — OIDC-only mode
// ---------------------------------------------------------------------------
describe('changePassword — OIDC-only mode', () => {
it('AUTH-DB-036: returns 403 when oidc_only=true', () => {
const { user, password } = createUser(testDb);
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_only', 'true')").run();
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_issuer', 'https://x')").run();
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('oidc_client_id', 'id')").run();
const result = changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' });
expect(result.status).toBe(403);
});
});
describe('changePassword — session invalidation', () => {
const pvOf = (id: number) =>
(testDb.prepare('SELECT password_version FROM users WHERE id = ?').get(id) as { password_version: number }).password_version;
const mcpCount = (id: number) =>
(testDb.prepare('SELECT COUNT(*) c FROM mcp_tokens WHERE user_id = ?').get(id) as { c: number }).c;
it('AUTH-DB-036b: bumps password_version, prunes MCP tokens, and re-issues a session', () => {
const { user, password } = createUser(testDb);
createMcpToken(user.id, 'cli');
expect(pvOf(user.id)).toBe(0);
expect(mcpCount(user.id)).toBe(1);
const result = changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' });
expect(result.success).toBe(true);
expect(typeof result.token).toBe('string'); // fresh session for the current device
expect(pvOf(user.id)).toBe(1); // old JWT/cookie sessions now rejected by the pv gate
expect(mcpCount(user.id)).toBe(0); // static MCP tokens revoked
});
it('AUTH-DB-036c: a token minted before the change no longer validates afterwards', () => {
const { user, password } = createUser(testDb);
const stolen = generateToken({ id: user.id }); // pv=0 at mint time
expect(verifyJwtAndLoadUser(stolen)).not.toBeNull();
changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' });
expect(verifyJwtAndLoadUser(stolen)).toBeNull(); // invalidated by the pv bump
});
});
// ---------------------------------------------------------------------------
// disableMfa — require_mfa policy
// ---------------------------------------------------------------------------
describe('disableMfa — require_mfa policy', () => {
it('AUTH-DB-037: returns 403 when require_mfa=true is set globally', () => {
const { user } = createUser(testDb);
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('require_mfa', 'true')").run();
const result = disableMfa(user.id, user.email, { password: 'pass', code: '123456' });
expect(result.status).toBe(403);
expect(result.error).toMatch(/cannot be disabled/i);
});
});
// ---------------------------------------------------------------------------
// verifyMfaLogin — validation
// ---------------------------------------------------------------------------
describe('verifyMfaLogin — validation', () => {
it('AUTH-DB-038: returns 400 when mfa_token or code is missing', () => {
const result = verifyMfaLogin({ mfa_token: undefined, code: undefined });
expect(result.status).toBe(400);
});
it('AUTH-DB-039: returns 401 when mfa_token has wrong purpose', () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const jwt = require('jsonwebtoken');
const tok = jwt.sign({ id: 1, purpose: 'wrong' }, 'test-secret', { expiresIn: '5m', algorithm: 'HS256' });
const result = verifyMfaLogin({ mfa_token: tok, code: '123456' });
expect(result.status).toBe(401);
expect(result.error).toMatch(/invalid/i);
});
it('AUTH-DB-040: returns 401 when user not found for valid mfa_token', () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const jwt = require('jsonwebtoken');
const tok = jwt.sign({ id: 99999, purpose: 'mfa_login' }, 'test-secret', { expiresIn: '5m', algorithm: 'HS256' });
const result = verifyMfaLogin({ mfa_token: tok, code: '123456' });
expect(result.status).toBe(401);
});
});
// ---------------------------------------------------------------------------
// MCP token service
// ---------------------------------------------------------------------------
describe('MCP token service', () => {
it('AUTH-DB-041: createMcpToken returns 400 when name is missing', () => {
const { user } = createUser(testDb);
const result = createMcpToken(user.id, undefined);
expect(result.status).toBe(400);
});
it('AUTH-DB-042: createMcpToken returns 400 when name exceeds 100 chars', () => {
const { user } = createUser(testDb);
const result = createMcpToken(user.id, 'a'.repeat(101));
expect(result.status).toBe(400);
});
it('AUTH-DB-043: createMcpToken creates token and returns raw_token', () => {
const { user } = createUser(testDb);
const result = createMcpToken(user.id, 'My Token');
expect(result.token).toBeDefined();
expect((result.token as any).raw_token).toMatch(/^trek_/);
});
it('AUTH-DB-044: createMcpToken returns 400 when user has 10 tokens already', () => {
const { user } = createUser(testDb);
for (let i = 0; i < 10; i++) {
testDb.prepare(
'INSERT INTO mcp_tokens (user_id, name, token_hash, token_prefix) VALUES (?, ?, ?, ?)'
).run(user.id, `Token ${i}`, `hash${i}`, `trek_prefix${i}`);
}
const result = createMcpToken(user.id, 'One More');
expect(result.status).toBe(400);
});
it('AUTH-DB-045: deleteMcpToken returns 404 for non-existent token', () => {
const { user } = createUser(testDb);
const result = deleteMcpToken(user.id, '99999');
expect(result.status).toBe(404);
});
it('AUTH-DB-046: deleteMcpToken deletes the token and returns success', () => {
const { user } = createUser(testDb);
const created = createMcpToken(user.id, 'Deletable Token');
const tokenId = String((created.token as any).id);
const result = deleteMcpToken(user.id, tokenId);
expect(result).toEqual({ success: true });
const row = testDb.prepare('SELECT id FROM mcp_tokens WHERE id = ?').get(tokenId);
expect(row).toBeUndefined();
});
});
// ── getTravelStats — dashboard passport card ────────────────────────────────
describe('getTravelStats', () => {
function endpoint(reservationId: number, role: 'from' | 'to' | 'stop', sequence: number, lat: number, lng: number) {
testDb.prepare(
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, lat, lng) VALUES (?, ?, ?, ?, ?, ?)'
).run(reservationId, role, sequence, `Endpoint ${sequence}`, lat, lng);
}
it('AUTH-DB-047: #1486 counts the from/to countries of a flight', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Tokyo Trip' });
const res = createReservation(testDb, trip.id, { type: 'flight' });
endpoint(res.id, 'from', 0, 50.9014, 4.4844); // Brussels
endpoint(res.id, 'to', 1, 35.6762, 139.6503); // Tokyo
const stats = getTravelStats(user.id);
expect(stats.countries).toContain('BE');
expect(stats.countries).toContain('JP');
});
it('AUTH-DB-048: #1486 a connecting-flight layover does NOT count as visited', () => {
// The Atlas query grew a role filter for #1486 but this copy of it did not, so the
// dashboard passport card still counted a plane change as a visited country.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Connection Trip' });
const res = createReservation(testDb, trip.id, { type: 'flight' });
endpoint(res.id, 'from', 0, 50.9014, 4.4844); // Brussels
endpoint(res.id, 'stop', 1, 35.6762, 139.6503); // Tokyo — never leaves the airport
endpoint(res.id, 'to', 2, -33.8688, 151.2093); // Sydney
const stats = getTravelStats(user.id);
expect(stats.countries).toContain('BE');
expect(stats.countries).toContain('AU');
expect(stats.countries).not.toContain('JP');
});
it('AUTH-DB-049: #1490 a country removed in Atlas is not counted on the dashboard either', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Tokyo Trip' });
const res = createReservation(testDb, trip.id, { type: 'flight' });
endpoint(res.id, 'from', 0, 50.9014, 4.4844);
endpoint(res.id, 'to', 1, 35.6762, 139.6503);
expect(getTravelStats(user.id).countries).toContain('JP');
unmarkCountryVisited(user.id, 'JP');
const after = getTravelStats(user.id);
expect(after.countries).not.toContain('JP');
expect(after.countries).toContain('BE');
});
});
+1 -1
View File
@@ -4,7 +4,7 @@
* an OIDC `picture` claim (#1399); the helper resolves both to a renderable src.
*/
import { describe, it, expect } from 'vitest';
import { avatarUrl } from '../../../src/services/avatarUrl';
import { avatarUrl } from '../../../src/nest/common/avatarUrl';
describe('avatarUrl', () => {
it('AVATAR-URL-001: prefixes an uploaded file name with the avatars path', () => {
File diff suppressed because it is too large Load Diff
@@ -1,476 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// ── DB mock setup ────────────────────────────────────────────────────────────
const mockDb = vi.hoisted(() => {
return {
db: {
prepare: vi.fn(() => ({
all: vi.fn(() => []),
get: vi.fn(() => undefined),
run: vi.fn(),
})),
},
canAccessTrip: vi.fn(() => true),
};
});
vi.mock('../../../src/db/database', () => mockDb);
const mockRates = vi.hoisted(() => ({ getRates: vi.fn() }));
vi.mock('../../../src/services/exchangeRateService', () => mockRates);
import { calculateSettlement, updateSettlement, freezeForeignRate } from '../../../src/services/budgetService';
import type { BudgetItem, BudgetItemMember, BudgetItemPayer } from '../../../src/types';
// ── Helpers ──────────────────────────────────────────────────────────────────
// Who actually paid is recorded as explicit payers (budget_item_payers); members
// are only the equal-split participants.
function makeItem(id: number, total_price: number, trip_id = 1): BudgetItem {
return { id, trip_id, name: `Item ${id}`, total_price, category: 'other' } as BudgetItem;
}
function makeMember(budget_item_id: number, user_id: number, username: string): BudgetItemMember & { budget_item_id: number } {
return { budget_item_id, user_id, paid: 0, username, avatar: null } as BudgetItemMember & { budget_item_id: number };
}
function makePayer(budget_item_id: number, user_id: number, amount: number, username: string): BudgetItemPayer & { budget_item_id: number } {
return { budget_item_id, user_id, amount, username, avatar: null } as BudgetItemPayer & { budget_item_id: number };
}
// A raw budget_settlements row as listSettlements reads it (joined usernames/avatars).
function makeSettlementRow(
id: number, from_user_id: number, to_user_id: number, amount: number,
currency: string | null = null, exchange_rate = 1,
) {
return {
id, trip_id: 1, from_user_id, to_user_id, amount, currency, exchange_rate,
created_at: '2026-01-01', created_by_user_id: from_user_id,
from_username: `u${from_user_id}`, from_avatar: null,
to_username: `u${to_user_id}`, to_avatar: null,
};
}
function setupDb(
items: BudgetItem[],
members: (BudgetItemMember & { budget_item_id: number })[],
payers: (BudgetItemPayer & { budget_item_id: number })[] = [],
settlements: ReturnType<typeof makeSettlementRow>[] = [],
) {
mockDb.db.prepare.mockImplementation((sql: string) => {
if (sql.includes('SELECT * FROM budget_items')) {
return { all: vi.fn(() => items), get: vi.fn(), run: vi.fn() };
}
if (sql.includes('budget_item_members')) {
return { all: vi.fn(() => members), get: vi.fn(), run: vi.fn() };
}
if (sql.includes('budget_item_payers')) {
return { all: vi.fn(() => payers), get: vi.fn(), run: vi.fn() };
}
if (sql.includes('budget_settlements')) {
return { all: vi.fn(() => settlements), get: vi.fn(), run: vi.fn() };
}
return { all: vi.fn(() => []), get: vi.fn(), run: vi.fn() };
});
}
beforeEach(() => {
vi.clearAllMocks();
setupDb([], [], []);
});
// ── calculateSettlement ──────────────────────────────────────────────────────
describe('calculateSettlement', () => {
it('returns empty balances and flows when trip has no items', () => {
setupDb([], [], []);
const result = calculateSettlement(1);
expect(result.balances).toEqual([]);
expect(result.flows).toEqual([]);
});
it('returns no flows when there are items but no members', () => {
setupDb([makeItem(1, 100)], [], [makePayer(1, 1, 100, 'alice')]);
const result = calculateSettlement(1);
expect(result.flows).toEqual([]);
});
it('returns no flows when no one has paid', () => {
setupDb(
[makeItem(1, 100)],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob')],
[],
);
const result = calculateSettlement(1);
expect(result.flows).toEqual([]);
});
it('2 members, 1 payer: payer is owed half, non-payer owes half', () => {
// Item: $100. Alice paid all, [Alice, Bob] split. Each owes $50. Alice net: +$50. Bob: -$50.
setupDb(
[makeItem(1, 100)],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob')],
[makePayer(1, 1, 100, 'alice')],
);
const result = calculateSettlement(1);
const alice = result.balances.find(b => b.user_id === 1)!;
const bob = result.balances.find(b => b.user_id === 2)!;
expect(alice.balance).toBe(50);
expect(bob.balance).toBe(-50);
expect(result.flows).toHaveLength(1);
expect(result.flows[0].from.user_id).toBe(2); // Bob owes
expect(result.flows[0].to.user_id).toBe(1); // Alice is owed
expect(result.flows[0].amount).toBe(50);
});
it('3 members, 1 payer: correct 3-way split', () => {
// Item: $90. Alice paid. Each of 3 owes $30. Alice net: +$60. Bob: -$30. Carol: -$30.
setupDb(
[makeItem(1, 90)],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob'), makeMember(1, 3, 'carol')],
[makePayer(1, 1, 90, 'alice')],
);
const result = calculateSettlement(1);
const alice = result.balances.find(b => b.user_id === 1)!;
const bob = result.balances.find(b => b.user_id === 2)!;
const carol = result.balances.find(b => b.user_id === 3)!;
expect(alice.balance).toBe(60);
expect(bob.balance).toBe(-30);
expect(carol.balance).toBe(-30);
expect(result.flows).toHaveLength(2);
});
it('all paid equally: all balances are zero, no flows', () => {
// Item: $60. 3 members, each paid $20 and owes $20. Net: 0 for everyone.
setupDb(
[makeItem(1, 60)],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob'), makeMember(1, 3, 'carol')],
[makePayer(1, 1, 20, 'alice'), makePayer(1, 2, 20, 'bob'), makePayer(1, 3, 20, 'carol')],
);
const result = calculateSettlement(1);
for (const b of result.balances) {
expect(Math.abs(b.balance)).toBeLessThanOrEqual(0.01);
}
expect(result.flows).toHaveLength(0);
});
it('flow direction: from is debtor (owes), to is creditor (is owed)', () => {
// Alice paid $100 for 2 people. Bob owes Alice $50.
setupDb(
[makeItem(1, 100)],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob')],
[makePayer(1, 1, 100, 'alice')],
);
const result = calculateSettlement(1);
const flow = result.flows[0];
expect(flow.from.username).toBe('bob'); // debtor
expect(flow.to.username).toBe('alice'); // creditor
});
it('amounts are rounded to 2 decimal places', () => {
// Item: $10. 3 members, 1 payer. Share = 3.333... Each rounded to 3.33.
setupDb(
[makeItem(1, 10)],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob'), makeMember(1, 3, 'carol')],
[makePayer(1, 1, 10, 'alice')],
);
const result = calculateSettlement(1);
for (const b of result.balances) {
const str = b.balance.toString();
const decimals = str.includes('.') ? str.split('.')[1].length : 0;
expect(decimals).toBeLessThanOrEqual(2);
}
for (const flow of result.flows) {
const str = flow.amount.toString();
const decimals = str.includes('.') ? str.split('.')[1].length : 0;
expect(decimals).toBeLessThanOrEqual(2);
}
});
it('2 items with different payers: aggregates balances correctly', () => {
// Item 1: $100, Alice paid, [Alice, Bob] (Alice net: +50, Bob: -50)
// Item 2: $60, Bob paid, [Alice, Bob] (Bob net: +30, Alice: -30)
// Final: Alice: +50 - 30 = +20, Bob: -50 + 30 = -20
setupDb(
[makeItem(1, 100), makeItem(2, 60)],
[
makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob'),
makeMember(2, 1, 'alice'), makeMember(2, 2, 'bob'),
],
[makePayer(1, 1, 100, 'alice'), makePayer(2, 2, 60, 'bob')],
);
const result = calculateSettlement(1);
const alice = result.balances.find(b => b.user_id === 1)!;
const bob = result.balances.find(b => b.user_id === 2)!;
expect(alice.balance).toBe(20);
expect(bob.balance).toBe(-20);
expect(result.flows).toHaveLength(1);
expect(result.flows[0].amount).toBe(20);
});
it('counts a settlement with no matching expense as an amount still to square up', () => {
// bob paid alice 30 but every expense behind it was deleted: alice now owes bob.
mockDb.db.prepare.mockImplementation((sql: string) => {
if (sql.includes('FROM budget_settlements')) {
return { all: vi.fn(() => [
{ id: 1, trip_id: 1, from_user_id: 2, to_user_id: 1, amount: 30, from_username: 'bob', to_username: 'alice', from_avatar: null, to_avatar: null },
]), get: vi.fn(), run: vi.fn() };
}
return { all: vi.fn(() => []), get: vi.fn(), run: vi.fn() };
});
const result = calculateSettlement(1);
const alice = result.balances.find(b => b.user_id === 1)!;
const bob = result.balances.find(b => b.user_id === 2)!;
expect(bob.balance).toBe(30);
expect(alice.balance).toBe(-30);
expect(result.flows).toEqual([
expect.objectContaining({ amount: 30, from: expect.objectContaining({ user_id: 1 }), to: expect.objectContaining({ user_id: 2 }) }),
]);
});
it('#1335 converts a foreign expense with the frozen exchange_rate, not live rates', () => {
// $110 booked at a frozen rate of 1.1 (USD per 1 EUR) = 100 EUR. Live rates have since
// drifted to 1.2, but the converted amount must stay on the frozen rate so an already
// settled position isn't re-opened with a residual.
setupDb(
[{ ...makeItem(1, 110), currency: 'USD', exchange_rate: 1.1 } as BudgetItem],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob')],
[makePayer(1, 1, 110, 'alice')],
);
const result = calculateSettlement(1, { base: 'EUR', tripCurrency: 'EUR', rates: { EUR: 1, USD: 1.2 } });
const bob = result.balances.find(b => b.user_id === 2)!;
// 110 / 1.1 = 100 EUR; Bob owes half = 50 (frozen). With the live 1.2 it would be ~45.83.
expect(bob.balance).toBeCloseTo(-50, 2);
});
it('#1335 a legacy row (exchange_rate = 1) still converts with live rates', () => {
setupDb(
[{ ...makeItem(1, 120), currency: 'USD', exchange_rate: 1 } as BudgetItem],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob')],
[makePayer(1, 1, 120, 'alice')],
);
const result = calculateSettlement(1, { base: 'EUR', tripCurrency: 'EUR', rates: { EUR: 1, USD: 1.2 } });
const bob = result.balances.find(b => b.user_id === 2)!;
// 120 / 1.2 (live) = 100 EUR; Bob owes 50 — unchanged behaviour for pre-#1335 rows.
expect(bob.balance).toBeCloseTo(-50, 2);
});
it('#1445 a settle-up transfer with a frozen currency+rate keeps the position balanced when rates drift', () => {
// Trip currency EUR; Bob viewed in USD (display) and owes Alice 50 EUR = 62.50 USD
// at the settle-time rate of 1.25 USD/EUR. He records that 62.50 USD transfer, which
// freezes currency=USD, exchange_rate=1.25. Live rates have since drifted (now the
// recompute passes EUR=0.5 per 1 USD), but the frozen transfer still nets to -50+50=0.
setupDb(
[makeItem(1, 100)], // trip-currency expense (currency NULL)
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob')],
[makePayer(1, 1, 100, 'alice')],
[makeSettlementRow(1, 2, 1, 62.5, 'USD', 1.25)],
);
const result = calculateSettlement(1, { base: 'USD', tripCurrency: 'EUR', rates: { USD: 1, EUR: 0.5 } });
const bob = result.balances.find(b => b.user_id === 2)!;
expect(bob.balance).toBeCloseTo(0, 2); // settled — no residual re-opens
});
it('#1445 a legacy settle-up transfer (currency NULL) still converts with live rates', () => {
// Same shape, but the transfer predates the fix (currency NULL). It is re-converted
// to trip currency with live rates, so a drift re-opens the position — unchanged
// legacy behaviour that normalises once the row is re-edited.
setupDb(
[makeItem(1, 100)],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob')],
[makePayer(1, 1, 100, 'alice')],
[makeSettlementRow(1, 2, 1, 62.5, null, 1)],
);
const result = calculateSettlement(1, { base: 'USD', tripCurrency: 'EUR', rates: { USD: 1, EUR: 0.5 } });
const bob = result.balances.find(b => b.user_id === 2)!;
// settleToTrip(62.5) = 62.5 * 0.5 = 31.25 EUR; balance -50 + 31.25 = -18.75 EUR → reopens.
expect(Math.abs(bob.balance)).toBeGreaterThan(1);
});
// ── Multi-payer (#1426 regression): several people front one bill ──────────
// The UI could only send one payer between 3.2.0 and this fix, but the ledger
// has credited each payer individually since 3.1.0. These pin that.
it('2 payers, 3 members: each payer is credited what they actually paid', () => {
// $90 bill split 3 ways ($30 each). Alice and Bob each fronted $45.
// Alice: +45 - 30 = +15. Bob: +45 - 30 = +15. Carol: -30.
setupDb(
[makeItem(1, 90)],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob'), makeMember(1, 3, 'carol')],
[makePayer(1, 1, 45, 'alice'), makePayer(1, 2, 45, 'bob')],
);
const result = calculateSettlement(1);
const balance = (uid: number) => result.balances.find(b => b.user_id === uid)!.balance;
expect(balance(1)).toBeCloseTo(15, 2);
expect(balance(2)).toBeCloseTo(15, 2);
expect(balance(3)).toBeCloseTo(-30, 2);
});
it('2 payers with unequal amounts: credits follow the actual amounts paid', () => {
// $100 bill split 2 ways ($50 each). Alice fronted $70, Bob fronted $30.
// Alice: +70 - 50 = +20. Bob: +30 - 50 = -20. Bob owes Alice $20.
setupDb(
[makeItem(1, 100)],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob')],
[makePayer(1, 1, 70, 'alice'), makePayer(1, 2, 30, 'bob')],
);
const result = calculateSettlement(1);
const balance = (uid: number) => result.balances.find(b => b.user_id === uid)!.balance;
expect(balance(1)).toBeCloseTo(20, 2);
expect(balance(2)).toBeCloseTo(-20, 2);
expect(result.flows).toHaveLength(1);
expect(result.flows[0].from.user_id).toBe(2);
expect(result.flows[0].to.user_id).toBe(1);
expect(result.flows[0].amount).toBeCloseTo(20, 2);
});
it('multi-payer balances sum to zero (no money invented or destroyed)', () => {
// The invariant that makes settle-up trustworthy: credits == debits.
setupDb(
[makeItem(1, 90), makeItem(2, 55)],
[
makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob'), makeMember(1, 3, 'carol'),
makeMember(2, 1, 'alice'), makeMember(2, 3, 'carol'),
],
[
makePayer(1, 1, 45, 'alice'), makePayer(1, 2, 45, 'bob'),
makePayer(2, 2, 25, 'bob'), makePayer(2, 3, 30, 'carol'),
],
);
const result = calculateSettlement(1);
const sum = result.balances.reduce((a, b) => a + b.balance, 0);
expect(sum).toBeCloseTo(0, 2);
});
it('3 payers on one bill: an odd total still splits to the cent', () => {
// $100.01 split 3 ways. splitEqualShares distributes the remainder cent,
// so debits must still exactly cancel the $100.01 of credits.
setupDb(
[makeItem(1, 100.01)],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob'), makeMember(1, 3, 'carol')],
[makePayer(1, 1, 33.34, 'alice'), makePayer(1, 2, 33.34, 'bob'), makePayer(1, 3, 33.33, 'carol')],
);
const result = calculateSettlement(1);
const sum = result.balances.reduce((a, b) => a + b.balance, 0);
expect(sum).toBeCloseTo(0, 2);
});
});
// ── freezeForeignRate (write-path FX freeze, #1445) ───────────────────────────
describe('freezeForeignRate', () => {
const tripRow = (currency: string) => ({
get: vi.fn(() => ({ currency })), all: vi.fn(), run: vi.fn(),
});
it('freezes the live rate for a foreign currency into exchange_rate', async () => {
mockDb.db.prepare.mockImplementation((sql: string) => {
if (sql.includes('FROM trips')) return tripRow('EUR');
return { get: vi.fn(), all: vi.fn(() => []), run: vi.fn() };
});
mockRates.getRates.mockResolvedValue({ EUR: 1, USD: 1.25 });
const data: { currency?: string | null; exchange_rate?: number } = { currency: 'usd' };
await freezeForeignRate(1, data);
expect(mockRates.getRates).toHaveBeenCalledWith('EUR');
expect(data.exchange_rate).toBe(1.25);
});
it('leaves the rate unset when the currency equals the trip currency', async () => {
mockDb.db.prepare.mockImplementation((sql: string) =>
sql.includes('FROM trips') ? tripRow('EUR') : { get: vi.fn(), all: vi.fn(() => []), run: vi.fn() });
const data: { currency?: string | null; exchange_rate?: number } = { currency: 'EUR' };
await freezeForeignRate(1, data);
expect(mockRates.getRates).not.toHaveBeenCalled();
expect(data.exchange_rate).toBeUndefined();
});
it('respects an explicit exchange_rate from the caller', async () => {
const data: { currency?: string | null; exchange_rate?: number } = { currency: 'USD', exchange_rate: 2 };
await freezeForeignRate(1, data);
expect(mockRates.getRates).not.toHaveBeenCalled();
expect(data.exchange_rate).toBe(2);
});
it('degrades to live rates (no freeze) when the rate fetch fails', async () => {
mockDb.db.prepare.mockImplementation((sql: string) =>
sql.includes('FROM trips') ? tripRow('EUR') : { get: vi.fn(), all: vi.fn(() => []), run: vi.fn() });
mockRates.getRates.mockResolvedValue(null);
const data: { currency?: string | null; exchange_rate?: number } = { currency: 'USD' };
await freezeForeignRate(1, data);
expect(data.exchange_rate).toBeUndefined();
});
it('does not re-freeze on update when the currency is unchanged', async () => {
mockDb.db.prepare.mockImplementation((sql: string) => {
if (sql.includes('FROM budget_items')) return { get: vi.fn(() => ({ currency: 'USD' })), all: vi.fn(), run: vi.fn() };
if (sql.includes('FROM trips')) return tripRow('EUR');
return { get: vi.fn(), all: vi.fn(() => []), run: vi.fn() };
});
const data: { currency?: string | null; exchange_rate?: number } = { currency: 'USD' };
await freezeForeignRate(1, data, 9);
expect(mockRates.getRates).not.toHaveBeenCalled();
expect(data.exchange_rate).toBeUndefined();
});
it('does not re-freeze a settlement edit when its stored currency is unchanged (#1445)', async () => {
mockDb.db.prepare.mockImplementation((sql: string) =>
sql.includes('FROM trips') ? tripRow('EUR') : { get: vi.fn(), all: vi.fn(() => []), run: vi.fn() });
const data: { currency?: string | null; exchange_rate?: number } = { currency: 'USD' };
// the settlement already holds USD — pass it as existingCurrency → keep the frozen rate
await freezeForeignRate(1, data, undefined, 'USD');
expect(mockRates.getRates).not.toHaveBeenCalled();
expect(data.exchange_rate).toBeUndefined();
});
it('re-freezes a settlement edit when its currency actually changes', async () => {
mockDb.db.prepare.mockImplementation((sql: string) =>
sql.includes('FROM trips') ? tripRow('EUR') : { get: vi.fn(), all: vi.fn(() => []), run: vi.fn() });
mockRates.getRates.mockResolvedValue({ EUR: 1, USD: 1.25 });
const data: { currency?: string | null; exchange_rate?: number } = { currency: 'USD' };
await freezeForeignRate(1, data, undefined, 'GBP'); // was GBP → now USD → re-freeze
expect(data.exchange_rate).toBe(1.25);
});
});
// ── updateSettlement ──────────────────────────────────────────────────────────
describe('updateSettlement', () => {
it('returns null when the settlement is not in the trip', () => {
mockDb.db.prepare.mockImplementation((sql: string) => {
if (sql.includes('SELECT id FROM budget_settlements')) {
return { get: vi.fn(() => undefined), all: vi.fn(), run: vi.fn() };
}
return { get: vi.fn(), all: vi.fn(() => []), run: vi.fn() };
});
expect(updateSettlement(7, 1, { from_user_id: 2, to_user_id: 1, amount: 10 })).toBeNull();
});
it('updates the row (rounded to cents) and returns the refreshed settlement', () => {
const run = vi.fn();
mockDb.db.prepare.mockImplementation((sql: string) => {
if (sql.includes('SELECT id FROM budget_settlements')) {
return { get: vi.fn(() => ({ id: 7 })), all: vi.fn(), run: vi.fn() };
}
if (sql.includes('UPDATE budget_settlements')) {
return { get: vi.fn(), all: vi.fn(), run };
}
if (sql.includes('FROM budget_settlements')) {
return { get: vi.fn(), all: vi.fn(() => [
{ id: 7, trip_id: 1, from_user_id: 2, to_user_id: 1, amount: 10.13, from_username: 'bob', to_username: 'alice', from_avatar: null, to_avatar: null },
]), run: vi.fn() };
}
return { get: vi.fn(), all: vi.fn(() => []), run: vi.fn() };
});
const res = updateSettlement(7, 1, { from_user_id: 2, to_user_id: 1, amount: 10.126 });
// from, to, rounded amount, currency-flag(0)/value(null), rate-flag(null)/value(1), id.
// No currency/exchange_rate passed → both CASE guards keep the existing columns.
expect(run).toHaveBeenCalledWith(2, 1, 10.13, 0, null, null, 1, 7);
expect(res).toMatchObject({ id: 7, from_user_id: 2, to_user_id: 1, amount: 10.13 });
});
});
@@ -1,349 +0,0 @@
/**
* DB-backed unit tests for budgetService trip-scoping (BUDGET-SVC-DB-001+).
* Uses a real in-memory SQLite DB so the SQL WHERE clauses are exercised.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
// Frozen snapshot of the rates in play in #1543 (rates[X] = units of X per 1 base).
const RATES: Record<string, Record<string, number>> = {
RUB: { RUB: 1, USD: 0.013042, EUR: 0.011412 },
EUR: { EUR: 1, USD: 1.1429, RUB: 87.63 },
};
vi.mock('../../../src/services/exchangeRateService', () => ({
getRates: vi.fn(async (base: string) => RATES[base.toUpperCase()] ?? null),
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { createBudgetItem, updateBudgetItem, updateMembers, toggleMemberPaid, calculateSettlement, rebaseTripCurrency } from '../../../src/services/budgetService';
import { createGuest, deleteGuest } from '../../../src/services/tripService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
function paidFlag(itemId: number, memberId: number): number | undefined {
const row = testDb
.prepare('SELECT paid FROM budget_item_members WHERE budget_item_id = ? AND user_id = ?')
.get(itemId, memberId) as { paid: number } | undefined;
return row?.paid;
}
describe('deleting a member re-splits their expenses (#1553)', () => {
function personsOf(itemId: number): number | null {
return (testDb.prepare('SELECT persons FROM budget_items WHERE id = ?').get(itemId) as { persons: number | null }).persons;
}
function memberCount(itemId: number): number {
return (testDb.prepare('SELECT COUNT(*) AS count FROM budget_item_members WHERE budget_item_id = ?')
.get(itemId) as { count: number }).count;
}
it('BUDGET-SVC-DB-010: re-derives the persons divisor when a guest in the split is deleted', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const guests = ['G1', 'G2', 'G3'].map(n => createGuest(trip.id, n, owner.id).member);
const item = createBudgetItem(trip.id, {
name: 'Dinner', total_price: 400,
member_ids: [owner.id, ...guests.map(g => g.id)],
});
expect(personsOf(item.id)).toBe(4);
deleteGuest(trip.id, guests[0].id);
deleteGuest(trip.id, guests[1].id);
// The member rows cascade with the users row; `persons` is denormalized and has to
// be re-derived, or the per-person column keeps dividing by the departed.
expect(memberCount(item.id)).toBe(2);
expect(personsOf(item.id)).toBe(2);
});
it('BUDGET-SVC-DB-011: leaves a manually entered persons count alone', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const guest = createGuest(trip.id, 'G1', owner.id).member;
// No member rows — `persons` is just a number someone typed.
const item = createBudgetItem(trip.id, { name: 'Rental', total_price: 300, persons: 6 });
deleteGuest(trip.id, guest.id);
expect(personsOf(item.id)).toBe(6);
});
it('BUDGET-SVC-DB-012: drops the last member to a null divisor rather than zero', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const guest = createGuest(trip.id, 'G1', owner.id).member;
const item = createBudgetItem(trip.id, { name: 'Taxi', total_price: 50, member_ids: [guest.id] });
deleteGuest(trip.id, guest.id);
expect(memberCount(item.id)).toBe(0);
expect(personsOf(item.id)).toBeNull();
});
it('BUDGET-SVC-DB-013: saves a split from a stale client instead of failing on the users FK', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const guest = createGuest(trip.id, 'G1', owner.id).member;
const item = createBudgetItem(trip.id, { name: 'Dinner', total_price: 200, member_ids: [owner.id, guest.id] });
deleteGuest(trip.id, guest.id);
// A client that loaded before the deletion still sends the guest back (#1553).
const updated = updateBudgetItem(item.id, trip.id, { member_ids: [owner.id, guest.id] });
expect(updated!.members.map(m => m.user_id)).toEqual([owner.id]);
expect(personsOf(item.id)).toBe(1);
});
it('BUDGET-SVC-DB-014: ignores a deleted member arriving through updateMembers', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const guest = createGuest(trip.id, 'G1', owner.id).member;
const item = createBudgetItem(trip.id, { name: 'Drinks', total_price: 60, member_ids: [owner.id, guest.id] });
deleteGuest(trip.id, guest.id);
const result = updateMembers(item.id, trip.id, [owner.id, guest.id]);
expect(result!.members.map(m => m.user_id)).toEqual([owner.id]);
expect(personsOf(item.id)).toBe(1);
});
});
describe('toggleMemberPaid trip-scoping', () => {
it('BUDGET-SVC-DB-001: toggles paid for an item that belongs to the given trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip A' });
const item = createBudgetItem(trip.id, { name: 'Hotel', total_price: 100 });
updateMembers(item.id, trip.id, [user.id]);
const member = toggleMemberPaid(item.id, trip.id, user.id, true);
expect(member).not.toBeNull();
expect(paidFlag(item.id, user.id)).toBe(1);
});
it('BUDGET-SVC-DB-002: refuses to toggle an item from a different trip (cross-trip IDOR)', () => {
const { user } = createUser(testDb);
const tripA = createTrip(testDb, user.id, { title: 'Trip A' });
const tripB = createTrip(testDb, user.id, { title: 'Trip B' });
const itemB = createBudgetItem(tripB.id, { name: 'Foreign expense', total_price: 50 });
updateMembers(itemB.id, tripB.id, [user.id]);
// Caller passes a trip they can access (A) but the item lives in trip B.
const member = toggleMemberPaid(itemB.id, tripA.id, user.id, true);
expect(member).toBeNull();
expect(paidFlag(itemB.id, user.id)).toBe(0); // unchanged
});
});
describe('calculateSettlement custom splits', () => {
it('BUDGET-SVC-DB-003: settles by the custom per-member amounts, not the equal split (#1458)', () => {
const { user: alice } = createUser(testDb, { username: 'alice' });
const { user: bob } = createUser(testDb, { username: 'bob' });
const trip = createTrip(testDb, alice.id, { title: 'Trip' });
// 100 total, custom split: Alice owes 90, Bob owes 10. Alice paid the whole bill.
createBudgetItem(trip.id, {
name: 'Dinner',
payers: [{ user_id: alice.id, amount: 100 }],
members: [
{ user_id: alice.id, amount: 90 },
{ user_id: bob.id, amount: 10 },
],
});
const result = calculateSettlement(trip.id);
// Alice paid 100 but owes 90 → net +10 (creditor); Bob owes 10 → net -10 (debtor).
// With the equal-split bug both owe 50, so the flow would be 50 instead of 10.
expect(result.flows).toEqual([
expect.objectContaining({
from: expect.objectContaining({ user_id: bob.id }),
to: expect.objectContaining({ user_id: alice.id }),
amount: 10,
}),
]);
});
});
/** The exact trip from #1543: RUB base, three members, one expense booked in USD. */
function seedIssue1543Trip(tripCurrency: string) {
const { user: me } = createUser(testDb, { username: 'me' });
const { user: danil } = createUser(testDb, { username: 'danil' });
const { user: serega } = createUser(testDb, { username: 'serega' });
const trip = createTrip(testDb, me.id, { title: 'Trip' });
testDb.prepare('UPDATE trips SET currency = ? WHERE id = ?').run(tripCurrency, trip.id);
const members = [{ user_id: me.id }, { user_id: danil.id }, { user_id: serega.id }];
// 9 000 ₽ nobody has paid yet, 9 000 ₽ paid by me, and $100 paid by me. The USD row
// carries the rate frozen at entry time: units of USD per 1 RUB.
createBudgetItem(trip.id, { name: 'Проезд обратно', total_price: 9000, currency: 'RUB', members });
createBudgetItem(trip.id, { name: 'Проезд туда', currency: 'RUB', payers: [{ user_id: me.id, amount: 9000 }], members });
createBudgetItem(trip.id, {
name: 'test', currency: 'USD', exchange_rate: 0.013042,
payers: [{ user_id: me.id, amount: 100 }], members,
});
return { trip, me, danil, serega };
}
describe('calculateSettlement with a foreign-currency expense (#1543)', () => {
it('BUDGET-SVC-DB-004: nets in the trip currency instead of inflating the foreign share ~27x', () => {
const { trip, me, danil, serega } = seedIssue1543Trip('RUB');
const result = calculateSettlement(trip.id, { base: 'RUB', tripCurrency: 'RUB', rates: RATES.RUB });
const balanceOf = (id: number) => result.balances.find(b => b.user_id === id)!.balance;
// Total spend is 9 000 + 9 000 + $100 (≈7 668 ₽), so each of the three owes a third
// of it and I am owed back everything I fronted beyond my own share. The bug divided
// the RUB shares by the USD rate and reported +451 092 / −230 080 / −230 012 instead.
// Tolerance is a rouble: the cent-rotation in splitEqualShares moves the odd cent of
// the $100 between members, which the USD rate magnifies ~77x.
const totalSpend = 18000 + 100 / RATES.RUB.USD;
const share = totalSpend / 3;
expect(balanceOf(me.id)).toBeCloseTo(9000 + 100 / RATES.RUB.USD - share, -1);
expect(balanceOf(danil.id)).toBeCloseTo(-share, -1);
expect(balanceOf(serega.id)).toBeCloseTo(-share, -1);
// The 9 000 ₽ expense nobody paid is the only imbalance in the trip.
expect(result.balances.reduce((a, b) => a + b.balance, 0)).toBeCloseTo(-9000, 1);
});
it('BUDGET-SVC-DB-005: reports the same balances when the display currency differs from the trip currency', () => {
const { trip, danil } = seedIssue1543Trip('RUB');
// Same trip, viewed in EUR: every balance is the RUB one converted once, at the end.
const inEur = calculateSettlement(trip.id, { base: 'EUR', tripCurrency: 'RUB', rates: RATES.EUR });
const danilEur = inEur.balances.find(b => b.user_id === danil.id)!.balance;
const shareRub = (18000 + 100 / RATES.RUB.USD) / 3;
expect(danilEur).toBeCloseTo(-shareRub / RATES.EUR.RUB, 0);
});
});
describe('rebaseTripCurrency', () => {
const itemRow = (id: number) =>
testDb.prepare('SELECT currency, exchange_rate FROM budget_items WHERE id = ?')
.get(id) as { currency: string | null; exchange_rate: number };
it('BUDGET-SVC-DB-006: pins currency-less expenses to the outgoing currency and re-freezes the rest', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip' });
testDb.prepare("UPDATE trips SET currency = 'EUR' WHERE id = ?").run(trip.id);
const members = [{ user_id: user.id }];
// An expense that inherits the trip's base (currency NULL), one booked in USD, and
// one already in the incoming currency.
const implicit = createBudgetItem(trip.id, { name: 'Implicit', total_price: 100, members }) as { id: number };
const usd = createBudgetItem(trip.id, { name: 'USD', total_price: 100, currency: 'USD', exchange_rate: 1.1429, members }) as { id: number };
const rub = createBudgetItem(trip.id, { name: 'RUB', total_price: 9000, currency: 'RUB', exchange_rate: 87.63, members }) as { id: number };
await rebaseTripCurrency(trip.id, 'RUB');
// The implicit row really held euros, so it is stamped EUR rather than silently
// becoming 100 ₽, and every rate is re-anchored to the new base.
expect(itemRow(implicit.id)).toEqual({ currency: 'EUR', exchange_rate: RATES.RUB.EUR });
expect(itemRow(usd.id)).toEqual({ currency: 'USD', exchange_rate: RATES.RUB.USD });
// Already in the trip's new currency → no conversion left to freeze.
expect(itemRow(rub.id)).toEqual({ currency: 'RUB', exchange_rate: 1 });
});
it('BUDGET-SVC-DB-007: keeps every balance at the same real-world value across the switch', async () => {
const { user: alice } = createUser(testDb, { username: 'alice' });
const { user: bob } = createUser(testDb, { username: 'bob' });
const trip = createTrip(testDb, alice.id, { title: 'Trip' });
testDb.prepare("UPDATE trips SET currency = 'EUR' WHERE id = ?").run(trip.id);
const members = [{ user_id: alice.id }, { user_id: bob.id }];
createBudgetItem(trip.id, { name: 'Hotel', payers: [{ user_id: alice.id, amount: 100 }], members });
createBudgetItem(trip.id, { name: 'Dinner', currency: 'USD', exchange_rate: 1.1429, payers: [{ user_id: bob.id, amount: 60 }], members });
const before = calculateSettlement(trip.id, { base: 'EUR', tripCurrency: 'EUR', rates: RATES.EUR });
await rebaseTripCurrency(trip.id, 'RUB');
testDb.prepare("UPDATE trips SET currency = 'RUB' WHERE id = ?").run(trip.id);
const after = calculateSettlement(trip.id, { base: 'RUB', tripCurrency: 'RUB', rates: RATES.RUB });
for (const b of before.balances) {
const rub = after.balances.find(x => x.user_id === b.user_id)!.balance;
expect(rub).toBeCloseTo(b.balance * 87.63, 0); // same money, different unit
}
});
it('BUDGET-SVC-DB-009: pins currency-less place prices to the outgoing currency', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip' });
testDb.prepare("UPDATE trips SET currency = 'EUR' WHERE id = ?").run(trip.id);
const priced = (price: number | null, currency: string | null) => {
const r = testDb.prepare('INSERT INTO places (trip_id, name, price, currency) VALUES (?, ?, ?, ?)')
.run(trip.id, 'Place', price, currency);
return Number(r.lastInsertRowid);
};
// A place that inherits the trip's base (currency NULL), one priced in its own
// currency, and one with no price at all.
const implicit = priced(15, null);
const jpy = priced(1500, 'JPY');
const free = priced(null, null);
await rebaseTripCurrency(trip.id, 'JPY');
const placeRow = (id: number) =>
testDb.prepare('SELECT price, currency FROM places WHERE id = ?')
.get(id) as { price: number | null; currency: string | null };
// The implicit place really held euros, so it is stamped EUR rather than silently
// becoming ¥15 — the amount the user typed is never rewritten.
expect(placeRow(implicit)).toEqual({ price: 15, currency: 'EUR' });
expect(placeRow(jpy)).toEqual({ price: 1500, currency: 'JPY' });
// Nothing to denominate without a price: leave it inheriting the trip's currency.
expect(placeRow(free)).toEqual({ price: null, currency: null });
});
it('BUDGET-SVC-DB-008: is a no-op when the currency is unchanged', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip' });
testDb.prepare("UPDATE trips SET currency = 'EUR' WHERE id = ?").run(trip.id);
const item = createBudgetItem(trip.id, { name: 'Implicit', total_price: 100, members: [{ user_id: user.id }] }) as { id: number };
await rebaseTripCurrency(trip.id, 'EUR');
expect(itemRow(item.id)).toEqual({ currency: null, exchange_rate: 1 });
});
});
@@ -1,189 +0,0 @@
/**
* Unit tests for categoryService — CAT-SVC-001 through CAT-SVC-015.
* Uses a real in-memory SQLite DB so SQL logic is exercised faithfully.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
import {
listCategories,
createCategory,
getCategoryById,
updateCategory,
deleteCategory,
} from '../../../src/services/categoryService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ── listCategories ────────────────────────────────────────────────────────────
describe('listCategories', () => {
it('CAT-SVC-001 — returns an array (seeded defaults are present after migrations)', () => {
// Migrations seed default categories, so the list is never empty in a fully initialized DB
const cats = listCategories() as any[];
expect(Array.isArray(cats)).toBe(true);
expect(cats.length).toBeGreaterThan(0);
});
it('CAT-SVC-002 — results are ordered by name ascending (custom categories sort correctly)', () => {
const { user } = createUser(testDb);
createCategory(user.id, 'Zoo');
createCategory(user.id, 'Aquarium');
// Migrations seed default categories; verify ordering by checking our custom ones appear in sorted order
const names = (listCategories() as any[]).map((c: any) => c.name);
const aquariumIdx = names.indexOf('Aquarium');
const zooIdx = names.indexOf('Zoo');
expect(aquariumIdx).toBeGreaterThanOrEqual(0);
expect(zooIdx).toBeGreaterThanOrEqual(0);
expect(aquariumIdx).toBeLessThan(zooIdx);
});
it('CAT-SVC-003 — returns categories from all users (including seeded defaults)', () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
const before = (listCategories() as any[]).length;
createCategory(a.id, 'Cat-A');
createCategory(b.id, 'Cat-B');
expect(listCategories()).toHaveLength(before + 2);
});
});
// ── createCategory ────────────────────────────────────────────────────────────
describe('createCategory', () => {
it('CAT-SVC-004 — creates a category with name, color, and icon', () => {
const { user } = createUser(testDb);
const cat = createCategory(user.id, 'Restaurant', '#ff5500', '🍽️') as any;
expect(cat.name).toBe('Restaurant');
expect(cat.color).toBe('#ff5500');
expect(cat.icon).toBe('🍽️');
expect(cat.user_id).toBe(user.id);
});
it('CAT-SVC-005 — defaults color to #6366f1 when not provided', () => {
const { user } = createUser(testDb);
const cat = createCategory(user.id, 'Default Color') as any;
expect(cat.color).toBe('#6366f1');
});
it('CAT-SVC-006 — defaults icon to 📍 when not provided', () => {
const { user } = createUser(testDb);
const cat = createCategory(user.id, 'Default Icon') as any;
expect(cat.icon).toBe('📍');
});
it('CAT-SVC-007 — returns the inserted row with an id', () => {
const { user } = createUser(testDb);
const cat = createCategory(user.id, 'WithId') as any;
expect(typeof cat.id).toBe('number');
expect(cat.id).toBeGreaterThan(0);
});
});
// ── getCategoryById ───────────────────────────────────────────────────────────
describe('getCategoryById', () => {
it('CAT-SVC-008 — returns category for a valid id', () => {
const { user } = createUser(testDb);
const created = createCategory(user.id, 'Find Me') as any;
const found = getCategoryById(created.id) as any;
expect(found).toBeDefined();
expect(found.name).toBe('Find Me');
});
it('CAT-SVC-009 — returns undefined for non-existent id', () => {
expect(getCategoryById(99999)).toBeUndefined();
});
it('CAT-SVC-010 — accepts string id (coerced by SQLite)', () => {
const { user } = createUser(testDb);
const created = createCategory(user.id, 'StringId') as any;
const found = getCategoryById(String(created.id)) as any;
expect(found).toBeDefined();
expect(found.id).toBe(created.id);
});
});
// ── updateCategory ────────────────────────────────────────────────────────────
describe('updateCategory', () => {
it('CAT-SVC-011 — updates name, color, and icon', () => {
const { user } = createUser(testDb);
const cat = createCategory(user.id, 'Old', '#aaaaaa', '❓') as any;
const updated = updateCategory(cat.id, 'New', '#bbbbbb', '✅') as any;
expect(updated.name).toBe('New');
expect(updated.color).toBe('#bbbbbb');
expect(updated.icon).toBe('✅');
});
it('CAT-SVC-012 — COALESCE: omitting name preserves existing name', () => {
const { user } = createUser(testDb);
const cat = createCategory(user.id, 'KeepName', '#aaaaaa', '⭐') as any;
const updated = updateCategory(cat.id, undefined, '#cccccc', '🔥') as any;
expect(updated.name).toBe('KeepName');
expect(updated.color).toBe('#cccccc');
});
it('CAT-SVC-013 — COALESCE: omitting color preserves existing color', () => {
const { user } = createUser(testDb);
const cat = createCategory(user.id, 'KeepColor', '#dddddd', '⭐') as any;
const updated = updateCategory(cat.id, 'NewName', undefined, '🌟') as any;
expect(updated.name).toBe('NewName');
expect(updated.color).toBe('#dddddd');
});
});
// ── deleteCategory ────────────────────────────────────────────────────────────
describe('deleteCategory', () => {
it('CAT-SVC-014 — deletes the category from the database', () => {
const { user } = createUser(testDb);
const cat = createCategory(user.id, 'ToDelete') as any;
deleteCategory(cat.id);
expect(getCategoryById(cat.id)).toBeUndefined();
});
it('CAT-SVC-015 — deleting a non-existent category does not throw', () => {
expect(() => deleteCategory(99999)).not.toThrow();
});
});
@@ -1,193 +0,0 @@
/**
* A plugin channel may only ever ADD a channel — never override or shadow a built-in.
*
* The runtime mints plugin ids with pluginChannelId() and leaves the built-in-only
* privileges off, so none of this is reachable through a manifest. These tests pin the
* REGISTRY's own enforcement, so the guarantee survives a bug or a future caller that
* hands the registry a channel it shouldn't. Without it, a channel claiming `email`
* rides the user's email opt-in and receives admin-scoped notifications.
*/
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: () => null, isOwner: () => false, getPlaceWithTags: () => null } };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'x'.repeat(40), ENCRYPTION_KEY: 'a'.repeat(64), updateJwtSecret: () => {} }));
vi.mock('../../../src/services/apiKeyCrypto', () => ({ decrypt_api_key: (v: string) => v, maybe_encrypt_api_key: (v: string) => v, encrypt_api_key: (v: string) => v }));
const { sendMailMock } = vi.hoisted(() => ({ sendMailMock: vi.fn().mockResolvedValue({ accepted: ['a@b.c'] }) }));
vi.mock('nodemailer', () => ({ default: { createTransport: vi.fn(() => ({ sendMail: sendMailMock, verify: vi.fn() })) } }));
vi.stubGlobal('fetch', vi.fn());
vi.mock('../../../src/websocket', () => ({ broadcastToUser: vi.fn() }));
vi.mock('../../../src/utils/ssrfGuard', () => ({ checkSsrf: vi.fn(async () => ({ allowed: true, resolvedIp: '1.2.3.4' })), createPinnedDispatcher: vi.fn(() => ({})) }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createAdmin, setAppSetting, setNotificationChannels } from '../../helpers/factories';
import { send } from '../../../src/services/notificationService';
import { getPreferencesMatrix } from '../../../src/services/notificationPreferencesService';
import {
setPluginChannelSource,
listChannels,
getChannel,
registerChannel,
type ExternalChannel,
} from '../../../src/services/notifications/channelRegistry';
beforeAll(() => { createTables(testDb); runMigrations(testDb); });
beforeEach(() => { resetTestDb(testDb); setPluginChannelSource(null); });
const rogueSend = vi.fn().mockResolvedValue(true);
const rogueGlobal = vi.fn().mockResolvedValue(true);
function setSmtp(): void {
setAppSetting(testDb, 'smtp_host', 'mail.test.com');
setAppSetting(testDb, 'smtp_port', '587');
setAppSetting(testDb, 'smtp_from', 'trek@test.com');
}
/** A channel claiming a BUILT-IN id plus the built-in-only privilege flags. */
function rogue(over: Partial<ExternalChannel> = {}): ExternalChannel {
return {
id: 'email',
source: 'builtin',
bypassesActiveToggleForAdminEvents: true,
supportsAdminGlobal: true,
supportsEvent: () => true,
isConfiguredFor: () => true,
sendToUser: rogueSend,
sendGlobal: rogueGlobal,
...over,
} as ExternalChannel;
}
const TRIP_INVITE = { event: 'trip_invite', actorId: null, scope: 'user', targetId: 0, params: { trip: 'Rome', actor: 'A', invitee: 'B', tripId: '1' } } as const;
describe('a plugin channel can never override a built-in', () => {
beforeEach(() => { rogueSend.mockClear(); rogueGlobal.mockClear(); });
it('CHOVR-001 — a channel claiming a built-in id is dropped from the registry', () => {
setPluginChannelSource(() => [rogue()]);
expect(listChannels().filter(c => c.id === 'email')).toHaveLength(1);
expect(getChannel('email')!.source).toBe('builtin');
});
it('CHOVR-002 — it does NOT ride the user’s email opt-in', async () => {
const { user } = createUser(testDb);
setSmtp();
setNotificationChannels(testDb, 'email'); // the user enabled EMAIL, not a plugin
setPluginChannelSource(() => [rogue()]);
await send({ ...TRIP_INVITE, targetId: user.id });
expect(rogueSend).not.toHaveBeenCalled();
expect(sendMailMock).toHaveBeenCalledTimes(1); // the real email channel still delivers
});
it('CHOVR-003 — an un-namespaced id is dropped even when it collides with nothing', () => {
setPluginChannelSource(() => [rogue({ id: 'carrier-pigeon', source: 'plugin' })]);
expect(listChannels().map(c => c.id)).not.toContain('carrier-pigeon');
});
it('CHOVR-004 — a properly namespaced channel IS admitted', () => {
setPluginChannelSource(() => [rogue({ id: 'plugin:gotify', source: 'plugin' })]);
expect(listChannels().map(c => c.id)).toContain('plugin:gotify');
});
it('CHOVR-005 — an admitted plugin channel has its built-in-only privileges stripped', () => {
setPluginChannelSource(() => [rogue({ id: 'plugin:gotify' })]);
const ch = getChannel('plugin:gotify')!;
expect(ch.source).toBe('plugin'); // it cannot self-declare as a built-in
expect(ch.bypassesActiveToggleForAdminEvents).toBe(false);
expect(ch.supportsAdminGlobal).toBe(false);
expect(ch.sendGlobal).toBeUndefined();
});
it('CHOVR-006 — a plugin channel gets NO admin-scoped event, even claiming to support one', async () => {
createAdmin(testDb);
setSmtp();
setNotificationChannels(testDb, 'plugin:gotify');
// supportsEvent lies and says yes to everything; the registry strips what makes it matter.
setPluginChannelSource(() => [rogue({ id: 'plugin:gotify', supportsEvent: () => true })]);
await send({ event: 'version_available', actorId: null, scope: 'admin', targetId: 0, params: { version: '9.9.9' } });
expect(rogueSend).not.toHaveBeenCalled();
expect(rogueGlobal).not.toHaveBeenCalled();
});
it('CHOVR-007 — duplicate plugin ids collapse to one (no double send, no double column)', async () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'plugin:gotify');
setPluginChannelSource(() => [rogue({ id: 'plugin:gotify' }), rogue({ id: 'plugin:gotify' })]);
expect(listChannels().filter(c => c.id === 'plugin:gotify')).toHaveLength(1);
await send({ ...TRIP_INVITE, targetId: user.id });
expect(rogueSend).toHaveBeenCalledTimes(1);
});
it('CHOVR-008 — the preferences matrix never shows a duplicate column', () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'email');
setPluginChannelSource(() => [rogue()]);
const ids = getPreferencesMatrix(user.id, 'user').channels.map(c => c.id);
expect(ids.filter(i => i === 'email')).toHaveLength(1);
expect(new Set(ids).size).toBe(ids.length);
});
it('CHOVR-009 — a built-in may not claim the plugin namespace either', () => {
expect(() => registerChannel(rogue({ id: 'plugin:sneaky' }))).toThrow(/plugin namespace/);
});
});
describe('a live plugin channel needs no second opt-in', () => {
beforeEach(() => { rogueSend.mockClear(); });
it('CHOVR-011 — it appears in the matrix with NOTHING in notification_channels', () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'none'); // the admin has enabled no built-in at all
setPluginChannelSource(() => [rogue({ id: 'plugin:gotify', source: 'plugin', label: 'Gotify' })]);
const matrix = getPreferencesMatrix(user.id, 'user');
const ch = matrix.channels.find(c => c.id === 'plugin:gotify')!;
// Enabling the PLUGIN is the opt-in. There is no UI that can write a `plugin:` id into
// the notification_channels CSV, so requiring one meant the channel could never show.
expect(ch.active).toBe(true);
expect(ch.label).toBe('Gotify');
expect(matrix.implemented_combos['trip_invite']).toContain('plugin:gotify');
});
it('CHOVR-012 — and it actually DELIVERS with nothing in notification_channels', async () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'none');
setPluginChannelSource(() => [rogue({ id: 'plugin:gotify', source: 'plugin' })]);
await send({ ...TRIP_INVITE, targetId: user.id });
expect(rogueSend).toHaveBeenCalledTimes(1);
});
it('CHOVR-013 — a BUILT-IN still needs its explicit switch', async () => {
const { user } = createUser(testDb);
setSmtp();
setNotificationChannels(testDb, 'none'); // email NOT enabled
sendMailMock.mockClear();
await send({ ...TRIP_INVITE, targetId: user.id });
expect(sendMailMock).not.toHaveBeenCalled();
});
it('CHOVR-014 — an unconfigured user sees the column but gets no delivery', async () => {
const { user } = createUser(testDb);
setPluginChannelSource(() => [rogue({ id: 'plugin:gotify', source: 'plugin', isConfiguredFor: () => false })]);
const ch = getPreferencesMatrix(user.id, 'user').channels.find(c => c.id === 'plugin:gotify')!;
expect(ch.active).toBe(true); // shown — so they can see it and go configure it
expect(ch.configured).toBe(false); // …but flagged as needing setup
await send({ ...TRIP_INVITE, targetId: user.id });
expect(rogueSend).not.toHaveBeenCalled(); // no credentials → nothing to send with
});
});
@@ -1,115 +0,0 @@
/**
* Unit tests for the external notification channel registry.
* Covers CHREG-001 to CHREG-008.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
listChannels,
getChannel,
registerChannel,
setPluginChannelSource,
pluginChannelId,
isPluginChannelId,
__resetChannelsForTest,
type ChannelMessage,
type ExternalChannel,
} from '../../../src/services/notifications/channelRegistry';
import { registerBuiltinChannels } from '../../../src/services/notifications/builtins';
function fakeChannel(id: string, over: Partial<ExternalChannel> = {}): ExternalChannel {
return {
id,
source: 'plugin',
label: id,
supportsEvent: () => true,
isConfiguredFor: () => true,
sendToUser: async () => true,
...over,
};
}
const MSG: ChannelMessage = { event: 'trip_invite', title: 't', body: 'b' };
beforeEach(() => {
__resetChannelsForTest();
registerBuiltinChannels();
});
afterEach(() => {
setPluginChannelSource(null);
});
describe('channelRegistry', () => {
it('CHREG-001 — the three built-in external channels are registered; in-app is not', () => {
expect(listChannels().map(c => c.id)).toEqual(['email', 'webhook', 'ntfy']);
expect(getChannel('inapp')).toBeUndefined();
});
it('CHREG-002 — plugin channels come from the injected source and are namespaced', () => {
setPluginChannelSource(() => [fakeChannel(pluginChannelId('gotify'))]);
expect(listChannels().map(c => c.id)).toContain('plugin:gotify');
expect(getChannel('plugin:gotify')?.source).toBe('plugin');
expect(isPluginChannelId('plugin:gotify')).toBe(true);
expect(isPluginChannelId('email')).toBe(false);
});
it('CHREG-003 — a plugin channel disappears when the runtime stops reporting it', () => {
let live = true;
setPluginChannelSource(() => (live ? [fakeChannel('plugin:gotify')] : []));
expect(getChannel('plugin:gotify')).toBeDefined();
live = false;
expect(getChannel('plugin:gotify')).toBeUndefined();
expect(listChannels().map(c => c.id)).toEqual(['email', 'webhook', 'ntfy']);
});
it('CHREG-004 — a throwing plugin source cannot take notifications down', () => {
setPluginChannelSource(() => {
throw new Error('runtime exploded');
});
expect(listChannels().map(c => c.id)).toEqual(['email', 'webhook', 'ntfy']);
});
it('CHREG-005 — a plugin can never claim a built-in id', () => {
// The prefix is the whole defence: an id without it is not a plugin channel id,
// and pluginChannelId() is the only way the runtime mints one.
expect(pluginChannelId('email')).toBe('plugin:email');
expect(getChannel('email')?.source).toBe('builtin');
});
it('CHREG-006 — only email declares the admin-scoped toggle bypass', () => {
expect(getChannel('email')?.bypassesActiveToggleForAdminEvents).toBe(true);
expect(getChannel('webhook')?.bypassesActiveToggleForAdminEvents).toBeUndefined();
expect(getChannel('ntfy')?.bypassesActiveToggleForAdminEvents).toBeUndefined();
});
it('CHREG-007 — webhook and ntfy deliver the admin-global copy; email does not', () => {
expect(getChannel('webhook')?.supportsAdminGlobal).toBe(true);
expect(getChannel('ntfy')?.supportsAdminGlobal).toBe(true);
expect(getChannel('email')?.supportsAdminGlobal).toBeUndefined();
});
it('CHREG-008 — built-ins carry every event except synology_session_cleared', () => {
for (const id of ['email', 'webhook', 'ntfy']) {
expect(getChannel(id)!.supportsEvent('trip_invite')).toBe(true);
expect(getChannel(id)!.supportsEvent('version_available')).toBe(true);
expect(getChannel(id)!.supportsEvent('synology_session_cleared')).toBe(false);
}
});
it('CHREG-009 — registerChannel replaces an existing id rather than duplicating it', () => {
registerChannel(fakeChannel('email', { source: 'builtin' }));
expect(listChannels().filter(c => c.id === 'email')).toHaveLength(1);
});
it('CHREG-010 — a channel that rejects is the caller’s problem, not the registry’s', async () => {
const boom = fakeChannel('plugin:boom', {
sendToUser: async () => {
throw new Error('nope');
},
});
setPluginChannelSource(() => [boom]);
await expect(getChannel('plugin:boom')!.sendToUser(1, MSG)).rejects.toThrow('nope');
// and the registry is unharmed
expect(listChannels()).toHaveLength(4);
});
});
@@ -1,405 +0,0 @@
/**
* Unit tests for collabService — COLLAB-SVC-001 to COLLAB-SVC-030.
* Covers votePoll edge cases, listMessages pagination, deleteMessage ownership,
* updateNote partial fields, fetchLinkPreview, avatarUrl, createMessage reply validation.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
// ── DB setup ─────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`
SELECT t.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: () => {},
}));
// Stub checkSsrf so fetchLinkPreview tests can control SSRF behaviour
const { mockCheckSsrf, mockCreatePinnedDispatcher } = vi.hoisted(() => ({
mockCheckSsrf: vi.fn(async () => ({ allowed: true, resolvedIp: '93.184.216.34' })),
mockCreatePinnedDispatcher: vi.fn(() => ({})),
}));
vi.mock('../../../src/utils/ssrfGuard', () => ({
checkSsrf: mockCheckSsrf,
createPinnedDispatcher: mockCreatePinnedDispatcher,
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import {
avatarUrl,
votePoll,
listMessages,
createMessage,
deleteMessage,
updateNote,
createNote,
createPoll,
closePoll,
fetchLinkPreview,
} from '../../../src/services/collabService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
mockCheckSsrf.mockResolvedValue({ allowed: true, resolvedIp: '93.184.216.34' });
});
afterAll(() => {
testDb.close();
});
afterEach(() => {
vi.unstubAllGlobals();
mockCheckSsrf.mockReset();
mockCheckSsrf.mockResolvedValue({ allowed: true, resolvedIp: '93.184.216.34' });
});
// ── Helpers ───────────────────────────────────────────────────────────────────
function setup() {
const { user: user1 } = createUser(testDb);
const { user: user2 } = createUser(testDb);
const trip = createTrip(testDb, user1.id);
return { user1, user2, trip };
}
// ── avatarUrl ─────────────────────────────────────────────────────────────────
describe('avatarUrl', () => {
it('COLLAB-SVC-001: returns null when avatar is null', () => {
expect(avatarUrl({ avatar: null })).toBeNull();
});
it('COLLAB-SVC-002: returns upload path when avatar is set', () => {
expect(avatarUrl({ avatar: 'abc.jpg' })).toBe('/uploads/avatars/abc.jpg');
});
it('COLLAB-SVC-003: returns null when avatar is empty string', () => {
expect(avatarUrl({ avatar: '' })).toBeNull();
});
});
// ── votePoll ──────────────────────────────────────────────────────────────────
describe('votePoll', () => {
it('COLLAB-SVC-004: returns error "closed" when poll is closed', () => {
const { user1, trip } = setup();
const poll = createPoll(trip.id, user1.id, { question: 'Q?', options: ['A', 'B'] });
closePoll(trip.id, poll!.id);
const result = votePoll(trip.id, poll!.id, user1.id, 0);
expect(result.error).toBe('closed');
});
it('COLLAB-SVC-005: returns error "invalid_index" for negative index', () => {
const { user1, trip } = setup();
const poll = createPoll(trip.id, user1.id, { question: 'Q?', options: ['A', 'B'] });
const result = votePoll(trip.id, poll!.id, user1.id, -1);
expect(result.error).toBe('invalid_index');
});
it('COLLAB-SVC-006: returns error "invalid_index" for out-of-range index', () => {
const { user1, trip } = setup();
const poll = createPoll(trip.id, user1.id, { question: 'Q?', options: ['A', 'B'] });
const result = votePoll(trip.id, poll!.id, user1.id, 5);
expect(result.error).toBe('invalid_index');
});
it('COLLAB-SVC-007: returns error "not_found" for nonexistent poll', () => {
const { user1, trip } = setup();
const result = votePoll(trip.id, 9999, user1.id, 0);
expect(result.error).toBe('not_found');
});
it('COLLAB-SVC-008: successfully votes and returns poll with voters', () => {
const { user1, trip } = setup();
const poll = createPoll(trip.id, user1.id, { question: 'Q?', options: ['Yes', 'No'] });
const result = votePoll(trip.id, poll!.id, user1.id, 0);
expect(result.error).toBeUndefined();
expect(result.poll).toBeDefined();
expect(result.poll!.options[0].voters).toHaveLength(1);
});
it('COLLAB-SVC-009: toggles vote off when voted again on same option', () => {
const { user1, trip } = setup();
const poll = createPoll(trip.id, user1.id, { question: 'Q?', options: ['Yes', 'No'] });
votePoll(trip.id, poll!.id, user1.id, 0);
const result = votePoll(trip.id, poll!.id, user1.id, 0);
expect(result.poll!.options[0].voters).toHaveLength(0);
});
});
// ── listMessages with before cursor ──────────────────────────────────────────
describe('listMessages', () => {
it('COLLAB-SVC-010: returns all messages when no before cursor', () => {
const { user1, trip } = setup();
createMessage(trip.id, user1.id, 'Hello');
createMessage(trip.id, user1.id, 'World');
const msgs = listMessages(trip.id);
expect(msgs).toHaveLength(2);
});
it('COLLAB-SVC-011: paginates using before cursor (returns messages with id < before)', () => {
const { user1, trip } = setup();
const r1 = createMessage(trip.id, user1.id, 'First');
const r2 = createMessage(trip.id, user1.id, 'Second');
const r3 = createMessage(trip.id, user1.id, 'Third');
const id3 = r3.message!.id;
const msgs = listMessages(trip.id, id3);
expect(msgs.length).toBe(2);
const texts = msgs.map(m => m.text);
expect(texts).toContain('First');
expect(texts).toContain('Second');
expect(texts).not.toContain('Third');
});
it('COLLAB-SVC-012: returns messages in ascending order (reversed after DESC query)', () => {
const { user1, trip } = setup();
createMessage(trip.id, user1.id, 'A');
createMessage(trip.id, user1.id, 'B');
createMessage(trip.id, user1.id, 'C');
const msgs = listMessages(trip.id);
expect(msgs[0].text).toBe('A');
expect(msgs[2].text).toBe('C');
});
it('COLLAB-SVC-013: includes reactions grouped by emoji', () => {
const { user1, trip } = setup();
const r = createMessage(trip.id, user1.id, 'React me');
const msgId = r.message!.id;
testDb.prepare('INSERT INTO collab_message_reactions (message_id, user_id, emoji) VALUES (?, ?, ?)').run(msgId, user1.id, '👍');
const msgs = listMessages(trip.id);
expect(msgs[0].reactions).toBeDefined();
expect(msgs[0].reactions).toHaveLength(1);
expect(msgs[0].reactions[0].emoji).toBe('👍');
});
});
// ── createMessage with invalid replyTo ───────────────────────────────────────
describe('createMessage', () => {
it('COLLAB-SVC-014: returns error when replyTo message does not exist', () => {
const { user1, trip } = setup();
const result = createMessage(trip.id, user1.id, 'Reply to nothing', 9999);
expect(result.error).toBe('reply_not_found');
});
it('COLLAB-SVC-015: creates message with valid replyTo', () => {
const { user1, trip } = setup();
const r1 = createMessage(trip.id, user1.id, 'Original');
const r2 = createMessage(trip.id, user1.id, 'Reply', r1.message!.id);
expect(r2.error).toBeUndefined();
expect(r2.message!.reply_to).toBe(r1.message!.id);
});
});
// ── deleteMessage ownership check ─────────────────────────────────────────────
describe('deleteMessage', () => {
it('COLLAB-SVC-016: returns error "not_owner" when user does not own message', () => {
const { user1, user2, trip } = setup();
const r = createMessage(trip.id, user1.id, 'My message');
const result = deleteMessage(trip.id, r.message!.id, user2.id);
expect(result.error).toBe('not_owner');
});
it('COLLAB-SVC-017: returns error "not_found" for nonexistent message', () => {
const { user1, trip } = setup();
const result = deleteMessage(trip.id, 9999, user1.id);
expect(result.error).toBe('not_found');
});
it('COLLAB-SVC-018: marks message as deleted when owner deletes it', () => {
const { user1, trip } = setup();
const r = createMessage(trip.id, user1.id, 'Delete me');
const result = deleteMessage(trip.id, r.message!.id, user1.id);
expect(result.error).toBeUndefined();
const row = testDb.prepare('SELECT deleted FROM collab_messages WHERE id = ?').get(r.message!.id) as any;
expect(row.deleted).toBe(1);
});
});
// ── updateNote partial fields ─────────────────────────────────────────────────
describe('updateNote', () => {
it('COLLAB-SVC-019: updates only title when other fields are undefined', () => {
const { user1, trip } = setup();
const note = createNote(trip.id, user1.id, { title: 'Original', content: 'Some content', website: 'https://example.com' });
updateNote(trip.id, note.id, { title: 'Updated' });
const updated = testDb.prepare('SELECT * FROM collab_notes WHERE id = ?').get(note.id) as any;
expect(updated.title).toBe('Updated');
expect(updated.content).toBe('Some content'); // unchanged
expect(updated.website).toBe('https://example.com'); // unchanged
});
it('COLLAB-SVC-020: clears content when content is explicitly set to empty string', () => {
const { user1, trip } = setup();
const note = createNote(trip.id, user1.id, { title: 'T', content: 'Old content' });
updateNote(trip.id, note.id, { content: '' });
const updated = testDb.prepare('SELECT * FROM collab_notes WHERE id = ?').get(note.id) as any;
expect(updated.content).toBe('');
});
it('COLLAB-SVC-021: updates website when website is defined', () => {
const { user1, trip } = setup();
const note = createNote(trip.id, user1.id, { title: 'T' });
updateNote(trip.id, note.id, { website: 'https://new.example.com' });
const updated = testDb.prepare('SELECT * FROM collab_notes WHERE id = ?').get(note.id) as any;
expect(updated.website).toBe('https://new.example.com');
});
it('COLLAB-SVC-022: clears website when website is explicitly set to empty string', () => {
const { user1, trip } = setup();
const note = createNote(trip.id, user1.id, { title: 'T', website: 'https://old.com' });
updateNote(trip.id, note.id, { website: '' });
const updated = testDb.prepare('SELECT * FROM collab_notes WHERE id = ?').get(note.id) as any;
expect(updated.website).toBe('');
});
it('COLLAB-SVC-023: returns null when note does not exist', () => {
const { trip } = setup();
const result = updateNote(trip.id, 9999, { title: 'Ghost' });
expect(result).toBeNull();
});
it('COLLAB-SVC-024: updates pinned flag', () => {
const { user1, trip } = setup();
const note = createNote(trip.id, user1.id, { title: 'T', pinned: false });
updateNote(trip.id, note.id, { pinned: true });
const updated = testDb.prepare('SELECT * FROM collab_notes WHERE id = ?').get(note.id) as any;
expect(updated.pinned).toBe(1);
});
});
// ── fetchLinkPreview ──────────────────────────────────────────────────────────
describe('fetchLinkPreview', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('COLLAB-SVC-025: returns OG title and description from HTML', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => `
<html>
<head>
<meta property="og:title" content="Test Title" />
<meta property="og:description" content="Test Description" />
<meta property="og:image" content="https://example.com/image.jpg" />
<meta property="og:site_name" content="Example" />
</head>
</html>
`,
}));
const result = await fetchLinkPreview('https://example.com/page');
expect(result.title).toBe('Test Title');
expect(result.description).toBe('Test Description');
expect(result.image).toBe('https://example.com/image.jpg');
expect(result.url).toBe('https://example.com/page');
});
it('COLLAB-SVC-026: falls back to <title> tag when no og:title', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => `<html><head><title>Page Title</title></head></html>`,
}));
const result = await fetchLinkPreview('https://example.com/');
expect(result.title).toBe('Page Title');
});
it('COLLAB-SVC-027: returns fallback when fetch response is not ok', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: false,
text: async () => '',
}));
const result = await fetchLinkPreview('https://example.com/bad');
expect(result.title).toBeNull();
expect(result.description).toBeNull();
expect(result.url).toBe('https://example.com/bad');
});
it('COLLAB-SVC-028: returns fallback when SSRF check blocks the URL', async () => {
mockCheckSsrf.mockResolvedValue({ allowed: false, error: 'SSRF blocked' });
const result = await fetchLinkPreview('https://169.254.169.254/');
expect(result.title).toBeNull();
});
it('COLLAB-SVC-029: returns fallback when fetch throws (network error)', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network error')));
const result = await fetchLinkPreview('https://example.com/net-error');
expect(result.title).toBeNull();
expect(result.url).toBe('https://example.com/net-error');
});
it('COLLAB-SVC-030: falls back to meta description tag when no og:description', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => `
<html><head>
<meta name="description" content="Meta description here" />
</head></html>
`,
}));
const result = await fetchLinkPreview('https://example.com/meta');
expect(result.description).toBe('Meta description here');
});
});
@@ -1,570 +0,0 @@
/**
* Unit tests for collectionsService (COLLECTIONS-SVC-001 … 040).
* Real in-memory SQLite (full schema + migrations) so the SQL — owner/member
* visibility, the collection-scoped dedup, the fusion state machine and the
* widened photo-cache reference check — is exercised faithfully.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock, broadcastToUser } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const broadcastToUser = vi.fn();
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: number | string, userId: number) =>
db
.prepare(
'SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)',
)
.get(userId, tripId, userId),
isOwner: () => false,
};
return { testDb: db, dbMock: mock, broadcastToUser };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/websocket', () => ({ broadcastToUser, broadcast: vi.fn() }));
const notifSend = vi.fn().mockResolvedValue(undefined);
vi.mock('../../../src/services/notificationService', () => ({ send: notifSend }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { createUser, createTrip, createPlace, createCategory, createTag, addTripMember } from '../../helpers/factories';
import * as svc from '../../../src/services/collectionsService';
import { removeIfUnreferenced } from '../../../src/services/placePhotoCache';
function clearCollections() {
testDb.exec(`
DELETE FROM collection_place_labels;
DELETE FROM collection_labels;
DELETE FROM collection_place_tags;
DELETE FROM collection_places;
DELETE FROM collection_members;
DELETE FROM collections;
DELETE FROM google_place_photo_meta;
DELETE FROM place_tags;
DELETE FROM places;
DELETE FROM trip_members;
DELETE FROM trips;
DELETE FROM users;
`);
}
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
clearCollections();
broadcastToUser.mockClear();
notifSend.mockClear();
});
afterAll(() => {
testDb.close();
});
// ── Lists CRUD + visibility ──────────────────────────────────────────────────
describe('collections CRUD + visibility', () => {
it('COLLECTIONS-SVC-001: createCollection + listCollections is owner-scoped', () => {
const a = createUser(testDb).user;
const b = createUser(testDb).user;
const col = svc.createCollection(a.id, { name: 'Tokyo' });
expect(col.is_owner).toBe(true);
expect(col.owner_id).toBe(a.id);
expect(svc.listCollections(a.id).collections).toHaveLength(1);
expect(svc.listCollections(b.id).collections).toHaveLength(0);
});
it('COLLECTIONS-SVC-002: getCollection 404 for a non-member', () => {
const a = createUser(testDb).user;
const b = createUser(testDb).user;
const col = svc.createCollection(a.id, { name: 'Private' });
expect(() => svc.getCollection(b.id, col.id)).toThrow();
try { svc.getCollection(b.id, col.id); } catch (e) { expect((e as { status: number }).status).toBe(404); }
});
it('COLLECTIONS-SVC-003: updateCollection renames; reorder only touches visible rows', () => {
const a = createUser(testDb).user;
const col = svc.createCollection(a.id, { name: 'Old' });
const updated = svc.updateCollection(a.id, col.id, { name: 'New' });
expect(updated.name).toBe('New');
const b = createUser(testDb).user;
const other = svc.createCollection(b.id, { name: 'B-list' }); // b's first list → sort_order 0
svc.reorderCollections(a.id, [other.id, col.id]); // a cannot see other → skipped; col → index 1
const otherRow = testDb.prepare('SELECT sort_order FROM collections WHERE id = ?').get(other.id) as { sort_order: number };
const colRow = testDb.prepare('SELECT sort_order FROM collections WHERE id = ?').get(col.id) as { sort_order: number };
expect(otherRow.sort_order).toBe(0); // untouched — not visible to a
expect(colRow.sort_order).toBe(1); // reordered to its index in the visible-filtered list
});
});
// ── Saved places + dedup ─────────────────────────────────────────────────────
describe('saved places + dedup', () => {
it('COLLECTIONS-SVC-010: savePlace sets owner_id=owner, saved_by=caller, no itinerary cols', () => {
const owner = createUser(testDb).user;
const member = createUser(testDb).user;
const col = svc.createCollection(owner.id, { name: 'Shared' });
testDb.prepare("INSERT INTO collection_members (collection_id, user_id, status) VALUES (?, ?, 'accepted')").run(col.id, member.id);
const res = svc.savePlace(member.id, { collection_id: col.id, name: 'Senso-ji', lat: 35.71, lng: 139.79 });
expect(res.place).toBeDefined();
const row = testDb.prepare('SELECT * FROM collection_places WHERE id = ?').get(res.place!.id) as Record<string, unknown>;
expect(row.owner_id).toBe(owner.id);
expect(row.saved_by).toBe(member.id);
expect('reservation_status' in row).toBe(false);
expect('place_time' in row).toBe(false);
});
it('COLLECTIONS-SVC-011: second identical save is a duplicate; force inserts', () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'Dedup' });
svc.savePlace(u.id, { collection_id: col.id, name: 'Eiffel Tower' });
const dup = svc.savePlace(u.id, { collection_id: col.id, name: 'eiffel tower' });
expect(dup.duplicate).toBe(true);
expect(dup.duplicateOf?.name).toBe('Eiffel Tower');
const forced = svc.savePlace(u.id, { collection_id: col.id, name: 'eiffel tower', force: true });
expect(forced.place).toBeDefined();
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_places WHERE collection_id = ?').get(col.id)).toEqual({ n: 2 });
});
it('COLLECTIONS-SVC-012: savePlace attaches tags', () => {
const u = createUser(testDb).user;
const tag = createTag(testDb, u.id, { name: 'food' });
const col = svc.createCollection(u.id, { name: 'Tagged' });
const res = svc.savePlace(u.id, { collection_id: col.id, name: 'Ramen', tag_ids: [tag.id] });
expect(res.place!.tags?.map((t) => t.name)).toContain('food');
});
it('COLLECTIONS-SVC-013: savePlace rejects an inaccessible collection (404)', () => {
const a = createUser(testDb).user;
const b = createUser(testDb).user;
const col = svc.createCollection(a.id, { name: 'Locked' });
expect(() => svc.savePlace(b.id, { collection_id: col.id, name: 'X' })).toThrow();
});
});
// ── save-from-trip provenance + IDOR ─────────────────────────────────────────
describe('saveFromTripPlace', () => {
it('COLLECTIONS-SVC-014: records provenance from a readable trip', () => {
const u = createUser(testDb).user;
createCategory(testDb);
const trip = createTrip(testDb, u.id);
const place = createPlace(testDb, trip.id, { name: 'Louvre' });
const col = svc.createCollection(u.id, { name: 'From trip' });
const res = svc.saveFromTripPlace(u.id, col.id, trip.id, place.id);
expect(res.place!.source_trip_id).toBe(trip.id);
expect(res.place!.source_place_id).toBe(place.id);
expect(res.place!.name).toBe('Louvre');
});
it('COLLECTIONS-SVC-015: rejects a trip the user cannot read (no IDOR)', () => {
const owner = createUser(testDb).user;
const stranger = createUser(testDb).user;
createCategory(testDb);
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id, { name: 'Secret' });
const col = svc.createCollection(stranger.id, { name: 'Mine' });
expect(() => svc.saveFromTripPlace(stranger.id, col.id, trip.id, place.id)).toThrow();
try { svc.saveFromTripPlace(stranger.id, col.id, trip.id, place.id); } catch (e) { expect((e as { status: number }).status).toBe(404); }
});
});
// ── status + move ────────────────────────────────────────────────────────────
describe('status + updatePlace move', () => {
it('COLLECTIONS-SVC-016: setStatus cycles idea→want→visited', () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'S' });
const p = svc.savePlace(u.id, { collection_id: col.id, name: 'Place' }).place!;
expect(p.status).toBe('idea');
expect(svc.setStatus(u.id, p.id, 'want').status).toBe('want');
expect(svc.setStatus(u.id, p.id, 'visited').status).toBe('visited');
});
it('COLLECTIONS-SVC-017: updatePlace moves to another list (asserts access on target, resets owner_id)', () => {
const owner = createUser(testDb).user;
const a = svc.createCollection(owner.id, { name: 'A' });
const targetOwner = createUser(testDb).user;
const b = svc.createCollection(targetOwner.id, { name: 'B' });
// owner is also an accepted member of b so the move target is visible to them
testDb.prepare("INSERT INTO collection_members (collection_id, user_id, status) VALUES (?, ?, 'accepted')").run(b.id, owner.id);
const p = svc.savePlace(owner.id, { collection_id: a.id, name: 'Movable' }).place!;
const moved = svc.updatePlace(owner.id, p.id, { collection_id: b.id });
expect(moved.collection_id).toBe(b.id);
const row = testDb.prepare('SELECT owner_id FROM collection_places WHERE id = ?').get(p.id) as { owner_id: number };
expect(row.owner_id).toBe(targetOwner.id); // reset to the target collection's owner
});
it('COLLECTIONS-SVC-018: updatePlace move to an inaccessible target is rejected', () => {
const owner = createUser(testDb).user;
const a = svc.createCollection(owner.id, { name: 'A' });
const stranger = createUser(testDb).user;
const b = svc.createCollection(stranger.id, { name: 'B' });
const p = svc.savePlace(owner.id, { collection_id: a.id, name: 'X' }).place!;
expect(() => svc.updatePlace(owner.id, p.id, { collection_id: b.id })).toThrow();
});
});
// ── copy to trip ─────────────────────────────────────────────────────────────
describe('copyToTrip', () => {
it('COLLECTIONS-SVC-020: reduced INSERT (itinerary defaults), skips dups, copies tags', () => {
const u = createUser(testDb).user;
createCategory(testDb);
const trip = createTrip(testDb, u.id);
const tag = createTag(testDb, u.id, { name: 'must-see' });
const col = svc.createCollection(u.id, { name: 'Plan' });
const p1 = svc.savePlace(u.id, { collection_id: col.id, name: 'Colosseum', tag_ids: [tag.id] }).place!;
// pre-existing trip place that should make a duplicate
createPlace(testDb, trip.id, { name: 'Pantheon' });
const p2 = svc.savePlace(u.id, { collection_id: col.id, name: 'Pantheon' }).place!;
const res = svc.copyToTrip(u.id, { trip_id: trip.id, place_ids: [p1.id, p2.id] });
expect(res.copied).toBe(1);
expect(res.skipped.map((s) => s.name)).toEqual(['Pantheon']);
const inserted = testDb.prepare("SELECT * FROM places WHERE trip_id = ? AND name = 'Colosseum'").get(trip.id) as Record<string, unknown>;
expect(inserted.reservation_status).toBe('none'); // itinerary column took the table default
expect(inserted.duration_minutes).toBe(60);
const tagLink = testDb.prepare('SELECT COUNT(*) n FROM place_tags WHERE place_id = ?').get(inserted.id);
expect(tagLink).toEqual({ n: 1 });
});
it('COLLECTIONS-SVC-021: rejects place_ids from a collection the user cannot see', () => {
const owner = createUser(testDb).user;
const stranger = createUser(testDb).user;
createCategory(testDb);
const hidden = svc.createCollection(owner.id, { name: 'Hidden' });
const p = svc.savePlace(owner.id, { collection_id: hidden.id, name: 'Secret' }).place!;
const trip = createTrip(testDb, stranger.id);
expect(() => svc.copyToTrip(stranger.id, { trip_id: trip.id, place_ids: [p.id] })).toThrow();
});
it('COLLECTIONS-SVC-022: rejects a trip the user cannot edit (403/404)', () => {
const u = createUser(testDb).user;
const owner2 = createUser(testDb).user;
createCategory(testDb);
const trip = createTrip(testDb, owner2.id); // u has no access
const col = svc.createCollection(u.id, { name: 'C' });
const p = svc.savePlace(u.id, { collection_id: col.id, name: 'X' }).place!;
expect(() => svc.copyToTrip(u.id, { trip_id: trip.id, place_ids: [p.id] })).toThrow();
});
it('COLLECTIONS-SVC-023: a trip MEMBER can copy (place_edit allowed)', () => {
const owner2 = createUser(testDb).user;
const member = createUser(testDb).user;
createCategory(testDb);
const trip = createTrip(testDb, owner2.id);
addTripMember(testDb, trip.id, member.id);
const col = svc.createCollection(member.id, { name: 'C' });
const p = svc.savePlace(member.id, { collection_id: col.id, name: 'Forum' }).place!;
const res = svc.copyToTrip(member.id, { trip_id: trip.id, place_ids: [p.id] });
expect(res.copied).toBe(1);
});
});
// ── delete + delete-many ─────────────────────────────────────────────────────
describe('delete places', () => {
it('COLLECTIONS-SVC-024: deletePlace + deletePlacesMany assert access', () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'D' });
const p1 = svc.savePlace(u.id, { collection_id: col.id, name: 'A' }).place!;
const p2 = svc.savePlace(u.id, { collection_id: col.id, name: 'B' }).place!;
svc.deletePlace(u.id, p1.id);
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_places WHERE collection_id = ?').get(col.id)).toEqual({ n: 1 });
expect(svc.deletePlacesMany(u.id, [p2.id])).toEqual([p2.id]);
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_places WHERE collection_id = ?').get(col.id)).toEqual({ n: 0 });
});
});
// ── Fusion state machine ─────────────────────────────────────────────────────
describe('fusion invitations', () => {
function setup() {
const owner = createUser(testDb).user;
const target = createUser(testDb).user;
const col = svc.createCollection(owner.id, { name: 'Fusion' });
return { owner, target, col };
}
it('COLLECTIONS-SVC-030: sendInvite — self 400, unknown 404, non-owner 403, happy path', async () => {
const { owner, target, col } = setup();
expect(svc.sendInvite(col.id, owner.id, owner.username, owner.email, owner.id).status).toBe(400);
expect(svc.sendInvite(col.id, owner.id, owner.username, owner.email, 99999).status).toBe(404);
expect(svc.sendInvite(col.id, target.id, target.username, target.email, owner.id).status).toBe(403); // non-owner inviter
const ok = svc.sendInvite(col.id, owner.id, owner.username, owner.email, target.id);
expect(ok.error).toBeUndefined();
expect(broadcastToUser).toHaveBeenCalledWith(target.id, expect.objectContaining({ type: 'collections:invite' }));
// the notification send is fire-and-forget via a dynamic import — flush microtasks.
await vi.waitFor(() => expect(notifSend).toHaveBeenCalledWith(expect.objectContaining({ event: 'collection_invite', targetId: target.id })));
});
it('COLLECTIONS-SVC-031: double-invite while pending → 400; existing member → 400', () => {
const { owner, target, col } = setup();
svc.sendInvite(col.id, owner.id, owner.username, owner.email, target.id);
expect(svc.sendInvite(col.id, owner.id, owner.username, owner.email, target.id).status).toBe(400);
svc.acceptInvite(target.id, col.id, undefined);
expect(svc.sendInvite(col.id, owner.id, owner.username, owner.email, target.id).error).toBe('Already a member');
});
it('COLLECTIONS-SVC-032: acceptInvite — 404 with no pending; flips to accepted → member now sees list', () => {
const { owner, target, col } = setup();
expect(svc.acceptInvite(target.id, col.id, undefined).status).toBe(404);
svc.sendInvite(col.id, owner.id, owner.username, owner.email, target.id);
expect(svc.acceptInvite(target.id, col.id, undefined).error).toBeUndefined();
expect(svc.listCollections(target.id).collections.map((c) => c.id)).toContain(col.id);
});
it('COLLECTIONS-SVC-033: accept-after-cancel → 404 (no orphan accept)', () => {
const { owner, target, col } = setup();
svc.sendInvite(col.id, owner.id, owner.username, owner.email, target.id);
svc.cancelInvite(col.id, owner.id, target.id);
expect(svc.acceptInvite(target.id, col.id, undefined).status).toBe(404);
});
it('COLLECTIONS-SVC-034: declineInvite removes the pending row', () => {
const { owner, target, col } = setup();
svc.sendInvite(col.id, owner.id, owner.username, owner.email, target.id);
svc.declineInvite(target.id, col.id, undefined);
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_members WHERE collection_id = ?').get(col.id)).toEqual({ n: 0 });
});
it('COLLECTIONS-SVC-035: cancelInvite is owner-only', () => {
const { owner, target, col } = setup();
svc.sendInvite(col.id, owner.id, owner.username, owner.email, target.id);
expect(() => svc.cancelInvite(col.id, target.id, target.id)).toThrow(); // non-owner
svc.cancelInvite(col.id, owner.id, target.id); // owner ok
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_members WHERE collection_id = ?').get(col.id)).toEqual({ n: 0 });
});
it('COLLECTIONS-SVC-036: leaveCollection — member ok, owner blocked (400)', () => {
const { owner, target, col } = setup();
svc.sendInvite(col.id, owner.id, owner.username, owner.email, target.id);
svc.acceptInvite(target.id, col.id, undefined);
svc.leaveCollection(target.id, col.id, undefined);
expect(svc.listCollections(target.id).collections.map((c) => c.id)).not.toContain(col.id);
expect(() => svc.leaveCollection(owner.id, col.id, undefined)).toThrow();
try { svc.leaveCollection(owner.id, col.id, undefined); } catch (e) { expect((e as { status: number }).status).toBe(400); }
});
it('COLLECTIONS-SVC-037: availableUsers is scoped to THIS collection only (no one-fusion bug)', () => {
const owner = createUser(testDb).user;
const target = createUser(testDb).user;
const colA = svc.createCollection(owner.id, { name: 'A' });
const colB = svc.createCollection(owner.id, { name: 'B' });
// target is accepted in A; must still be invitable to B
svc.sendInvite(colA.id, owner.id, owner.username, owner.email, target.id);
svc.acceptInvite(target.id, colA.id, undefined);
const forB = svc.availableUsers(owner.id, colB.id).map((u) => u.id);
expect(forB).toContain(target.id);
const forA = svc.availableUsers(owner.id, colA.id).map((u) => u.id);
expect(forA).not.toContain(target.id); // already a member of A
});
it('COLLECTIONS-SVC-038: availableUsers excludes self + guests', () => {
const owner = createUser(testDb).user;
const normal = createUser(testDb).user;
const guest = createUser(testDb).user;
testDb.prepare('UPDATE users SET is_guest = 1 WHERE id = ?').run(guest.id);
const col = svc.createCollection(owner.id, { name: 'C' });
const ids = svc.availableUsers(owner.id, col.id).map((u) => u.id);
expect(ids).toContain(normal.id);
expect(ids).not.toContain(owner.id);
expect(ids).not.toContain(guest.id);
});
it('COLLECTIONS-SVC-039: visibility = owner OR accepted member (pending does NOT grant access)', () => {
const { owner, target, col } = setup();
svc.sendInvite(col.id, owner.id, owner.username, owner.email, target.id);
expect(() => svc.getCollection(target.id, col.id)).toThrow(); // pending, no access yet
svc.acceptInvite(target.id, col.id, undefined);
expect(svc.getCollection(target.id, col.id).collection.id).toBe(col.id);
});
});
// ── deleteCollection snapshot + broadcast + cascade ──────────────────────────
describe('deleteCollection', () => {
it('COLLECTIONS-SVC-040: owner-only; snapshots accepted+pending, broadcasts collections:deleted, cascades', () => {
const owner = createUser(testDb).user;
const accepted = createUser(testDb).user;
const pending = createUser(testDb).user;
const col = svc.createCollection(owner.id, { name: 'Doomed' });
svc.savePlace(owner.id, { collection_id: col.id, name: 'P' });
svc.sendInvite(col.id, owner.id, owner.username, owner.email, accepted.id);
svc.acceptInvite(accepted.id, col.id, undefined);
svc.sendInvite(col.id, owner.id, owner.username, owner.email, pending.id);
// a non-owner member cannot delete
expect(() => svc.deleteCollection(accepted.id, col.id)).toThrow();
broadcastToUser.mockClear();
svc.deleteCollection(owner.id, col.id);
const targets = broadcastToUser.mock.calls.map((c) => c[0]);
expect(targets).toEqual(expect.arrayContaining([accepted.id, pending.id]));
expect(targets).not.toContain(owner.id);
expect(broadcastToUser.mock.calls.every((c) => (c[1] as { type: string }).type === 'collections:deleted')).toBe(true);
expect(testDb.prepare('SELECT COUNT(*) n FROM collections WHERE id = ?').get(col.id)).toEqual({ n: 0 });
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_places WHERE collection_id = ?').get(col.id)).toEqual({ n: 0 });
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_members WHERE collection_id = ?').get(col.id)).toEqual({ n: 0 });
});
});
// ── owner_id semantics: member account deletion keeps shared content ─────────
describe('owner_id semantics', () => {
it('COLLECTIONS-SVC-041: deleting a MEMBER account nulls saved_by but keeps the place', () => {
const owner = createUser(testDb).user;
const member = createUser(testDb).user;
const col = svc.createCollection(owner.id, { name: 'Shared' });
testDb.prepare("INSERT INTO collection_members (collection_id, user_id, status) VALUES (?, ?, 'accepted')").run(col.id, member.id);
const p = svc.savePlace(member.id, { collection_id: col.id, name: 'Kept' }).place!;
testDb.prepare('DELETE FROM users WHERE id = ?').run(member.id);
const row = testDb.prepare('SELECT owner_id, saved_by FROM collection_places WHERE id = ?').get(p.id) as { owner_id: number; saved_by: number | null };
expect(row).toBeDefined();
expect(row.owner_id).toBe(owner.id);
expect(row.saved_by).toBeNull(); // ON DELETE SET NULL
});
});
// ── Photo-cache guard ────────────────────────────────────────────────────────
describe('photo-cache widening', () => {
it('COLLECTIONS-SVC-042: a collection_places row keeps a photo no places row references', () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'Photos' });
// cache meta for place_id 'gp-x', referenced ONLY by a collection_places row.
testDb.prepare('INSERT INTO google_place_photo_meta (place_id, attribution, fetched_at) VALUES (?, ?, ?)').run('gp-x', null, Date.now());
svc.savePlace(u.id, { collection_id: col.id, name: 'Cached', google_place_id: 'gp-x' });
removeIfUnreferenced('gp-x'); // would evict if isReferenced ignored collection_places
const meta = testDb.prepare('SELECT 1 FROM google_place_photo_meta WHERE place_id = ?').get('gp-x');
expect(meta).toBeDefined();
});
it('COLLECTIONS-SVC-043: an unreferenced photo is still reclaimable', () => {
testDb.prepare('INSERT INTO google_place_photo_meta (place_id, attribution, fetched_at) VALUES (?, ?, ?)').run('gp-orphan', null, Date.now());
removeIfUnreferenced('gp-orphan');
const meta = testDb.prepare('SELECT 1 FROM google_place_photo_meta WHERE place_id = ?').get('gp-orphan');
expect(meta).toBeUndefined();
});
});
// ── Labels ───────────────────────────────────────────────────────────────────
function addMember(colId: number, userId: number, role: 'viewer' | 'editor' | 'admin') {
testDb.prepare("INSERT INTO collection_members (collection_id, user_id, status, role) VALUES (?, ?, 'accepted', ?)").run(colId, userId, role);
}
describe('collection labels', () => {
it('COLLECTIONS-SVC-050: createLabel is returned by getCollection; duplicate name is 409', () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'Germany' });
const label = svc.createLabel(u.id, col.id, 'Berlin', '#ff0000');
expect(label.name).toBe('Berlin');
expect(label.collection_id).toBe(col.id);
expect(svc.getCollection(u.id, col.id).collection.labels).toHaveLength(1);
expect(() => svc.createLabel(u.id, col.id, 'berlin')).toThrow(); // case-insensitive dup
try { svc.createLabel(u.id, col.id, 'berlin'); } catch (e) { expect((e as { status: number }).status).toBe(409); }
});
it('COLLECTIONS-SVC-051: a viewer cannot manage labels (403); an editor can', () => {
const owner = createUser(testDb).user;
const viewer = createUser(testDb).user;
const col = svc.createCollection(owner.id, { name: 'Trip' });
addMember(col.id, viewer.id, 'viewer');
try { svc.createLabel(viewer.id, col.id, 'X'); } catch (e) { expect((e as { status: number }).status).toBe(403); }
const editor = createUser(testDb).user;
addMember(col.id, editor.id, 'editor');
expect(svc.createLabel(editor.id, col.id, 'Museums').id).toBeGreaterThan(0);
});
it('COLLECTIONS-SVC-052: updatePlace label_ids sets labels; a label from another list is ignored', () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'DE' });
const other = svc.createCollection(u.id, { name: 'Other' });
const l1 = svc.createLabel(u.id, col.id, 'Berlin');
const foreign = svc.createLabel(u.id, other.id, 'Paris');
const place = svc.savePlace(u.id, { collection_id: col.id, name: 'Gate' }).place!;
svc.updatePlace(u.id, place.id, { label_ids: [l1.id, foreign.id] });
const stored = svc.getCollection(u.id, col.id).places.find(p => p.id === place.id)!;
expect(stored.label_ids).toEqual([l1.id]);
});
it('COLLECTIONS-SVC-053: assignLabels bulk-adds then unassigns across places', () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'DE' });
const l = svc.createLabel(u.id, col.id, 'Coast');
const p1 = svc.savePlace(u.id, { collection_id: col.id, name: 'A' }).place!;
const p2 = svc.savePlace(u.id, { collection_id: col.id, name: 'B' }).place!;
expect(svc.assignLabels(u.id, [l.id], [p1.id, p2.id], false).changed).toBe(2);
expect(svc.getCollection(u.id, col.id).places.every(p => p.label_ids?.includes(l.id))).toBe(true);
svc.assignLabels(u.id, [l.id], [p1.id], true);
const after = svc.getCollection(u.id, col.id).places;
expect(after.find(p => p.id === p1.id)!.label_ids).toEqual([]);
expect(after.find(p => p.id === p2.id)!.label_ids).toEqual([l.id]);
});
it('COLLECTIONS-SVC-054: deleteLabel removes it and cascades its place assignments', () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'DE' });
const l = svc.createLabel(u.id, col.id, 'Berlin');
const p = svc.savePlace(u.id, { collection_id: col.id, name: 'Gate' }).place!;
svc.updatePlace(u.id, p.id, { label_ids: [l.id] });
svc.deleteLabel(u.id, l.id);
expect(svc.getCollection(u.id, col.id).collection.labels).toHaveLength(0);
expect(svc.getCollection(u.id, col.id).places.find(x => x.id === p.id)!.label_ids).toEqual([]);
});
it('COLLECTIONS-SVC-055: moving a place to another list drops its labels', () => {
const u = createUser(testDb).user;
const a = svc.createCollection(u.id, { name: 'A' });
const b = svc.createCollection(u.id, { name: 'B' });
const l = svc.createLabel(u.id, a.id, 'Berlin');
const p = svc.savePlace(u.id, { collection_id: a.id, name: 'Gate' }).place!;
svc.updatePlace(u.id, p.id, { label_ids: [l.id] });
svc.updatePlace(u.id, p.id, { collection_id: b.id });
expect(svc.getCollection(u.id, b.id).places.find(x => x.id === p.id)!.label_ids).toEqual([]);
});
});
@@ -38,9 +38,41 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { updatePlace, createPlace } from '../../../src/services/placeService';
import { createItem, updateItem } from '../../../src/services/packingService';
import { isUpdateConflict } from '../../../src/services/conflictResult';
import { isUpdateConflict } from '../../../src/nest/common/conflictResult';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { PackingService } from '../../../src/nest/packing/packing.service';
import { PlacesService } from '../../../src/nest/places/places.service';
import { MapsService } from '../../../src/nest/maps/maps.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
import { UnsplashService } from '../../../src/nest/unsplash/unsplash.service';
import { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-photo-cache.service';
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { notificationsStub } from '../../helpers/notifications';
import { makeStorageFixture } from '../../helpers/storage-fixture';
const dbs = new DatabaseService(testDb);
const realtime = new RealtimeService();
const runtimeEnv = new RuntimeEnvService();
// One cache instance shared by maps and places, the way the container wires it:
// the service's stampede guard only works if there is exactly one of them.
const photoCache = new PlacePhotoCacheService(dbs, makeStorageFixture('photos/google/').storage);
const packing = new PackingService(dbs, new PermissionsService(dbs), realtime, notificationsStub());
const places = new PlacesService(
dbs,
new PermissionsService(dbs),
realtime,
new MapsService(dbs, photoCache),
new QueryHelpersService(dbs),
new UnsplashService(dbs, runtimeEnv, makeStorageFixture('').storage),
photoCache,
new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs)),
makeStorageFixture('').storage,
);
beforeAll(() => {
createTables(testDb);
@@ -56,37 +88,37 @@ afterAll(() => {
});
function freshPlace(tripId: number) {
const place = createPlace(String(tripId), { name: 'Original' }) as { id: number; updated_at: string };
const place = places.create(String(tripId), { name: 'Original' }) as unknown as { id: number; updated_at: string };
return place;
}
describe('updatePlace — optimistic concurrency', () => {
it('updates normally when no If-Match token is sent (back-compat)', () => {
describe('PlacesService.update — optimistic concurrency', () => {
it('updates normally when no If-Match token is sent (back-compat)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = updatePlace(String(trip.id), String(place.id), { name: 'Edited' });
const result = await places.update(String(trip.id), String(place.id), { name: 'Edited' });
expect(isUpdateConflict(result)).toBe(false);
expect((result as { name: string }).name).toBe('Edited');
});
it('updates when the If-Match token matches the current updated_at', () => {
it('updates when the If-Match token matches the current updated_at', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = updatePlace(String(trip.id), String(place.id), { name: 'Edited' }, place.updated_at);
const result = await places.update(String(trip.id), String(place.id), { name: 'Edited' }, place.updated_at);
expect(isUpdateConflict(result)).toBe(false);
expect((result as { name: string }).name).toBe('Edited');
});
it('returns a conflict (with the server row) when the token is stale', () => {
it('returns a conflict (with the server row) when the token is stale', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = updatePlace(String(trip.id), String(place.id), { name: 'Mine' }, '1999-01-01 00:00:00');
const result = await places.update(String(trip.id), String(place.id), { name: 'Mine' }, '1999-01-01 00:00:00');
expect(isUpdateConflict(result)).toBe(true);
if (isUpdateConflict(result)) {
expect((result.server as { name: string }).name).toBe('Original');
@@ -96,10 +128,10 @@ describe('updatePlace — optimistic concurrency', () => {
expect(row.name).toBe('Original');
});
it('returns null for a place that does not exist', () => {
it('returns null for a place that does not exist', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(updatePlace(String(trip.id), '999999', { name: 'x' }, 'whatever')).toBeNull();
expect(await places.update(String(trip.id), '999999', { name: 'x' }, 'whatever')).toBeNull();
});
});
@@ -110,19 +142,19 @@ describe('updateItem (packing) — optimistic concurrency', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Socks' }) as { id: number; updated_at: string | null };
const item = packing.createItem(trip.id, { name: 'Socks' }) as { id: number; updated_at: string | null };
expect(item.updated_at).toBeTruthy();
});
it('returns a conflict when the packing token is stale', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Socks' }) as { id: number; updated_at: string };
const item = packing.createItem(trip.id, { name: 'Socks' }, user.id) as { id: number; updated_at: string };
const stale = updateItem(trip.id, item.id, { name: 'Mine' }, ['name'], '1999-01-01 00:00:00');
const stale = packing.updateItem(trip.id, item.id, { name: 'Mine' }, ['name'], '1999-01-01 00:00:00', user.id);
expect(isUpdateConflict(stale)).toBe(true);
const fresh = updateItem(trip.id, item.id, { name: 'Edited' }, ['name'], item.updated_at);
const fresh = packing.updateItem(trip.id, item.id, { name: 'Edited' }, ['name'], item.updated_at, user.id);
expect(isUpdateConflict(fresh)).toBe(false);
expect((fresh as { name: string }).name).toBe('Edited');
});
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { cookieOptions } from '../../../src/services/cookie';
import { cookieOptions } from '../../../src/nest/common/cookie';
import { SESSION_DURATION_MS, SESSION_DURATION_REMEMBER_MS } from '../../../src/config';
describe('cookieOptions', () => {
@@ -1,403 +0,0 @@
/**
* Unit tests for dayService — DAY-SVC-001 through DAY-SVC-030.
* Uses a real in-memory SQLite DB so SQL logic is exercised faithfully.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: (placeId: any) => {
const place: any = db.prepare(`
SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
FROM places p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?
`).get(placeId);
if (!place) return null;
const tags = db.prepare(`SELECT t.* FROM tags t JOIN place_tags pt ON t.id = pt.tag_id WHERE pt.place_id = ?`).all(placeId);
return { ...place, category: place.category_id ? { id: place.category_id, name: place.category_name, color: place.category_color, icon: place.category_icon } : null, tags };
},
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
isOwner: (tripId: any, userId: number) =>
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, createDayAssignment, createDayAccommodation } from '../../helpers/factories';
import {
verifyTripAccess,
getAssignmentsForDay,
listDays,
createDay as svcCreateDay,
getDay,
updateDay,
deleteDay,
listAccommodations,
validateAccommodationRefs,
createAccommodation,
getAccommodation,
updateAccommodation,
deleteAccommodation,
} from '../../../src/services/dayService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ── verifyTripAccess ──────────────────────────────────────────────────────────
describe('verifyTripAccess', () => {
it('DAY-SVC-001 — returns trip row for owner', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = verifyTripAccess(trip.id, user.id) as any;
expect(result).toBeDefined();
expect(result.id).toBe(trip.id);
});
it('DAY-SVC-002 — returns falsy for non-member', () => {
const { user: owner } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
expect(verifyTripAccess(trip.id, stranger.id)).toBeFalsy();
});
});
// ── getAssignmentsForDay ──────────────────────────────────────────────────────
describe('getAssignmentsForDay', () => {
it('DAY-SVC-003 — returns empty array when day has no assignments', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
expect(getAssignmentsForDay(day.id)).toEqual([]);
});
it('DAY-SVC-004 — returns assignments with nested place object', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Eiffel Tower', lat: 48.8, lng: 2.3 }) as any;
createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
const assignments = getAssignmentsForDay(day.id) as any[];
expect(assignments).toHaveLength(1);
expect(assignments[0].place).toBeDefined();
expect(assignments[0].place.name).toBe('Eiffel Tower');
expect(assignments[0].place.lat).toBe(48.8);
});
it('DAY-SVC-005 — assignment includes tags array (empty when place has none)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'No Tags' }) as any;
createDayAssignment(testDb, day.id, place.id);
const assignments = getAssignmentsForDay(day.id) as any[];
expect(Array.isArray(assignments[0].place.tags)).toBe(true);
});
it('DAY-SVC-006 — assignments are ordered by order_index ASC', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const p1 = createPlace(testDb, trip.id, { name: 'Second' }) as any;
const p2 = createPlace(testDb, trip.id, { name: 'First' }) as any;
createDayAssignment(testDb, day.id, p1.id, { order_index: 2 });
createDayAssignment(testDb, day.id, p2.id, { order_index: 1 });
const assignments = getAssignmentsForDay(day.id) as any[];
expect(assignments[0].place.name).toBe('First');
expect(assignments[1].place.name).toBe('Second');
});
});
// ── listDays ──────────────────────────────────────────────────────────────────
describe('listDays', () => {
it('DAY-SVC-007 — returns { days: [] } for trip with no days', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = listDays(trip.id) as any;
expect(result.days).toEqual([]);
});
it('DAY-SVC-008 — returns days with assignments nested', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createDay(testDb, trip.id);
const result = listDays(trip.id) as any;
expect(result.days).toHaveLength(1);
expect(Array.isArray(result.days[0].assignments)).toBe(true);
});
});
// ── createDay ─────────────────────────────────────────────────────────────────
describe('createDay (service)', () => {
it('DAY-SVC-009 — creates a day with auto-incremented day_number', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const d1 = svcCreateDay(trip.id) as any;
const d2 = svcCreateDay(trip.id) as any;
expect(d1.day_number).toBe(1);
expect(d2.day_number).toBe(2);
});
it('DAY-SVC-010 — returns day with empty assignments array', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = svcCreateDay(trip.id) as any;
expect(Array.isArray(day.assignments)).toBe(true);
expect(day.assignments).toHaveLength(0);
});
});
// ── getDay / updateDay / deleteDay ────────────────────────────────────────────
describe('getDay', () => {
it('DAY-SVC-011 — returns day when id and tripId match', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const found = getDay(day.id, trip.id) as any;
expect(found).toBeDefined();
expect(found.id).toBe(day.id);
});
it('DAY-SVC-012 — returns undefined for non-existent day', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(getDay(99999, trip.id)).toBeUndefined();
});
});
describe('updateDay', () => {
it('DAY-SVC-013 — updates notes and returns updated day with assignments', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const updated = updateDay(day.id, day, { notes: 'Updated notes' }) as any;
expect(updated.notes).toBe('Updated notes');
expect(Array.isArray(updated.assignments)).toBe(true);
});
it('DAY-SVC-014 — updates title', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const updated = updateDay(day.id, day, { title: 'Day 1 - City Tour' }) as any;
expect(updated.title).toBe('Day 1 - City Tour');
});
});
describe('deleteDay', () => {
it('DAY-SVC-015 — deletes the day', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
deleteDay(day.id);
expect(getDay(day.id, trip.id)).toBeUndefined();
});
});
// ── validateAccommodationRefs ─────────────────────────────────────────────────
describe('validateAccommodationRefs', () => {
it('DAY-SVC-016 — returns no errors when all refs are valid', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const errors = validateAccommodationRefs(trip.id, place.id, day.id, day.id);
expect(errors).toHaveLength(0);
});
it('DAY-SVC-017 — returns error when place does not exist in trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const errors = validateAccommodationRefs(trip.id, 99999, day.id, day.id);
expect(errors.some((e: any) => e.field === 'place_id')).toBe(true);
});
it('DAY-SVC-018 — returns error when start_day_id is invalid', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const errors = validateAccommodationRefs(trip.id, place.id, 99999, day.id);
expect(errors.some((e: any) => e.field === 'start_day_id')).toBe(true);
});
});
// ── createAccommodation ───────────────────────────────────────────────────────
describe('createAccommodation', () => {
it('DAY-SVC-019 — creates accommodation and returns it with place info', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Grand Hotel' }) as any;
const accom = createAccommodation(trip.id, {
place_id: place.id,
start_day_id: day.id,
end_day_id: day.id,
check_in: '15:00',
check_out: '11:00',
}) as any;
expect(accom).toBeDefined();
expect(accom.place_name).toBe('Grand Hotel');
});
it('DAY-SVC-020 — auto-creates a linked reservation', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'City Hotel' }) as any;
const accom = createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
const reservation = testDb.prepare('SELECT * FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
expect(reservation).toBeDefined();
expect(reservation.type).toBe('hotel');
expect(reservation.status).toBe('confirmed');
});
});
// ── getAccommodation ──────────────────────────────────────────────────────────
describe('getAccommodation', () => {
it('DAY-SVC-021 — returns accommodation for valid id and trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = createDayAccommodation(testDb, trip.id, place.id, day.id, day.id) as any;
const found = getAccommodation(accom.id, trip.id) as any;
expect(found).toBeDefined();
expect(found.id).toBe(accom.id);
});
it('DAY-SVC-022 — returns undefined for non-existent accommodation', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(getAccommodation(99999, trip.id)).toBeUndefined();
});
});
// ── updateAccommodation ───────────────────────────────────────────────────────
describe('updateAccommodation', () => {
it('DAY-SVC-023 — updates check-in and check-out times', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
const existing = getAccommodation(accom.id, trip.id)!;
const updated = updateAccommodation(accom.id, existing as any, { check_in: '16:00', check_out: '12:00' }) as any;
expect(updated).toBeDefined();
// Verify linked reservation metadata was synced
const reservation = testDb.prepare('SELECT * FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
expect(reservation).toBeDefined();
const meta = JSON.parse(reservation.metadata || '{}');
expect(meta.check_in_time).toBe('16:00');
expect(meta.check_out_time).toBe('12:00');
});
it('DAY-SVC-024 — preserves existing fields when not updated', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
confirmation: 'ABC123',
}) as any;
const existing = getAccommodation(accom.id, trip.id)!;
updateAccommodation(accom.id, existing as any, { check_in: '14:00' });
const row = getAccommodation(accom.id, trip.id) as any;
expect(row.confirmation).toBe('ABC123');
});
});
// ── deleteAccommodation ───────────────────────────────────────────────────────
describe('deleteAccommodation', () => {
it('DAY-SVC-025 — deletes accommodation and its linked reservation', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
const reservation = testDb.prepare('SELECT id FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
const result = deleteAccommodation(accom.id);
expect(result.linkedReservationId).toBe(reservation.id);
// Accommodation is gone
expect(getAccommodation(accom.id, trip.id)).toBeUndefined();
// Reservation is gone
const deletedRes = testDb.prepare('SELECT id FROM reservations WHERE id = ?').get(reservation.id);
expect(deletedRes).toBeUndefined();
});
it('DAY-SVC-026 — returns null linkedReservationId when no reservation was linked', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = createDayAccommodation(testDb, trip.id, place.id, day.id, day.id) as any;
// Remove the auto-created reservation so there's no linked one
testDb.prepare('DELETE FROM reservations WHERE accommodation_id = ?').run(accom.id);
const result = deleteAccommodation(accom.id);
expect(result.linkedReservationId).toBeNull();
});
});
@@ -1,116 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
// Reset module between tests that need a fresh token store
beforeEach(() => {
vi.resetModules();
});
describe('ephemeralTokens', () => {
async function getModule() {
return import('../../../src/services/ephemeralTokens');
}
// AUTH-030 — Resource token creation (single-use)
describe('createEphemeralToken', () => {
it('AUTH-030: creates a token and returns a hex string', async () => {
const { createEphemeralToken } = await getModule();
const token = createEphemeralToken(1, 'download');
expect(token).not.toBeNull();
expect(typeof token).toBe('string');
expect(token!.length).toBe(64); // 32 bytes hex
});
it('AUTH-030: different calls produce different tokens', async () => {
const { createEphemeralToken } = await getModule();
const t1 = createEphemeralToken(1, 'download');
const t2 = createEphemeralToken(1, 'download');
expect(t1).not.toBe(t2);
});
});
// AUTH-029 — WebSocket token expiry (single-use)
describe('consumeEphemeralToken', () => {
it('AUTH-030: token is consumed and returns userId on first use', async () => {
const { createEphemeralToken, consumeEphemeralToken } = await getModule();
const token = createEphemeralToken(42, 'download')!;
const userId = consumeEphemeralToken(token, 'download');
expect(userId).toBe(42);
});
it('AUTH-030: token is single-use — second consume returns null', async () => {
const { createEphemeralToken, consumeEphemeralToken } = await getModule();
const token = createEphemeralToken(42, 'download')!;
consumeEphemeralToken(token, 'download'); // first use
const second = consumeEphemeralToken(token, 'download'); // second use
expect(second).toBeNull();
});
it('AUTH-029: purpose mismatch returns null', async () => {
const { createEphemeralToken, consumeEphemeralToken } = await getModule();
const token = createEphemeralToken(42, 'ws')!;
const result = consumeEphemeralToken(token, 'download');
expect(result).toBeNull();
});
it('AUTH-029: expired token returns null', async () => {
vi.useFakeTimers();
const { createEphemeralToken, consumeEphemeralToken } = await getModule();
const token = createEphemeralToken(42, 'ws')!; // 30s TTL
vi.advanceTimersByTime(31_000); // advance past expiry
const result = consumeEphemeralToken(token, 'ws');
expect(result).toBeNull();
vi.useRealTimers();
});
it('returns null for unknown token', async () => {
const { consumeEphemeralToken } = await getModule();
const result = consumeEphemeralToken('nonexistent-token', 'download');
expect(result).toBeNull();
});
});
describe('startTokenCleanup / stopTokenCleanup', () => {
it('startTokenCleanup starts the interval (second call is no-op)', async () => {
vi.useFakeTimers();
const { createEphemeralToken, consumeEphemeralToken, startTokenCleanup, stopTokenCleanup } = await getModule();
startTokenCleanup();
startTokenCleanup(); // should be no-op, not throw
// Token created while cleanup is running should still be consumable (interval hasn't fired)
const token = createEphemeralToken(1, 'ws')!;
expect(consumeEphemeralToken(token, 'ws')).toBe(1);
stopTokenCleanup();
vi.useRealTimers();
});
it('stopTokenCleanup clears the interval and allows restart', async () => {
vi.useFakeTimers();
const { createEphemeralToken, consumeEphemeralToken, startTokenCleanup, stopTokenCleanup } = await getModule();
startTokenCleanup();
stopTokenCleanup();
stopTokenCleanup(); // calling stop twice should not throw
startTokenCleanup(); // should be able to start again after stop
stopTokenCleanup();
// After stop, tokens should still be consumable (cleanup didn't run)
const token = createEphemeralToken(2, 'download')!;
expect(consumeEphemeralToken(token, 'download')).toBe(2);
vi.useRealTimers();
});
it('cleanup interval removes expired tokens', async () => {
vi.useFakeTimers();
const { createEphemeralToken, consumeEphemeralToken, startTokenCleanup, stopTokenCleanup } = await getModule();
startTokenCleanup();
const token = createEphemeralToken(1, 'ws')!; // 30s TTL
// Advance past TTL AND past cleanup interval (60s)
vi.advanceTimersByTime(65_000);
// Token should have been cleaned up by the interval
const result = consumeEphemeralToken(token, 'ws');
expect(result).toBeNull();
stopTokenCleanup();
vi.useRealTimers();
});
});
});
@@ -1,21 +0,0 @@
/**
* Unit tests for inAppNotificationActions — NOTIF-ACT-001 through NOTIF-ACT-008.
* Pure Map registry — no DB or external dependencies.
*/
import { describe, it, expect } from 'vitest';
import { getAction } from '../../../src/services/inAppNotificationActions';
describe('getAction — built-in registrations', () => {
it('NOTIF-ACT-001 — test_approve is pre-registered', () => {
const handler = getAction('test_approve');
expect(handler).toBeDefined();
expect(typeof handler).toBe('function');
});
it('NOTIF-ACT-002 — test_deny is pre-registered', () => {
const handler = getAction('test_deny');
expect(handler).toBeDefined();
expect(typeof handler).toBe('function');
});
});
@@ -1,294 +0,0 @@
/**
* Unit tests for in-app notification preference filtering in createNotification().
* Covers INOTIF-001 to INOTIF-004.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
// Mock WebSocket broadcast — must use vi.hoisted() so broadcastMock is available
// when the vi.mock factory is evaluated (factories are hoisted before const declarations)
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcastToUser: broadcastMock }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createAdmin, disableNotificationPref } from '../../helpers/factories';
import { createNotification, createNotificationForRecipient, respondToBoolean } from '../../../src/services/inAppNotifications';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
broadcastMock.mockClear();
});
afterAll(() => {
testDb.close();
});
// ─────────────────────────────────────────────────────────────────────────────
// createNotification — preference filtering
// ─────────────────────────────────────────────────────────────────────────────
describe('createNotification — preference filtering', () => {
it('INOTIF-001 — notification without event_type is delivered to all recipients (backward compat)', () => {
const { user: admin } = createAdmin(testDb);
const { user: recipient } = createUser(testDb);
// The admin scope targets all admins — create a second admin as the sender
const { user: sender } = createAdmin(testDb);
// Send to a specific user (user scope) without event_type
const ids = createNotification({
type: 'simple',
scope: 'user',
target: recipient.id,
sender_id: sender.id,
title_key: 'notifications.test.title',
text_key: 'notifications.test.text',
// no event_type
});
expect(ids.length).toBe(1);
const row = testDb.prepare('SELECT * FROM notifications WHERE recipient_id = ?').get(recipient.id);
expect(row).toBeDefined();
// Also verify the admin who disabled all prefs still gets messages without event_type
disableNotificationPref(testDb, admin.id, 'trip_invite', 'inapp');
// admin still gets this since no event_type check
const adminIds = createNotification({
type: 'simple',
scope: 'user',
target: admin.id,
sender_id: sender.id,
title_key: 'notifications.test.title',
text_key: 'notifications.test.text',
});
expect(adminIds.length).toBe(1);
});
it('INOTIF-002 — notification with event_type skips recipients who have disabled that event on inapp', () => {
const { user: sender } = createAdmin(testDb);
const { user: recipient1 } = createUser(testDb);
const { user: recipient2 } = createUser(testDb);
// recipient2 has disabled inapp for trip_invite
disableNotificationPref(testDb, recipient2.id, 'trip_invite', 'inapp');
// Use a trip to target both members
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Test Trip', sender.id)).lastInsertRowid as number;
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, recipient1.id);
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, recipient2.id);
const ids = createNotification({
type: 'simple',
scope: 'trip',
target: tripId,
sender_id: sender.id,
event_type: 'trip_invite',
title_key: 'notifications.test.title',
text_key: 'notifications.test.text',
});
// sender excluded, recipient1 included, recipient2 skipped (disabled pref)
expect(ids.length).toBe(1);
const r1 = testDb.prepare('SELECT id FROM notifications WHERE recipient_id = ?').get(recipient1.id);
const r2 = testDb.prepare('SELECT id FROM notifications WHERE recipient_id = ?').get(recipient2.id);
expect(r1).toBeDefined();
expect(r2).toBeUndefined();
});
it('INOTIF-003 — notification with event_type delivers to recipients with no stored preferences', () => {
const { user: sender } = createAdmin(testDb);
const { user: recipient } = createUser(testDb);
// No preferences stored for recipient — should default to enabled
const ids = createNotification({
type: 'simple',
scope: 'user',
target: recipient.id,
sender_id: sender.id,
event_type: 'trip_invite',
title_key: 'notifications.test.title',
text_key: 'notifications.test.text',
});
expect(ids.length).toBe(1);
const row = testDb.prepare('SELECT id FROM notifications WHERE recipient_id = ?').get(recipient.id);
expect(row).toBeDefined();
});
it('INOTIF-003b — createNotificationForRecipient inserts a single notification and broadcasts via WS', () => {
const { user: sender } = createAdmin(testDb);
const { user: recipient } = createUser(testDb);
const id = createNotificationForRecipient(
{
type: 'navigate',
scope: 'user',
target: recipient.id,
sender_id: sender.id,
event_type: 'trip_invite',
title_key: 'notif.trip_invite.title',
text_key: 'notif.trip_invite.text',
navigate_text_key: 'notif.action.view_trip',
navigate_target: '/trips/99',
},
recipient.id,
{ username: 'admin', avatar: null }
);
expect(id).toBeTypeOf('number');
const row = testDb.prepare('SELECT * FROM notifications WHERE id = ?').get(id) as { recipient_id: number; navigate_target: string } | undefined;
expect(row).toBeDefined();
expect(row!.recipient_id).toBe(recipient.id);
expect(row!.navigate_target).toBe('/trips/99');
expect(broadcastMock).toHaveBeenCalledTimes(1);
expect(broadcastMock.mock.calls[0][0]).toBe(recipient.id);
});
it('INOTIF-004 — admin-scope version_available only reaches admins with enabled pref', () => {
const { user: admin1 } = createAdmin(testDb);
const { user: admin2 } = createAdmin(testDb);
// admin2 disables version_available inapp notifications
disableNotificationPref(testDb, admin2.id, 'version_available', 'inapp');
const ids = createNotification({
type: 'navigate',
scope: 'admin',
target: 0,
sender_id: null,
event_type: 'version_available',
title_key: 'notifications.versionAvailable.title',
text_key: 'notifications.versionAvailable.text',
navigate_text_key: 'notifications.versionAvailable.button',
navigate_target: '/admin',
});
// Only admin1 should receive it
expect(ids.length).toBe(1);
const admin1Row = testDb.prepare('SELECT id FROM notifications WHERE recipient_id = ?').get(admin1.id);
const admin2Row = testDb.prepare('SELECT id FROM notifications WHERE recipient_id = ?').get(admin2.id);
expect(admin1Row).toBeDefined();
expect(admin2Row).toBeUndefined();
});
});
// ─────────────────────────────────────────────────────────────────────────────
// respondToBoolean
// ─────────────────────────────────────────────────────────────────────────────
function insertBooleanNotification(recipientId: number, senderId: number | null = null): number {
const result = testDb.prepare(`
INSERT INTO notifications (
type, scope, target, sender_id, recipient_id,
title_key, title_params, text_key, text_params,
positive_text_key, negative_text_key, positive_callback, negative_callback
) VALUES ('boolean', 'user', ?, ?, ?, 'notif.test.title', '{}', 'notif.test.text', '{}',
'notif.action.accept', 'notif.action.decline',
'{"action":"test_approve","payload":{}}', '{"action":"test_deny","payload":{}}'
)
`).run(recipientId, senderId, recipientId);
return result.lastInsertRowid as number;
}
function insertSimpleNotification(recipientId: number): number {
const result = testDb.prepare(`
INSERT INTO notifications (
type, scope, target, sender_id, recipient_id,
title_key, title_params, text_key, text_params
) VALUES ('simple', 'user', ?, NULL, ?, 'notif.test.title', '{}', 'notif.test.text', '{}')
`).run(recipientId, recipientId);
return result.lastInsertRowid as number;
}
describe('respondToBoolean', () => {
it('INOTIF-005 — positive response sets response=positive, marks read, broadcasts update', async () => {
const { user } = createUser(testDb);
const id = insertBooleanNotification(user.id);
const result = await respondToBoolean(id, user.id, 'positive');
expect(result.success).toBe(true);
expect(result.notification).toBeDefined();
const row = testDb.prepare('SELECT * FROM notifications WHERE id = ?').get(id) as any;
expect(row.response).toBe('positive');
expect(row.is_read).toBe(1);
expect(broadcastMock).toHaveBeenCalledWith(user.id, expect.objectContaining({ type: 'notification:updated' }));
});
it('INOTIF-006 — negative response sets response=negative', async () => {
const { user } = createUser(testDb);
const id = insertBooleanNotification(user.id);
const result = await respondToBoolean(id, user.id, 'negative');
expect(result.success).toBe(true);
const row = testDb.prepare('SELECT response FROM notifications WHERE id = ?').get(id) as any;
expect(row.response).toBe('negative');
});
it('INOTIF-007 — double-response prevention returns error on second call', async () => {
const { user } = createUser(testDb);
const id = insertBooleanNotification(user.id);
await respondToBoolean(id, user.id, 'positive');
const result = await respondToBoolean(id, user.id, 'negative');
expect(result.success).toBe(false);
expect(result.error).toMatch(/already responded/i);
});
it('INOTIF-008 — response on a simple notification returns error', async () => {
const { user } = createUser(testDb);
const id = insertSimpleNotification(user.id);
const result = await respondToBoolean(id, user.id, 'positive');
expect(result.success).toBe(false);
expect(result.error).toMatch(/not a boolean/i);
});
it('INOTIF-009 — response on a non-existent notification returns error', async () => {
const { user } = createUser(testDb);
const result = await respondToBoolean(99999, user.id, 'positive');
expect(result.success).toBe(false);
expect(result.error).toMatch(/not found/i);
});
it('INOTIF-010 — response on notification belonging to another user returns error', async () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const id = insertBooleanNotification(owner.id);
const result = await respondToBoolean(id, other.id, 'positive');
expect(result.success).toBe(false);
expect(result.error).toMatch(/not found/i);
});
});
File diff suppressed because it is too large Load Diff
@@ -1,513 +0,0 @@
/**
* Unit tests for journeyShareService — JOURNEY-SHARE-001 through JOURNEY-SHARE-018.
* Uses a real in-memory SQLite DB so SQL logic is exercised faithfully.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// -- DB setup -----------------------------------------------------------------
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createJourney, createJourneyEntry } from '../../helpers/factories';
import {
createOrUpdateJourneyShareLink,
getJourneyShareLink,
deleteJourneyShareLink,
validateShareTokenForPhoto,
validateShareTokenForAsset,
getPublicJourney,
} from '../../../src/services/journeyShareService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// -- Helpers ------------------------------------------------------------------
/** Insert a trek_photos + journey_photos (gallery) + journey_entry_photos row and return the trek_photos id (used as photoId in public URLs). */
function insertJourneyPhoto(
entryId: number,
opts: { filePath?: string; assetId?: string; ownerId?: number } = {}
): number {
const provider = opts.assetId ? 'immich' : 'local';
const filePath = !opts.assetId ? (opts.filePath ?? '/photos/test.jpg') : null;
const trekResult = testDb.prepare(`
INSERT INTO trek_photos (provider, asset_id, file_path, owner_id, created_at)
VALUES (?, ?, ?, ?, ?)
`).run(provider, opts.assetId ?? null, filePath, opts.ownerId ?? null, Date.now());
const trekId = trekResult.lastInsertRowid as number;
// Look up journey_id from entry so gallery row is keyed to the journey (not entry).
const entryRow = testDb.prepare('SELECT journey_id FROM journey_entries WHERE id = ?').get(entryId) as { journey_id: number };
const journeyId = entryRow.journey_id;
const now = Date.now();
testDb.prepare(`
INSERT OR IGNORE INTO journey_photos (journey_id, photo_id, caption, sort_order, created_at)
VALUES (?, ?, NULL, 0, ?)
`).run(journeyId, trekId, now);
const galleryRow = testDb.prepare('SELECT id FROM journey_photos WHERE journey_id = ? AND photo_id = ?').get(journeyId, trekId) as { id: number };
testDb.prepare(`
INSERT OR IGNORE INTO journey_entry_photos (entry_id, journey_photo_id, sort_order, created_at)
VALUES (?, ?, 0, ?)
`).run(entryId, galleryRow.id, now);
// Return trek_photos.id — this is p.photo_id in the public API response
// and the value the client sends to /api/public/journey/:token/photos/:photoId/:kind
return trekId;
}
// -- Tests --------------------------------------------------------------------
describe('createOrUpdateJourneyShareLink', () => {
it('JOURNEY-SHARE-001: creates a new share link with default permissions', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const result = createOrUpdateJourneyShareLink(journey.id, user.id, {});
expect(result.created).toBe(true);
expect(result.token).toBeTruthy();
expect(result.token.length).toBeGreaterThan(10);
});
it('JOURNEY-SHARE-002: creates a share link with custom permissions', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true,
share_gallery: false,
share_map: false,
});
const link = getJourneyShareLink(journey.id);
expect(link).not.toBeNull();
expect(link!.share_timeline).toBe(true);
expect(link!.share_gallery).toBe(false);
expect(link!.share_map).toBe(false);
});
it('JOURNEY-SHARE-003: updates permissions on existing link without regenerating token', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const first = createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true,
share_gallery: true,
share_map: true,
});
const second = createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true,
share_gallery: false,
share_map: false,
});
expect(second.created).toBe(false);
expect(second.token).toBe(first.token);
const link = getJourneyShareLink(journey.id);
expect(link!.share_gallery).toBe(false);
expect(link!.share_map).toBe(false);
});
it('JOURNEY-SHARE-004: different journeys get different tokens', () => {
const { user } = createUser(testDb);
const j1 = createJourney(testDb, user.id);
const j2 = createJourney(testDb, user.id);
const r1 = createOrUpdateJourneyShareLink(j1.id, user.id, {});
const r2 = createOrUpdateJourneyShareLink(j2.id, user.id, {});
expect(r1.token).not.toBe(r2.token);
});
});
describe('getJourneyShareLink', () => {
it('JOURNEY-SHARE-005: returns null when no share link exists', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const result = getJourneyShareLink(journey.id);
expect(result).toBeNull();
});
it('JOURNEY-SHARE-006: returns share link info when it exists', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true,
share_gallery: false,
share_map: true,
});
const result = getJourneyShareLink(journey.id);
expect(result).not.toBeNull();
expect(result!.token).toBeTruthy();
expect(result!.share_timeline).toBe(true);
expect(result!.share_gallery).toBe(false);
expect(result!.share_map).toBe(true);
expect(result!.created_at).toBeTruthy();
});
});
describe('deleteJourneyShareLink', () => {
it('JOURNEY-SHARE-007: owner can remove an existing share link', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
createOrUpdateJourneyShareLink(journey.id, user.id, {});
const ok = deleteJourneyShareLink(journey.id, user.id);
expect(ok).toBe(true);
expect(getJourneyShareLink(journey.id)).toBeNull();
});
it('JOURNEY-SHARE-008: does not throw when deleting non-existent link', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
expect(() => deleteJourneyShareLink(journey.id, user.id)).not.toThrow();
});
});
describe('validateShareTokenForPhoto', () => {
it('JOURNEY-SHARE-009: returns journeyId and ownerId for valid token + photo', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
const photoId = insertJourneyPhoto(entry.id, { ownerId: user.id });
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = validateShareTokenForPhoto(token, photoId);
expect(result).not.toBeNull();
expect(result!.journeyId).toBe(journey.id);
expect(result!.ownerId).toBe(user.id);
});
it('JOURNEY-SHARE-010: returns null for invalid token', () => {
const result = validateShareTokenForPhoto('nonexistent-token', 1);
expect(result).toBeNull();
});
it('JOURNEY-SHARE-011: returns null when photo does not belong to shared journey', () => {
const { user } = createUser(testDb);
const journey1 = createJourney(testDb, user.id);
const journey2 = createJourney(testDb, user.id);
const entry2 = createJourneyEntry(testDb, journey2.id, user.id);
const photoId = insertJourneyPhoto(entry2.id);
const { token } = createOrUpdateJourneyShareLink(journey1.id, user.id, {});
const result = validateShareTokenForPhoto(token, photoId);
expect(result).toBeNull();
});
it('JOURNEY-SHARE-012: falls back to journey owner_id when photo has no owner_id', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
const photoId = insertJourneyPhoto(entry.id, { ownerId: undefined });
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = validateShareTokenForPhoto(token, photoId);
expect(result).not.toBeNull();
expect(result!.ownerId).toBe(user.id);
});
// Regression — GHSA-9hc8 sibling: the byte proxy must honour share_gallery.
it('JOURNEY-SHARE-017: returns null when the owner disabled the gallery (share_gallery=false)', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
const photoId = insertJourneyPhoto(entry.id, { ownerId: user.id });
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, { share_timeline: true, share_gallery: false, share_map: true });
expect(validateShareTokenForPhoto(token, photoId)).toBeNull();
});
it('JOURNEY-SHARE-016: resolves correctly when trek_photos.id differs from journey_photos.id (Immich bulk-sync scenario)', () => {
// Simulate a user who has many trek_photos from Immich syncs before adding a journey photo.
// trek_photos.id will be higher than journey_photos.id — the previous bug matched on jp.id
// instead of jp.photo_id, causing a 404 for Immich photos in public shares.
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
// Pre-populate trek_photos to push the autoincrement higher
for (let i = 0; i < 5; i++) {
testDb.prepare(`INSERT INTO trek_photos (provider, asset_id, owner_id, created_at) VALUES ('immich', ?, ?, ?)`).run(`bulk-asset-${i}`, user.id, Date.now());
}
// This trek_photos row gets a high id (e.g. 6) while journey_photos id will be 1
const trekPhotoId = insertJourneyPhoto(entry.id, { assetId: 'journey-asset-xyz', ownerId: user.id });
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
// photoId = trek_photos.id (6), not journey_photos.id (1)
const result = validateShareTokenForPhoto(token, trekPhotoId);
expect(result).not.toBeNull();
expect(result!.ownerId).toBe(user.id);
expect(result!.journeyId).toBe(journey.id);
});
});
describe('validateShareTokenForAsset', () => {
it('JOURNEY-SHARE-013: returns ownerId when asset belongs to shared journey', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
insertJourneyPhoto(entry.id, { assetId: 'immich-asset-123', ownerId: user.id });
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = validateShareTokenForAsset(token, 'immich-asset-123');
expect(result).not.toBeNull();
expect(result!.ownerId).toBe(user.id);
});
it('JOURNEY-SHARE-014: returns null for invalid token', () => {
const result = validateShareTokenForAsset('bad-token', 'some-asset');
expect(result).toBeNull();
});
// Regression — GHSA-9hc8 sibling: the asset proxy must honour share_gallery.
it('JOURNEY-SHARE-018: returns null when the owner disabled the gallery (share_gallery=false)', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id);
insertJourneyPhoto(entry.id, { assetId: 'immich-asset-999', ownerId: user.id });
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, { share_timeline: true, share_gallery: false, share_map: true });
expect(validateShareTokenForAsset(token, 'immich-asset-999')).toBeNull();
});
it('JOURNEY-SHARE-015: denies (returns null) when the asset is not part of the shared journey', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
// A valid share token must NOT resolve arbitrary asset IDs to the owner —
// otherwise it could proxy any asset out of the owner's Immich/Synology
// library (IDOR). Only assets actually in the journey may resolve.
const result = validateShareTokenForAsset(token, 'nonexistent-asset');
expect(result).toBeNull();
});
});
describe('getPublicJourney', () => {
it('JOURNEY-SHARE-016: returns null for invalid token', () => {
const result = getPublicJourney('invalid-token');
expect(result).toBeNull();
});
it('JOURNEY-SHARE-017: returns journey data with entries, stats, and permissions', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id, {
title: 'Japan 2026',
subtitle: 'Cherry blossom season',
});
const entry1 = createJourneyEntry(testDb, journey.id, user.id, {
type: 'entry',
title: 'Arrived in Tokyo',
entry_date: '2026-03-20',
location_name: 'Tokyo',
});
createJourneyEntry(testDb, journey.id, user.id, {
type: 'entry',
title: 'Kyoto Day Trip',
entry_date: '2026-03-22',
location_name: 'Kyoto',
});
insertJourneyPhoto(entry1.id);
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true,
share_gallery: true,
share_map: false,
});
const result = getPublicJourney(token);
expect(result).not.toBeNull();
expect(result!.journey.title).toBe('Japan 2026');
expect(result!.journey.subtitle).toBe('Cherry blossom season');
expect(result!.entries).toHaveLength(2);
expect(result!.stats.entries).toBe(2);
expect(result!.stats.photos).toBe(1);
expect(result!.stats.places).toBe(2);
expect(result!.permissions.share_timeline).toBe(true);
expect(result!.permissions.share_gallery).toBe(true);
expect(result!.permissions.share_map).toBe(false);
});
it('JOURNEY-SHARE-018: excludes skeleton entries from public view', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
createJourneyEntry(testDb, journey.id, user.id, {
type: 'entry',
title: 'Visible Entry',
entry_date: '2026-01-10',
});
createJourneyEntry(testDb, journey.id, user.id, {
type: 'skeleton',
title: 'Skeleton Entry',
entry_date: '2026-01-11',
});
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = getPublicJourney(token);
expect(result).not.toBeNull();
expect(result!.entries).toHaveLength(1);
expect(result!.entries[0].title).toBe('Visible Entry');
});
it('JOURNEY-SHARE-019: enriches entries with parsed tags and photos', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id, {
type: 'entry',
entry_date: '2026-04-01',
});
// Set tags on the entry directly
testDb.prepare('UPDATE journey_entries SET tags = ? WHERE id = ?')
.run(JSON.stringify(['food', 'culture']), entry.id);
insertJourneyPhoto(entry.id, { filePath: '/photos/a.jpg' });
insertJourneyPhoto(entry.id, { filePath: '/photos/b.jpg' });
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = getPublicJourney(token);
expect(result).not.toBeNull();
const enriched = result!.entries[0];
expect(enriched.tags).toEqual(['food', 'culture']);
expect(enriched.photos).toHaveLength(2);
});
it('JOURNEY-SHARE-020: returns empty entries array for journey with no entries', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id, { title: 'Empty Journey' });
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {});
const result = getPublicJourney(token);
expect(result).not.toBeNull();
expect(result!.entries).toEqual([]);
expect(result!.stats.entries).toBe(0);
expect(result!.stats.photos).toBe(0);
expect(result!.stats.places).toBe(0);
});
it('JOURNEY-SHARE-021: withholds timeline, gallery and GPS when all flags are off', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id, { title: 'Secret' });
const entry = createJourneyEntry(testDb, journey.id, user.id, {
type: 'entry', title: 'Day 1', story: 'private notes', entry_date: '2026-05-01', location_name: 'Paris',
});
testDb.prepare('UPDATE journey_entries SET location_lat = ?, location_lng = ? WHERE id = ?').run(48.8566, 2.3522, entry.id);
insertJourneyPhoto(entry.id);
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: false, share_gallery: false, share_map: false,
});
const result = getPublicJourney(token)!;
expect(result.entries).toEqual([]); // no timeline / story / GPS leaked
expect(result.gallery).toEqual([]); // no gallery leaked
expect(result.stats.entries).toBe(1); // counts stay accurate
});
it('JOURNEY-SHARE-022: shares the timeline but strips GPS when the map flag is off', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id, {
type: 'entry', title: 'Day 1', story: 'notes', entry_date: '2026-05-01', location_name: 'Paris',
});
testDb.prepare('UPDATE journey_entries SET location_lat = ?, location_lng = ? WHERE id = ?').run(48.8566, 2.3522, entry.id);
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true, share_gallery: true, share_map: false,
});
const result = getPublicJourney(token)!;
expect(result.entries).toHaveLength(1);
const e = result.entries[0] as Record<string, unknown>;
expect(e.story).toBe('notes'); // narrative present
expect(e.location_lat).toBeNull(); // GPS withheld
expect(e.location_lng).toBeNull();
});
it('JOURNEY-SHARE-023: map-only share exposes coordinates but not the story', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id, {
type: 'entry', title: 'Day 1', story: 'private notes', entry_date: '2026-05-01', location_name: 'Paris',
});
testDb.prepare('UPDATE journey_entries SET location_lat = ?, location_lng = ? WHERE id = ?').run(48.8566, 2.3522, entry.id);
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: false, share_gallery: false, share_map: true,
});
const result = getPublicJourney(token)!;
expect(result.entries).toHaveLength(1);
const e = result.entries[0] as Record<string, unknown>;
expect(e.location_lat).toBe(48.8566); // coords for the map
expect(e.story).toBeUndefined(); // narrative withheld
});
it('JOURNEY-SHARE-024: strips inline entry photos (and their asset metadata) when the gallery is off', () => {
const { user } = createUser(testDb);
const journey = createJourney(testDb, user.id);
const entry = createJourneyEntry(testDb, journey.id, user.id, {
type: 'entry', title: 'Day 1', story: 'notes', entry_date: '2026-05-01',
});
insertJourneyPhoto(entry.id, { ownerId: user.id });
const { token } = createOrUpdateJourneyShareLink(journey.id, user.id, {
share_timeline: true, share_gallery: false, share_map: true,
});
const result = getPublicJourney(token)!;
expect(result.gallery).toEqual([]); // gallery array withheld
expect(result.entries).toHaveLength(1);
expect((result.entries[0] as Record<string, unknown>).photos).toEqual([]); // inline photos withheld too
});
});
@@ -1,96 +0,0 @@
import { describe, it, expect } from 'vitest';
import {
buildCategoryNameLookup,
decodeUtf8WithWarning,
extractKmlPlacemarkNodes,
parseKmlPointCoordinates,
parsePlacemarkNode,
resolveCategoryIdForFolder,
sanitizeKmlDescription,
} from '../../../src/services/kmlImport';
describe('kmlImportUtils', () => {
it('sanitizes HTML descriptions with br to newline', () => {
const input = 'Line 1<br>Line <b>2</b> &amp; more';
const output = sanitizeKmlDescription(input);
expect(output).toBe('Line 1\nLine 2 & more');
});
it('unwraps CDATA sections before stripping tags', () => {
const input = '<![CDATA[Great spot<br>for photos <b>and</b> skyline.]]>';
expect(sanitizeKmlDescription(input)).toBe('Great spot\nfor photos and skyline.');
});
it('parses KML coordinate order lng,lat,alt', () => {
const parsed = parseKmlPointCoordinates('13.4050,52.5200,15');
expect(parsed).toEqual({ lat: 52.52, lng: 13.405 });
});
it('extracts placemarks from nested folders', () => {
const root = {
Document: {
Folder: {
name: 'Parent',
Folder: {
name: 'Child',
Placemark: { name: 'Nested', Point: { coordinates: '13.4,52.5,0' } },
},
},
},
};
const nodes = extractKmlPlacemarkNodes(root);
expect(nodes).toHaveLength(1);
expect(nodes[0].folderName).toBe('Child');
const parsed = parsePlacemarkNode(nodes[0]);
expect(parsed.name).toBe('Nested');
expect(parsed.lat).toBe(52.5);
expect(parsed.lng).toBe(13.4);
});
it('builds exact case-insensitive category lookup', () => {
const lookup = buildCategoryNameLookup([
{ id: 3, name: 'Museums' },
{ id: 4, name: 'Parks' },
]);
expect(resolveCategoryIdForFolder('museums', lookup)).toBe(3);
expect(resolveCategoryIdForFolder('Museum', lookup)).toBeNull();
expect(resolveCategoryIdForFolder('parks', lookup)).toBe(4);
});
it('decodes non-BMP decimal HTML entities (emoji)', () => {
// &#128512; = U+1F600 = 😀 — requires String.fromCodePoint, not fromCharCode
expect(sanitizeKmlDescription('&#128512;')).toBe('😀');
});
it('decodes non-BMP hex HTML entities (emoji)', () => {
// &#x1F600; = U+1F600 = 😀
expect(sanitizeKmlDescription('&#x1F600;')).toBe('😀');
});
it('does not produce [object Object] when description is a parsed object with #text', () => {
// fast-xml-parser can return an object for mixed-content nodes when stopNodes
// is not configured; the fallback in asTrimmedString must extract #text.
const result = sanitizeKmlDescription({ '#text': 'Hello <b>world</b>' } as any);
expect(result).not.toBe('[object Object]');
expect(result).toBe('Hello world');
});
it('returns null when description object has no #text', () => {
expect(sanitizeKmlDescription({ i: 'bold' } as any)).toBeNull();
});
it('returns warning for non-UTF8 payload', () => {
const buffer = Buffer.concat([
Buffer.from('<?xml version="1.0"?><kml><Document><Placemark><name>Caf'),
Buffer.from([0xe9]),
Buffer.from('</name></Placemark></Document></kml>'),
]);
const decoded = decodeUtf8WithWarning(buffer);
expect(decoded.warning).toContain('not valid UTF-8');
expect(decoded.text).toContain('<kml>');
});
});
@@ -1,61 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import path from 'path';
import fs from 'fs';
vi.mock('../../../src/db/database', () => ({
db: { prepare: vi.fn() },
getPlaceWithTags: vi.fn(),
}));
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { unpackKmzToKml, KMZ_DECOMPRESSED_SIZE_LIMIT } from '../../../src/services/placeService';
const KMZ_FIXTURE = path.join(__dirname, '../../fixtures/test.kmz');
describe('unpackKmzToKml', () => {
it('extracts the KML entry from a valid KMZ', async () => {
const kmzBuffer = fs.readFileSync(KMZ_FIXTURE);
const kmlBuffer = await unpackKmzToKml(kmzBuffer);
expect(kmlBuffer.length).toBeGreaterThan(0);
expect(kmlBuffer.toString('utf-8')).toContain('<kml');
});
it('rejects a KMZ whose KML entry exceeds the decompressed size limit', async () => {
const kmzBuffer = fs.readFileSync(KMZ_FIXTURE);
// test.kmz contains a KML with uncompressedSize 634 — set limit to 1 byte
await expect(unpackKmzToKml(kmzBuffer, 1)).rejects.toThrow('exceeds the maximum allowed decompressed size');
});
it('rejects a KMZ that contains no KML file', async () => {
// Craft a minimal ZIP containing only a non-KML entry using raw ZIP bytes
// We use the test GPX fixture (a real file) re-zipped via Node's zlib/archiver
// Simplest: a KMZ whose only file has a .txt extension
const Archiver = await import('archiver');
const archiver = Archiver.default;
const { PassThrough } = await import('stream');
const chunks: Buffer[] = [];
const output = new PassThrough();
output.on('data', (chunk) => chunks.push(chunk));
const archive = archiver('zip', { zlib: { level: 1 } });
archive.pipe(output);
archive.append(Buffer.from('not a kml'), { name: 'data.txt' });
await archive.finalize();
const zipBuffer = Buffer.concat(chunks);
await expect(unpackKmzToKml(zipBuffer)).rejects.toThrow('does not contain a KML file');
});
it('rejects a buffer that is not a valid ZIP archive', async () => {
await expect(unpackKmzToKml(Buffer.from('this is not a zip'))).rejects.toThrow('Invalid KMZ archive');
});
it('exports KMZ_DECOMPRESSED_SIZE_LIMIT as 50 MB', () => {
expect(KMZ_DECOMPRESSED_SIZE_LIMIT).toBe(50 * 1024 * 1024);
});
});
File diff suppressed because it is too large Load Diff
@@ -1,276 +0,0 @@
/**
* Unit tests for memories/helpersService — MEM-HELPERS-001 to MEM-HELPERS-020.
* Covers mapDbError, getAlbumIdFromLink, pipeAsset error paths.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ─────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`
SELECT t.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-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
const { mockSafeFetch } = vi.hoisted(() => ({
mockSafeFetch: vi.fn(),
}));
vi.mock('../../../src/utils/ssrfGuard', () => {
class SsrfBlockedError extends Error {
constructor(msg: string) { super(msg); this.name = 'SsrfBlockedError'; }
}
return {
safeFetch: mockSafeFetch,
SsrfBlockedError,
checkSsrf: vi.fn(async () => ({ allowed: true, resolvedIp: '1.2.3.4' })),
};
});
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { mapDbError, getAlbumIdFromLink, pipeAsset } from '../../../src/services/memories/helpersService';
import { SsrfBlockedError } from '../../../src/utils/ssrfGuard';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
mockSafeFetch.mockReset();
});
afterAll(() => {
testDb.close();
});
// ── mapDbError ────────────────────────────────────────────────────────────────
describe('mapDbError', () => {
it('MEM-HELPERS-001: returns 409 for unique constraint error', () => {
const err = new Error('UNIQUE constraint failed: users.email');
const result = mapDbError(err, 'fallback');
expect(result.success).toBe(false);
expect(result.error.status).toBe(409);
expect(result.error.message).toBe('Resource already exists');
});
it('MEM-HELPERS-002: returns 409 for generic constraint error', () => {
const err = new Error('constraint violation');
const result = mapDbError(err, 'fallback');
expect(result.success).toBe(false);
expect(result.error.status).toBe(409);
});
it('MEM-HELPERS-003: returns 500 with original message for non-constraint error', () => {
const err = new Error('Something went wrong');
const result = mapDbError(err, 'fallback');
expect(result.success).toBe(false);
expect(result.error.status).toBe(500);
expect(result.error.message).toBe('Something went wrong');
});
it('MEM-HELPERS-004: returns 500 for generic DB error', () => {
const err = new Error('disk I/O error');
const result = mapDbError(err, 'fallback');
expect(result.error.status).toBe(500);
});
});
// ── getAlbumIdFromLink ────────────────────────────────────────────────────────
describe('getAlbumIdFromLink', () => {
it('MEM-HELPERS-005: returns 404 when trip access is denied', () => {
const result = getAlbumIdFromLink('9999', 'link-1', 1);
expect(result.success).toBe(false);
expect(result.error.status).toBe(404);
});
it('MEM-HELPERS-006: returns 404 when album link is not found', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = getAlbumIdFromLink(String(trip.id), 'nonexistent-link', user.id);
expect(result.success).toBe(false);
expect(result.error.status).toBe(404);
expect(result.error.message).toBe('Album link not found');
});
it('MEM-HELPERS-007: returns album_id when link exists', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Insert with auto-increment id (INTEGER PRIMARY KEY)
const ins = testDb.prepare(
'INSERT INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)'
).run(trip.id, user.id, 'immich', 'album-123', 'My Album');
const linkId = ins.lastInsertRowid;
const result = getAlbumIdFromLink(String(trip.id), String(linkId), user.id);
expect(result.success).toBe(true);
expect((result as any).data).toBe('album-123');
});
});
// ── pipeAsset ─────────────────────────────────────────────────────────────────
describe('pipeAsset', () => {
function mockResponse(overrides: Record<string, any> = {}) {
return {
status: vi.fn().mockReturnThis(),
set: vi.fn().mockReturnThis(),
end: vi.fn(),
json: vi.fn(),
headersSent: false,
...overrides,
} as any;
}
it('MEM-HELPERS-009: calls response.end() when resp.body is null', async () => {
mockSafeFetch.mockResolvedValue({
status: 200,
headers: { get: vi.fn(() => null) },
body: null,
});
const res = mockResponse();
await pipeAsset('https://example.com/asset', res);
expect(res.end).toHaveBeenCalled();
});
it('MEM-HELPERS-010: returns 400 when SsrfBlockedError is thrown', async () => {
mockSafeFetch.mockRejectedValue(new SsrfBlockedError('SSRF blocked'));
const res = mockResponse({ headersSent: false });
await pipeAsset('https://internal.example.com/asset', res);
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
});
it('MEM-HELPERS-011: returns 500 for generic fetch error', async () => {
mockSafeFetch.mockRejectedValue(new Error('Network error'));
const res = mockResponse({ headersSent: false });
await pipeAsset('https://example.com/asset', res);
expect(res.status).toHaveBeenCalledWith(500);
expect(res.json).toHaveBeenCalledWith({ error: 'Failed to fetch asset' });
});
it('MEM-HELPERS-012: calls response.end() when headersSent is true on error', async () => {
mockSafeFetch.mockRejectedValue(new Error('fail'));
const res = mockResponse({ headersSent: true });
await pipeAsset('https://example.com/asset', res);
expect(res.end).toHaveBeenCalled();
expect(res.json).not.toHaveBeenCalled();
});
it('MEM-HELPERS-013: sets content-type header when present in response', async () => {
mockSafeFetch.mockResolvedValue({
status: 200,
headers: {
get: (h: string) => {
if (h === 'content-type') return 'image/jpeg';
return null;
},
},
body: null,
});
const res = mockResponse();
await pipeAsset('https://example.com/img.jpg', res);
expect(res.set).toHaveBeenCalledWith('Content-Type', 'image/jpeg');
expect(res.end).toHaveBeenCalled();
});
});
// ── pipeAsset fetch options (#1611) ───────────────────────────────────────────
describe('pipeAsset fetch options (#1611)', () => {
function mockResponse(overrides: Record<string, any> = {}) {
return {
status: vi.fn().mockReturnThis(),
set: vi.fn().mockReturnThis(),
end: vi.fn(),
json: vi.fn(),
headersSent: false,
...overrides,
} as any;
}
it('MEM-HELPERS-021: forwards fetchOptions to safeFetch', async () => {
mockSafeFetch.mockResolvedValue({
status: 200,
headers: { get: vi.fn(() => null) },
body: null,
});
const res = mockResponse();
await pipeAsset('https://example.com/asset', res, undefined, undefined, undefined, { rejectUnauthorized: false });
expect(mockSafeFetch).toHaveBeenCalledWith(
'https://example.com/asset',
expect.anything(),
{ rejectUnauthorized: false },
);
});
it('MEM-HELPERS-022: omitting fetchOptions leaves safeFetch options undefined', async () => {
mockSafeFetch.mockResolvedValue({
status: 200,
headers: { get: vi.fn(() => null) },
body: null,
});
const res = mockResponse();
await pipeAsset('https://example.com/asset', res);
expect(mockSafeFetch.mock.calls[0][2]).toBeUndefined();
});
it('MEM-HELPERS-023: logs the underlying error when responding 500', async () => {
const boom = new Error('unable to verify the first certificate');
mockSafeFetch.mockRejectedValue(boom);
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const res = mockResponse({ headersSent: false });
await pipeAsset('https://example.com/asset', res);
expect(res.status).toHaveBeenCalledWith(500);
expect(errorSpy).toHaveBeenCalledWith(expect.any(String), boom);
errorSpy.mockRestore();
});
});
@@ -1,216 +0,0 @@
/**
* Unit tests for memories/unifiedService — MEM-UNIFIED-001 to MEM-UNIFIED-010.
* Covers error paths: access denied, disabled provider, no providers enabled.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ─────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`
SELECT t.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-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
vi.mock('../../../src/services/notificationService', () => ({
send: vi.fn().mockResolvedValue(undefined),
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import {
listTripPhotos,
listTripAlbumLinks,
addTripPhotos,
setTripPhotoSharing,
removeTripPhoto,
createTripAlbumLink,
removeAlbumLink,
} from '../../../src/services/memories/unifiedService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
// Ensure default providers are enabled (resetTestDb seeds them but doesn't reset enabled flag)
testDb.prepare('UPDATE photo_providers SET enabled = 1').run();
});
afterAll(() => {
testDb.close();
});
// ── listTripPhotos ────────────────────────────────────────────────────────────
describe('listTripPhotos', () => {
it('MEM-UNIFIED-001: returns 404 when user cannot access trip', () => {
const result = listTripPhotos('9999', 1);
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(404);
});
it('MEM-UNIFIED-002: returns 400 when no photo providers are enabled', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Disable all providers
testDb.prepare('UPDATE photo_providers SET enabled = 0').run();
const result = listTripPhotos(String(trip.id), user.id);
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(400);
expect((result as any).error.message).toMatch(/no photo providers enabled/i);
});
});
// ── listTripAlbumLinks ────────────────────────────────────────────────────────
describe('listTripAlbumLinks', () => {
it('MEM-UNIFIED-003: returns 404 when user cannot access trip', () => {
const result = listTripAlbumLinks('9999', 1);
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(404);
});
it('MEM-UNIFIED-004: returns 400 when no photo providers are enabled', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('UPDATE photo_providers SET enabled = 0').run();
const result = listTripAlbumLinks(String(trip.id), user.id);
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(400);
});
});
// ── addTripPhotos ─────────────────────────────────────────────────────────────
describe('addTripPhotos', () => {
it('MEM-UNIFIED-005: returns 404 when user cannot access trip', async () => {
const result = await addTripPhotos('9999', 1, false, [{ provider: 'immich', asset_ids: ['a1'] }], 'sid');
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(404);
});
it('MEM-UNIFIED-006: returns 400 when provider is found but disabled (covers line 25)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Insert a disabled provider
testDb.prepare(
'INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?)'
).run('disabled-prov', 'Disabled', 'Disabled provider', 'Image', 0, 99);
const result = await addTripPhotos(
String(trip.id),
user.id,
false,
[{ provider: 'disabled-prov', asset_ids: ['asset-x'] }],
'sid',
);
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(400);
expect((result as any).error.message).toMatch(/not enabled/i);
});
it('MEM-UNIFIED-007: returns 400 when provider is not found', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = await addTripPhotos(
String(trip.id),
user.id,
false,
[{ provider: 'nonexistent-provider', asset_ids: ['asset-x'] }],
'sid',
);
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(400);
expect((result as any).error.message).toMatch(/not supported/i);
});
});
// ── setTripPhotoSharing ───────────────────────────────────────────────────────
describe('setTripPhotoSharing', () => {
it('MEM-UNIFIED-008: returns 404 when user cannot access trip', async () => {
const result = await setTripPhotoSharing('9999', 1, 'immich', 'asset-1', true);
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(404);
});
});
// ── removeTripPhoto ───────────────────────────────────────────────────────────
describe('removeTripPhoto', () => {
it('MEM-UNIFIED-009: returns 404 when user cannot access trip', () => {
const result = removeTripPhoto('9999', 1, 'immich', 'asset-1');
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(404);
});
});
// ── createTripAlbumLink ───────────────────────────────────────────────────────
describe('createTripAlbumLink', () => {
it('MEM-UNIFIED-010: returns 404 when user cannot access trip', () => {
const result = createTripAlbumLink('9999', 1, 'immich', 'album-1', 'My Album');
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(404);
});
it('MEM-UNIFIED-011: returns 400 when provider is disabled', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare(
'INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?)'
).run('disabled-prov2', 'Disabled2', 'desc', 'Image', 0, 100);
const result = createTripAlbumLink(String(trip.id), user.id, 'disabled-prov2', 'album-1', 'My Album');
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(400);
});
});
// ── removeAlbumLink ───────────────────────────────────────────────────────────
describe('removeAlbumLink', () => {
it('MEM-UNIFIED-012: returns 404 when user cannot access trip', () => {
const result = removeAlbumLink('9999', '1', 1);
expect(result.success).toBe(false);
expect((result as any).error.status).toBe(404);
});
});
+1 -1
View File
@@ -7,7 +7,7 @@ vi.mock('../../../src/config', () => ({
updateJwtSecret: () => {},
}));
import { encryptMfaSecret, decryptMfaSecret } from '../../../src/services/mfaCrypto';
import { encryptMfaSecret, decryptMfaSecret } from '../../../src/nest/common/crypto/mfaCrypto';
describe('mfaCrypto', () => {
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'; // typical base32 TOTP secret
@@ -1,339 +0,0 @@
/**
* Unit tests for notificationPreferencesService.
* Covers NPREF-001 to NPREF-021.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/services/apiKeyCrypto', () => ({
decrypt_api_key: (v: string | null) => v,
maybe_encrypt_api_key: (v: string) => v,
encrypt_api_key: (v: string) => v,
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createAdmin, setAppSetting, setNotificationChannels, disableNotificationPref } from '../../helpers/factories';
import {
isEnabledForEvent,
getPreferencesMatrix,
setPreferences,
setAdminPreferences,
getAdminGlobalPref,
getActiveChannels,
isSmtpConfigured,
isWebhookConfigured,
} from '../../../src/services/notificationPreferencesService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ─────────────────────────────────────────────────────────────────────────────
// isEnabledForEvent
// ─────────────────────────────────────────────────────────────────────────────
describe('isEnabledForEvent', () => {
it('NPREF-001 — returns true when no row exists (default enabled)', () => {
const { user } = createUser(testDb);
expect(isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(true);
});
it('NPREF-002 — returns true when row exists with enabled=1', () => {
const { user } = createUser(testDb);
testDb.prepare(
'INSERT INTO notification_channel_preferences (user_id, event_type, channel, enabled) VALUES (?, ?, ?, 1)'
).run(user.id, 'trip_invite', 'email');
expect(isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(true);
});
it('NPREF-003 — returns false when row exists with enabled=0', () => {
const { user } = createUser(testDb);
disableNotificationPref(testDb, user.id, 'trip_invite', 'email');
expect(isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(false);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// getPreferencesMatrix
// ─────────────────────────────────────────────────────────────────────────────
describe('getPreferencesMatrix', () => {
it('NPREF-004 — regular user does not see version_available in event_types', () => {
const { user } = createUser(testDb);
const { event_types } = getPreferencesMatrix(user.id, 'user');
expect(event_types).not.toContain('version_available');
// +1 for plugin_notification: users can mute host-mediated plugin notifications.
expect(event_types.length).toBe(11);
});
it('NPREF-005 — user scope excludes version_available for everyone including admins', () => {
const { user } = createAdmin(testDb);
const { event_types } = getPreferencesMatrix(user.id, 'admin', 'user');
expect(event_types).not.toContain('version_available');
expect(event_types.length).toBe(11);
});
it('NPREF-005b — admin scope returns only version_available', () => {
const { user } = createAdmin(testDb);
const { event_types } = getPreferencesMatrix(user.id, 'admin', 'admin');
expect(event_types).toContain('version_available');
expect(event_types.length).toBe(1);
});
it('NPREF-006 — returns default true for all preferences when no stored prefs', () => {
const { user } = createUser(testDb);
const { preferences } = getPreferencesMatrix(user.id, 'user');
for (const [, channels] of Object.entries(preferences)) {
for (const [, enabled] of Object.entries(channels as Record<string, boolean>)) {
expect(enabled).toBe(true);
}
}
});
it('NPREF-007 — reflects stored disabled preferences in the matrix', () => {
const { user } = createUser(testDb);
disableNotificationPref(testDb, user.id, 'trip_invite', 'email');
disableNotificationPref(testDb, user.id, 'collab_message', 'webhook');
const { preferences } = getPreferencesMatrix(user.id, 'user');
expect(preferences['trip_invite']!['email']).toBe(false);
expect(preferences['collab_message']!['webhook']).toBe(false);
// Others unaffected
expect(preferences['trip_invite']!['webhook']).toBe(true);
expect(preferences['booking_change']!['email']).toBe(true);
});
it('NPREF-008 — the inapp channel is always active', () => {
const { user } = createUser(testDb);
const { channels } = getPreferencesMatrix(user.id, 'user');
expect(channels.find(c => c.id === 'inapp')?.active).toBe(true);
});
it('NPREF-009 — email is active when email is in notification_channels', () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'email');
const { channels } = getPreferencesMatrix(user.id, 'user');
expect(channels.find(c => c.id === 'email')?.active).toBe(true);
});
it('NPREF-010 — email is inactive when email is not in notification_channels', () => {
const { user } = createUser(testDb);
// No notification_channels set → defaults to none
const { channels } = getPreferencesMatrix(user.id, 'user');
expect(channels.find(c => c.id === 'email')?.active).toBe(false);
});
it('NPREF-011 — implemented_combos maps version_available to [inapp, email, webhook, ntfy]', () => {
const { user } = createAdmin(testDb);
const { implemented_combos } = getPreferencesMatrix(user.id, 'admin', 'admin');
expect(implemented_combos['version_available']).toEqual(['inapp', 'email', 'webhook', 'ntfy']);
// All events now support all four channels
expect(implemented_combos['trip_invite']).toContain('inapp');
expect(implemented_combos['trip_invite']).toContain('email');
expect(implemented_combos['trip_invite']).toContain('webhook');
expect(implemented_combos['trip_invite']).toContain('ntfy');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// setPreferences
// ─────────────────────────────────────────────────────────────────────────────
describe('setPreferences', () => {
it('NPREF-012 — disabling a preference inserts a row with enabled=0', () => {
const { user } = createUser(testDb);
setPreferences(user.id, { trip_invite: { email: false } });
const row = testDb.prepare(
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?'
).get(user.id, 'trip_invite', 'email') as { enabled: number } | undefined;
expect(row).toBeDefined();
expect(row!.enabled).toBe(0);
});
it('NPREF-013 — re-enabling a preference removes the disabled row', () => {
const { user } = createUser(testDb);
// First disable
disableNotificationPref(testDb, user.id, 'trip_invite', 'email');
// Then re-enable
setPreferences(user.id, { trip_invite: { email: true } });
const row = testDb.prepare(
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?'
).get(user.id, 'trip_invite', 'email');
// Row should be deleted — default is enabled
expect(row).toBeUndefined();
});
it('NPREF-014 — bulk update handles multiple event+channel combos', () => {
const { user } = createUser(testDb);
setPreferences(user.id, {
trip_invite: { email: false, webhook: false },
booking_change: { email: false },
trip_reminder: { webhook: true },
});
expect(isEnabledForEvent(user.id, 'trip_invite', 'email')).toBe(false);
expect(isEnabledForEvent(user.id, 'trip_invite', 'webhook')).toBe(false);
expect(isEnabledForEvent(user.id, 'booking_change', 'email')).toBe(false);
// trip_reminder webhook was set to true → no row, default enabled
const row = testDb.prepare(
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?'
).get(user.id, 'trip_reminder', 'webhook');
expect(row).toBeUndefined();
});
});
// ─────────────────────────────────────────────────────────────────────────────
// getActiveChannels
// ─────────────────────────────────────────────────────────────────────────────
describe('getActiveChannels', () => {
it('NPREF-015 — returns [] when notification_channels is none', () => {
setAppSetting(testDb, 'notification_channels', 'none');
expect(getActiveChannels()).toEqual([]);
});
it('NPREF-016 — returns [email] when notification_channels is email', () => {
setAppSetting(testDb, 'notification_channels', 'email');
expect(getActiveChannels()).toEqual(['email']);
});
it('NPREF-017 — returns [email, webhook] when notification_channels is email,webhook', () => {
setAppSetting(testDb, 'notification_channels', 'email,webhook');
expect(getActiveChannels()).toEqual(['email', 'webhook']);
});
it('NPREF-018 — falls back to notification_channel (singular) when plural key absent', () => {
// Only set the singular key
setAppSetting(testDb, 'notification_channel', 'webhook');
// No notification_channels key
expect(getActiveChannels()).toEqual(['webhook']);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// SMTP / active-channel detection
// ─────────────────────────────────────────────────────────────────────────────
describe('channel availability', () => {
it('NPREF-019 — detects SMTP config from app_settings.smtp_host', () => {
setAppSetting(testDb, 'smtp_host', 'mail.example.com');
expect(isSmtpConfigured()).toBe(true);
});
it('NPREF-020 — webhook is active when admin has enabled the webhook channel', () => {
setNotificationChannels(testDb, 'webhook');
expect(getActiveChannels()).toContain('webhook');
});
it('NPREF-021 — detects SMTP config from env var SMTP_HOST', () => {
const original = process.env.SMTP_HOST;
process.env.SMTP_HOST = 'env-mail.example.com';
try {
expect(isSmtpConfigured()).toBe(true);
} finally {
if (original === undefined) delete process.env.SMTP_HOST;
else process.env.SMTP_HOST = original;
}
});
it('NPREF-022 — an unknown channel id in notification_channels is ignored', () => {
// e.g. a plugin channel left in the CSV after the plugin was uninstalled
setNotificationChannels(testDb, 'webhook,plugin:long-gone');
expect(getActiveChannels()).toEqual(['webhook']);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// setAdminPreferences
// ─────────────────────────────────────────────────────────────────────────────
describe('setAdminPreferences', () => {
it('NPREF-022 — disabling email for version_available stores global pref in app_settings', () => {
const { user } = createAdmin(testDb);
setAdminPreferences(user.id, { version_available: { email: false } });
expect(getAdminGlobalPref('version_available', 'email')).toBe(false);
const row = testDb.prepare("SELECT value FROM app_settings WHERE key = ?").get('admin_notif_pref_version_available_email') as { value: string } | undefined;
expect(row?.value).toBe('0');
});
it('NPREF-023 — disabling inapp for version_available stores per-user row in notification_channel_preferences', () => {
const { user } = createAdmin(testDb);
setAdminPreferences(user.id, { version_available: { inapp: false } });
const row = testDb.prepare(
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?'
).get(user.id, 'version_available', 'inapp') as { enabled: number } | undefined;
expect(row).toBeDefined();
expect(row!.enabled).toBe(0);
// Global app_settings should NOT have an inapp key
const globalRow = testDb.prepare("SELECT value FROM app_settings WHERE key = ?").get('admin_notif_pref_version_available_inapp');
expect(globalRow).toBeUndefined();
});
it('NPREF-024 — re-enabling inapp removes the disabled per-user row', () => {
const { user } = createAdmin(testDb);
// First disable
disableNotificationPref(testDb, user.id, 'version_available', 'inapp');
// Then re-enable via setAdminPreferences
setAdminPreferences(user.id, { version_available: { inapp: true } });
const row = testDb.prepare(
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?'
).get(user.id, 'version_available', 'inapp');
expect(row).toBeUndefined();
});
it('NPREF-025 — enabling email stores global pref as "1" in app_settings', () => {
const { user } = createAdmin(testDb);
// First disable, then re-enable
setAdminPreferences(user.id, { version_available: { email: false } });
setAdminPreferences(user.id, { version_available: { email: true } });
expect(getAdminGlobalPref('version_available', 'email')).toBe(true);
const row = testDb.prepare("SELECT value FROM app_settings WHERE key = ?").get('admin_notif_pref_version_available_email') as { value: string } | undefined;
expect(row?.value).toBe('1');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// isWebhookConfigured
// ─────────────────────────────────────────────────────────────────────────────
describe('isWebhookConfigured', () => {
it('NPREF-026 — returns false when webhook is not in active channels', () => {
// No notification_channels configured → defaults don't include webhook
expect(isWebhookConfigured()).toBe(false);
});
it('NPREF-027 — returns true when webhook is in active channels', () => {
setNotificationChannels(testDb, 'webhook');
expect(isWebhookConfigured()).toBe(true);
});
});
@@ -1,678 +0,0 @@
/**
* Unit tests for the unified notificationService.send().
* Covers NSVC-001 to NSVC-014.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/services/apiKeyCrypto', () => ({
decrypt_api_key: (v: string | null) => v,
maybe_encrypt_api_key: (v: string) => v,
encrypt_api_key: (v: string) => v,
}));
const { sendMailMock, fetchMock, broadcastMock } = vi.hoisted(() => ({
sendMailMock: vi.fn().mockResolvedValue({ accepted: ['test@test.com'] }),
fetchMock: vi.fn(),
broadcastMock: vi.fn(),
}));
vi.mock('nodemailer', () => ({
default: {
createTransport: vi.fn(() => ({
sendMail: sendMailMock,
verify: vi.fn().mockResolvedValue(true),
})),
},
}));
vi.stubGlobal('fetch', fetchMock);
vi.mock('../../../src/websocket', () => ({ broadcastToUser: broadcastMock }));
vi.mock('../../../src/utils/ssrfGuard', () => ({
checkSsrf: vi.fn(async () => ({ allowed: true, isPrivate: false, resolvedIp: '1.2.3.4' })),
createPinnedDispatcher: vi.fn(() => ({})),
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createAdmin, setAppSetting, setNotificationChannels, disableNotificationPref } from '../../helpers/factories';
import { send } from '../../../src/services/notificationService';
import { setPluginChannelSource, type ExternalChannel } from '../../../src/services/notifications/channelRegistry';
// ── Helpers ────────────────────────────────────────────────────────────────
function setSmtp(): void {
setAppSetting(testDb, 'smtp_host', 'mail.test.com');
setAppSetting(testDb, 'smtp_port', '587');
setAppSetting(testDb, 'smtp_from', 'trek@test.com');
}
function setUserWebhookUrl(userId: number, url = 'https://hooks.test.com/webhook'): void {
testDb.prepare("INSERT OR REPLACE INTO settings (user_id, key, value) VALUES (?, 'webhook_url', ?)").run(userId, url);
}
function setAdminWebhookUrl(url = 'https://hooks.test.com/admin-webhook'): void {
setAppSetting(testDb, 'admin_webhook_url', url);
}
function getInAppNotifications(recipientId: number) {
return testDb.prepare('SELECT * FROM notifications WHERE recipient_id = ? ORDER BY id').all(recipientId) as Array<{
id: number;
type: string;
scope: string;
navigate_target: string | null;
navigate_text_key: string | null;
title_key: string;
text_key: string;
}>;
}
function countAllNotifications(): number {
return (testDb.prepare('SELECT COUNT(*) as c FROM notifications').get() as { c: number }).c;
}
// ── Setup ──────────────────────────────────────────────────────────────────
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
sendMailMock.mockClear();
fetchMock.mockClear();
broadcastMock.mockClear();
fetchMock.mockResolvedValue({ ok: true, status: 200, text: async () => '' });
});
afterAll(() => {
testDb.close();
vi.unstubAllGlobals();
});
// ─────────────────────────────────────────────────────────────────────────────
// Multi-channel dispatch
// ─────────────────────────────────────────────────────────────────────────────
describe('send() — multi-channel dispatch', () => {
it('NSVC-001 — dispatches to all 3 channels (inapp, email, webhook) when all are active', async () => {
const { user } = createUser(testDb);
setSmtp();
setUserWebhookUrl(user.id);
setNotificationChannels(testDb, 'email,webhook');
testDb.prepare('UPDATE users SET email = ? WHERE id = ?').run('recipient@test.com', user.id);
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Paris', user.id)).lastInsertRowid as number;
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Paris', actor: 'Alice', invitee: 'Bob', tripId: String(tripId) } });
expect(sendMailMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(broadcastMock).toHaveBeenCalledTimes(1);
expect(countAllNotifications()).toBe(1);
});
it('NSVC-002 — skips email/webhook when no channels are active (in-app still fires)', async () => {
const { user } = createUser(testDb);
setSmtp();
setUserWebhookUrl(user.id);
setNotificationChannels(testDb, 'none');
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Rome', user.id)).lastInsertRowid as number;
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Rome', actor: 'Alice', invitee: 'Bob', tripId: String(tripId) } });
expect(sendMailMock).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
expect(broadcastMock).toHaveBeenCalledTimes(1);
expect(countAllNotifications()).toBe(1);
});
it('NSVC-003 — sends only email when only email channel is active', async () => {
const { user } = createUser(testDb);
setSmtp();
setNotificationChannels(testDb, 'email');
testDb.prepare('UPDATE users SET email = ? WHERE id = ?').run('recipient@test.com', user.id);
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Berlin', user.id)).lastInsertRowid as number;
await send({ event: 'booking_change', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Berlin', actor: 'Bob', booking: 'Hotel', type: 'hotel', tripId: String(tripId) } });
expect(sendMailMock).toHaveBeenCalledTimes(1);
expect(fetchMock).not.toHaveBeenCalled();
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Per-user preference filtering
// ─────────────────────────────────────────────────────────────────────────────
describe('send() — per-user preference filtering', () => {
it('NSVC-004 — skips email for a user who disabled trip_invite on email channel', async () => {
const { user } = createUser(testDb);
setSmtp();
setNotificationChannels(testDb, 'email');
testDb.prepare('UPDATE users SET email = ? WHERE id = ?').run('recipient@test.com', user.id);
disableNotificationPref(testDb, user.id, 'trip_invite', 'email');
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Paris', user.id)).lastInsertRowid as number;
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Paris', actor: 'Alice', invitee: 'Bob', tripId: String(tripId) } });
expect(sendMailMock).not.toHaveBeenCalled();
// in-app still fires
expect(broadcastMock).toHaveBeenCalledTimes(1);
});
it('NSVC-005 — skips in-app for a user who disabled the event on inapp channel', async () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'none');
disableNotificationPref(testDb, user.id, 'collab_message', 'inapp');
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Trip', user.id)).lastInsertRowid as number;
await send({ event: 'collab_message', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Trip', actor: 'Alice', tripId: String(tripId) } });
expect(broadcastMock).not.toHaveBeenCalled();
expect(countAllNotifications()).toBe(0);
});
it('NSVC-006 — still sends webhook when user has email disabled but webhook enabled', async () => {
const { user } = createUser(testDb);
setSmtp();
setUserWebhookUrl(user.id);
setNotificationChannels(testDb, 'email,webhook');
testDb.prepare('UPDATE users SET email = ? WHERE id = ?').run('recipient@test.com', user.id);
disableNotificationPref(testDb, user.id, 'trip_invite', 'email');
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Paris', user.id)).lastInsertRowid as number;
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Paris', actor: 'Alice', invitee: 'Bob', tripId: String(tripId) } });
expect(sendMailMock).not.toHaveBeenCalled();
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Recipient resolution
// ─────────────────────────────────────────────────────────────────────────────
describe('send() — recipient resolution', () => {
it('NSVC-007 — trip scope sends to owner + members, excludes actorId', async () => {
const { user: owner } = createUser(testDb);
const { user: member1 } = createUser(testDb);
const { user: member2 } = createUser(testDb);
const { user: actor } = createUser(testDb);
setNotificationChannels(testDb, 'none');
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Trip', owner.id)).lastInsertRowid as number;
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, member1.id);
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, member2.id);
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, actor.id);
await send({ event: 'booking_change', actorId: actor.id, scope: 'trip', targetId: tripId, params: { trip: 'Trip', actor: 'Actor', booking: 'Hotel', type: 'hotel', tripId: String(tripId) } });
// Owner, member1, member2 get it; actor is excluded
expect(countAllNotifications()).toBe(3);
const recipients = (testDb.prepare('SELECT recipient_id FROM notifications ORDER BY recipient_id').all() as { recipient_id: number }[]).map(r => r.recipient_id);
expect(recipients).toContain(owner.id);
expect(recipients).toContain(member1.id);
expect(recipients).toContain(member2.id);
expect(recipients).not.toContain(actor.id);
});
it('NSVC-007b — guests are never notified, on trip or user scope (#1362)', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
setNotificationChannels(testDb, 'none');
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Trip', owner.id)).lastInsertRowid as number;
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, member.id);
// A guest joined into the trip — assignable, but has no inbox.
const guestId = (testDb.prepare("INSERT INTO users (username, email, password_hash, role, is_guest) VALUES ('Guest', 'guest-x@guests.invalid', '', 'user', 1)").run()).lastInsertRowid as number;
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, guestId);
await send({ event: 'booking_change', actorId: owner.id, scope: 'trip', targetId: tripId, params: { trip: 'Trip', actor: 'Owner', booking: 'Hotel', type: 'hotel', tripId: String(tripId) } });
let recipients = (testDb.prepare('SELECT recipient_id FROM notifications').all() as { recipient_id: number }[]).map(r => r.recipient_id);
expect(recipients).toContain(member.id);
expect(recipients).not.toContain(guestId);
// Even a direct user-scope notification (e.g. a todo assigned to the guest) is dropped.
await send({ event: 'vacay_invite', actorId: owner.id, scope: 'user', targetId: guestId, params: { actor: 'owner@test.com', planId: '1' } });
recipients = (testDb.prepare('SELECT recipient_id FROM notifications').all() as { recipient_id: number }[]).map(r => r.recipient_id);
expect(recipients).not.toContain(guestId);
});
it('NSVC-008 — user scope sends to exactly one user', async () => {
const { user: target } = createUser(testDb);
const { user: other } = createUser(testDb);
setNotificationChannels(testDb, 'none');
await send({ event: 'vacay_invite', actorId: other.id, scope: 'user', targetId: target.id, params: { actor: 'other@test.com', planId: '42' } });
expect(countAllNotifications()).toBe(1);
const notif = testDb.prepare('SELECT recipient_id FROM notifications LIMIT 1').get() as { recipient_id: number };
expect(notif.recipient_id).toBe(target.id);
});
it('NSVC-009 — admin scope sends to all admins (not regular users)', async () => {
const { user: admin1 } = createAdmin(testDb);
const { user: admin2 } = createAdmin(testDb);
createUser(testDb); // regular user — should NOT receive
setNotificationChannels(testDb, 'none');
await send({ event: 'version_available', actorId: null, scope: 'admin', targetId: 0, params: { version: '2.0.0' } });
expect(countAllNotifications()).toBe(2);
const recipients = (testDb.prepare('SELECT recipient_id FROM notifications ORDER BY recipient_id').all() as { recipient_id: number }[]).map(r => r.recipient_id);
expect(recipients).toContain(admin1.id);
expect(recipients).toContain(admin2.id);
});
it('NSVC-010 — admin scope fires admin webhook URL when set', async () => {
createAdmin(testDb);
setAdminWebhookUrl();
setNotificationChannels(testDb, 'none');
await send({ event: 'version_available', actorId: null, scope: 'admin', targetId: 0, params: { version: '2.0.0' } });
// Wait for fire-and-forget admin webhook
await new Promise(r => setTimeout(r, 10));
expect(fetchMock).toHaveBeenCalledTimes(1);
const callUrl = fetchMock.mock.calls[0][0];
expect(callUrl).toBe('https://hooks.test.com/admin-webhook');
});
it('NSVC-011 — does nothing when there are no recipients', async () => {
// Trip with no members, sending as the trip owner (actor excluded from trip scope)
const { user: owner } = createUser(testDb);
setNotificationChannels(testDb, 'none');
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Solo', owner.id)).lastInsertRowid as number;
await send({ event: 'booking_change', actorId: owner.id, scope: 'trip', targetId: tripId, params: { trip: 'Solo', actor: 'owner@test.com', booking: 'Hotel', type: 'hotel', tripId: String(tripId) } });
expect(countAllNotifications()).toBe(0);
expect(broadcastMock).not.toHaveBeenCalled();
});
});
// ─────────────────────────────────────────────────────────────────────────────
// In-app notification content
// ─────────────────────────────────────────────────────────────────────────────
describe('send() — in-app notification content', () => {
it('NSVC-012 — creates navigate in-app notification with correct title/text/navigate keys', async () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'none');
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Paris', actor: 'Alice', invitee: 'Bob', tripId: '42' } });
const notifs = getInAppNotifications(user.id);
expect(notifs.length).toBe(1);
expect(notifs[0].type).toBe('navigate');
expect(notifs[0].title_key).toBe('notif.trip_invite.title');
expect(notifs[0].text_key).toBe('notif.trip_invite.text');
expect(notifs[0].navigate_text_key).toBe('notif.action.view_trip');
expect(notifs[0].navigate_target).toBe('/trips/42');
});
it('NSVC-013 — creates simple in-app notification when no navigate target is available', async () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'none');
// vacay_invite without planId → no navigate target → simple type
await send({ event: 'vacay_invite', actorId: null, scope: 'user', targetId: user.id, params: { actor: 'Alice' } });
const notifs = getInAppNotifications(user.id);
expect(notifs.length).toBe(1);
expect(notifs[0].type).toBe('simple');
expect(notifs[0].navigate_target).toBeNull();
});
it('NSVC-014 — navigate_target uses /admin for version_available event', async () => {
const { user: admin } = createAdmin(testDb);
setNotificationChannels(testDb, 'none');
await send({ event: 'version_available', actorId: null, scope: 'admin', targetId: 0, params: { version: '9.9.9' } });
const notifs = getInAppNotifications(admin.id);
expect(notifs.length).toBe(1);
expect(notifs[0].navigate_target).toBe('/admin');
expect(notifs[0].title_key).toBe('notif.version_available.title');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Email/webhook link generation
// ─────────────────────────────────────────────────────────────────────────────
describe('send() — email/webhook links', () => {
it('NSVC-015 — email subject and body are localized per recipient language', async () => {
const { user } = createUser(testDb);
setSmtp();
setNotificationChannels(testDb, 'email');
testDb.prepare('UPDATE users SET email = ? WHERE id = ?').run('recipient@test.com', user.id);
// Set user language to French
testDb.prepare("INSERT OR REPLACE INTO settings (user_id, key, value) VALUES (?, 'language', 'fr')").run(user.id);
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Paris', user.id)).lastInsertRowid as number;
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Paris', actor: 'Alice', invitee: 'Bob', tripId: String(tripId) } });
expect(sendMailMock).toHaveBeenCalledTimes(1);
const mailArgs = sendMailMock.mock.calls[0][0];
// French title for trip_invite should contain "Invitation"
expect(mailArgs.subject).toContain('Invitation');
});
it('NSVC-016 — webhook payload includes link field when navigate target is available', async () => {
const { user } = createUser(testDb);
setUserWebhookUrl(user.id, 'https://hooks.test.com/generic-webhook');
setNotificationChannels(testDb, 'webhook');
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Paris', actor: 'Alice', invitee: 'Bob', tripId: '55' } });
expect(fetchMock).toHaveBeenCalledTimes(1);
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
// Generic webhook — link should contain /trips/55
expect(body.link).toContain('/trips/55');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Boolean in-app type
// ─────────────────────────────────────────────────────────────────────────────
describe('send() — boolean in-app type', () => {
it('NSVC-017 — creates boolean in-app notification with callbacks when inApp.type override is boolean', async () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'none');
await send({
event: 'trip_invite',
actorId: null,
scope: 'user',
targetId: user.id,
params: { trip: 'Paris', actor: 'Alice', invitee: 'Bob', tripId: '1' },
inApp: {
type: 'boolean',
positiveTextKey: 'notif.action.accept',
negativeTextKey: 'notif.action.decline',
positiveCallback: { action: 'test_approve', payload: { tripId: 1 } },
negativeCallback: { action: 'test_deny', payload: { tripId: 1 } },
},
});
const notifs = getInAppNotifications(user.id);
expect(notifs.length).toBe(1);
const row = notifs[0] as any;
expect(row.type).toBe('boolean');
expect(row.positive_callback).toContain('test_approve');
expect(row.negative_callback).toContain('test_deny');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Channel failure resilience
// ─────────────────────────────────────────────────────────────────────────────
describe('send() — channel failure resilience', () => {
it('NSVC-018 — email failure does not prevent in-app or webhook delivery', async () => {
const { user } = createUser(testDb);
setSmtp();
setUserWebhookUrl(user.id);
setNotificationChannels(testDb, 'email,webhook');
testDb.prepare('UPDATE users SET email = ? WHERE id = ?').run('recipient@test.com', user.id);
// Make email throw
sendMailMock.mockRejectedValueOnce(new Error('SMTP connection refused'));
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Trip', user.id)).lastInsertRowid as number;
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Trip', actor: 'Alice', invitee: 'Bob', tripId: String(tripId) } });
// In-app and webhook still fire despite email failure
expect(broadcastMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(countAllNotifications()).toBe(1);
});
it('NSVC-019 — webhook failure does not prevent in-app or email delivery', async () => {
const { user } = createUser(testDb);
setSmtp();
setUserWebhookUrl(user.id);
setNotificationChannels(testDb, 'email,webhook');
testDb.prepare('UPDATE users SET email = ? WHERE id = ?').run('recipient@test.com', user.id);
// Make webhook throw
fetchMock.mockRejectedValueOnce(new Error('Network error'));
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Trip', user.id)).lastInsertRowid as number;
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Trip', actor: 'Alice', invitee: 'Bob', tripId: String(tripId) } });
// In-app and email still fire despite webhook failure
expect(broadcastMock).toHaveBeenCalledTimes(1);
expect(sendMailMock).toHaveBeenCalledTimes(1);
expect(countAllNotifications()).toBe(1);
});
});
// ── Ntfy dispatch ─────────────────────────────────────────────────────────────
function setUserNtfyTopic(userId: number, topic = 'my-trek-topic'): void {
testDb.prepare("INSERT OR REPLACE INTO settings (user_id, key, value) VALUES (?, 'ntfy_topic', ?)").run(userId, topic);
}
function setAdminNtfyTopic(topic = 'trek-admin-alerts'): void {
setAppSetting(testDb, 'admin_ntfy_topic', topic);
}
describe('send() — ntfy channel dispatch', () => {
beforeEach(() => {
fetchMock.mockResolvedValue({ ok: true, text: async () => '' });
});
it('NTFY-SVCB-001 — ntfy fires when channel active and user has topic configured', async () => {
const { user } = createUser(testDb);
setUserNtfyTopic(user.id);
setNotificationChannels(testDb, 'ntfy');
const tripId = (testDb.prepare('INSERT INTO trips (title, user_id) VALUES (?, ?)').run('Tokyo', user.id)).lastInsertRowid as number;
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Tokyo', actor: 'Alice', invitee: 'Bob', tripId: String(tripId) } });
const ntfyCalls = fetchMock.mock.calls.filter(([url]: [string]) => url.includes('ntfy.sh'));
expect(ntfyCalls.length).toBeGreaterThan(0);
// Header-based API: metadata in headers, body = plain text
expect(ntfyCalls[0][1].headers['Priority']).toBe('4'); // trip_invite = high priority
expect(ntfyCalls[0][1].headers['Tags']).toContain('loudspeaker');
});
it('NTFY-SVCB-002 — ntfy skips when channel not in active channels', async () => {
const { user } = createUser(testDb);
setUserNtfyTopic(user.id);
setNotificationChannels(testDb, 'none');
fetchMock.mockClear();
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Paris', actor: 'Alice', invitee: 'Bob', tripId: '1' } });
const ntfyCalls = fetchMock.mock.calls.filter(([url]: [string]) => url.includes('ntfy.sh'));
expect(ntfyCalls.length).toBe(0);
});
it('NTFY-SVCB-003 — ntfy skips when user has no topic configured', async () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'ntfy');
// No ntfy_topic set — resolveNtfyUrl requires a user topic, so it returns null
fetchMock.mockClear();
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Rome', actor: 'Alice', invitee: 'Bob', tripId: '1' } });
const ntfyCalls = fetchMock.mock.calls.filter(([url]: [string]) => url.includes('ntfy.sh'));
expect(ntfyCalls.length).toBe(0);
});
it('NTFY-SVCB-005 — ntfy does not fall back to admin topic when user has no topic (#1608)', async () => {
const { user } = createUser(testDb);
setAdminNtfyTopic();
setNotificationChannels(testDb, 'ntfy');
fetchMock.mockClear();
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Oslo', actor: 'Alice', invitee: 'Bob', tripId: '1' } });
const ntfyCalls = fetchMock.mock.calls.filter(([url]: [string]) => url.includes('ntfy.sh'));
expect(ntfyCalls.length).toBe(0);
});
it('NTFY-SVCB-004 — admin-scoped version_available fires admin ntfy topic', async () => {
createAdmin(testDb);
setAdminNtfyTopic();
setNotificationChannels(testDb, 'none');
fetchMock.mockClear();
await send({ event: 'version_available', actorId: null, scope: 'admin', targetId: 0, params: { version: '3.0.0' } });
const ntfyCalls = fetchMock.mock.calls.filter(([url]: [string]) => url.includes('ntfy.sh'));
expect(ntfyCalls.length).toBeGreaterThan(0);
expect(ntfyCalls[0][1].headers['Priority']).toBe('4'); // version_available = high priority
expect(ntfyCalls[0][1].headers['Tags']).toContain('package');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Plugin notification channels (hook:notification-channel)
// ─────────────────────────────────────────────────────────────────────────────
describe('send() — plugin notification channels', () => {
const sendSpy = vi.fn();
function installPluginChannel(over: Partial<ExternalChannel> = {}): void {
sendSpy.mockClear();
sendSpy.mockResolvedValue(undefined);
setPluginChannelSource(() => [
{
id: 'plugin:gotify',
source: 'plugin',
label: 'Gotify',
supportsEvent: (e: string) => e !== 'version_available' && e !== 'synology_session_cleared',
isConfiguredFor: () => true,
sendToUser: sendSpy,
...over,
} as ExternalChannel,
]);
}
afterEach(() => setPluginChannelSource(null));
it('NSVC-PLUG-001 — delivers to a plugin channel the admin enabled', async () => {
const { user } = createUser(testDb);
installPluginChannel();
setNotificationChannels(testDb, 'plugin:gotify');
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Rome', actor: 'Alice', invitee: 'Bob', tripId: '1' } });
expect(sendSpy).toHaveBeenCalledTimes(1);
const [recipientId, msg] = sendSpy.mock.calls[0];
expect(recipientId).toBe(user.id);
// The host renders the text — a channel plugin never touches i18n.
expect(msg.event).toBe('trip_invite');
expect(msg.title).toBeTruthy();
expect(msg.body).toContain('Rome');
});
it('NSVC-PLUG-002 — delivers with NOTHING in notification_channels: enabling the plugin IS the opt-in', async () => {
const { user } = createUser(testDb);
installPluginChannel();
setNotificationChannels(testDb, 'none');
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Rome', actor: 'Alice', invitee: 'Bob', tripId: '1' } });
// A built-in always exists in the code, so it needs an explicit switch. A plugin
// channel only exists because an admin installed and enabled that plugin — and
// nothing can write a `plugin:` id into this CSV anyway, so requiring a second
// opt-in meant the channel could never be turned on at all.
expect(sendSpy).toHaveBeenCalledTimes(1);
});
it('NSVC-PLUG-003 — skipped when the user opted out of this event on it', async () => {
const { user } = createUser(testDb);
installPluginChannel();
setNotificationChannels(testDb, 'plugin:gotify');
disableNotificationPref(testDb, user.id, 'trip_invite', 'plugin:gotify');
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Rome', actor: 'Alice', invitee: 'Bob', tripId: '1' } });
expect(sendSpy).not.toHaveBeenCalled();
});
it('NSVC-PLUG-004 — skipped when the user has not set their credentials', async () => {
const { user } = createUser(testDb);
installPluginChannel({ isConfiguredFor: () => false });
setNotificationChannels(testDb, 'plugin:gotify');
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Rome', actor: 'Alice', invitee: 'Bob', tripId: '1' } });
expect(sendSpy).not.toHaveBeenCalled();
});
it('NSVC-PLUG-005 — a throwing plugin channel does not stop in-app or email delivery', async () => {
const { user } = createUser(testDb);
installPluginChannel({ sendToUser: vi.fn().mockRejectedValue(new Error('gotify is down')) });
setSmtp();
setNotificationChannels(testDb, 'email,plugin:gotify');
sendMailMock.mockClear();
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Rome', actor: 'Alice', invitee: 'Bob', tripId: '1' } });
expect(sendMailMock).toHaveBeenCalledTimes(1);
expect(getInAppNotifications(user.id).length).toBe(1);
});
it('NSVC-PLUG-006 — never receives an admin-scoped event', async () => {
createAdmin(testDb);
// Even if a (malicious) channel claims to support it, ADMIN_SCOPED_EVENTS is
// gated host-side: only a channel that bypasses the toggle (email) delivers those.
installPluginChannel({ supportsEvent: () => true });
setNotificationChannels(testDb, 'plugin:gotify');
await send({ event: 'version_available', actorId: null, scope: 'admin', targetId: 0, params: { version: '3.0.0' } });
expect(sendSpy).not.toHaveBeenCalled();
});
it('NSVC-PLUG-007 — a channel that narrows its events only gets those', async () => {
const { user } = createUser(testDb);
installPluginChannel({ supportsEvent: (e: string) => e === 'booking_change' });
setNotificationChannels(testDb, 'plugin:gotify');
await send({ event: 'trip_invite', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Rome', actor: 'Alice', invitee: 'Bob', tripId: '1' } });
expect(sendSpy).not.toHaveBeenCalled();
await send({ event: 'booking_change', actorId: null, scope: 'user', targetId: user.id, params: { trip: 'Rome', actor: 'Alice', tripId: '1' } });
expect(sendSpy).toHaveBeenCalledTimes(1);
});
});
@@ -1,500 +0,0 @@
import { describe, it, expect, vi, afterEach, afterAll, beforeEach } from 'vitest';
vi.mock('../../../src/db/database', () => ({
db: { prepare: () => ({ get: vi.fn(() => undefined), all: vi.fn(() => []) }) },
}));
vi.mock('../../../src/services/apiKeyCrypto', () => ({
decrypt_api_key: vi.fn((v) => v),
maybe_encrypt_api_key: vi.fn((v) => v),
}));
vi.mock('../../../src/services/auditLog', () => ({
logInfo: vi.fn(),
logDebug: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
writeAudit: vi.fn(),
getClientIp: vi.fn(),
}));
vi.mock('nodemailer', () => ({ default: { createTransport: vi.fn(() => ({ sendMail: vi.fn() })) } }));
vi.stubGlobal('fetch', vi.fn());
// ssrfGuard is mocked per-test in the SSRF describe block; default passes all
vi.mock('../../../src/utils/ssrfGuard', () => ({
checkSsrf: vi.fn(async () => ({ allowed: true, isPrivate: false, resolvedIp: '1.2.3.4' })),
createPinnedDispatcher: vi.fn(() => ({})),
}));
import { getEventText, buildEmailHtml, buildWebhookBody, sendWebhook, sendNtfy, resolveNtfyUrl, resolveAdminNtfyUrl, type NtfyConfig } from '../../../src/services/notifications';
import { checkSsrf } from '../../../src/utils/ssrfGuard';
import { logError } from '../../../src/services/auditLog';
afterEach(() => {
vi.unstubAllEnvs();
});
// ── getEventText ─────────────────────────────────────────────────────────────
describe('getEventText', () => {
const params = {
trip: 'Tokyo Adventure',
actor: 'Alice',
invitee: 'Bob',
booking: 'Hotel Sakura',
type: 'hotel',
count: '5',
preview: 'See you there!',
category: 'Clothing',
};
it('returns English title and body for lang=en', () => {
const result = getEventText('en', 'trip_invite', params);
expect(result.title).toBeTruthy();
expect(result.body).toBeTruthy();
expect(result.title).toContain('Tokyo Adventure');
expect(result.body).toContain('Alice');
});
it('returns German text for lang=de', () => {
const result = getEventText('de', 'trip_invite', params);
expect(result.title).toContain('Tokyo Adventure');
// German version uses "Einladung"
expect(result.title).toContain('Einladung');
});
it('falls back to English for unknown language code', () => {
const en = getEventText('en', 'trip_invite', params);
const unknown = getEventText('xx', 'trip_invite', params);
expect(unknown.title).toBe(en.title);
expect(unknown.body).toBe(en.body);
});
it('interpolates params into trip_invite correctly', () => {
const result = getEventText('en', 'trip_invite', params);
expect(result.title).toContain('Tokyo Adventure');
expect(result.body).toContain('Alice');
expect(result.body).toContain('Bob');
});
it('all 7 event types produce non-empty title and body in English', () => {
const events = ['trip_invite', 'booking_change', 'trip_reminder', 'vacay_invite', 'photos_shared', 'collab_message', 'packing_tagged'] as const;
for (const event of events) {
const result = getEventText('en', event, params);
expect(result.title, `title for ${event}`).toBeTruthy();
expect(result.body, `body for ${event}`).toBeTruthy();
}
});
it('all 7 event types produce non-empty title and body in German', () => {
const events = ['trip_invite', 'booking_change', 'trip_reminder', 'vacay_invite', 'photos_shared', 'collab_message', 'packing_tagged'] as const;
for (const event of events) {
const result = getEventText('de', event, params);
expect(result.title, `de title for ${event}`).toBeTruthy();
expect(result.body, `de body for ${event}`).toBeTruthy();
}
});
});
// ── buildWebhookBody ─────────────────────────────────────────────────────────
describe('buildWebhookBody', () => {
const payload = {
event: 'trip_invite',
title: 'Trip Invite',
body: 'Alice invited you',
tripName: 'Tokyo Adventure',
};
it('Discord URL produces embeds array format', () => {
const body = JSON.parse(buildWebhookBody('https://discord.com/api/webhooks/123/abc', payload));
expect(body).toHaveProperty('embeds');
expect(Array.isArray(body.embeds)).toBe(true);
expect(body.embeds[0]).toHaveProperty('title');
expect(body.embeds[0]).toHaveProperty('description', payload.body);
expect(body.embeds[0]).toHaveProperty('color');
expect(body.embeds[0]).toHaveProperty('footer');
expect(body.embeds[0]).toHaveProperty('timestamp');
});
it('Discord embed title is prefixed with compass emoji', () => {
const body = JSON.parse(buildWebhookBody('https://discord.com/api/webhooks/123/abc', payload));
expect(body.embeds[0].title).toContain('📍');
expect(body.embeds[0].title).toContain(payload.title);
});
it('Discord embed footer contains trip name when provided', () => {
const body = JSON.parse(buildWebhookBody('https://discord.com/api/webhooks/123/abc', payload));
expect(body.embeds[0].footer.text).toContain('Tokyo Adventure');
});
it('Discord embed footer defaults to TREK when no trip name', () => {
const noTrip = { ...payload, tripName: undefined };
const body = JSON.parse(buildWebhookBody('https://discord.com/api/webhooks/123/abc', noTrip));
expect(body.embeds[0].footer.text).toBe('TREK');
});
it('discordapp.com URL is also detected as Discord', () => {
const body = JSON.parse(buildWebhookBody('https://discordapp.com/api/webhooks/123/abc', payload));
expect(body).toHaveProperty('embeds');
});
it('Slack URL produces text field format', () => {
const body = JSON.parse(buildWebhookBody('https://hooks.slack.com/services/X/Y/Z', payload));
expect(body).toHaveProperty('text');
expect(body.text).toContain(payload.title);
expect(body.text).toContain(payload.body);
});
it('Slack text includes italic trip name when provided', () => {
const body = JSON.parse(buildWebhookBody('https://hooks.slack.com/services/X/Y/Z', payload));
expect(body.text).toContain('Tokyo Adventure');
});
it('Slack text omits trip name when not provided', () => {
const noTrip = { ...payload, tripName: undefined };
const body = JSON.parse(buildWebhookBody('https://hooks.slack.com/services/X/Y/Z', noTrip));
// Should not contain the trip name string
expect(body.text).not.toContain('Tokyo Adventure');
});
it('generic URL produces plain JSON with original fields plus timestamp and source', () => {
const body = JSON.parse(buildWebhookBody('https://mywebhook.example.com/hook', payload));
expect(body).toHaveProperty('event', payload.event);
expect(body).toHaveProperty('title', payload.title);
expect(body).toHaveProperty('body', payload.body);
expect(body).toHaveProperty('timestamp');
expect(body).toHaveProperty('source', 'TREK');
});
});
// ── buildEmailHtml ────────────────────────────────────────────────────────────
describe('buildEmailHtml', () => {
it('returns a string containing <!DOCTYPE html>', () => {
const html = buildEmailHtml('Test Subject', 'Test body text', 'en');
expect(html).toContain('<!DOCTYPE html>');
});
it('contains the subject text', () => {
const html = buildEmailHtml('My Email Subject', 'Some body', 'en');
expect(html).toContain('My Email Subject');
});
it('contains the body text', () => {
const html = buildEmailHtml('Subject', 'Hello world, this is the body!', 'en');
expect(html).toContain('Hello world, this is the body!');
});
it('uses English i18n strings for lang=en', () => {
const html = buildEmailHtml('Subject', 'Body', 'en');
expect(html).toContain('notifications enabled in TREK');
});
it('uses German i18n strings for lang=de', () => {
const html = buildEmailHtml('Subject', 'Body', 'de');
expect(html).toContain('TREK aktiviert');
});
it('falls back to English i18n for unknown language', () => {
const en = buildEmailHtml('Subject', 'Body', 'en');
const unknown = buildEmailHtml('Subject', 'Body', 'xx');
// Both should have the same footer text
expect(unknown).toContain('notifications enabled in TREK');
});
});
// ── SEC: XSS escaping in buildEmailHtml ──────────────────────────────────────
describe('buildEmailHtml XSS prevention (SEC-016)', () => {
it('escapes HTML special characters in subject', () => {
const html = buildEmailHtml('<script>alert(1)</script>', 'Body', 'en');
expect(html).not.toContain('<script>');
expect(html).toContain('&lt;script&gt;');
});
it('escapes HTML special characters in body', () => {
const html = buildEmailHtml('Subject', '<img src=x onerror=alert(1)>', 'en');
expect(html).toContain('&lt;img');
expect(html).not.toContain('<img src=x');
});
it('escapes double quotes in subject to prevent attribute injection', () => {
const html = buildEmailHtml('He said "hello"', 'Body', 'en');
expect(html).toContain('&quot;');
expect(html).not.toContain('"hello"');
});
it('escapes ampersands in body', () => {
const html = buildEmailHtml('Subject', 'a & b', 'en');
expect(html).toContain('&amp;');
expect(html).not.toMatch(/>[^<]*a & b[^<]*</);
});
it('escapes user-controlled actor and preview in collab_message body', () => {
const { body } = getEventText('en', 'collab_message', {
trip: 'MyTrip',
actor: '<evil>',
preview: '<script>xss()</script>',
});
const html = buildEmailHtml('Subject', body, 'en');
expect(html).not.toContain('<evil>');
expect(html).not.toContain('<script>');
expect(html).toContain('&lt;evil&gt;');
expect(html).toContain('&lt;script&gt;');
});
});
// ── SEC: SSRF protection in sendWebhook ──────────────────────────────────────
describe('sendWebhook SSRF protection (SEC-017)', () => {
const payload = { event: 'test', title: 'T', body: 'B' };
beforeEach(() => {
vi.mocked(logError).mockClear();
});
it('allows a public URL and calls fetch', async () => {
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValueOnce({ ok: true, text: async () => '' } as never);
vi.mocked(checkSsrf).mockResolvedValueOnce({ allowed: true, isPrivate: false, resolvedIp: '1.2.3.4' });
const result = await sendWebhook('https://example.com/hook', payload);
expect(result).toBe(true);
expect(mockFetch).toHaveBeenCalled();
});
it('blocks loopback address and returns false', async () => {
vi.mocked(checkSsrf).mockResolvedValueOnce({
allowed: false, isPrivate: true, resolvedIp: '127.0.0.1',
error: 'Requests to loopback and link-local addresses are not allowed',
});
const result = await sendWebhook('http://localhost/secret', payload);
expect(result).toBe(false);
expect(vi.mocked(logError)).toHaveBeenCalledWith(expect.stringContaining('SSRF'));
});
it('blocks cloud metadata endpoint (169.254.169.254) and returns false', async () => {
vi.mocked(checkSsrf).mockResolvedValueOnce({
allowed: false, isPrivate: true, resolvedIp: '169.254.169.254',
error: 'Requests to loopback and link-local addresses are not allowed',
});
const result = await sendWebhook('http://169.254.169.254/latest/meta-data', payload);
expect(result).toBe(false);
expect(vi.mocked(logError)).toHaveBeenCalledWith(expect.stringContaining('SSRF'));
});
it('blocks private network addresses and returns false', async () => {
vi.mocked(checkSsrf).mockResolvedValueOnce({
allowed: false, isPrivate: true, resolvedIp: '192.168.1.1',
error: 'Requests to private/internal network addresses are not allowed',
});
const result = await sendWebhook('http://192.168.1.1/hook', payload);
expect(result).toBe(false);
expect(vi.mocked(logError)).toHaveBeenCalledWith(expect.stringContaining('SSRF'));
});
it('blocks non-HTTP protocols', async () => {
vi.mocked(checkSsrf).mockResolvedValueOnce({
allowed: false, isPrivate: false,
error: 'Only HTTP and HTTPS URLs are allowed',
});
const result = await sendWebhook('file:///etc/passwd', payload);
expect(result).toBe(false);
});
it('does not call fetch when SSRF check blocks the URL', async () => {
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockClear();
vi.mocked(checkSsrf).mockResolvedValueOnce({
allowed: false, isPrivate: true, resolvedIp: '127.0.0.1',
error: 'blocked',
});
await sendWebhook('http://localhost/secret', payload);
expect(mockFetch).not.toHaveBeenCalled();
});
});
afterAll(() => vi.unstubAllGlobals());
// ── resolveNtfyUrl ────────────────────────────────────────────────────────────
describe('resolveNtfyUrl', () => {
const adminCfg: NtfyConfig = { server: 'https://ntfy.sh', topic: 'admin-topic', token: null };
it('returns null when no user config, even when admin topic is set (#1608)', () => {
expect(resolveNtfyUrl(adminCfg, null)).toBeNull();
});
it('returns null when user config has no topic, even when admin topic is set (#1608)', () => {
const user: NtfyConfig = { server: 'https://ntfy.example.com', topic: null, token: null };
expect(resolveNtfyUrl(adminCfg, user)).toBeNull();
});
it('uses user topic with admin server fallback', () => {
const user: NtfyConfig = { server: null, topic: 'my-topic', token: null };
expect(resolveNtfyUrl(adminCfg, user)).toBe('https://ntfy.sh/my-topic');
});
it('uses user server override', () => {
const user: NtfyConfig = { server: 'https://ntfy.example.com', topic: 'my-topic', token: null };
expect(resolveNtfyUrl(adminCfg, user)).toBe('https://ntfy.example.com/my-topic');
});
it('strips trailing slash from server', () => {
const user: NtfyConfig = { server: 'https://ntfy.example.com/', topic: 'alerts', token: null };
expect(resolveNtfyUrl(adminCfg, user)).toBe('https://ntfy.example.com/alerts');
});
it('falls back to https://ntfy.sh when no server configured', () => {
const noServer: NtfyConfig = { server: null, topic: null, token: null };
const user: NtfyConfig = { server: null, topic: 'my-topic', token: null };
expect(resolveNtfyUrl(noServer, user)).toBe('https://ntfy.sh/my-topic');
});
});
describe('resolveAdminNtfyUrl', () => {
it('builds URL from admin topic and server', () => {
expect(resolveAdminNtfyUrl({ server: 'https://ntfy.example.com', topic: 'admin-topic', token: null })).toBe('https://ntfy.example.com/admin-topic');
});
it('returns null when no admin topic', () => {
expect(resolveAdminNtfyUrl({ server: 'https://ntfy.sh', topic: null, token: null })).toBeNull();
});
it('falls back to https://ntfy.sh when no server configured', () => {
expect(resolveAdminNtfyUrl({ server: null, topic: 'alerts', token: null })).toBe('https://ntfy.sh/alerts');
});
it('strips trailing slash from server', () => {
expect(resolveAdminNtfyUrl({ server: 'https://ntfy.sh/', topic: 'alerts', token: null })).toBe('https://ntfy.sh/alerts');
});
});
// ── sendNtfy ─────────────────────────────────────────────────────────────────
describe('sendNtfy', () => {
const ntfyUrl = 'https://ntfy.sh/trek-test';
const payload = { event: 'trip_invite', title: 'Test Title', body: 'Test body' };
beforeEach(() => {
vi.mocked(logError).mockClear();
(globalThis.fetch as ReturnType<typeof vi.fn>).mockClear();
vi.mocked(checkSsrf).mockResolvedValue({ allowed: true, isPrivate: false, resolvedIp: '1.2.3.4' });
});
it('NTFY-001 — sends POST to topic URL with plain text body and metadata in headers', async () => {
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValueOnce({ ok: true, text: async () => '' } as never);
const result = await sendNtfy(ntfyUrl, null, payload);
expect(result).toBe(true);
expect(mockFetch).toHaveBeenCalledOnce();
const [calledUrl, calledOpts] = mockFetch.mock.calls[0];
expect(calledUrl).toBe(ntfyUrl);
// Body should be plain text, not JSON
expect(calledOpts.body).toBe('Test body');
// Title, Priority, Tags go in headers
expect(calledOpts.headers['Title']).toBe('Test Title');
expect(calledOpts.headers['Priority']).toBe('4'); // trip_invite maps to priority 4
expect(calledOpts.headers['Tags']).toContain('loudspeaker');
});
it('NTFY-002 — attaches Bearer token when token provided', async () => {
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValueOnce({ ok: true, text: async () => '' } as never);
await sendNtfy(ntfyUrl, 'my-secret-token', payload);
const [, calledOpts] = mockFetch.mock.calls[0];
expect(calledOpts.headers['Authorization']).toBe('Bearer my-secret-token');
});
it('NTFY-003 — no Authorization header when token is null', async () => {
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValueOnce({ ok: true, text: async () => '' } as never);
await sendNtfy(ntfyUrl, null, payload);
const [, calledOpts] = mockFetch.mock.calls[0];
expect(calledOpts.headers['Authorization']).toBeUndefined();
});
it('NTFY-004 — includes Click header when link is provided', async () => {
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValueOnce({ ok: true, text: async () => '' } as never);
await sendNtfy(ntfyUrl, null, { ...payload, link: 'https://trek.example.com/trips/5' });
const [, calledOpts] = mockFetch.mock.calls[0];
expect(calledOpts.headers['Click']).toBe('https://trek.example.com/trips/5');
});
it('NTFY-005 — SSRF guard blocks private URL and returns false', async () => {
vi.mocked(checkSsrf).mockResolvedValueOnce({
allowed: false, isPrivate: true, resolvedIp: '192.168.1.1',
error: 'Requests to private/internal network addresses are not allowed',
});
const result = await sendNtfy('http://192.168.1.1/ntfy', null, payload);
expect(result).toBe(false);
expect(vi.mocked(logError)).toHaveBeenCalledWith(expect.stringContaining('SSRF'));
expect(globalThis.fetch as ReturnType<typeof vi.fn>).not.toHaveBeenCalled();
});
it('NTFY-006 — HTTP non-2xx response returns false and logs error', async () => {
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValueOnce({ ok: false, status: 403, text: async () => 'Forbidden' } as never);
const result = await sendNtfy(ntfyUrl, null, payload);
expect(result).toBe(false);
expect(vi.mocked(logError)).toHaveBeenCalledWith(expect.stringContaining('403'));
});
it('NTFY-007 — network error returns false', async () => {
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockRejectedValueOnce(new Error('Network failure'));
const result = await sendNtfy(ntfyUrl, null, payload);
expect(result).toBe(false);
expect(vi.mocked(logError)).toHaveBeenCalledWith(expect.stringContaining('Network failure'));
});
it('NTFY-008 — unknown event falls back to priority 3 and no Tags header', async () => {
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValueOnce({ ok: true, text: async () => '' } as never);
await sendNtfy(ntfyUrl, null, { event: 'unknown_event', title: 'T', body: 'B' });
const [, calledOpts] = mockFetch.mock.calls[0];
expect(calledOpts.headers['Priority']).toBe('3');
expect(calledOpts.headers['Tags']).toBeUndefined(); // empty tags = no header
});
it('NTFY-009 — title with non-Latin-1 chars is RFC 2047 encoded', async () => {
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValueOnce({ ok: true, text: async () => '' } as never);
await sendNtfy(ntfyUrl, null, { ...payload, title: 'Buy →€ ticket' });
const [, calledOpts] = mockFetch.mock.calls[0];
const encoded = calledOpts.headers['Title'] as string;
expect(encoded).toMatch(/^=\?UTF-8\?B\?/);
const b64 = encoded.replace(/^=\?UTF-8\?B\?/, '').replace(/\?=$/, '');
expect(Buffer.from(b64, 'base64').toString('utf8')).toBe('Buy →€ ticket');
});
it('NTFY-010 — ASCII-only title is passed through verbatim', async () => {
const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValueOnce({ ok: true, text: async () => '' } as never);
await sendNtfy(ntfyUrl, null, { ...payload, title: 'Simple ASCII title' });
const [, calledOpts] = mockFetch.mock.calls[0];
expect(calledOpts.headers['Title']).toBe('Simple ASCII title');
});
});
@@ -1,958 +0,0 @@
/**
* Unit tests for server/src/services/oauthService.ts.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
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: (tripId: any, userId: number) =>
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
isOwner: (tripId: any, userId: number) =>
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/services/apiKeyCrypto', () => ({
encrypt_api_key: (v: string) => v,
decrypt_api_key: (v: string) => v,
maybe_encrypt_api_key: (v: string) => v,
}));
vi.mock('../../../src/mcp/sessionManager', () => ({ revokeUserSessions: vi.fn(), revokeUserSessionsForClient: vi.fn(), sessions: new Map() }));
import { revokeUserSessionsForClient } from '../../../src/mcp/sessionManager';
vi.mock('../../../src/demo/demo-reset', () => ({ saveBaseline: vi.fn() }));
vi.mock('../../../src/services/adminService', () => ({
isAddonEnabled: vi.fn().mockReturnValue(true),
getCollabFeatures: vi.fn().mockReturnValue({ chat: true, notes: true, polls: true, whatsnext: true }),
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
// PKCE helper — generates a valid code_verifier + code_challenge pair (RFC 7636)
function makePkce() {
const verifier = crypto.randomBytes(32).toString('base64url'); // 43 chars
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url'); // 43 chars
return { verifier, challenge };
}
import {
createOAuthClient,
listOAuthClients,
deleteOAuthClient,
rotateOAuthClientSecret,
createAuthCode,
consumeAuthCode,
issueTokens,
getUserByAccessToken,
refreshTokens,
revokeToken,
listOAuthSessions,
revokeSession,
validateAuthorizeRequest,
verifyPKCE,
authenticateClient,
saveConsent,
getConsent,
isConsentSufficient,
} from '../../../src/services/oauthService';
import { isAddonEnabled } from '../../../src/services/adminService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
// Clear oauth tables manually since they're not in the standard reset list
testDb.exec('DELETE FROM oauth_tokens');
testDb.exec('DELETE FROM oauth_consents');
testDb.exec('DELETE FROM oauth_clients');
vi.mocked(isAddonEnabled).mockReturnValue(true);
});
afterAll(() => {
testDb.close();
});
// ---------------------------------------------------------------------------
// Helper
// ---------------------------------------------------------------------------
function makeClient(
userId: number,
overrides: Partial<{ name: string; redirectUris: string[]; scopes: string[] }> = {}
) {
return createOAuthClient(
userId,
overrides.name ?? 'Test Client',
overrides.redirectUris ?? ['https://example.com/callback'],
overrides.scopes ?? ['trips:read'],
);
}
// ---------------------------------------------------------------------------
// createOAuthClient
// ---------------------------------------------------------------------------
describe('createOAuthClient', () => {
it('creates a client successfully and returns client_secret only on creation', () => {
const { user } = createUser(testDb);
const result = makeClient(user.id);
expect(result.error).toBeUndefined();
expect(result.client).toBeDefined();
expect(typeof result.client!.client_secret).toBe('string');
expect((result.client!.client_secret as string).startsWith('trekcs_')).toBe(true);
});
it('client_id is a UUID', () => {
const { user } = createUser(testDb);
const result = makeClient(user.id);
expect(result.client!.client_id).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
);
});
it('returns 400 error if name is empty', () => {
const { user } = createUser(testDb);
const result = createOAuthClient(user.id, '', ['https://example.com/cb'], ['trips:read']);
expect(result.status).toBe(400);
expect(result.error).toContain('Name');
});
it('returns 400 error if name exceeds 100 characters', () => {
const { user } = createUser(testDb);
const longName = 'A'.repeat(101);
const result = createOAuthClient(user.id, longName, ['https://example.com/cb'], ['trips:read']);
expect(result.status).toBe(400);
expect(result.error).toContain('100');
});
it('returns 400 error if no redirect URIs provided', () => {
const { user } = createUser(testDb);
const result = createOAuthClient(user.id, 'Test', [], ['trips:read']);
expect(result.status).toBe(400);
expect(result.error).toContain('redirect URI');
});
it('returns 400 error if more than 10 redirect URIs provided', () => {
const { user } = createUser(testDb);
const uris = Array.from({ length: 11 }, (_, i) => `https://example${i}.com/cb`);
const result = createOAuthClient(user.id, 'Test', uris, ['trips:read']);
expect(result.status).toBe(400);
expect(result.error).toContain('10');
});
it('returns 400 error for invalid URI format', () => {
const { user } = createUser(testDb);
const result = createOAuthClient(user.id, 'Test', ['not-a-url'], ['trips:read']);
expect(result.status).toBe(400);
expect(result.error).toContain('Invalid redirect URI');
});
it('returns 400 error for non-https URI (not localhost)', () => {
const { user } = createUser(testDb);
const result = createOAuthClient(user.id, 'Test', ['http://example.com/cb'], ['trips:read']);
expect(result.status).toBe(400);
expect(result.error).toContain('HTTPS');
});
it('allows http://localhost redirect URI', () => {
const { user } = createUser(testDb);
const result = createOAuthClient(user.id, 'Test', ['http://localhost:3000/callback'], ['trips:read']);
expect(result.error).toBeUndefined();
expect(result.client).toBeDefined();
});
it('allows http://127.0.0.1 redirect URI', () => {
const { user } = createUser(testDb);
const result = createOAuthClient(user.id, 'Test', ['http://127.0.0.1:5000/callback'], ['trips:read']);
expect(result.error).toBeUndefined();
expect(result.client).toBeDefined();
});
it('returns 400 error if no scopes provided', () => {
const { user } = createUser(testDb);
const result = createOAuthClient(user.id, 'Test', ['https://example.com/cb'], []);
expect(result.status).toBe(400);
expect(result.error).toContain('scope');
});
it('returns 400 error for invalid scopes', () => {
const { user } = createUser(testDb);
const result = createOAuthClient(user.id, 'Test', ['https://example.com/cb'], ['invalid:scope']);
expect(result.status).toBe(400);
expect(result.error).toContain('Invalid scopes');
});
it('enforces max 10 clients per user', () => {
const { user } = createUser(testDb);
for (let i = 0; i < 10; i++) {
const r = makeClient(user.id, { name: `Client ${i}` });
expect(r.error).toBeUndefined();
}
const eleventh = makeClient(user.id, { name: 'Eleventh' });
expect(eleventh.status).toBe(400);
expect(eleventh.error).toContain('10');
});
});
// ---------------------------------------------------------------------------
// listOAuthClients
// ---------------------------------------------------------------------------
describe('listOAuthClients', () => {
it('returns empty array for user with no clients', () => {
const { user } = createUser(testDb);
expect(listOAuthClients(user.id)).toEqual([]);
});
it('returns created clients with redirect_uris and allowed_scopes as arrays', () => {
const { user } = createUser(testDb);
makeClient(user.id, { name: 'Client A', redirectUris: ['https://a.com/cb'], scopes: ['trips:read', 'budget:read'] });
const clients = listOAuthClients(user.id);
expect(clients).toHaveLength(1);
expect(clients[0].name).toBe('Client A');
expect(Array.isArray(clients[0].redirect_uris)).toBe(true);
expect(Array.isArray(clients[0].allowed_scopes)).toBe(true);
expect(clients[0].allowed_scopes).toContain('trips:read');
});
});
// ---------------------------------------------------------------------------
// deleteOAuthClient
// ---------------------------------------------------------------------------
describe('deleteOAuthClient', () => {
it('deletes own client successfully', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientRowId = created.client!.id as string;
const result = deleteOAuthClient(user.id, clientRowId);
expect(result.success).toBe(true);
expect(listOAuthClients(user.id)).toHaveLength(0);
});
it('returns 404 for non-existent client', () => {
const { user } = createUser(testDb);
const result = deleteOAuthClient(user.id, 'non-existent-id');
expect(result.status).toBe(404);
});
it("returns 404 for another user's client", () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const created = makeClient(owner.id);
const result = deleteOAuthClient(other.id, created.client!.id as string);
expect(result.status).toBe(404);
});
});
// ---------------------------------------------------------------------------
// rotateOAuthClientSecret
// ---------------------------------------------------------------------------
describe('rotateOAuthClientSecret', () => {
it('rotates secret and returns new client_secret starting with trekcs_', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const oldSecret = created.client!.client_secret as string;
const result = rotateOAuthClientSecret(user.id, created.client!.id as string);
expect(result.error).toBeUndefined();
expect(result.client_secret).toBeDefined();
expect((result.client_secret as string).startsWith('trekcs_')).toBe(true);
expect(result.client_secret).not.toBe(oldSecret);
});
it('returns 404 for non-existent client', () => {
const { user } = createUser(testDb);
const result = rotateOAuthClientSecret(user.id, 'non-existent-id');
expect(result.status).toBe(404);
});
it('revokes old tokens after rotation', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const { access_token } = issueTokens(clientId, user.id, ['trips:read']);
expect(getUserByAccessToken(access_token)).not.toBeNull();
rotateOAuthClientSecret(user.id, created.client!.id as string);
expect(getUserByAccessToken(access_token)).toBeNull();
});
});
// ---------------------------------------------------------------------------
// createAuthCode + consumeAuthCode
// ---------------------------------------------------------------------------
describe('createAuthCode + consumeAuthCode', () => {
it('create code and consume it once returns the pending entry', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const code = createAuthCode({
clientId,
userId: user.id,
redirectUri: 'https://example.com/callback',
scopes: ['trips:read'],
codeChallenge: 'abc123',
codeChallengeMethod: 'S256',
});
const entry = consumeAuthCode(code);
expect(entry).not.toBeNull();
expect(entry!.userId).toBe(user.id);
expect(entry!.clientId).toBe(clientId);
});
it('returns null for non-existent code', () => {
expect(consumeAuthCode('does-not-exist')).toBeNull();
});
it('consuming same code twice returns null (one-time use)', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const code = createAuthCode({
clientId,
userId: user.id,
redirectUri: 'https://example.com/callback',
scopes: ['trips:read'],
codeChallenge: 'abc123',
codeChallengeMethod: 'S256',
});
consumeAuthCode(code);
expect(consumeAuthCode(code)).toBeNull();
});
});
// ---------------------------------------------------------------------------
// issueTokens + getUserByAccessToken
// ---------------------------------------------------------------------------
describe('issueTokens + getUserByAccessToken', () => {
it('issues tokens with correct prefixes', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const tokens = issueTokens(clientId, user.id, ['trips:read']);
expect(tokens.access_token.startsWith('trekoa_')).toBe(true);
expect(tokens.refresh_token.startsWith('trekrf_')).toBe(true);
expect(tokens.token_type).toBe('Bearer');
expect(typeof tokens.expires_in).toBe('number');
});
it('getUserByAccessToken returns user and scopes for a valid token', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const { access_token } = issueTokens(clientId, user.id, ['trips:read', 'budget:write']);
const info = getUserByAccessToken(access_token);
expect(info).not.toBeNull();
expect(info!.user.email).toBe(user.email);
expect(info!.scopes).toContain('trips:read');
expect(info!.scopes).toContain('budget:write');
});
it('getUserByAccessToken returns null for unknown token', () => {
expect(getUserByAccessToken('trekoa_unknown')).toBeNull();
});
it('getUserByAccessToken returns null for revoked token', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const { access_token } = issueTokens(clientId, user.id, ['trips:read']);
revokeToken(access_token, clientId);
expect(getUserByAccessToken(access_token)).toBeNull();
});
});
// ---------------------------------------------------------------------------
// refreshTokens
// ---------------------------------------------------------------------------
describe('refreshTokens', () => {
it('exchanges a refresh token for a new token pair', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const rawSecret = created.client!.client_secret as string;
const { refresh_token } = issueTokens(clientId, user.id, ['trips:read']);
const result = refreshTokens(refresh_token, clientId, rawSecret);
expect(result.error).toBeUndefined();
expect(result.tokens).toBeDefined();
expect(result.tokens!.access_token.startsWith('trekoa_')).toBe(true);
});
it('old tokens are revoked after refresh (rotation)', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const rawSecret = created.client!.client_secret as string;
const { access_token, refresh_token } = issueTokens(clientId, user.id, ['trips:read']);
refreshTokens(refresh_token, clientId, rawSecret);
expect(getUserByAccessToken(access_token)).toBeNull();
});
it('does not revoke the active MCP session on a normal (non-replayed) refresh (#1475)', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const rawSecret = created.client!.client_secret as string;
const { refresh_token } = issueTokens(clientId, user.id, ['trips:read']);
const callsBefore = vi.mocked(revokeUserSessionsForClient).mock.calls.length;
const result = refreshTokens(refresh_token, clientId, rawSecret);
expect(result.error).toBeUndefined();
expect(vi.mocked(revokeUserSessionsForClient).mock.calls.length).toBe(callsBefore);
});
it('returns invalid_grant for unknown refresh token', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const rawSecret = created.client!.client_secret as string;
const result = refreshTokens('trekrf_unknown', clientId, rawSecret);
expect(result.error).toBe('invalid_grant');
expect(result.status).toBe(400);
});
it('returns invalid_grant for revoked token', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const rawSecret = created.client!.client_secret as string;
const { access_token, refresh_token } = issueTokens(clientId, user.id, ['trips:read']);
revokeToken(access_token, clientId);
const result = refreshTokens(refresh_token, clientId, rawSecret);
expect(result.error).toBe('invalid_grant');
});
it('returns invalid_client for wrong client_secret', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const { refresh_token } = issueTokens(clientId, user.id, ['trips:read']);
const result = refreshTokens(refresh_token, clientId, 'wrong-secret');
expect(result.error).toBe('invalid_client');
expect(result.status).toBe(401);
});
});
// ---------------------------------------------------------------------------
// revokeToken
// ---------------------------------------------------------------------------
describe('revokeToken', () => {
it('after revoking access token, getUserByAccessToken returns null', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const { access_token } = issueTokens(clientId, user.id, ['trips:read']);
expect(getUserByAccessToken(access_token)).not.toBeNull();
revokeToken(access_token, clientId);
expect(getUserByAccessToken(access_token)).toBeNull();
});
});
// ---------------------------------------------------------------------------
// listOAuthSessions + revokeSession
// ---------------------------------------------------------------------------
describe('listOAuthSessions + revokeSession', () => {
it('lists active sessions', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
issueTokens(clientId, user.id, ['trips:read']);
const sessions = listOAuthSessions(user.id);
expect(sessions).toHaveLength(1);
expect(sessions[0].client_id).toBe(clientId);
});
it('revoked session is not listed', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const { access_token } = issueTokens(clientId, user.id, ['trips:read']);
revokeToken(access_token, clientId);
const sessions = listOAuthSessions(user.id);
expect(sessions).toHaveLength(0);
});
it('revokeSession returns 404 for unknown session', () => {
const { user } = createUser(testDb);
const result = revokeSession(user.id, 99999);
expect(result.status).toBe(404);
});
it('revokeSession by session id removes session from list', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
issueTokens(clientId, user.id, ['trips:read']);
const sessions = listOAuthSessions(user.id);
const sessionId = sessions[0].id as number;
const result = revokeSession(user.id, sessionId);
expect(result.success).toBe(true);
expect(listOAuthSessions(user.id)).toHaveLength(0);
});
});
// ---------------------------------------------------------------------------
// validateAuthorizeRequest
// ---------------------------------------------------------------------------
describe('validateAuthorizeRequest', () => {
// Use a proper 43-char S256 code_challenge to pass H1 format validation
const { challenge: VALID_CHALLENGE } = makePkce();
function makeParams(overrides: Partial<{
response_type: string;
client_id: string;
redirect_uri: string;
scope: string;
code_challenge: string;
code_challenge_method: string;
}> = {}) {
return {
response_type: 'code',
client_id: '',
redirect_uri: 'https://example.com/callback',
scope: 'trips:read',
code_challenge: VALID_CHALLENGE,
code_challenge_method: 'S256',
...overrides,
};
}
it('returns mcp_disabled when isAddonEnabled returns false', () => {
vi.mocked(isAddonEnabled).mockReturnValue(false);
const result = validateAuthorizeRequest(makeParams({ client_id: 'x' }), null);
expect(result.valid).toBe(false);
expect(result.error).toBe('mcp_disabled');
});
it('requires response_type=code', () => {
const { user } = createUser(testDb);
const result = validateAuthorizeRequest(makeParams({ response_type: 'token', client_id: 'x' }), user.id);
expect(result.valid).toBe(false);
expect(result.error).toBe('unsupported_response_type');
});
it('requires PKCE with S256', () => {
const { user } = createUser(testDb);
const result = validateAuthorizeRequest(makeParams({ client_id: 'x', code_challenge_method: 'plain' }), user.id);
expect(result.valid).toBe(false);
expect(result.error).toBe('invalid_request');
});
it('requires valid client_id', () => {
const { user } = createUser(testDb);
const result = validateAuthorizeRequest(makeParams({ client_id: 'nonexistent' }), user.id);
expect(result.valid).toBe(false);
expect(result.error).toBe('invalid_client');
});
it('validates redirect_uri against registered URIs', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id, { redirectUris: ['https://example.com/callback'] });
const clientId = created.client!.client_id as string;
const result = validateAuthorizeRequest(
makeParams({ client_id: clientId, redirect_uri: 'https://evil.com/callback' }),
user.id
);
expect(result.valid).toBe(false);
expect(result.error).toBe('invalid_redirect_uri');
});
it('validates scope against client allowed_scopes', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id, { scopes: ['trips:read'] });
const clientId = created.client!.client_id as string;
const result = validateAuthorizeRequest(
makeParams({ client_id: clientId, scope: 'budget:write' }),
user.id
);
expect(result.valid).toBe(false);
expect(result.error).toBe('invalid_scope');
});
it('returns loginRequired when userId is null', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const result = validateAuthorizeRequest(makeParams({ client_id: clientId }), null);
expect(result.valid).toBe(true);
expect(result.loginRequired).toBe(true);
});
it('returns consentRequired=true when consent not yet saved', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const result = validateAuthorizeRequest(makeParams({ client_id: clientId }), user.id);
expect(result.valid).toBe(true);
expect(result.consentRequired).toBe(true);
});
it('returns consentRequired=false when consent already saved and sufficient', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
saveConsent(clientId, user.id, ['trips:read']);
const result = validateAuthorizeRequest(makeParams({ client_id: clientId }), user.id);
expect(result.valid).toBe(true);
expect(result.consentRequired).toBe(false);
});
});
// ---------------------------------------------------------------------------
// verifyPKCE
// ---------------------------------------------------------------------------
describe('verifyPKCE', () => {
it('returns true for valid code_verifier / code_challenge pair (SHA256 base64url)', () => {
const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
expect(verifyPKCE(verifier, challenge)).toBe(true);
});
it('returns false for wrong verifier', () => {
const verifier = 'correct-verifier';
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
expect(verifyPKCE('wrong-verifier', challenge)).toBe(false);
});
});
// ---------------------------------------------------------------------------
// authenticateClient
// ---------------------------------------------------------------------------
describe('authenticateClient', () => {
it('returns client row for correct credentials', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const rawSecret = created.client!.client_secret as string;
const client = authenticateClient(clientId, rawSecret);
expect(client).not.toBeNull();
expect(client!.client_id).toBe(clientId);
});
it('returns null for wrong secret', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
expect(authenticateClient(clientId, 'wrong-secret')).toBeNull();
});
it('returns null for unknown client_id', () => {
expect(authenticateClient('unknown-client-id', 'any-secret')).toBeNull();
});
});
// ---------------------------------------------------------------------------
// saveConsent + getConsent + isConsentSufficient
// ---------------------------------------------------------------------------
describe('saveConsent + getConsent + isConsentSufficient', () => {
it('saves and retrieves consent', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
saveConsent(clientId, user.id, ['trips:read', 'budget:write']);
const consent = getConsent(clientId, user.id);
expect(consent).not.toBeNull();
expect(consent).toContain('trips:read');
expect(consent).toContain('budget:write');
});
it('isConsentSufficient returns true when all requested scopes are in existing', () => {
expect(isConsentSufficient(['trips:read', 'budget:write'], ['trips:read'])).toBe(true);
expect(isConsentSufficient(['trips:read', 'budget:write'], ['trips:read', 'budget:write'])).toBe(true);
});
it('isConsentSufficient returns false when some scopes are missing', () => {
expect(isConsentSufficient(['trips:read'], ['trips:read', 'budget:write'])).toBe(false);
expect(isConsentSufficient([], ['trips:read'])).toBe(false);
});
});
// ---------------------------------------------------------------------------
// M5 — saveConsent unions instead of replacing
// ---------------------------------------------------------------------------
describe('saveConsent — scope union (M5)', () => {
it('unioning scopes: approving B after A leaves both in consent', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id, { scopes: ['trips:read', 'budget:write'] });
const clientId = created.client!.client_id as string;
saveConsent(clientId, user.id, ['trips:read']);
saveConsent(clientId, user.id, ['budget:write']);
const consent = getConsent(clientId, user.id);
expect(consent).toContain('trips:read');
expect(consent).toContain('budget:write');
});
it('re-approving a superset scope still preserves previously-consented scopes', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id, { scopes: ['trips:read', 'trips:write'] });
const clientId = created.client!.client_id as string;
saveConsent(clientId, user.id, ['trips:read', 'trips:write']);
// approve only trips:read on a later request
saveConsent(clientId, user.id, ['trips:read']);
const consent = getConsent(clientId, user.id);
// trips:write should NOT be removed (union semantics)
expect(consent).toContain('trips:read');
expect(consent).toContain('trips:write');
});
it('consent is sufficient after sequential approvals — no re-prompt needed', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id, { scopes: ['trips:read', 'budget:write'] });
const clientId = created.client!.client_id as string;
saveConsent(clientId, user.id, ['trips:read']);
saveConsent(clientId, user.id, ['budget:write']);
// Should not require consent again for either scope
expect(isConsentSufficient(getConsent(clientId, user.id)!, ['trips:read'])).toBe(true);
expect(isConsentSufficient(getConsent(clientId, user.id)!, ['budget:write'])).toBe(true);
expect(isConsentSufficient(getConsent(clientId, user.id)!, ['trips:read', 'budget:write'])).toBe(true);
});
});
// ---------------------------------------------------------------------------
// C2 — getUserByAccessToken returns clientId
// ---------------------------------------------------------------------------
describe('getUserByAccessToken — includes clientId (C2)', () => {
it('returns clientId matching the issuing OAuth client', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const { access_token } = issueTokens(clientId, user.id, ['trips:read']);
const info = getUserByAccessToken(access_token);
expect(info).not.toBeNull();
expect(info!.clientId).toBe(clientId);
});
});
// ---------------------------------------------------------------------------
// C3 — Refresh token replay detection and chain revocation
// ---------------------------------------------------------------------------
describe('refreshTokens — replay detection (C3)', () => {
it('replaying a revoked refresh token returns invalid_grant', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const rawSecret = created.client!.client_secret as string;
// Issue tokens, then rotate once (old token becomes revoked)
const { refresh_token: firstRefresh } = issueTokens(clientId, user.id, ['trips:read']);
const rotateResult = refreshTokens(firstRefresh, clientId, rawSecret);
expect(rotateResult.error).toBeUndefined();
const { refresh_token: secondRefresh } = rotateResult.tokens!;
// Replay the FIRST (now revoked) refresh token
const callsBefore = vi.mocked(revokeUserSessionsForClient).mock.calls.length;
const replayResult = refreshTokens(firstRefresh, clientId, rawSecret);
expect(replayResult.error).toBe('invalid_grant');
expect(replayResult.status).toBe(400);
// Replay IS a security event — sessions must still be torn down here.
expect(vi.mocked(revokeUserSessionsForClient).mock.calls.length).toBe(callsBefore + 1);
expect(vi.mocked(revokeUserSessionsForClient)).toHaveBeenLastCalledWith(user.id, clientId);
});
it('replaying a revoked token also revokes the entire rotation chain', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const rawSecret = created.client!.client_secret as string;
// Issue → rotate once
const { refresh_token: first } = issueTokens(clientId, user.id, ['trips:read']);
const r1 = refreshTokens(first, clientId, rawSecret);
const { access_token: access2, refresh_token: second } = r1.tokens!;
// Replay first (revoked) refresh token → chain revoke
refreshTokens(first, clientId, rawSecret);
// The rotated access token should also be dead now
expect(getUserByAccessToken(access2)).toBeNull();
// The second refresh token should also be revoked
const r2 = refreshTokens(second, clientId, rawSecret);
expect(r2.error).toBe('invalid_grant');
});
it('new rotation chain after replay is independent', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const rawSecret = created.client!.client_secret as string;
const { refresh_token: first } = issueTokens(clientId, user.id, ['trips:read']);
// Rotate once
const r1 = refreshTokens(first, clientId, rawSecret);
const { refresh_token: second } = r1.tokens!;
// Rotate again on the second token
const r2 = refreshTokens(second, clientId, rawSecret);
expect(r2.error).toBeUndefined();
const { refresh_token: third } = r2.tokens!;
// Replay the first revoked token → revokes chain containing first+second+third
refreshTokens(first, clientId, rawSecret);
// third should now be revoked too (it's in the same chain)
const r3 = refreshTokens(third, clientId, rawSecret);
expect(r3.error).toBe('invalid_grant');
});
});
// ---------------------------------------------------------------------------
// H1 — PKCE code_challenge / code_verifier format validation
// ---------------------------------------------------------------------------
describe('verifyPKCE — format validation (H1)', () => {
it('returns false for a code_verifier that is too short (< 43 chars)', () => {
const { challenge } = makePkce();
expect(verifyPKCE('short', challenge)).toBe(false);
});
it('returns false for a code_verifier that is too long (> 128 chars)', () => {
const { challenge } = makePkce();
const longVerifier = 'a'.repeat(129);
expect(verifyPKCE(longVerifier, challenge)).toBe(false);
});
it('returns false for a code_verifier with invalid characters', () => {
const { challenge } = makePkce();
const badVerifier = 'A'.repeat(42) + ' '; // space is not allowed
expect(verifyPKCE(badVerifier, challenge)).toBe(false);
});
it('returns true for a valid 43-char verifier matching its challenge', () => {
const { verifier, challenge } = makePkce();
expect(verifyPKCE(verifier, challenge)).toBe(true);
});
});
describe('validateAuthorizeRequest — PKCE format (H1)', () => {
it('returns invalid_request when code_challenge is shorter than 43 chars', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const result = validateAuthorizeRequest({
response_type: 'code',
client_id: clientId,
redirect_uri: 'https://example.com/callback',
scope: 'trips:read',
code_challenge: 'tooshort',
code_challenge_method: 'S256',
}, user.id);
expect(result.valid).toBe(false);
expect(result.error).toBe('invalid_request');
});
it('returns invalid_request when code_challenge contains invalid characters', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
// 43 chars but includes '=' which is not base64url
const badChallenge = '='.repeat(43);
const result = validateAuthorizeRequest({
response_type: 'code',
client_id: clientId,
redirect_uri: 'https://example.com/callback',
scope: 'trips:read',
code_challenge: badChallenge,
code_challenge_method: 'S256',
}, user.id);
expect(result.valid).toBe(false);
expect(result.error).toBe('invalid_request');
});
});
// ---------------------------------------------------------------------------
// H3 — validateAuthorizeRequest: loginRequired response strips client info
// ---------------------------------------------------------------------------
describe('validateAuthorizeRequest — unauthenticated strips client info (H3)', () => {
it('loginRequired response does not include client.name or allowed_scopes', () => {
const { user } = createUser(testDb);
const created = makeClient(user.id);
const clientId = created.client!.client_id as string;
const { challenge } = makePkce();
const result = validateAuthorizeRequest({
response_type: 'code',
client_id: clientId,
redirect_uri: 'https://example.com/callback',
scope: 'trips:read',
code_challenge: challenge,
code_challenge_method: 'S256',
}, null /* unauthenticated */);
expect(result.valid).toBe(true);
expect(result.loginRequired).toBe(true);
// Must NOT expose client metadata to unauthenticated callers
expect(result.client).toBeUndefined();
expect(result.scopes).toBeUndefined();
});
});
@@ -1,676 +0,0 @@
/**
* Unit tests for oidcService — OIDC-SVC-001 through OIDC-SVC-025.
* Covers state management, auth codes, role resolution, findOrCreateUser,
* discover caching, and the ReDoS-sensitive issuer trailing-slash regex.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
import { generateKeyPairSync } from 'crypto';
import jwtLib from 'jsonwebtoken';
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: 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: () => {},
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import {
createState,
consumeState,
createAuthCode,
consumeAuthCode,
resolveOidcRole,
frontendUrl,
findOrCreateUser,
discover,
verifyIdToken,
} from '../../../src/services/oidcService';
const MOCK_CONFIG = {
issuer: 'https://oidc.example.com',
clientId: 'client-id',
clientSecret: 'client-secret',
displayName: 'SSO',
discoveryUrl: null,
};
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
delete process.env.OIDC_ADMIN_VALUE;
delete process.env.OIDC_ADMIN_CLAIM;
delete process.env.NODE_ENV;
});
afterAll(() => {
vi.unstubAllGlobals();
testDb.close();
});
// ── createState / consumeState ────────────────────────────────────────────────
describe('createState / consumeState', () => {
it('OIDC-SVC-001: createState returns a hex token + PKCE S256 challenge', () => {
const { state, codeChallenge } = createState('https://example.com/callback');
expect(state).toMatch(/^[0-9a-f]{64}$/);
expect(codeChallenge).toMatch(/^[A-Za-z0-9_-]{43}$/); // base64url SHA-256, no padding
});
it('OIDC-SVC-002: consumeState returns stored data (incl. verifier) and deletes state', () => {
const { state } = createState('https://example.com/callback', 'invite-abc');
const data = consumeState(state);
expect(data).not.toBeNull();
expect(data!.redirectUri).toBe('https://example.com/callback');
expect(data!.inviteToken).toBe('invite-abc');
expect(typeof data!.codeVerifier).toBe('string');
expect(data!.codeVerifier.length).toBeGreaterThan(20);
// State is consumed — second call returns null
expect(consumeState(state)).toBeNull();
});
it('OIDC-SVC-003: consumeState returns null for unknown state', () => {
expect(consumeState('not-a-real-state')).toBeNull();
});
it('OIDC-SVC-004: two different states do not conflict', () => {
const { state: s1 } = createState('http://a.example.com');
const { state: s2 } = createState('http://b.example.com');
expect(s1).not.toBe(s2);
expect(consumeState(s1)!.redirectUri).toBe('http://a.example.com');
expect(consumeState(s2)!.redirectUri).toBe('http://b.example.com');
});
});
// ── createAuthCode / consumeAuthCode ─────────────────────────────────────────
describe('createAuthCode / consumeAuthCode', () => {
it('OIDC-SVC-005: createAuthCode returns a UUID-like string', () => {
const code = createAuthCode('my.jwt.token');
expect(typeof code).toBe('string');
expect(code.length).toBeGreaterThan(0);
});
it('OIDC-SVC-006: consumeAuthCode returns the stored token', () => {
const code = createAuthCode('real.jwt.here');
const result = consumeAuthCode(code);
expect('token' in result).toBe(true);
expect((result as { token: string }).token).toBe('real.jwt.here');
});
it('OIDC-SVC-007: auth code is single-use (second consume returns error)', () => {
const code = createAuthCode('single.use.token');
consumeAuthCode(code); // first use
const second = consumeAuthCode(code);
expect('error' in second).toBe(true);
});
it('OIDC-SVC-008: consumeAuthCode returns error for unknown code', () => {
const result = consumeAuthCode('not-a-real-code');
expect('error' in result).toBe(true);
});
});
// ── resolveOidcRole ───────────────────────────────────────────────────────────
describe('resolveOidcRole', () => {
it('OIDC-SVC-009: returns admin when isFirstUser is true', () => {
expect(resolveOidcRole({ sub: 'x' }, true)).toBe('admin');
});
it('OIDC-SVC-010: returns user when no OIDC_ADMIN_VALUE is set', () => {
delete process.env.OIDC_ADMIN_VALUE;
expect(resolveOidcRole({ sub: 'x', groups: ['admins'] }, false)).toBe('user');
});
it('OIDC-SVC-011: returns admin when groups array contains OIDC_ADMIN_VALUE', () => {
process.env.OIDC_ADMIN_VALUE = 'trek-admins';
expect(resolveOidcRole({ sub: 'x', groups: ['trek-users', 'trek-admins'] }, false)).toBe('admin');
});
it('OIDC-SVC-012: returns user when groups array does not contain OIDC_ADMIN_VALUE', () => {
process.env.OIDC_ADMIN_VALUE = 'trek-admins';
expect(resolveOidcRole({ sub: 'x', groups: ['trek-users'] }, false)).toBe('user');
});
it('OIDC-SVC-013: uses custom OIDC_ADMIN_CLAIM when set', () => {
process.env.OIDC_ADMIN_VALUE = 'superadmin';
process.env.OIDC_ADMIN_CLAIM = 'roles';
expect(resolveOidcRole({ sub: 'x', roles: ['superadmin', 'editor'] }, false)).toBe('admin');
});
it('OIDC-SVC-014: handles string claim (exact match)', () => {
process.env.OIDC_ADMIN_VALUE = 'admin';
process.env.OIDC_ADMIN_CLAIM = 'role';
expect(resolveOidcRole({ sub: 'x', role: 'admin' }, false)).toBe('admin');
expect(resolveOidcRole({ sub: 'x', role: 'editor' }, false)).toBe('user');
});
});
// ── frontendUrl ───────────────────────────────────────────────────────────────
describe('frontendUrl', () => {
it('OIDC-SVC-015: prepends localhost:5173 in non-production', () => {
delete process.env.NODE_ENV;
expect(frontendUrl('/login?oidc_code=abc')).toBe('http://localhost:5173/login?oidc_code=abc');
});
it('OIDC-SVC-016: returns bare path in production', () => {
process.env.NODE_ENV = 'production';
expect(frontendUrl('/login?oidc_code=abc')).toBe('/login?oidc_code=abc');
delete process.env.NODE_ENV;
});
});
// ── discover ──────────────────────────────────────────────────────────────────
describe('discover', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('OIDC-SVC-017: fetches and returns discovery document', async () => {
const doc = {
authorization_endpoint: 'https://oidc.example.com/auth',
token_endpoint: 'https://oidc.example.com/token',
userinfo_endpoint: 'https://oidc.example.com/userinfo',
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => doc,
}));
// Use unique issuer to bypass module-level cache from other tests
const result = await discover('https://unique-1.example.com');
expect(result.authorization_endpoint).toBe(doc.authorization_endpoint);
expect(result.token_endpoint).toBe(doc.token_endpoint);
});
it('OIDC-SVC-018: throws when provider returns non-ok response', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }));
await expect(discover('https://bad-issuer.example.com')).rejects.toThrow();
});
it('OIDC-SVC-037: accepts mismatched doc issuer when discoveryUrl is explicit', async () => {
const doc = {
issuer: 'https://auth.example.com/application/o/myapp/',
authorization_endpoint: 'https://auth.example.com/application/o/myapp/authorize/',
token_endpoint: 'https://auth.example.com/application/o/token/',
userinfo_endpoint: 'https://auth.example.com/application/o/userinfo/',
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => doc }));
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const result = await discover(
'https://auth.example.com',
'https://auth.example.com/application/o/myapp/.well-known/openid-configuration',
);
expect(result.issuer).toBe(doc.issuer);
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('differs from configured OIDC_ISSUER'));
warnSpy.mockRestore();
});
it('OIDC-SVC-038: throws on mismatched doc issuer when discoveryUrl is omitted', async () => {
const doc = {
issuer: 'https://evil.example.com',
authorization_endpoint: 'https://unique-2.example.com/auth',
token_endpoint: 'https://unique-2.example.com/token',
userinfo_endpoint: 'https://unique-2.example.com/userinfo',
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => doc }));
await expect(discover('https://unique-2.example.com')).rejects.toThrow(
'OIDC discovery issuer mismatch',
);
});
it('OIDC-SVC-039: trailing-slash-only mismatch with explicit discoveryUrl does not warn', async () => {
const doc = {
issuer: 'https://auth.example.com/',
authorization_endpoint: 'https://auth.example.com/auth',
token_endpoint: 'https://auth.example.com/token',
userinfo_endpoint: 'https://auth.example.com/userinfo',
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => doc }));
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
await discover(
'https://auth.example.com',
'https://auth.example.com/.well-known/openid-configuration',
);
expect(warnSpy).not.toHaveBeenCalled();
warnSpy.mockRestore();
});
});
// ── issuer trailing-slash regex (ReDoS guard) ─────────────────────────────────
describe('getOidcConfig issuer trailing-slash regex', () => {
it('OIDC-SVC-019: /\\/+$/ strips trailing slashes in < 5ms', () => {
// The regex /\/+$/ in getOidcConfig: issuer.replace(/\/+$/, '')
// Adversarial input: many trailing slashes — should not backtrack catastrophically
const adversarial = 'https://oidc.example.com' + '/'.repeat(10000);
const start = Date.now();
const result = adversarial.replace(/\/+$/, '');
const elapsed = Date.now() - start;
expect(result).toBe('https://oidc.example.com');
expect(elapsed).toBeLessThan(100);
});
});
// ── findOrCreateUser ──────────────────────────────────────────────────────────
describe('findOrCreateUser', () => {
it('OIDC-SVC-020: finds existing user by oidc_sub', () => {
const { user } = createUser(testDb, { email: 'alice@example.com' });
// Link the sub manually
testDb.prepare('UPDATE users SET oidc_sub = ?, oidc_issuer = ? WHERE id = ?')
.run('sub-alice-123', MOCK_CONFIG.issuer, user.id);
const result = findOrCreateUser(
{ sub: 'sub-alice-123', email: 'alice@example.com', name: 'Alice' },
MOCK_CONFIG
);
expect('user' in result).toBe(true);
expect((result as { user: any }).user.id).toBe(user.id);
});
it('OIDC-SVC-021: finds existing user by email when no sub match', () => {
const { user } = createUser(testDb, { email: 'bob@example.com' });
const result = findOrCreateUser(
{ sub: 'sub-bob-new', email: 'bob@example.com', name: 'Bob', email_verified: true },
MOCK_CONFIG
);
expect('user' in result).toBe(true);
expect((result as { user: any }).user.id).toBe(user.id);
});
it('OIDC-SVC-022: creates new user when registration is open', () => {
const result = findOrCreateUser(
{ sub: 'sub-new-1', email: 'newuser@example.com', name: 'New User' },
MOCK_CONFIG
);
expect('user' in result).toBe(true);
const newUser = testDb.prepare("SELECT * FROM users WHERE email = 'newuser@example.com'").get();
expect(newUser).toBeDefined();
});
it('OIDC-SVC-023: first user gets admin role', () => {
// DB is empty after resetTestDb
const result = findOrCreateUser(
{ sub: 'sub-first', email: 'first@example.com', name: 'First' },
MOCK_CONFIG
);
expect('user' in result).toBe(true);
expect((result as { user: any }).user.role).toBe('admin');
});
it('OIDC-SVC-024: returns registration_disabled error when registration is off', () => {
createUser(testDb, { email: 'existing@example.com' });
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'false')").run();
const result = findOrCreateUser(
{ sub: 'sub-blocked', email: 'blocked@example.com', name: 'Blocked' },
MOCK_CONFIG
);
expect('error' in result).toBe(true);
expect((result as { error: string }).error).toBe('registration_disabled');
});
it('OIDC-SVC-025: links oidc_sub when existing user has none (verified email)', () => {
const { user } = createUser(testDb, { email: 'charlie@example.com' });
// Ensure no oidc_sub set
testDb.prepare('UPDATE users SET oidc_sub = NULL, oidc_issuer = NULL WHERE id = ?').run(user.id);
findOrCreateUser(
{ sub: 'sub-charlie-linked', email: 'charlie@example.com', name: 'Charlie', email_verified: true },
MOCK_CONFIG
);
const updated = testDb.prepare('SELECT oidc_sub FROM users WHERE id = ?').get(user.id) as any;
expect(updated.oidc_sub).toBe('sub-charlie-linked');
});
it('OIDC-SVC-025b: refuses to link an unverified email to an existing local account', () => {
const { user } = createUser(testDb, { email: 'dora@example.com' });
testDb.prepare('UPDATE users SET oidc_sub = NULL, oidc_issuer = NULL WHERE id = ?').run(user.id);
// No email_verified claim — an IdP that lets users set arbitrary emails must
// not be able to take over a pre-existing password account.
const result = findOrCreateUser(
{ sub: 'sub-dora-attacker', email: 'dora@example.com', name: 'Dora' },
MOCK_CONFIG
);
expect('error' in result).toBe(true);
expect((result as { error: string }).error).toBe('email_not_verified');
const updated = testDb.prepare('SELECT oidc_sub FROM users WHERE id = ?').get(user.id) as any;
expect(updated.oidc_sub).toBeNull(); // account not linked / not hijacked
});
it('OIDC-SVC-026: existing user role is updated when OIDC claim mapping changes it', () => {
const { user } = createUser(testDb, { email: 'diana@example.com', role: 'user' });
// Link oidc_sub manually so the user is found by sub lookup
testDb.prepare('UPDATE users SET oidc_sub = ?, oidc_issuer = ? WHERE id = ?')
.run('sub-diana-role', MOCK_CONFIG.issuer, user.id);
process.env.OIDC_ADMIN_VALUE = 'admins';
const result = findOrCreateUser(
{ sub: 'sub-diana-role', email: 'diana@example.com', name: 'Diana', groups: ['admins'] },
MOCK_CONFIG
);
expect('user' in result).toBe(true);
expect((result as { user: any }).user.role).toBe('admin');
const dbUser = testDb.prepare('SELECT role FROM users WHERE id = ?').get(user.id) as any;
expect(dbUser.role).toBe('admin');
});
it('OIDC-SVC-027: new user with valid invite token increments used_count', () => {
const { user: creator } = createUser(testDb, { email: 'creator@example.com' });
testDb.prepare(
"INSERT INTO invite_tokens (token, max_uses, used_count, created_by) VALUES ('tok-valid', 5, 0, ?)"
).run(creator.id);
const result = findOrCreateUser(
{ sub: 'sub-invite-user', email: 'invitee@example.com', name: 'Invitee' },
MOCK_CONFIG,
'tok-valid'
);
expect('user' in result).toBe(true);
const token = testDb.prepare("SELECT used_count FROM invite_tokens WHERE token = 'tok-valid'").get() as any;
expect(token.used_count).toBe(1);
});
it('OIDC-SVC-028: new user with expired invite token is created but invite is ignored', () => {
const { user: creator } = createUser(testDb, { email: 'creator2@example.com' });
testDb.prepare(
"INSERT INTO invite_tokens (token, max_uses, used_count, expires_at, created_by) VALUES ('tok-expired', 5, 0, '2000-01-01T00:00:00.000Z', ?)"
).run(creator.id);
const result = findOrCreateUser(
{ sub: 'sub-expired-invite', email: 'expired-invitee@example.com', name: 'ExpiredInvitee' },
MOCK_CONFIG,
'tok-expired'
);
// User is still created because open registration is allowed
expect('user' in result).toBe(true);
const newUser = testDb.prepare("SELECT id FROM users WHERE email = 'expired-invitee@example.com'").get();
expect(newUser).toBeDefined();
// Invite used_count must remain 0 (token was treated as invalid)
const token = testDb.prepare("SELECT used_count FROM invite_tokens WHERE token = 'tok-expired'").get() as any;
expect(token.used_count).toBe(0);
});
it('OIDC-SVC-029: new user with max_uses exceeded invite token is created but invite is ignored', () => {
const { user: creator } = createUser(testDb, { email: 'creator3@example.com' });
testDb.prepare(
"INSERT INTO invite_tokens (token, max_uses, used_count, created_by) VALUES ('tok-full', 1, 1, ?)"
).run(creator.id);
const result = findOrCreateUser(
{ sub: 'sub-full-invite', email: 'full-invitee@example.com', name: 'FullInvitee' },
MOCK_CONFIG,
'tok-full'
);
// User is still created because open registration is allowed
expect('user' in result).toBe(true);
const newUser = testDb.prepare("SELECT id FROM users WHERE email = 'full-invitee@example.com'").get();
expect(newUser).toBeDefined();
// Invite used_count must remain 1 (token was treated as invalid)
const token = testDb.prepare("SELECT used_count FROM invite_tokens WHERE token = 'tok-full'").get() as any;
expect(token.used_count).toBe(1);
});
// ── OIDC picture claim → avatar (#1399) ──────────────────────────────────
it('OIDC-SVC-040: new user stores the https picture claim as their avatar', () => {
const result = findOrCreateUser(
{ sub: 'sub-pic-1', email: 'pic1@example.com', name: 'Pic One', picture: 'https://idp.example.com/u/pic1.png' },
MOCK_CONFIG
);
expect('user' in result).toBe(true);
const row = testDb.prepare("SELECT avatar FROM users WHERE email = 'pic1@example.com'").get() as any;
expect(row.avatar).toBe('https://idp.example.com/u/pic1.png');
});
it('OIDC-SVC-041: new user with a non-https picture claim stores no avatar', () => {
findOrCreateUser(
{ sub: 'sub-pic-2', email: 'pic2@example.com', name: 'Pic Two', picture: 'http://idp.example.com/u/pic2.png' },
MOCK_CONFIG
);
const row = testDb.prepare("SELECT avatar FROM users WHERE email = 'pic2@example.com'").get() as any;
expect(row.avatar).toBeNull();
});
it('OIDC-SVC-042: existing user with no avatar gets the OIDC picture', () => {
const { user } = createUser(testDb, { email: 'pic3@example.com' });
testDb.prepare('UPDATE users SET oidc_sub = ?, oidc_issuer = ?, avatar = NULL WHERE id = ?')
.run('sub-pic-3', MOCK_CONFIG.issuer, user.id);
findOrCreateUser(
{ sub: 'sub-pic-3', email: 'pic3@example.com', name: 'Pic Three', picture: 'https://idp.example.com/u/pic3.png' },
MOCK_CONFIG
);
const row = testDb.prepare('SELECT avatar FROM users WHERE id = ?').get(user.id) as any;
expect(row.avatar).toBe('https://idp.example.com/u/pic3.png');
});
it('OIDC-SVC-043: a custom uploaded avatar is never overwritten by the OIDC picture', () => {
const { user } = createUser(testDb, { email: 'pic4@example.com' });
testDb.prepare('UPDATE users SET oidc_sub = ?, oidc_issuer = ?, avatar = ? WHERE id = ?')
.run('sub-pic-4', MOCK_CONFIG.issuer, 'uploaded-abc.jpg', user.id);
findOrCreateUser(
{ sub: 'sub-pic-4', email: 'pic4@example.com', name: 'Pic Four', picture: 'https://idp.example.com/u/pic4.png' },
MOCK_CONFIG
);
const row = testDb.prepare('SELECT avatar FROM users WHERE id = ?').get(user.id) as any;
expect(row.avatar).toBe('uploaded-abc.jpg');
});
it('OIDC-SVC-044: a previously stored OIDC picture URL is refreshed on next login', () => {
const { user } = createUser(testDb, { email: 'pic5@example.com' });
testDb.prepare('UPDATE users SET oidc_sub = ?, oidc_issuer = ?, avatar = ? WHERE id = ?')
.run('sub-pic-5', MOCK_CONFIG.issuer, 'https://idp.example.com/u/old.png', user.id);
findOrCreateUser(
{ sub: 'sub-pic-5', email: 'pic5@example.com', name: 'Pic Five', picture: 'https://idp.example.com/u/new.png' },
MOCK_CONFIG
);
const row = testDb.prepare('SELECT avatar FROM users WHERE id = ?').get(user.id) as any;
expect(row.avatar).toBe('https://idp.example.com/u/new.png');
});
it('OIDC-SVC-045: a trip-bound invite auto-adds the new SSO user as a trip member (#1402)', () => {
const { user: admin } = createUser(testDb, { role: 'admin' });
const trip = createTrip(testDb, admin.id);
testDb.prepare(
'INSERT INTO invite_tokens (token, max_uses, used_count, expires_at, created_by, trip_id) VALUES (?, 5, 0, NULL, ?, ?)'
).run('inv-trip-join', admin.id, trip.id);
const result = findOrCreateUser(
{ sub: 'sub-trip-join', email: 'joiner@example.com', name: 'Joiner' },
MOCK_CONFIG,
'inv-trip-join'
);
expect('user' in result).toBe(true);
const uid = (result as { user: any }).user.id;
const member = testDb.prepare('SELECT * FROM trip_members WHERE trip_id = ? AND user_id = ?').get(trip.id, uid);
expect(member).toBeTruthy();
});
});
// ── exchangeCodeForToken ──────────────────────────────────────────────────────
describe('exchangeCodeForToken', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('OIDC-SVC-030: sends correct POST body and returns token data', async () => {
const { exchangeCodeForToken } = await import('../../../src/services/oidcService');
const mockTokenData = { access_token: 'tok', token_type: 'Bearer' };
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: async () => mockTokenData,
}));
const doc = { token_endpoint: 'https://oidc.example.com/token' } as any;
const result = await exchangeCodeForToken(doc, 'auth-code-123', 'https://app/callback', 'client-id', 'client-secret');
expect(result.access_token).toBe('tok');
expect(result._ok).toBe(true);
expect(result._status).toBe(200);
const fetchCall = (fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(fetchCall[0]).toBe('https://oidc.example.com/token');
expect(fetchCall[1].method).toBe('POST');
});
it('OIDC-SVC-031: reflects _ok=false when provider returns error status', async () => {
const { exchangeCodeForToken } = await import('../../../src/services/oidcService');
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: false,
status: 400,
json: async () => ({ error: 'invalid_grant' }),
}));
const doc = { token_endpoint: 'https://oidc.example.com/token' } as any;
const result = await exchangeCodeForToken(doc, 'bad-code', 'https://app/callback', 'c', 's');
expect(result._ok).toBe(false);
expect(result._status).toBe(400);
});
});
// ── getUserInfo ───────────────────────────────────────────────────────────────
describe('getUserInfo', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('OIDC-SVC-032: fetches userinfo with Bearer token and returns parsed JSON', async () => {
const { getUserInfo } = await import('../../../src/services/oidcService');
const userInfoData = { sub: 'user-sub', email: 'user@example.com', name: 'User Name' };
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
json: async () => userInfoData,
}));
const result = await getUserInfo('https://oidc.example.com/userinfo', 'access-token-123');
expect(result.sub).toBe('user-sub');
expect(result.email).toBe('user@example.com');
const fetchCall = (fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(fetchCall[1].headers.Authorization).toBe('Bearer access-token-123');
});
});
// ── verifyIdToken ─────────────────────────────────────────────────────────────
describe('verifyIdToken', () => {
const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const jwk = publicKey.export({ format: 'jwk' }) as Record<string, unknown>;
const ISSUER = 'https://auth.example.com/application/o/trek';
const CLIENT_ID = 'trek-client';
const JWKS_URI = 'https://auth.example.com/.well-known/jwks.json';
function mockJwks() {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ keys: [jwk] }),
}));
}
function makeToken(iss: string, overrides: object = {}) {
return jwtLib.sign(
{ sub: 'user-sub', email: 'user@example.com', ...overrides },
privateKey,
{ algorithm: 'RS256', audience: CLIENT_ID, issuer: iss, expiresIn: '1h' }
);
}
const doc = { jwks_uri: JWKS_URI } as any;
afterEach(() => { vi.unstubAllGlobals(); });
it('OIDC-SVC-033: accepts token whose iss matches expectedIssuer exactly', async () => {
mockJwks();
const token = makeToken(ISSUER);
const result = await verifyIdToken(token, doc, CLIENT_ID, ISSUER);
expect(result.ok).toBe(true);
});
it('OIDC-SVC-034: accepts token whose iss has a trailing slash (Authentik)', async () => {
mockJwks();
const token = makeToken(ISSUER + '/');
const result = await verifyIdToken(token, doc, CLIENT_ID, ISSUER);
expect(result.ok).toBe(true);
});
it('OIDC-SVC-035: rejects token with wrong issuer', async () => {
mockJwks();
const token = makeToken('https://evil.example.com');
const result = await verifyIdToken(token, doc, CLIENT_ID, ISSUER);
expect(result.ok).toBe(false);
expect((result as any).error).toMatch('jwt issuer invalid');
});
it('OIDC-SVC-036: rejects token with wrong audience', async () => {
mockJwks();
const token = makeToken(ISSUER, {});
const wrongAudToken = jwtLib.sign(
{ sub: 'user-sub', iss: ISSUER },
privateKey,
{ algorithm: 'RS256', audience: 'wrong-client', expiresIn: '1h' }
);
const result = await verifyIdToken(wrongAudToken, doc, CLIENT_ID, ISSUER);
expect(result.ok).toBe(false);
});
});
@@ -1,570 +0,0 @@
/**
* Unit tests for packingService.ts — uncovered functions.
* Covers PACK-SVC-001 to PACK-SVC-012.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB mock setup (vi.hoisted so it is available before vi.mock calls) ────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import {
saveAsTemplate,
applyTemplate,
listTemplates,
setBagMembers,
createBag,
updateBag,
deleteBag,
bulkImport,
createItem,
updateItem,
deleteItem,
listItems,
setItemSharing,
addContributor,
removeContributor,
cloneItem,
} from '../../../src/services/packingService';
// ── Lifecycle ─────────────────────────────────────────────────────────────────
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ── saveAsTemplate ────────────────────────────────────────────────────────────
describe('saveAsTemplate', () => {
it('PACK-SVC-001: saves packing items as a template with correct categories and item count', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Shirt', 'Clothes', 0);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Shorts', 'Clothes', 1);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Toothbrush', 'Toiletries', 2);
const result = saveAsTemplate(trip.id, user.id, 'My Template');
expect(result).not.toBeNull();
expect(result!.name).toBe('My Template');
expect(result!.categoryCount).toBe(2);
expect(result!.itemCount).toBe(3);
const template = testDb.prepare('SELECT * FROM packing_templates WHERE id = ?').get(result!.id) as any;
expect(template).toBeDefined();
expect(template.name).toBe('My Template');
expect(template.created_by).toBe(user.id);
});
it('PACK-SVC-002: returns null when trip has no packing items', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = saveAsTemplate(trip.id, user.id, 'Empty');
expect(result).toBeNull();
});
});
// ── listTemplates ───────────────────────────────────────────────────────────────
describe('listTemplates', () => {
it('PACK-SVC-LIST-001: returns templates with id, name and item_count', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Shirt', 'Clothes', 0);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Toothbrush', 'Toiletries', 1);
const saved = saveAsTemplate(trip.id, user.id, 'Weekend');
const templates = listTemplates();
expect(templates).toHaveLength(1);
expect(templates[0]).toMatchObject({ id: saved!.id, name: 'Weekend', item_count: 2 });
});
it('PACK-SVC-LIST-002: returns an empty array when no templates exist', () => {
expect(listTemplates()).toEqual([]);
});
});
// ── applyTemplate ─────────────────────────────────────────────────────────────
/** A one-category template with the given item names. Returns its id. */
function seedTemplate(userId: number, itemNames: string[]): number {
const templateId = testDb.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run('Camping', userId).lastInsertRowid as number;
const catId = testDb.prepare('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)').run(templateId, 'Gear', 0).lastInsertRowid as number;
itemNames.forEach((name, i) => {
testDb.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, name, i);
});
return templateId;
}
describe('applyTemplate', () => {
it('PACK-SVC-003: adds template items to a trip packing list', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Insert a template with one category and two items directly
const templateResult = testDb.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run('Camping', user.id);
const templateId = templateResult.lastInsertRowid as number;
const catResult = testDb.prepare('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)').run(templateId, 'Gear', 0);
const catId = catResult.lastInsertRowid as number;
testDb.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, 'Tent', 0);
testDb.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, 'Sleeping Bag', 1);
const result = applyTemplate(trip.id, templateId);
expect(result).not.toBeNull();
expect(Array.isArray(result)).toBe(true);
expect((result as any[]).length).toBe(2);
const items = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(trip.id) as any[];
expect(items.length).toBe(2);
expect(items.map((i: any) => i.name)).toContain('Tent');
expect(items.map((i: any) => i.name)).toContain('Sleeping Bag');
});
it('PACK-SVC-004: returns null when template has no items', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateResult = testDb.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run('Empty Template', user.id);
const templateId = templateResult.lastInsertRowid as number;
const result = applyTemplate(trip.id, templateId);
expect(result).toBeNull();
});
// #1565: the applied items must land in the view the user is on, not always Common.
it('PACK-SVC-046: applies into the personal list when visibility is personal', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateId = seedTemplate(user.id, ['Tent']);
const result = applyTemplate(trip.id, templateId, 'personal', user.id) as any[];
expect(result[0].is_private).toBe(1);
expect(result[0].owner_id).toBe(user.id);
expect(listItems(trip.id, user.id).filter((i: any) => i.is_private)).toHaveLength(1);
});
it('PACK-SVC-047: a personally applied template stays hidden from other members', () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb, { username: 'other' });
const trip = createTrip(testDb, user.id);
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(trip.id, other.id);
const templateId = seedTemplate(user.id, ['Tent']);
applyTemplate(trip.id, templateId, 'personal', user.id);
expect(listItems(trip.id, other.id)).toHaveLength(0);
});
it('PACK-SVC-048: applies into the common pool by default, leaving items unowned', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateId = seedTemplate(user.id, ['Tent']);
const result = applyTemplate(trip.id, templateId, 'common', user.id) as any[];
expect(result[0].is_private).toBe(0);
// Unowned, so any member may still re-share it (setItemSharing claims a null owner).
expect(result[0].owner_id).toBeNull();
});
it('PACK-SVC-049: falls back to common when no owner is given, so items stay visible', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateId = seedTemplate(user.id, ['Tent']);
// A private item with no owner would be invisible to everyone.
const result = applyTemplate(trip.id, templateId, 'personal') as any[];
expect(result[0].is_private).toBe(0);
expect(listItems(trip.id, user.id)).toHaveLength(1);
});
});
// ── createBag / deleteBag ─────────────────────────────────────────────────────
describe('createBag / deleteBag', () => {
it('PACK-SVC-005: createBag inserts a bag and returns it', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = createBag(trip.id, { name: 'Carry-On', color: '#ff0000' }) as any;
expect(result).not.toBeNull();
expect(result.name).toBe('Carry-On');
expect(result.color).toBe('#ff0000');
expect(result.trip_id).toBe(trip.id);
const bag = testDb.prepare('SELECT * FROM packing_bags WHERE id = ?').get(result.id) as any;
expect(bag).toBeDefined();
expect(bag.name).toBe('Carry-On');
});
it('PACK-SVC-006: deleteBag removes the bag and returns true', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const bag = createBag(trip.id, { name: 'Checked Bag' }) as any;
expect(bag).not.toBeNull();
const deleted = deleteBag(trip.id, bag.id);
expect(deleted).toBe(true);
const row = testDb.prepare('SELECT * FROM packing_bags WHERE id = ?').get(bag.id);
expect(row).toBeUndefined();
});
it('PACK-SVC-007: deleteBag returns false for non-existent bag', () => {
const result = deleteBag(1, 99999);
expect(result).toBe(false);
});
});
// ── setBagMembers ─────────────────────────────────────────────────────────────
describe('setBagMembers', () => {
it('PACK-SVC-008: sets bag members (replaces existing)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const bag = createBag(trip.id, { name: 'Main Bag' }) as any;
const result = setBagMembers(trip.id, bag.id, [user.id]) as any[];
expect(result).not.toBeNull();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBe(1);
expect(result[0].user_id).toBe(user.id);
});
it('PACK-SVC-009: setBagMembers with empty array clears all members', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const bag = createBag(trip.id, { name: 'Main Bag' }) as any;
// First add a member
setBagMembers(trip.id, bag.id, [user.id]);
// Then clear
const result = setBagMembers(trip.id, bag.id, []) as any[];
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBe(0);
});
it('PACK-SVC-010: setBagMembers returns null for non-existent bag', () => {
const result = setBagMembers(1, 99999, []);
expect(result).toBeNull();
});
it('PACK-SVC-010a: setBagMembers drops a user who is not on the trip roster', () => {
const { user } = createUser(testDb);
const outsider = createUser(testDb).user;
const trip = createTrip(testDb, user.id);
const bag = createBag(trip.id, { name: 'Main Bag' }) as any;
// owner is on the roster; the outsider (not owner, not a member) must be filtered out
const result = setBagMembers(trip.id, bag.id, [user.id, outsider.id]) as any[];
const ids = result.map((m) => m.user_id);
expect(ids).toContain(user.id);
expect(ids).not.toContain(outsider.id);
});
it('PACK-SVC-010b: updateBag ignores an off-roster user_id, leaving the bag unassigned', () => {
const { user } = createUser(testDb);
const outsider = createUser(testDb).user;
const trip = createTrip(testDb, user.id);
const bag = createBag(trip.id, { name: 'Main Bag' }) as any;
// assigning to an outsider must not stick — the CASE keeps user_id null
updateBag(trip.id, bag.id, { user_id: outsider.id }, ['user_id']);
const stored = testDb.prepare('SELECT user_id FROM packing_bags WHERE id = ?').get(bag.id) as { user_id: number | null };
expect(stored.user_id).toBeNull();
// assigning to the owner (on the roster) does stick
updateBag(trip.id, bag.id, { user_id: user.id }, ['user_id']);
const stored2 = testDb.prepare('SELECT user_id FROM packing_bags WHERE id = ?').get(bag.id) as { user_id: number | null };
expect(stored2.user_id).toBe(user.id);
});
});
// ── bulkImport with bag field ─────────────────────────────────────────────────
describe('bulkImport with bag field', () => {
it('PACK-SVC-011: bulk import with bag field creates the bag if it does not exist', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = bulkImport(trip.id, [{ name: 'Shirt', bag: 'Carry-On' }]);
expect(result).toHaveLength(1);
expect(result[0]).toBeDefined();
const bags = testDb.prepare('SELECT * FROM packing_bags WHERE trip_id = ? AND name = ?').all(trip.id, 'Carry-On') as any[];
expect(bags).toHaveLength(1);
const items = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(trip.id) as any[];
expect(items).toHaveLength(1);
expect(items[0].bag_id).toBe(bags[0].id);
});
it('PACK-SVC-012: bulk import with same bag name reuses existing bag', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = bulkImport(trip.id, [
{ name: 'Shirt', bag: 'Carry-On' },
{ name: 'Pants', bag: 'Carry-On' },
]);
expect(result).toHaveLength(2);
const bags = testDb.prepare('SELECT * FROM packing_bags WHERE trip_id = ? AND name = ?').all(trip.id, 'Carry-On') as any[];
expect(bags).toHaveLength(1);
const items = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(trip.id) as any[];
expect(items).toHaveLength(2);
expect(items[0].bag_id).toBe(bags[0].id);
expect(items[1].bag_id).toBe(bags[0].id);
});
});
// ── bulkImport with quantity field ────────────────────────────────────────────
describe('bulkImport with quantity field', () => {
it('PACK-SVC-013: bulk import respects per-item quantity, defaults to 1, and clamps out-of-range', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
bulkImport(trip.id, [
{ name: 'Socks', quantity: 5 },
{ name: 'Toothbrush' },
{ name: 'Batteries', quantity: 9999 },
{ name: 'Charger', quantity: 0 },
]);
const byName = (n: string) =>
testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ? AND name = ?').get(trip.id, n) as any;
expect(byName('Socks').quantity).toBe(5);
expect(byName('Toothbrush').quantity).toBe(1);
expect(byName('Batteries').quantity).toBe(999);
expect(byName('Charger').quantity).toBe(1);
});
});
// ── Private items (#858) ──────────────────────────────────────────────────────
describe('private items (#858)', () => {
it('PACK-SVC-014: createItem stamps the owner and is_private flag', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const shared = createItem(trip.id, { name: 'Tent' }, user.id) as any;
const secret = createItem(trip.id, { name: 'Gift', is_private: true }, user.id) as any;
expect(shared.is_private).toBe(0);
expect(shared.owner_id).toBe(user.id);
expect(secret.is_private).toBe(1);
expect(secret.owner_id).toBe(user.id);
});
it('PACK-SVC-015: listItems hides another member\'s private items but shows the owner theirs', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
createItem(trip.id, { name: 'Shared' }, owner.id);
createItem(trip.id, { name: 'Private', is_private: true }, owner.id);
const ownerView = listItems(trip.id, owner.id) as any[];
const otherView = listItems(trip.id, other.id) as any[];
const unscoped = listItems(trip.id) as any[];
expect(ownerView.map(i => i.name).sort()).toEqual(['Private', 'Shared']);
expect(otherView.map(i => i.name)).toEqual(['Shared']);
// Without a viewer (internal callers) nothing is filtered.
expect(unscoped).toHaveLength(2);
});
it('PACK-SVC-016: updateItem toggles privacy and claims an unowned item for the actor', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Legacy-style row with no owner.
const id = Number((testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, sort_order) VALUES (?, ?, 0, 0)').run(trip.id, 'Legacy') as any).lastInsertRowid);
const updated = updateItem(trip.id, id, { is_private: true }, ['is_private'], undefined, user.id) as any;
expect(updated.is_private).toBe(1);
expect(updated.owner_id).toBe(user.id);
const back = updateItem(trip.id, id, { is_private: false }, ['is_private'], undefined, user.id) as any;
expect(back.is_private).toBe(0);
// Ownership is retained once claimed.
expect(back.owner_id).toBe(user.id);
});
it('PACK-SVC-017: deleteItem returns the removed row (with privacy fields)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Private', is_private: true }, user.id) as any;
const deleted = deleteItem(trip.id, item.id) as any;
expect(deleted).not.toBeNull();
expect(deleted.is_private).toBe(1);
expect(deleted.owner_id).toBe(user.id);
expect(deleteItem(trip.id, item.id)).toBeNull();
});
it('PACK-SVC-018: bulkImport stamps the owner on every item', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
bulkImport(trip.id, [{ name: 'A' }, { name: 'B', is_private: true }], user.id);
const rows = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ? ORDER BY name').all(trip.id) as any[];
expect(rows.every(r => r.owner_id === user.id)).toBe(true);
expect(rows.find(r => r.name === 'B').is_private).toBe(1);
expect(rows.find(r => r.name === 'A').is_private).toBe(0);
});
});
// ── Three-tier sharing (#858 follow-up) ───────────────────────────────────────
describe('three-tier packing sharing (#858)', () => {
const names = (rows: any[]) => rows.map(r => r.name).sort();
it('PACK-SVC-040: existing/common items are visible to everyone (non-breaking)', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
// A legacy-style row written directly (is_private defaults 0) = Common.
testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, sort_order) VALUES (?, ?, 0, 0)').run(trip.id, 'Tent');
createItem(trip.id, { name: 'Stove', visibility: 'common' }, owner.id);
expect(names(listItems(trip.id, owner.id) as any[])).toEqual(['Stove', 'Tent']);
expect(names(listItems(trip.id, other.id) as any[])).toEqual(['Stove', 'Tent']);
});
it('PACK-SVC-041: a Shared item is visible to its owner + recipients only, marked with the bringer', () => {
const { user: owner } = createUser(testDb);
const { user: friend } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const item = createItem(trip.id, { name: 'Power bank', visibility: 'shared', recipient_ids: [friend.id] }, owner.id) as any;
expect(item.is_private).toBe(1);
expect(item.owner_username).toBe(owner.username);
expect(item.recipients.map((r: any) => r.user_id)).toEqual([friend.id]);
expect(names(listItems(trip.id, owner.id) as any[])).toEqual(['Power bank']); // bringer
expect(names(listItems(trip.id, friend.id) as any[])).toEqual(['Power bank']); // covered person
expect(names(listItems(trip.id, stranger.id) as any[])).toEqual([]); // nobody else
});
it('PACK-SVC-042: a Personal item is visible only to its owner', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
createItem(trip.id, { name: 'Diary', visibility: 'personal' }, owner.id);
expect(names(listItems(trip.id, owner.id) as any[])).toEqual(['Diary']);
expect(names(listItems(trip.id, other.id) as any[])).toEqual([]);
});
it('PACK-SVC-043: setItemSharing changes the tier + recipients; only the owner may', () => {
const { user: owner } = createUser(testDb);
const { user: friend } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const item = createItem(trip.id, { name: 'First aid', visibility: 'personal' }, owner.id) as any;
// A non-owner is rejected.
expect((setItemSharing(trip.id, item.id, friend.id, 'shared', [friend.id]) as any).forbidden).toBe(true);
const updated = setItemSharing(trip.id, item.id, owner.id, 'shared', [friend.id]) as any;
expect(updated.recipients.map((r: any) => r.user_id)).toEqual([friend.id]);
expect(names(listItems(trip.id, friend.id) as any[])).toEqual(['First aid']);
// Back to common → visible to everyone, recipients cleared.
setItemSharing(trip.id, item.id, owner.id, 'common', []);
const { user: stranger } = createUser(testDb);
expect(names(listItems(trip.id, stranger.id) as any[])).toEqual(['First aid']);
});
it('PACK-SVC-044: contributors ("I can bring that too") only attach to Common items', () => {
const { user: owner } = createUser(testDb);
const { user: helper } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const common = createItem(trip.id, { name: 'Sunscreen', visibility: 'common' }, owner.id) as any;
const personal = createItem(trip.id, { name: 'Meds', visibility: 'personal' }, owner.id) as any;
const withHelper = addContributor(trip.id, common.id, helper.id) as any;
expect(withHelper.contributors.map((c: any) => c.user_id)).toEqual([helper.id]);
// The bringer can't co-contribute to their own item, and personal items have no pool.
expect(addContributor(trip.id, common.id, owner.id)).toBeNull();
expect(addContributor(trip.id, personal.id, helper.id)).toBeNull();
const cleared = removeContributor(trip.id, common.id, helper.id) as any;
expect(cleared.contributors).toEqual([]);
});
it('PACK-SVC-045: cloneItem copies an item onto the cloner\'s personal list', () => {
const { user: owner } = createUser(testDb);
const { user: cloner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const common = createItem(trip.id, { name: 'Travel adapter', category: 'Electronics', visibility: 'common' }, owner.id) as any;
const clone = cloneItem(trip.id, common.id, cloner.id) as any;
expect(clone.name).toBe('Travel adapter');
expect(clone.category).toBe('Electronics');
expect(clone.is_private).toBe(1);
expect(clone.owner_id).toBe(cloner.id);
// The clone is the cloner's alone.
expect(names(listItems(trip.id, owner.id) as any[])).toEqual(['Travel adapter']); // owner sees only the common one
expect(names(listItems(trip.id, cloner.id) as any[])).toEqual(['Travel adapter', 'Travel adapter']); // common + own clone
});
});
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { validatePassword } from '../../../src/services/passwordPolicy';
import { validatePassword } from '../../../src/nest/common/passwordPolicy';
describe('validatePassword', () => {
// AUTH-006 — Registration with weak password
@@ -1,114 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
// Mutable rows array so individual tests can inject DB rows
const dbRows: { key: string; value: string }[] = [];
// Mock database — permissions module queries app_settings at runtime
vi.mock('../../../src/db/database', () => ({
db: {
prepare: () => ({
all: () => dbRows, // no custom permissions → fall back to defaults
run: vi.fn(),
get: vi.fn(),
}),
transaction: (fn: () => void) => fn,
},
}));
import { checkPermission, getPermissionLevel, savePermissions, invalidatePermissionsCache, PERMISSION_ACTIONS } from '../../../src/services/permissions';
describe('permissions', () => {
describe('checkPermission — admin bypass', () => {
it('admin always passes regardless of permission level', () => {
for (const action of PERMISSION_ACTIONS) {
expect(checkPermission(action.key, 'admin', 1, 1, false)).toBe(true);
expect(checkPermission(action.key, 'admin', 99, 1, false)).toBe(true);
}
});
});
describe('checkPermission — everybody level', () => {
it('trip_create (everybody) allows any authenticated user', () => {
expect(checkPermission('trip_create', 'user', null, 42, false)).toBe(true);
});
});
describe('checkPermission — trip_owner level', () => {
const ownerId = 10;
const memberId = 20;
it('trip owner passes trip_owner check', () => {
expect(checkPermission('trip_delete', 'user', ownerId, ownerId, false)).toBe(true);
});
it('member fails trip_owner check', () => {
expect(checkPermission('trip_delete', 'user', ownerId, memberId, true)).toBe(false);
});
it('non-member non-owner fails trip_owner check', () => {
expect(checkPermission('trip_delete', 'user', ownerId, memberId, false)).toBe(false);
});
});
describe('checkPermission — trip_member level', () => {
const ownerId = 10;
const memberId = 20;
const outsiderId = 30;
it('trip owner passes trip_member check', () => {
expect(checkPermission('day_edit', 'user', ownerId, ownerId, false)).toBe(true);
});
it('trip member passes trip_member check', () => {
expect(checkPermission('day_edit', 'user', ownerId, memberId, true)).toBe(true);
});
it('outsider fails trip_member check', () => {
expect(checkPermission('day_edit', 'user', ownerId, outsiderId, false)).toBe(false);
});
});
describe('getPermissionLevel — defaults', () => {
it('returns default level for known actions (no DB overrides)', () => {
const defaults: Record<string, string> = {
trip_create: 'everybody',
trip_delete: 'trip_owner',
day_edit: 'trip_member',
budget_edit: 'trip_member',
};
for (const [key, expected] of Object.entries(defaults)) {
expect(getPermissionLevel(key)).toBe(expected);
}
});
it('returns trip_owner for unknown action key', () => {
expect(getPermissionLevel('nonexistent_action')).toBe('trip_owner');
});
});
describe('savePermissions — invalid action key is skipped', () => {
it('returns skipped array containing invalid action key', () => {
const result = savePermissions({ nonexistent_action: 'trip_member' });
expect(result.skipped).toContain('nonexistent_action');
});
it('returns skipped array when level is not in allowedLevels for the action', () => {
// trip_delete only allows ['admin', 'trip_owner'], so 'trip_member' is invalid
const result = savePermissions({ trip_delete: 'trip_member' });
expect(result.skipped).toContain('trip_delete');
});
});
describe('checkPermission — default case', () => {
it('returns false when permission level is an unrecognized value', () => {
// Inject a DB row with an unknown level for trip_edit, then invalidate cache
dbRows.push({ key: 'perm_trip_edit', value: 'unknown_level' });
invalidatePermissionsCache();
const result = checkPermission('trip_edit', 'user', 10, 10, false);
// Clean up for subsequent tests
dbRows.length = 0;
invalidatePermissionsCache();
expect(result).toBe(false);
});
});
});
@@ -1,49 +0,0 @@
/**
* Unit tests for the import-enrichment match selector (#886).
* Covers PENRICH-001 to PENRICH-004 — the coordinate-validation guard that
* prevents a name search from overwriting an imported place with the wrong POI.
*/
import { describe, it, expect, vi } from 'vitest';
// placeEnrichment pulls in the DB, websocket and maps service at import time;
// stub them so the pure match selector can be tested in isolation.
vi.mock('../../../src/db/database', () => ({ db: {}, getPlaceWithTags: () => null }));
vi.mock('../../../src/websocket', () => ({ broadcast: () => {} }));
vi.mock('../../../src/services/mapsService', () => ({
getMapsKey: () => null,
searchPlaces: async () => ({ places: [], source: 'none' }),
getPlacePhoto: async () => ({ photoUrl: '', attribution: null }),
}));
import { pickEnrichmentMatch } from '../../../src/services/placeEnrichment';
const target = { lat: 48.85, lng: 2.35 };
describe('pickEnrichmentMatch', () => {
it('PENRICH-001: picks the closest Google candidate within the radius', () => {
const candidates = [
{ google_place_id: 'far', lat: 48.8512, lng: 2.3512 }, // ~170 m
{ google_place_id: 'near', lat: 48.85, lng: 2.35 }, // exact
];
const match = pickEnrichmentMatch(candidates, target);
expect(match?.google_place_id).toBe('near');
});
it('PENRICH-002: returns null when every candidate is beyond the radius', () => {
const candidates = [{ google_place_id: 'A', lat: 48.86, lng: 2.36 }]; // ~1.2 km
expect(pickEnrichmentMatch(candidates, target)).toBeNull();
});
it('PENRICH-003: ignores candidates without a google_place_id (e.g. OSM results)', () => {
const candidates = [
{ google_place_id: null, lat: 48.85, lng: 2.35 },
{ name: 'no id', lat: 48.85, lng: 2.35 },
];
expect(pickEnrichmentMatch(candidates, target)).toBeNull();
});
it('PENRICH-004: ignores candidates with non-numeric coordinates', () => {
const candidates = [{ google_place_id: 'A', lat: 'x', lng: 'y' }];
expect(pickEnrichmentMatch(candidates as never, target)).toBeNull();
});
});
@@ -1,158 +0,0 @@
/**
* Unit tests for placePhotoCache — PPC-001 through PPC-010.
* Covers the downscale guard in put(), removeIfUnreferenced(), and sweepOrphans().
* Uses a real in-memory SQLite DB and a throwaway temp upload dir
* (TREK_PLACE_PHOTO_DIR) so the real uploads tree is never touched.
*/
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
import path from 'node:path';
import fs from 'node:fs';
import os from 'node:os';
import crypto from 'node:crypto';
import { Jimp, JimpMime } from 'jimp';
import Database from 'better-sqlite3';
// Throwaway upload dir — set before importing the module under test (it reads the
// env at load time and mkdirs the dir).
const TMP_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'ppc-'));
process.env.TREK_PLACE_PHOTO_DIR = TMP_DIR;
// Minimal real DB with just the tables placePhotoCache touches. isReferenced now
// UNIONs collection_places (#1081 photo-cache fix), so the bare fixture must
// declare it too or the reference check would throw "no such table".
const testDb = new Database(':memory:');
testDb.exec(`
CREATE TABLE places (
id INTEGER PRIMARY KEY AUTOINCREMENT,
google_place_id TEXT,
image_url TEXT
);
CREATE TABLE collection_places (
id INTEGER PRIMARY KEY AUTOINCREMENT,
google_place_id TEXT,
image_url TEXT
);
CREATE TABLE google_place_photo_meta (
place_id TEXT PRIMARY KEY,
attribution TEXT,
fetched_at INTEGER NOT NULL,
error_at INTEGER
);
`);
vi.mock('../../../src/db/database', () => ({ db: testDb }));
function filePathFor(placeId: string): string {
const hash = crypto.createHash('sha1').update(placeId).digest('hex');
return path.join(TMP_DIR, `${hash}.jpg`);
}
async function makeJpeg(width: number, height: number): Promise<Buffer> {
const img = new Jimp({ width, height, color: 0xff0000ff });
return img.getBuffer(JimpMime.jpeg, { quality: 80 });
}
let cache: typeof import('../../../src/services/placePhotoCache');
beforeAll(async () => {
cache = await import('../../../src/services/placePhotoCache');
});
beforeEach(() => {
testDb.exec('DELETE FROM places; DELETE FROM google_place_photo_meta;');
for (const f of fs.readdirSync(TMP_DIR)) fs.rmSync(path.join(TMP_DIR, f), { force: true });
});
afterAll(() => {
testDb.close();
fs.rmSync(TMP_DIR, { recursive: true, force: true });
});
describe('placePhotoCache.put() downscale guard', () => {
it('PPC-001: downscales an oversized image to <= 800px', async () => {
const big = await makeJpeg(1600, 1200);
await cache.put('big-place', big, 'Alice');
const written = fs.readFileSync(filePathFor('big-place'));
const decoded = await Jimp.read(written);
expect(Math.max(decoded.bitmap.width, decoded.bitmap.height)).toBeLessThanOrEqual(800);
expect(written.length).toBeLessThan(big.length);
});
it('PPC-002: passes a small image through unchanged', async () => {
const small = await makeJpeg(100, 100);
await cache.put('small-place', small, null);
const written = fs.readFileSync(filePathFor('small-place'));
expect(written.equals(small)).toBe(true);
});
it('PPC-003: falls back to original bytes when the input is not a decodable image', async () => {
const garbage = Buffer.from('definitely not an image');
await cache.put('garbage-place', garbage, null);
const written = fs.readFileSync(filePathFor('garbage-place'));
expect(written.equals(garbage)).toBe(true);
});
});
describe('placePhotoCache.removeIfUnreferenced()', () => {
it('PPC-004: removes a cache entry that no place references', async () => {
await cache.put('orphan', await makeJpeg(50, 50), null);
expect(fs.existsSync(filePathFor('orphan'))).toBe(true);
cache.removeIfUnreferenced('orphan');
expect(fs.existsSync(filePathFor('orphan'))).toBe(false);
expect(testDb.prepare('SELECT 1 FROM google_place_photo_meta WHERE place_id = ?').get('orphan')).toBeUndefined();
});
it('PPC-005: keeps an entry still referenced by google_place_id', async () => {
await cache.put('gid-1', await makeJpeg(50, 50), null);
testDb.prepare('INSERT INTO places (google_place_id) VALUES (?)').run('gid-1');
cache.removeIfUnreferenced('gid-1');
expect(fs.existsSync(filePathFor('gid-1'))).toBe(true);
});
it('PPC-006: keeps an entry referenced by a coords proxy URL in image_url', async () => {
const id = 'coords:48.8:2.3';
await cache.put(id, await makeJpeg(50, 50), null);
const proxy = `/api/maps/place-photo/${encodeURIComponent(id)}/bytes`;
testDb.prepare('INSERT INTO places (image_url) VALUES (?)').run(proxy);
cache.removeIfUnreferenced(id);
expect(fs.existsSync(filePathFor(id))).toBe(true);
});
});
describe('placePhotoCache.sweepOrphans()', () => {
it('PPC-007: removes orphaned meta rows + files, keeps referenced ones, deletes stray files', async () => {
await cache.put('keep-gid', await makeJpeg(50, 50), null);
await cache.put('drop-me', await makeJpeg(50, 50), null);
testDb.prepare('INSERT INTO places (google_place_id) VALUES (?)').run('keep-gid');
// A stray .jpg on disk with no meta row (e.g. a crash between write and upsert).
const strayPath = path.join(TMP_DIR, 'deadbeef'.padEnd(40, '0') + '.jpg');
fs.writeFileSync(strayPath, 'stray');
const removed = cache.sweepOrphans();
expect(fs.existsSync(filePathFor('keep-gid'))).toBe(true);
expect(fs.existsSync(filePathFor('drop-me'))).toBe(false);
expect(fs.existsSync(strayPath)).toBe(false);
expect(testDb.prepare('SELECT 1 FROM google_place_photo_meta WHERE place_id = ?').get('drop-me')).toBeUndefined();
expect(testDb.prepare('SELECT 1 FROM google_place_photo_meta WHERE place_id = ?').get('keep-gid')).toBeDefined();
expect(removed).toBe(2); // drop-me (orphan meta+file) + stray file
});
it('PPC-008: returns 0 when every entry is referenced', async () => {
await cache.put('ref-a', await makeJpeg(50, 50), null);
testDb.prepare('INSERT INTO places (google_place_id) VALUES (?)').run('ref-a');
expect(cache.sweepOrphans()).toBe(0);
expect(fs.existsSync(filePathFor('ref-a'))).toBe(true);
});
});
@@ -1,699 +0,0 @@
/**
* Unit tests for placeService — PLACE-SVC-001 through PLACE-SVC-025.
* Uses a real in-memory SQLite DB so SQL logic is exercised faithfully.
* External fetches are mocked where needed.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: (placeId: any) => {
const place: any = db.prepare(`
SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
FROM places p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?
`).get(placeId);
if (!place) return null;
const tags = db.prepare(`SELECT t.* FROM tags t JOIN place_tags pt ON t.id = pt.tag_id WHERE pt.place_id = ?`).all(placeId);
return { ...place, category: place.category_id ? { id: place.category_id, name: place.category_name, color: place.category_color, icon: place.category_icon } : null, tags };
},
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
isOwner: (tripId: any, userId: number) =>
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
// Spy on the photo-cache reclaim hook so delete tests assert the wiring without
// touching disk. The removal logic itself is covered in placePhotoCache.test.ts.
const { removeIfUnreferencedSpy } = vi.hoisted(() => ({ removeIfUnreferencedSpy: vi.fn() }));
vi.mock('../../../src/services/placePhotoCache', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/services/placePhotoCache')>()),
removeIfUnreferenced: removeIfUnreferencedSpy,
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createPlace, createCategory, createTag } from '../../helpers/factories';
import path from 'path';
import fs from 'fs';
import { listPlaces, createPlace as svcCreatePlace, getPlace, updatePlace, updatePlacesMany, deletePlace, importGpx, importKmlPlaces, importGoogleList, searchPlaceImage } from '../../../src/services/placeService';
const GPX_FIXTURE = path.join(__dirname, '../../fixtures/test.gpx');
const KML_FIXTURE = path.join(__dirname, '../../fixtures/test.kml');
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ── listPlaces ────────────────────────────────────────────────────────────────
describe('listPlaces', () => {
it('PLACE-SVC-001 — returns empty array when trip has no places', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(listPlaces(String(trip.id), {})).toEqual([]);
});
it('PLACE-SVC-002 — returns all places for a trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPlace(testDb, trip.id, { name: 'Alpha' });
createPlace(testDb, trip.id, { name: 'Beta' });
const places = listPlaces(String(trip.id), {}) as any[];
expect(places).toHaveLength(2);
});
it('PLACE-SVC-003 — does not return places from other trips', () => {
const { user } = createUser(testDb);
const t1 = createTrip(testDb, user.id);
const t2 = createTrip(testDb, user.id);
createPlace(testDb, t1.id, { name: 'T1 Place' });
createPlace(testDb, t2.id, { name: 'T2 Place' });
const places = listPlaces(String(t1.id), {}) as any[];
expect(places).toHaveLength(1);
expect(places[0].name).toBe('T1 Place');
});
it('PLACE-SVC-004 — filters by search term (name)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
createPlace(testDb, trip.id, { name: 'Louvre Museum' });
const places = listPlaces(String(trip.id), { search: 'Eiffel' }) as any[];
expect(places).toHaveLength(1);
expect(places[0].name).toBe('Eiffel Tower');
});
it('PLACE-SVC-005 — attaches tags array to each place (empty when none)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPlace(testDb, trip.id, { name: 'No Tags' });
const places = listPlaces(String(trip.id), {}) as any[];
expect(Array.isArray(places[0].tags)).toBe(true);
expect(places[0].tags).toHaveLength(0);
});
it('PLACE-SVC-006 — attaches category object when place has a category', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const cat = createCategory(testDb, { name: 'Museum', user_id: user.id }) as any;
const place = createPlace(testDb, trip.id, { name: 'Art Museum' }) as any;
testDb.prepare('UPDATE places SET category_id = ? WHERE id = ?').run(cat.id, place.id);
const places = listPlaces(String(trip.id), {}) as any[];
expect(places[0].category).toBeDefined();
expect(places[0].category.name).toBe('Museum');
});
});
// ── createPlace (via service) ─────────────────────────────────────────────────
describe('createPlace (service)', () => {
it('PLACE-SVC-007 — creates a place and returns it with tags array', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = svcCreatePlace(String(trip.id), { name: 'New Place', lat: 48.8, lng: 2.3 }) as any;
expect(place).toBeDefined();
expect(place.name).toBe('New Place');
expect(Array.isArray(place.tags)).toBe(true);
});
it('PLACE-SVC-008 — creates a place with tags', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const tag = createTag(testDb, user.id, { name: 'Highlight' }) as any;
const place = svcCreatePlace(String(trip.id), { name: 'Tagged Place', tags: [tag.id] }) as any;
expect(place.tags).toHaveLength(1);
expect(place.tags[0].id).toBe(tag.id);
});
it('PLACE-SVC-009 — place is associated with correct trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = svcCreatePlace(String(trip.id), { name: 'My Place' }) as any;
const row = testDb.prepare('SELECT trip_id FROM places WHERE id = ?').get(place.id) as any;
expect(row.trip_id).toBe(trip.id);
});
});
// ── getPlace ──────────────────────────────────────────────────────────────────
describe('getPlace', () => {
it('PLACE-SVC-010 — returns the place when tripId and placeId match', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Find Me' }) as any;
const found = getPlace(String(trip.id), String(place.id)) as any;
expect(found).toBeDefined();
expect(found.name).toBe('Find Me');
});
it('PLACE-SVC-011 — returns null when place belongs to different trip', () => {
const { user } = createUser(testDb);
const t1 = createTrip(testDb, user.id);
const t2 = createTrip(testDb, user.id);
const place = createPlace(testDb, t1.id, { name: 'T1 Place' }) as any;
expect(getPlace(String(t2.id), String(place.id))).toBeNull();
});
it('PLACE-SVC-012 — returns null for non-existent placeId', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(getPlace(String(trip.id), '99999')).toBeNull();
});
});
// ── updatePlace ───────────────────────────────────────────────────────────────
describe('updatePlace', () => {
it('PLACE-SVC-013 — updates place name and lat/lng', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Old', lat: 0, lng: 0 }) as any;
const updated = updatePlace(String(trip.id), String(place.id), { name: 'New', lat: 48.8, lng: 2.3 }) as any;
expect(updated.name).toBe('New');
expect(updated.lat).toBe(48.8);
expect(updated.lng).toBe(2.3);
});
it('PLACE-SVC-014 — returns null for non-existent place', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(updatePlace(String(trip.id), '99999', { name: 'Ghost' })).toBeNull();
});
it('PLACE-SVC-015 — updates tags (replaces old set)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const tag1 = createTag(testDb, user.id, { name: 'Old Tag' }) as any;
const tag2 = createTag(testDb, user.id, { name: 'New Tag' }) as any;
const place = svcCreatePlace(String(trip.id), { name: 'Taggable', tags: [tag1.id] }) as any;
const updated = updatePlace(String(trip.id), String(place.id), { tags: [tag2.id] }) as any;
expect(updated.tags).toHaveLength(1);
expect(updated.tags[0].id).toBe(tag2.id);
});
it('PLACE-SVC-016 — clears tags when tags: [] is passed', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const tag = createTag(testDb, user.id, { name: 'Temp' }) as any;
const place = svcCreatePlace(String(trip.id), { name: 'Untaggable', tags: [tag.id] }) as any;
const updated = updatePlace(String(trip.id), String(place.id), { tags: [] }) as any;
expect(updated.tags).toHaveLength(0);
});
});
// ── updatePlacesMany ────────────────────────────────────────────────────────────
describe('updatePlacesMany', () => {
it('PLACE-SVC-039 — applies the same fields to many places, preserving the rest', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const a = createPlace(testDb, trip.id, { name: 'A' }) as any;
const b = createPlace(testDb, trip.id, { name: 'B' }) as any;
const c = createPlace(testDb, trip.id, { name: 'C' }) as any;
const updated = updatePlacesMany(String(trip.id), [a.id, b.id, c.id], { notes: 'visited', transport_mode: 'walking' });
expect(updated).toHaveLength(3);
for (const p of updated) {
expect((p as any).notes).toBe('visited');
expect((p as any).transport_mode).toBe('walking');
}
// Only the provided fields change — names are untouched.
expect(updated.map(p => (p as any).name).sort()).toEqual(['A', 'B', 'C']);
});
it('PLACE-SVC-040 — skips ids that are not in the trip and reports the rest', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const mine = createPlace(testDb, trip.id, { name: 'Mine' }) as any;
const foreign = createPlace(testDb, other.id, { name: 'Foreign' }) as any;
const updated = updatePlacesMany(String(trip.id), [mine.id, foreign.id, 99999], { notes: 'tagged' });
expect(updated).toHaveLength(1);
expect((updated[0] as any).id).toBe(mine.id);
// The place from the other trip stays untouched.
expect((getPlace(String(other.id), String(foreign.id)) as any).notes).toBeNull();
});
it('PLACE-SVC-041 — returns [] for an empty id list', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(updatePlacesMany(String(trip.id), [], { notes: 'x' })).toEqual([]);
});
});
// ── deletePlace ───────────────────────────────────────────────────────────────
describe('deletePlace', () => {
it('PLACE-SVC-017 — deletes a place and returns true', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'To Delete' }) as any;
expect(deletePlace(String(trip.id), String(place.id))).toBe(true);
expect(getPlace(String(trip.id), String(place.id))).toBeNull();
});
it('PLACE-SVC-018 — returns false for non-existent place', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(deletePlace(String(trip.id), '99999')).toBe(false);
});
it('PLACE-SVC-019 — deleting one place does not remove others', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const p1 = createPlace(testDb, trip.id, { name: 'Keep' }) as any;
const p2 = createPlace(testDb, trip.id, { name: 'Remove' }) as any;
deletePlace(String(trip.id), String(p2.id));
const remaining = listPlaces(String(trip.id), {}) as any[];
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe(p1.id);
});
it('PLACE-SVC-019b — reclaims the photo cache for the deleted place', () => {
removeIfUnreferencedSpy.mockClear();
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'With Photo' }) as any;
testDb.prepare('UPDATE places SET google_place_id = ? WHERE id = ?').run('ChIJgid', place.id);
deletePlace(String(trip.id), String(place.id));
expect(removeIfUnreferencedSpy).toHaveBeenCalledWith('ChIJgid');
});
});
// ── importGpx ─────────────────────────────────────────────────────────────────
describe('importGpx', () => {
it('PLACE-SVC-020 — returns null when buffer has no <gpx> root', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = importGpx(String(trip.id), Buffer.from('<not-gpx/>'));
expect(result).toBeNull();
});
it('PLACE-SVC-021 — imports <wpt> waypoints as places', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<wpt lat="48.8566" lon="2.3522"><name>Paris</name></wpt>
<wpt lat="51.5074" lon="-0.1278"><name>London</name></wpt>
</gpx>`);
const result = importGpx(String(trip.id), gpx) as any;
expect(result.places).toHaveLength(2);
expect(result.places[0].name).toBe('Paris');
expect(result.places[1].name).toBe('London');
});
it('PLACE-SVC-022 — imports <rte> as a single polyline-place with routeGeometry', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<rte>
<name>My Route</name>
<rtept lat="48.8566" lon="2.3522"><name>Start</name></rtept>
<rtept lat="51.5074" lon="-0.1278"><name>End</name></rtept>
</rte>
</gpx>`);
const result = importGpx(String(trip.id), gpx) as any;
expect(result.places).toHaveLength(1);
expect(result.places[0].name).toBe('My Route');
expect(result.places[0].lat).toBe(48.8566);
expect(result.places[0].lng).toBe(2.3522);
expect(result.places[0].route_geometry).toBeTruthy();
const coords = JSON.parse(result.places[0].route_geometry);
expect(coords).toHaveLength(2);
});
it('PLACE-SVC-023 — imports <trk> track as a single place with routeGeometry', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<trk>
<name>My Track</name>
<trkseg>
<trkpt lat="48.8566" lon="2.3522"><ele>100</ele></trkpt>
<trkpt lat="48.8570" lon="2.3530"><ele>102</ele></trkpt>
</trkseg>
</trk>
</gpx>`);
const result = importGpx(String(trip.id), gpx) as any;
expect(result.places).toHaveLength(1);
expect(result.places[0].name).toBe('My Track');
const geometry = JSON.parse(result.places[0].route_geometry);
expect(Array.isArray(geometry)).toBe(true);
expect(geometry).toHaveLength(2);
});
it('PLACE-SVC-024 — <wpt> and <trk> together: waypoints plus track appended', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<wpt lat="48.8566" lon="2.3522"><name>POI</name></wpt>
<trk>
<name>Track</name>
<trkseg>
<trkpt lat="48.8566" lon="2.3522"></trkpt>
<trkpt lat="48.8570" lon="2.3530"></trkpt>
</trkseg>
</trk>
</gpx>`);
const result = importGpx(String(trip.id), gpx) as any;
// 1 wpt + 1 trk
expect(result.places).toHaveLength(2);
const trackPlace = result.places.find((p: any) => p.name === 'Track') as any;
expect(trackPlace).toBeDefined();
const geometry = JSON.parse(trackPlace.route_geometry);
expect(geometry).toHaveLength(2);
});
it('PLACE-SVC-025 — returns null when GPX has no usable elements', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1"></gpx>`);
const result = importGpx(String(trip.id), gpx);
expect(result).toBeNull();
});
it('PLACE-SVC-037 — multiple unnamed tracks in one file get distinct names instead of collapsing to one', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<trk><trkseg>
<trkpt lat="48.8566" lon="2.3522"></trkpt>
<trkpt lat="48.8570" lon="2.3530"></trkpt>
</trkseg></trk>
<trk><trkseg>
<trkpt lat="40.0000" lon="-3.0000"></trkpt>
<trkpt lat="40.1000" lon="-3.1000"></trkpt>
</trkseg></trk>
</gpx>`);
const result = importGpx(String(trip.id), gpx) as any;
expect(result.places).toHaveLength(2);
const names = result.places.map((p: any) => p.name);
expect(new Set(names).size).toBe(2);
});
it('PLACE-SVC-038 — unnamed tracks fall back to the source filename', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<trk><trkseg>
<trkpt lat="48.8566" lon="2.3522"></trkpt>
<trkpt lat="48.8570" lon="2.3530"></trkpt>
</trkseg></trk>
</gpx>`);
const result = importGpx(String(trip.id), gpx, { defaultName: 'morning-hike.gpx' }) as any;
expect(result.places).toHaveLength(1);
expect(result.places[0].name).toBe('morning-hike');
});
});
// ── importGoogleList ──────────────────────────────────────────────────────────
describe('importGoogleList', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('PLACE-SVC-026 — returns error when list ID cannot be extracted from URL', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = await importGoogleList(String(trip.id), 'https://example.com/no-id-here') as any;
expect(result.error).toMatch(/Could not extract list ID/);
expect(result.status).toBe(400);
});
it('PLACE-SVC-026b — a single-place link gives a guiding error instead of the generic one (#1304)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const url = 'https://www.google.com/maps/place/Eiffel+Tower/@48.8584,2.2945,17z/data=!3m1';
const result = await importGoogleList(String(trip.id), url) as any;
expect(result.status).toBe(400);
expect(result.error).toMatch(/single place/i);
});
it('PLACE-SVC-027 — returns error when Google Maps API responds with non-ok status', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, text: async () => '', status: 502 }));
const url = 'https://www.google.com/maps/placelists/list/ABC123DEF456';
const result = await importGoogleList(String(trip.id), url) as any;
expect(result.error).toMatch(/Failed to fetch list/);
expect(result.status).toBe(502);
});
it('PLACE-SVC-028 — imports places from a valid Google Maps list response', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const listPayload = [
[null, null, null, null, 'My Test List', null, null, null, [
[null, [null, null, null, null, null, [null, null, 48.8566, 2.3522]], 'Paris', null],
[null, [null, null, null, null, null, [null, null, 51.5074, -0.1278]], 'London', 'Great city'],
]],
];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => 'prefix\n' + JSON.stringify(listPayload),
}));
const url = 'https://www.google.com/maps/placelists/list/ABC123DEF456';
const result = await importGoogleList(String(trip.id), url) as any;
expect(result.listName).toBe('My Test List');
expect(result.places).toHaveLength(2);
expect(result.places[0].name).toBe('Paris');
expect(result.places[1].name).toBe('London');
});
it('PLACE-SVC-028b — stores a Google Maps ftid separately from google_place_id', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const listPayload = [
[null, null, null, null, 'My Test List', null, null, null, [
[null, [null, null, null, null, '878 Weber St N', [null, null, 43.5118527, -80.5542617], ['-8634542354666695567', '-8822026229683971437']], "St. Jacobs Farmers' Market"],
]],
];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => 'prefix\n' + JSON.stringify(listPayload),
}));
const url = 'https://www.google.com/maps/placelists/list/ABC123DEF456';
const result = await importGoogleList(String(trip.id), url) as any;
expect(result.places).toHaveLength(1);
expect(result.places[0].google_place_id).toBeNull();
expect(result.places[0].google_ftid).toBe('0x882bf179e806d471:0x8591dde29c821a93');
});
it('PLACE-SVC-028c — backfills google_ftid when re-import skips a duplicate', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const existing = createPlace(testDb, trip.id, {
name: "St. Jacobs Farmers' Market",
lat: 43.5118527,
lng: -80.5542617,
}) as any;
const listPayload = [
[null, null, null, null, 'My Test List', null, null, null, [
[null, [null, null, null, null, '878 Weber St N', [null, null, 43.5118527, -80.5542617], ['-8634542354666695567', '-8822026229683971437']], "St. Jacobs Farmers' Market"],
]],
];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => 'prefix\n' + JSON.stringify(listPayload),
}));
const url = 'https://www.google.com/maps/placelists/list/ABC123DEF456';
const result = await importGoogleList(String(trip.id), url) as any;
const row = testDb.prepare('SELECT google_place_id, google_ftid FROM places WHERE id = ?').get(existing.id) as any;
expect(result.places).toHaveLength(0);
expect(result.skipped).toBe(1);
expect(row.google_place_id).toBeNull();
expect(row.google_ftid).toBe('0x882bf179e806d471:0x8591dde29c821a93');
});
it('PLACE-SVC-029 — returns error when list items array is empty', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const listPayload = [[null, null, null, null, 'Empty List', null, null, null, []]];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => 'prefix\n' + JSON.stringify(listPayload),
}));
const url = 'https://www.google.com/maps/placelists/list/ABC123DEF456';
const result = await importGoogleList(String(trip.id), url) as any;
expect(result.error).toBeDefined();
expect(result.status).toBe(400);
});
});
// ── searchPlaceImage ──────────────────────────────────────────────────────────
describe('searchPlaceImage', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('PLACE-SVC-030 — returns 404 when place does not exist', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = await searchPlaceImage(String(trip.id), '99999', user.id) as any;
expect(result.error).toBeDefined();
expect(result.status).toBe(404);
});
it('PLACE-SVC-031 — searches Unsplash without a stored API key', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Eiffel Tower' }) as any;
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
results: [
{ id: 'photo1', urls: { regular: 'https://img.example.com/1', thumb: 'https://img.example.com/t1' }, description: 'Tower', user: { name: 'Photographer' }, links: { html: 'https://unsplash.com/1' } },
],
}),
status: 200,
}));
const result = await searchPlaceImage(String(trip.id), String(place.id), user.id) as any;
expect(result.photos).toHaveLength(1);
const [url] = (fetch as any).mock.calls[0];
expect(url).toContain('https://unsplash.com/napi/search/photos?');
expect(url).not.toContain('client_id=');
});
it('PLACE-SVC-032 — returns photos when Unsplash API responds successfully', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Eiffel Tower' }) as any;
const mockPhotos = [
{ id: 'photo1', urls: { regular: 'https://img.example.com/1', thumb: 'https://img.example.com/t1' }, description: 'Tower', user: { name: 'Photographer' }, links: { html: 'https://unsplash.com/1' } },
];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ results: mockPhotos }),
status: 200,
}));
const result = await searchPlaceImage(String(trip.id), String(place.id), user.id) as any;
expect(result.photos).toHaveLength(1);
expect(result.photos[0].id).toBe('photo1');
expect(result.photos[0].url).toBe('https://img.example.com/1');
expect(result.photos[0].photographer).toBe('Photographer');
});
});
// ── Import deduplication ──────────────────────────────────────────────────────
describe('importGpx deduplication', () => {
it('PLACE-SVC-033 — skips waypoints already in trip by name', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const buf = fs.readFileSync(GPX_FIXTURE);
// First import
const first = importGpx(String(trip.id), buf) as any;
expect(first.count).toBeGreaterThan(0);
// Second import — all names already present, nothing new created
const second = importGpx(String(trip.id), buf) as any;
expect(second.count).toBe(0);
expect(second.skipped).toBe(first.count);
// Total places in DB should equal first import count
const total = (listPlaces(String(trip.id), {}) as any[]).length;
expect(total).toBe(first.count);
});
it('PLACE-SVC-034 — imports new places while skipping existing ones', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const buf = fs.readFileSync(GPX_FIXTURE);
const first = importGpx(String(trip.id), buf) as any;
// Manually add a brand-new place so total > first.count
createPlace(testDb, trip.id, { name: 'Unique Extra Place', lat: 99, lng: 99 });
// Re-import: the fixture places are skipped, the extra place remains untouched
const second = importGpx(String(trip.id), buf) as any;
expect(second.count).toBe(0);
const total = (listPlaces(String(trip.id), {}) as any[]).length;
expect(total).toBe(first.count + 1);
});
});
describe('importKmlPlaces deduplication', () => {
it('PLACE-SVC-035 — skips placemarks already in trip by name', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const buf = fs.readFileSync(KML_FIXTURE);
const first = importKmlPlaces(String(trip.id), buf);
expect(first.count).toBeGreaterThan(0);
const second = importKmlPlaces(String(trip.id), buf);
expect(second.count).toBe(0);
expect(second.summary.skippedCount).toBeGreaterThanOrEqual(first.count);
expect(second.summary.warnings.some((w: string) => w.includes('skipped'))).toBe(true);
});
it('PLACE-SVC-036 — deduplicates within the same file (intra-batch)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Craft a KML with two placemarks sharing the same name
const kml = Buffer.from(`<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2"><Document>
<Placemark><name>Dupe Place</name><Point><coordinates>2.0,48.0,0</coordinates></Point></Placemark>
<Placemark><name>Dupe Place</name><Point><coordinates>2.1,48.1,0</coordinates></Point></Placemark>
</Document></kml>`);
const result = importKmlPlaces(String(trip.id), kml);
expect(result.count).toBe(1);
expect(result.summary.skippedCount).toBe(1);
});
});
@@ -1,94 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('../../../src/db/database', () => ({
db: { prepare: () => ({ all: () => [], get: vi.fn() }) },
}));
import { formatAssignmentWithPlace } from '../../../src/services/queryHelpers';
import type { AssignmentRow, Tag, Participant } from '../../../src/types';
function makeRow(overrides: Partial<AssignmentRow> = {}): AssignmentRow {
return {
id: 1,
day_id: 10,
place_id: 100,
order_index: 0,
notes: 'assignment note',
created_at: '2024-01-01T00:00:00Z',
place_name: 'Eiffel Tower',
place_description: 'Famous landmark',
lat: 48.8584,
lng: 2.2945,
address: 'Champ de Mars, Paris',
category_id: 5,
category_name: 'Sightseeing',
category_color: '#3b82f6',
category_icon: 'landmark',
price: 25.0,
place_currency: 'EUR',
place_time: '10:00',
end_time: '12:00',
duration_minutes: 120,
place_notes: 'Bring tickets',
image_url: 'https://example.com/img.jpg',
transport_mode: 'walk',
google_place_id: 'ChIJLU7jZClu5kcR4PcOOO6p3I0',
google_ftid: '0x47e66e2c94e34e2d:0x8ddca9ee380ef7e0',
website: 'https://eiffel-tower.com',
phone: '+33 1 2345 6789',
...overrides,
} as AssignmentRow;
}
const sampleTags: Partial<Tag>[] = [
{ id: 1, name: 'Must-see', color: '#ef4444' },
];
const sampleParticipants: Participant[] = [
{ user_id: 42, username: 'alice', avatar: null },
];
describe('formatAssignmentWithPlace', () => {
it('nests place fields correctly from flat row', () => {
const result = formatAssignmentWithPlace(makeRow(), [], []);
const { place } = result;
expect(place.id).toBe(100);
expect(place.name).toBe('Eiffel Tower');
expect(place.description).toBe('Famous landmark');
expect(place.lat).toBe(48.8584);
expect(place.lng).toBe(2.2945);
expect(place.address).toBe('Champ de Mars, Paris');
expect(place.price).toBe(25.0);
expect(place.currency).toBe('EUR');
expect(place.place_time).toBe('10:00');
expect(place.end_time).toBe('12:00');
expect(place.duration_minutes).toBe(120);
expect(place.notes).toBe('Bring tickets');
expect(place.image_url).toBe('https://example.com/img.jpg');
expect(place.transport_mode).toBe('walk');
expect(place.google_place_id).toBe('ChIJLU7jZClu5kcR4PcOOO6p3I0');
expect(place.google_ftid).toBe('0x47e66e2c94e34e2d:0x8ddca9ee380ef7e0');
expect(place.website).toBe('https://eiffel-tower.com');
expect(place.phone).toBe('+33 1 2345 6789');
});
it('constructs place.category object when category_id is present', () => {
const result = formatAssignmentWithPlace(makeRow(), [], []);
expect(result.place.category).toEqual({
id: 5,
name: 'Sightseeing',
color: '#3b82f6',
icon: 'landmark',
});
});
it('sets place.category to null when category_id is null', () => {
const result = formatAssignmentWithPlace(makeRow({ category_id: null as any }), [], []);
expect(result.place.category).toBeNull();
});
it('sets place.category to null when category_id is 0 (falsy)', () => {
const result = formatAssignmentWithPlace(makeRow({ category_id: 0 as any }), [], []);
expect(result.place.category).toBeNull();
});
});
@@ -1,224 +0,0 @@
/**
* Unit tests for settingsService — SET-SVC-001 through SET-SVC-020.
* Uses a real in-memory SQLite DB; apiKeyCrypto is mocked to a passthrough
* so we don't need real encryption for most tests.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB + apiKeyCrypto mock ────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
// Passthrough crypto — value comes back unchanged for most tests
vi.mock('../../../src/services/apiKeyCrypto', () => ({
maybe_encrypt_api_key: (v: string) => v,
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
import { getUserSettings, upsertSetting, bulkUpsertSettings } from '../../../src/services/settingsService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ── getUserSettings ───────────────────────────────────────────────────────────
describe('getUserSettings', () => {
it('SET-SVC-001 — returns empty object when user has no settings', () => {
const { user } = createUser(testDb);
expect(getUserSettings(user.id)).toEqual({});
});
it('SET-SVC-002 — returns stored plain string values', () => {
const { user } = createUser(testDb);
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'theme', 'dark')").run(user.id);
const s = getUserSettings(user.id);
expect(s.theme).toBe('dark');
});
it('SET-SVC-003 — JSON-parses values that are valid JSON', () => {
const { user } = createUser(testDb);
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'count', '42')").run(user.id);
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'flag', 'true')").run(user.id);
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'obj', '{\"x\":1}')").run(user.id);
const s = getUserSettings(user.id);
expect(s.count).toBe(42);
expect(s.flag).toBe(true);
expect(s.obj).toEqual({ x: 1 });
});
it('SET-SVC-004 — falls back to raw string when value is not valid JSON', () => {
const { user } = createUser(testDb);
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'raw', 'not-json')").run(user.id);
const s = getUserSettings(user.id);
expect(s.raw).toBe('not-json');
});
it('SET-SVC-005 — webhook_url with a value is masked as ••••••••', () => {
const { user } = createUser(testDb);
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'webhook_url', 'https://secret.example.com')").run(user.id);
const s = getUserSettings(user.id);
expect(s.webhook_url).toBe('••••••••');
});
it('SET-SVC-006 — webhook_url with empty value returns empty string', () => {
const { user } = createUser(testDb);
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'webhook_url', '')").run(user.id);
const s = getUserSettings(user.id);
expect(s.webhook_url).toBe('');
});
it('SET-SVC-007 — only returns settings for the requesting user', () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'key_a', '\"a\"')").run(a.id);
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'key_b', '\"b\"')").run(b.id);
const s = getUserSettings(a.id);
expect(s).toHaveProperty('key_a');
expect(s).not.toHaveProperty('key_b');
});
});
// ── upsertSetting ─────────────────────────────────────────────────────────────
describe('upsertSetting', () => {
it('SET-SVC-008 — inserts a new setting', () => {
const { user } = createUser(testDb);
upsertSetting(user.id, 'language', 'en');
const s = getUserSettings(user.id);
expect(s.language).toBe('en');
});
it('SET-SVC-009 — updates an existing setting (ON CONFLICT)', () => {
const { user } = createUser(testDb);
upsertSetting(user.id, 'language', 'en');
upsertSetting(user.id, 'language', 'fr');
const s = getUserSettings(user.id);
expect(s.language).toBe('fr');
});
it('SET-SVC-010 — serializes object values as JSON', () => {
const { user } = createUser(testDb);
upsertSetting(user.id, 'prefs', { dark: true, size: 14 });
const raw = testDb.prepare("SELECT value FROM settings WHERE user_id = ? AND key = 'prefs'").get(user.id) as any;
expect(raw.value).toBe('{"dark":true,"size":14}');
});
it('SET-SVC-011 — serializes boolean values as strings', () => {
const { user } = createUser(testDb);
upsertSetting(user.id, 'notifications', true);
const raw = testDb.prepare("SELECT value FROM settings WHERE user_id = ? AND key = 'notifications'").get(user.id) as any;
expect(raw.value).toBe('true');
});
it('SET-SVC-012 — webhook_url passes through maybe_encrypt_api_key', () => {
const { user } = createUser(testDb);
upsertSetting(user.id, 'webhook_url', 'https://hook.example.com');
// With passthrough mock, value is stored as-is
const raw = testDb.prepare("SELECT value FROM settings WHERE user_id = ? AND key = 'webhook_url'").get(user.id) as any;
expect(raw.value).toBe('https://hook.example.com');
// But getUserSettings masks it
const s = getUserSettings(user.id);
expect(s.webhook_url).toBe('••••••••');
});
});
// ── bulkUpsertSettings ────────────────────────────────────────────────────────
describe('bulkUpsertSettings', () => {
it('SET-SVC-013 — inserts multiple settings in one call', () => {
const { user } = createUser(testDb);
bulkUpsertSettings(user.id, { a: 'alpha', b: 'beta', c: 'gamma' });
const s = getUserSettings(user.id);
expect(s.a).toBe('alpha');
expect(s.b).toBe('beta');
expect(s.c).toBe('gamma');
});
it('SET-SVC-014 — returns the count of settings processed', () => {
const { user } = createUser(testDb);
const count = bulkUpsertSettings(user.id, { x: 1, y: 2, z: 3 });
expect(count).toBe(3);
});
it('SET-SVC-015 — updates existing keys (ON CONFLICT)', () => {
const { user } = createUser(testDb);
upsertSetting(user.id, 'theme', 'light');
bulkUpsertSettings(user.id, { theme: 'dark', lang: 'en' });
const s = getUserSettings(user.id);
expect(s.theme).toBe('dark');
expect(s.lang).toBe('en');
});
it('SET-SVC-016 — returns 0 for empty settings object', () => {
const { user } = createUser(testDb);
const count = bulkUpsertSettings(user.id, {});
expect(count).toBe(0);
});
it('SET-SVC-017 — all changes are committed atomically (transaction)', () => {
const { user } = createUser(testDb);
bulkUpsertSettings(user.id, { p: '1', q: '2' });
const rows = testDb.prepare('SELECT key FROM settings WHERE user_id = ?').all(user.id) as any[];
const keys = rows.map((r: any) => r.key);
expect(keys).toContain('p');
expect(keys).toContain('q');
});
it('SET-SVC-018 — settings from different users do not interfere', () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
bulkUpsertSettings(a.id, { shared_key: 'from-a' });
bulkUpsertSettings(b.id, { shared_key: 'from-b' });
expect((getUserSettings(a.id) as any).shared_key).toBe('from-a');
expect((getUserSettings(b.id) as any).shared_key).toBe('from-b');
});
it('SET-SVC-019 — rolls back and re-throws when DB write fails mid-transaction', () => {
const { user } = createUser(testDb);
const origPrepare = testDb.prepare.bind(testDb);
let intercepted = false;
vi.spyOn(testDb, 'prepare').mockImplementationOnce((sql: string) => {
const stmt = origPrepare(sql);
intercepted = true;
return { run: () => { throw new Error('forced DB error'); } } as any;
});
expect(() => bulkUpsertSettings(user.id, { k: 'v' })).toThrow('forced DB error');
expect(intercepted).toBe(true);
vi.restoreAllMocks();
});
});
@@ -1,180 +0,0 @@
/**
* Unit tests for tagService — TAG-SVC-001 through TAG-SVC-015.
* Uses a real in-memory SQLite DB so SQL logic is exercised faithfully.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
import { listTags, createTag, getTagByIdAndUser, updateTag, deleteTag } from '../../../src/services/tagService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ── listTags ──────────────────────────────────────────────────────────────────
describe('listTags', () => {
it('TAG-SVC-001 — returns empty array when user has no tags', () => {
const { user } = createUser(testDb);
expect(listTags(user.id)).toEqual([]);
});
it('TAG-SVC-002 — returns only tags belonging to the user', () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
createTag(a.id, 'A-Tag');
createTag(b.id, 'B-Tag');
const tags = listTags(a.id) as any[];
expect(tags).toHaveLength(1);
expect(tags[0].name).toBe('A-Tag');
});
it('TAG-SVC-003 — results are ordered by name ascending', () => {
const { user } = createUser(testDb);
createTag(user.id, 'Zebra');
createTag(user.id, 'Apple');
createTag(user.id, 'Mango');
const names = (listTags(user.id) as any[]).map((t: any) => t.name);
expect(names).toEqual(['Apple', 'Mango', 'Zebra']);
});
});
// ── createTag ─────────────────────────────────────────────────────────────────
describe('createTag', () => {
it('TAG-SVC-004 — creates a tag with provided name and color', () => {
const { user } = createUser(testDb);
const tag = createTag(user.id, 'Beach', '#ff0000') as any;
expect(tag.name).toBe('Beach');
expect(tag.color).toBe('#ff0000');
expect(tag.user_id).toBe(user.id);
});
it('TAG-SVC-005 — defaults to #10b981 when no color provided', () => {
const { user } = createUser(testDb);
const tag = createTag(user.id, 'Default') as any;
expect(tag.color).toBe('#10b981');
});
it('TAG-SVC-006 — returns the inserted row with an id', () => {
const { user } = createUser(testDb);
const tag = createTag(user.id, 'WithId') as any;
expect(typeof tag.id).toBe('number');
expect(tag.id).toBeGreaterThan(0);
});
});
// ── getTagByIdAndUser ─────────────────────────────────────────────────────────
describe('getTagByIdAndUser', () => {
it('TAG-SVC-007 — returns the tag when id and user_id match', () => {
const { user } = createUser(testDb);
const created = createTag(user.id, 'Find Me') as any;
const found = getTagByIdAndUser(created.id, user.id) as any;
expect(found).toBeDefined();
expect(found.name).toBe('Find Me');
});
it('TAG-SVC-008 — returns undefined when tag belongs to different user', () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
const tag = createTag(a.id, 'Private') as any;
expect(getTagByIdAndUser(tag.id, b.id)).toBeUndefined();
});
it('TAG-SVC-009 — returns undefined for non-existent tag id', () => {
const { user } = createUser(testDb);
expect(getTagByIdAndUser(99999, user.id)).toBeUndefined();
});
});
// ── updateTag ─────────────────────────────────────────────────────────────────
describe('updateTag', () => {
it('TAG-SVC-010 — updates both name and color', () => {
const { user } = createUser(testDb);
const tag = createTag(user.id, 'Old', '#aaaaaa') as any;
const updated = updateTag(tag.id, 'New', '#bbbbbb') as any;
expect(updated.name).toBe('New');
expect(updated.color).toBe('#bbbbbb');
});
it('TAG-SVC-011 — COALESCE: omitting name preserves existing name', () => {
const { user } = createUser(testDb);
const tag = createTag(user.id, 'KeepMe', '#aaaaaa') as any;
const updated = updateTag(tag.id, undefined, '#cccccc') as any;
expect(updated.name).toBe('KeepMe');
expect(updated.color).toBe('#cccccc');
});
it('TAG-SVC-012 — COALESCE: omitting color preserves existing color', () => {
const { user } = createUser(testDb);
const tag = createTag(user.id, 'ColorKeep', '#dddddd') as any;
const updated = updateTag(tag.id, 'NewName', undefined) as any;
expect(updated.name).toBe('NewName');
expect(updated.color).toBe('#dddddd');
});
});
// ── deleteTag ─────────────────────────────────────────────────────────────────
describe('deleteTag', () => {
it('TAG-SVC-013 — deletes the tag from the database', () => {
const { user } = createUser(testDb);
const tag = createTag(user.id, 'ToDelete') as any;
deleteTag(tag.id);
expect(getTagByIdAndUser(tag.id, user.id)).toBeUndefined();
});
it('TAG-SVC-014 — deleting a non-existent tag does not throw', () => {
expect(() => deleteTag(99999)).not.toThrow();
});
it('TAG-SVC-015 — deleting one tag does not affect other tags', () => {
const { user } = createUser(testDb);
const t1 = createTag(user.id, 'Keep') as any;
const t2 = createTag(user.id, 'Remove') as any;
deleteTag(t2.id);
const remaining = listTags(user.id) as any[];
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe(t1.id);
});
});
@@ -1,4 +1,4 @@
import { localParts, resolveTimeZone } from '../../../src/services/timezoneService';
import { localParts, resolveTimeZone } from '../../../src/nest/common/timezoneService';
import { describe, expect, it } from 'vitest';
@@ -1,287 +0,0 @@
/**
* Unit tests for todoService — TODO-SVC-001 through TODO-SVC-020.
* Uses a real in-memory SQLite DB so SQL logic is exercised faithfully.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: 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-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, addTripMember } from '../../helpers/factories';
import {
verifyTripAccess,
listItems,
createItem,
updateItem,
deleteItem,
getCategoryAssignees,
updateCategoryAssignees,
reorderItems,
} from '../../../src/services/todoService';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ── verifyTripAccess ──────────────────────────────────────────────────────────
describe('verifyTripAccess', () => {
it('TODO-SVC-001: returns trip for owner', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = verifyTripAccess(trip.id, user.id);
expect(result).toBeDefined();
expect((result as any).id).toBe(trip.id);
});
it('TODO-SVC-002: returns null for non-member', () => {
const { user: owner } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
expect(verifyTripAccess(trip.id, stranger.id)).toBeFalsy();
});
it('TODO-SVC-003: returns trip for member', () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
const result = verifyTripAccess(trip.id, member.id);
expect(result).toBeDefined();
});
});
// ── listItems / createItem ────────────────────────────────────────────────────
describe('listItems and createItem', () => {
it('TODO-SVC-004: listItems returns empty array for new trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(listItems(trip.id)).toEqual([]);
});
it('TODO-SVC-005: createItem inserts a todo with name only', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Buy snacks' }) as any;
expect(item).toBeDefined();
expect(item.name).toBe('Buy snacks');
expect(item.checked).toBe(0);
expect(item.trip_id).toBe(trip.id);
expect(item.sort_order).toBe(0);
});
it('TODO-SVC-006: createItem assigns incrementing sort_order', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const a = createItem(trip.id, { name: 'A' }) as any;
const b = createItem(trip.id, { name: 'B' }) as any;
expect(b.sort_order).toBe(a.sort_order + 1);
});
it('TODO-SVC-007: createItem stores optional fields', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, {
name: 'Pack bag',
category: 'Prep',
description: 'All the gear',
priority: 3,
}) as any;
expect(item.category).toBe('Prep');
expect(item.description).toBe('All the gear');
expect(item.priority).toBe(3);
});
it('TODO-SVC-008: listItems returns items ordered by sort_order', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createItem(trip.id, { name: 'First' });
createItem(trip.id, { name: 'Second' });
createItem(trip.id, { name: 'Third' });
const items = listItems(trip.id) as any[];
expect(items).toHaveLength(3);
expect(items[0].sort_order).toBeLessThanOrEqual(items[1].sort_order);
expect(items[1].sort_order).toBeLessThanOrEqual(items[2].sort_order);
});
});
// ── updateItem ────────────────────────────────────────────────────────────────
describe('updateItem', () => {
it('TODO-SVC-009: returns null for non-existent item', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(updateItem(trip.id, 99999, { name: 'Ghost' }, ['name'])).toBeNull();
});
it('TODO-SVC-010: toggles checked status', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Visit museum' }) as any;
const updated = updateItem(trip.id, item.id, { checked: 1 }, ['checked']) as any;
expect(updated.checked).toBe(1);
const back = updateItem(trip.id, item.id, { checked: 0 }, ['checked']) as any;
expect(back.checked).toBe(0);
});
it('TODO-SVC-011: updates name and category', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Old' }) as any;
const updated = updateItem(trip.id, item.id, { name: 'New', category: 'Misc' }, ['name', 'category']) as any;
expect(updated.name).toBe('New');
expect(updated.category).toBe('Misc');
});
it('TODO-SVC-012: clears due_date when key is present with null value', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Task', due_date: '2026-06-01' }) as any;
const updated = updateItem(trip.id, item.id, { due_date: null }, ['due_date']) as any;
expect(updated.due_date).toBeNull();
});
});
// ── deleteItem ────────────────────────────────────────────────────────────────
describe('deleteItem', () => {
it('TODO-SVC-013: returns false for non-existent item', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(deleteItem(trip.id, 99999)).toBe(false);
});
it('TODO-SVC-014: deletes item and returns true', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Gone' }) as any;
expect(deleteItem(trip.id, item.id)).toBe(true);
expect(listItems(trip.id)).toHaveLength(0);
});
});
// ── reorderItems ──────────────────────────────────────────────────────────────
describe('reorderItems', () => {
it('TODO-SVC-015: assigns sort_order matching orderedIds array position', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const a = createItem(trip.id, { name: 'A' }) as any;
const b = createItem(trip.id, { name: 'B' }) as any;
const c = createItem(trip.id, { name: 'C' }) as any;
reorderItems(trip.id, [c.id, a.id, b.id]);
const rows = testDb.prepare('SELECT id, sort_order FROM todo_items WHERE trip_id = ? ORDER BY sort_order').all(trip.id) as any[];
expect(rows[0].id).toBe(c.id);
expect(rows[1].id).toBe(a.id);
expect(rows[2].id).toBe(b.id);
});
});
// ── category assignees ────────────────────────────────────────────────────────
describe('getCategoryAssignees / updateCategoryAssignees', () => {
it('TODO-SVC-016: returns empty object for new trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(getCategoryAssignees(trip.id)).toEqual({});
});
it('TODO-SVC-017: updateCategoryAssignees sets assignees for a category', () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
const rows = updateCategoryAssignees(trip.id, 'Packing', [owner.id, member.id]) as any[];
expect(rows).toHaveLength(2);
const assignees = getCategoryAssignees(trip.id) as any;
expect(assignees['Packing']).toHaveLength(2);
});
it('TODO-SVC-018: updateCategoryAssignees with empty array clears assignees', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
updateCategoryAssignees(trip.id, 'Packing', [owner.id]);
const cleared = updateCategoryAssignees(trip.id, 'Packing', []) as any[];
expect(cleared).toHaveLength(0);
const assignees = getCategoryAssignees(trip.id) as any;
expect(assignees['Packing']).toBeUndefined();
});
it('TODO-SVC-019: getCategoryAssignees groups by category name', () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
updateCategoryAssignees(trip.id, 'Shopping', [owner.id]);
updateCategoryAssignees(trip.id, 'Logistics', [member.id]);
const assignees = getCategoryAssignees(trip.id) as any;
expect(Object.keys(assignees)).toHaveLength(2);
expect(assignees['Shopping']).toHaveLength(1);
expect(assignees['Logistics']).toHaveLength(1);
});
it('TODO-SVC-020: updateCategoryAssignees replaces existing assignees (not append)', () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
updateCategoryAssignees(trip.id, 'Food', [owner.id, member.id]);
// Replace with just owner
updateCategoryAssignees(trip.id, 'Food', [owner.id]);
const assignees = getCategoryAssignees(trip.id) as any;
expect(assignees['Food']).toHaveLength(1);
expect(assignees['Food'][0].user_id).toBe(owner.id);
});
});
@@ -1,171 +0,0 @@
/**
* Unit tests for transitService — TRANSIT-SVC-001..010.
* The Transitous/MOTIS proxy (#1065): input validation, mode whitelist,
* response mapping (colors, walk time, wall-clock duration) and caching.
*/
import { deriveTransitStats, geocode, plan, type TransitLeg } from '../../../src/services/transitService';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
vi.mock('../../../src/services/notifications', () => ({ getAppUrl: () => 'https://trek.example.com' }));
vi.mock('../../../src/services/mapsService', () => ({ buildUserAgent: () => 'TREK-Test-UA' }));
const fetchMock = vi.fn();
beforeEach(() => {
vi.stubGlobal('fetch', fetchMock);
fetchMock.mockReset();
});
afterEach(() => vi.unstubAllGlobals());
function okJson(data: unknown) {
return { ok: true, json: async () => data };
}
describe('geocode', () => {
it('TRANSIT-SVC-001: returns [] without calling upstream for short queries', async () => {
const r = await geocode('a');
expect(r.results).toEqual([]);
expect(fetchMock).not.toHaveBeenCalled();
});
it('TRANSIT-SVC-002: maps matches to compact places and sends the UA', async () => {
fetchMock.mockResolvedValueOnce(
okJson([
{ name: 'Alexanderplatz', lat: 52.52, lon: 13.41, type: 'STOP', areas: [{ name: 'Berlin', default: true }] },
{ name: 'no-coords' },
]),
);
const r = await geocode('alexanderplatz-u1');
expect(r.results).toEqual([{ name: 'Alexanderplatz', lat: 52.52, lng: 13.41, type: 'STOP', area: 'Berlin' }]);
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toContain('/api/v1/geocode?');
expect(init.headers['User-Agent']).toBe('TREK-Test-UA');
});
it('TRANSIT-SVC-003: ignores an invalid near bias instead of forwarding it', async () => {
fetchMock.mockResolvedValueOnce(okJson([]));
await geocode('hauptbahnhof-x1', undefined, 'not,coords');
expect(String(fetchMock.mock.calls[0][0])).not.toContain('place=');
});
});
describe('plan validation', () => {
it('TRANSIT-SVC-004: rejects malformed coordinates with 400', async () => {
await expect(plan({ from: 'x', to: '52.5,13.4' })).rejects.toMatchObject({ status: 400 });
await expect(plan({ from: '95,13.4', to: '52.5,13.4' })).rejects.toMatchObject({ status: 400 });
expect(fetchMock).not.toHaveBeenCalled();
});
it('TRANSIT-SVC-005: rejects modes outside the whitelist', async () => {
await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', modes: 'BUS,CAR' })).rejects.toMatchObject({
status: 400,
});
expect(fetchMock).not.toHaveBeenCalled();
});
it('TRANSIT-SVC-006: rejects out-of-range maxTransfers and bad time', async () => {
await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', maxTransfers: 99 })).rejects.toMatchObject({
status: 400,
});
await expect(plan({ from: '52.50,13.40', to: '52.51,13.41', time: 'not-a-date' })).rejects.toMatchObject({
status: 400,
});
});
});
describe('itinerary statistics', () => {
it('derives wall-clock duration, walking time, and transfers from canonical legs', () => {
const leg = (mode: string, duration: number) => ({ mode, duration }) as TransitLeg;
const stats = deriveTransitStats('2026-07-13T08:00:00Z', '2026-07-13T08:30:00Z', [
leg('WALK', 300),
leg('BUS', 600),
leg('RAIL', 600),
]);
expect(stats).toEqual({ duration: 1800, transfers: 1, walkSeconds: 300 });
expect(deriveTransitStats('2026-07-13T08:00:00Z', '2026-07-13T08:30:00Z', [leg('BUS', 1800)], 2).transfers).toBe(2);
});
});
describe('plan mapping', () => {
const motisResponse = {
itineraries: [
{
duration: 999, // deliberately wrong — mapping must use wall-clock instead
startTime: '2026-07-13T08:00:00Z',
endTime: '2026-07-13T08:30:00Z',
transfers: 1,
legs: [
{
mode: 'WALK',
duration: 300,
distance: 250.7,
from: { name: 'A', lat: 1, lon: 2, departure: '2026-07-13T08:00:00Z' },
to: { name: 'Stop 1', lat: 1.1, lon: 2.1, arrival: '2026-07-13T08:05:00Z' },
},
{
mode: 'BUS',
duration: 1200,
routeShortName: '100',
routeColor: 'FF0000',
routeTextColor: '#ffffff',
headsign: 'Zoo',
agencyName: 'BVG',
intermediateStops: [{}, {}],
from: { name: 'Stop 1', lat: 1.1, lon: 2.1, departure: '2026-07-13T08:07:00Z', track: '2' },
to: { name: 'Stop 2', lat: 1.2, lon: 2.2, arrival: '2026-07-13T08:27:00Z' },
},
],
},
],
};
it('TRANSIT-SVC-007: maps legs compactly, normalises GTFS colors and counts walk seconds', async () => {
fetchMock.mockResolvedValueOnce(okJson(motisResponse));
const r = await plan({ from: '52.5000,13.4000', to: '52.5100,13.4100' });
expect(r.itineraries).toHaveLength(1);
const it = r.itineraries[0];
// Wall-clock 08:00→08:30, not the reported 999s.
expect(it.duration).toBe(1800);
expect(it.walkSeconds).toBe(300);
expect(it.transfers).toBe(1);
const bus = it.legs[1];
expect(bus.line).toBe('100');
expect(bus.lineColor).toBe('#FF0000');
expect(bus.lineTextColor).toBe('#ffffff');
expect(bus.intermediateStops).toBe(2);
expect(bus.from.track).toBe('2');
expect(it.legs[0].distance).toBe(251);
});
it('TRANSIT-SVC-008: forwards only whitelisted params and pins directModes=WALK', async () => {
fetchMock.mockResolvedValueOnce(okJson({ itineraries: [] }));
await plan({
from: '48.1000,11.5000',
to: '48.2000,11.6000',
modes: 'BUS,TRAM',
maxTransfers: 2,
arriveBy: true,
time: '2026-07-13T09:00:00Z',
});
const url = String(fetchMock.mock.calls[0][0]);
expect(url).toContain('/api/v6/plan?');
expect(url).toContain('transitModes=BUS%2CTRAM');
expect(url).toContain('maxTransfers=2');
expect(url).toContain('arriveBy=true');
expect(url).toContain('directModes=WALK');
});
it('TRANSIT-SVC-009: identical plans hit the cache (single upstream call)', async () => {
fetchMock.mockResolvedValue(okJson({ itineraries: [] }));
await plan({ from: '40.0000,-3.0000', to: '40.1000,-3.1000' });
await plan({ from: '40.0000,-3.0000', to: '40.1000,-3.1000' });
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('TRANSIT-SVC-010: upstream failure surfaces as a 502-style error', async () => {
fetchMock.mockResolvedValueOnce({ ok: false, status: 500 });
await expect(plan({ from: '41.0000,2.0000', to: '41.1000,2.1000' })).rejects.toMatchObject({ status: 502 });
});
});
@@ -23,7 +23,16 @@ vi.mock('../../../src/config', () => ({
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { createUser } from '../../helpers/factories';
import { getOrCreateLocalTrekPhoto, getOrCreateTrekPhoto, resolveTrekPhoto } from '../../../src/services/memories/photoResolverService';
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, deleted with the other three that had no consumer outside
// the container. These call the repository directly now.
const trekPhotos = new TrekPhotosRepository(new DatabaseService(trekDb));
const getOrCreateTrekPhoto = (...a: Parameters<TrekPhotosRepository['getOrCreate']>) => trekPhotos.getOrCreate(...a);
const getOrCreateLocalTrekPhoto = (...a: Parameters<TrekPhotosRepository['getOrCreateLocal']>) => trekPhotos.getOrCreateLocal(...a);
const resolveTrekPhoto = (id: number) => trekPhotos.resolve(id);
beforeAll(() => {
createTables(testDb);
@@ -1,92 +0,0 @@
/**
* Unit tests for tripInviteService — TRIP-INVITE-001..006.
* Per-trip invite links (#1143): one rotating token, optional expiry, resolve.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA foreign_keys = ON');
return { testDb: db, dbMock: { db } };
});
vi.mock('../../../src/db/database', () => dbMock);
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import {
getTripInviteLink,
createOrRotateTripInviteLink,
deleteTripInviteLink,
resolveTripInvite,
} from '../../../src/services/tripInviteService';
beforeAll(() => { createTables(testDb); runMigrations(testDb); });
beforeEach(() => resetTestDb(testDb));
afterAll(() => testDb.close());
function setup() {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
return { owner, trip };
}
describe('tripInviteService', () => {
it('TRIP-INVITE-001: no link exists initially', () => {
const { trip } = setup();
expect(getTripInviteLink(trip.id)).toBeNull();
});
it('TRIP-INVITE-002: create returns a token and get reads it back', () => {
const { owner, trip } = setup();
const info = createOrRotateTripInviteLink(trip.id, owner.id);
expect(info.token).toMatch(/^[A-Za-z0-9_-]{20,}$/);
expect(getTripInviteLink(trip.id)?.token).toBe(info.token);
});
it('TRIP-INVITE-003: rotating replaces the token and keeps a single row', () => {
const { owner, trip } = setup();
const first = createOrRotateTripInviteLink(trip.id, owner.id);
const second = createOrRotateTripInviteLink(trip.id, owner.id);
expect(second.token).not.toBe(first.token);
const count = testDb.prepare('SELECT COUNT(*) as n FROM trip_invite_tokens WHERE trip_id = ?').get(trip.id) as { n: number };
expect(count.n).toBe(1);
// The old token no longer resolves.
expect(resolveTripInvite(first.token)).toBeNull();
});
it('TRIP-INVITE-004: resolve returns the trip for a valid token', () => {
const { owner, trip } = setup();
const info = createOrRotateTripInviteLink(trip.id, owner.id);
expect(resolveTripInvite(info.token)).toEqual({ trip_id: trip.id, title: trip.title });
});
it('TRIP-INVITE-005: an expired token does not resolve (ISO expiry, incl. same-day)', () => {
const { owner, trip } = setup();
const info = createOrRotateTripInviteLink(trip.id, owner.id);
// Use the exact ISO-8601 format the service writes, one hour in the past —
// this catches the lexicographic-SQL-comparison bug where a same-UTC-day
// expiry would otherwise still resolve.
testDb.prepare('UPDATE trip_invite_tokens SET expires_at = ? WHERE trip_id = ?')
.run(new Date(Date.now() - 3600_000).toISOString(), trip.id);
expect(resolveTripInvite(info.token)).toBeNull();
});
it('TRIP-INVITE-005b: a not-yet-expired token still resolves', () => {
const { owner, trip } = setup();
const info = createOrRotateTripInviteLink(trip.id, owner.id);
testDb.prepare('UPDATE trip_invite_tokens SET expires_at = ? WHERE trip_id = ?')
.run(new Date(Date.now() + 3600_000).toISOString(), trip.id);
expect(resolveTripInvite(info.token)).toEqual({ trip_id: trip.id, title: trip.title });
});
it('TRIP-INVITE-006: delete removes the link', () => {
const { owner, trip } = setup();
const info = createOrRotateTripInviteLink(trip.id, owner.id);
deleteTripInviteLink(trip.id);
expect(getTripInviteLink(trip.id)).toBeNull();
expect(resolveTripInvite(info.token)).toBeNull();
});
});
@@ -1,66 +0,0 @@
/**
* Unit tests for joinTripAsMember — TRIP-JOIN-001..004.
* The shared add-by-id helper behind trip invite links (#1143) and trip-bound
* admin invites (#1402): idempotent, owner-safe, missing-trip-safe.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA foreign_keys = ON');
return { testDb: db, dbMock: { db } };
});
vi.mock('../../../src/db/database', () => dbMock);
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { joinTripAsMember } from '../../../src/services/tripMembership';
beforeAll(() => { createTables(testDb); runMigrations(testDb); });
beforeEach(() => resetTestDb(testDb));
afterAll(() => testDb.close());
function memberRow(tripId: number, userId: number) {
return testDb.prepare('SELECT * FROM trip_members WHERE trip_id = ? AND user_id = ?').get(tripId, userId);
}
describe('joinTripAsMember', () => {
it('TRIP-JOIN-001: adds a non-member and reports joined', () => {
const { user: owner } = createUser(testDb);
const { user: joiner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const r = joinTripAsMember(trip.id, joiner.id, null);
expect(r).toEqual({ joined: true, tripId: trip.id });
expect(memberRow(trip.id, joiner.id)).toBeTruthy();
});
it('TRIP-JOIN-002: never adds the trip owner as a member', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const r = joinTripAsMember(trip.id, owner.id, null);
expect(r.joined).toBe(false);
expect(memberRow(trip.id, owner.id)).toBeUndefined();
});
it('TRIP-JOIN-003: is idempotent for an existing member (no duplicate row)', () => {
const { user: owner } = createUser(testDb);
const { user: joiner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
expect(joinTripAsMember(trip.id, joiner.id, owner.id).joined).toBe(true);
expect(joinTripAsMember(trip.id, joiner.id, owner.id).joined).toBe(false);
const count = testDb.prepare('SELECT COUNT(*) as n FROM trip_members WHERE trip_id = ? AND user_id = ?').get(trip.id, joiner.id) as { n: number };
expect(count.n).toBe(1);
});
it('TRIP-JOIN-004: no-ops for a missing trip', () => {
const { user: joiner } = createUser(testDb);
const r = joinTripAsMember(999999, joiner.id, null);
expect(r.joined).toBe(false);
});
});
@@ -1,804 +0,0 @@
/**
* Unit tests for tripService — exportICS function (TRIP-SVC-001 through TRIP-SVC-009).
* Uses a real in-memory SQLite DB so SQL logic is exercised faithfully.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createReservation, createPlace, createDay, createDayAssignment, createDayNote, addTripMember } from '../../helpers/factories';
import { exportICS, generateDays, deleteOldCover, updateTrip, transferOwnership, createGuest, renameGuest, deleteGuest, listMembers, addMember } from '../../../src/services/tripService';
import { createAccommodation } from '../../../src/services/dayService';
import fs from 'fs';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ── Helpers ───────────────────────────────────────────────────────────────────
function getDays(tripId: number) {
return testDb.prepare('SELECT * FROM days WHERE trip_id = ? ORDER BY day_number').all(tripId) as {
id: number; trip_id: number; day_number: number; date: string | null;
}[];
}
function getAssignments(dayId: number) {
return testDb.prepare('SELECT * FROM day_assignments WHERE day_id = ?').all(dayId) as { id: number; day_id: number }[];
}
function getNotes(dayId: number) {
return testDb.prepare('SELECT * FROM day_notes WHERE day_id = ?').all(dayId) as { id: number; day_id: number }[];
}
// ── Tests ─────────────────────────────────────────────────────────────────────
describe('generateDays', () => {
it('TRIP-SVC-010: full range shift preserves day assignments and notes positionally', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-06-01', end_date: '2025-06-05' });
const daysBefore = getDays(trip.id);
expect(daysBefore).toHaveLength(5);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, daysBefore[0].id, place.id);
const note = createDayNote(testDb, daysBefore[1].id, trip.id, { text: 'packed' });
// Shift forward 9 days — zero overlap with original dates
generateDays(trip.id, '2025-06-10', '2025-06-14');
const daysAfter = getDays(trip.id);
expect(daysAfter).toHaveLength(5);
expect(daysAfter.map(d => d.date)).toEqual([
'2025-06-10', '2025-06-11', '2025-06-12', '2025-06-13', '2025-06-14',
]);
// day_number 1 (formerly June 1) now has date June 10 — assignment still attached
const day1 = daysAfter[0];
const day2 = daysAfter[1];
expect(getAssignments(day1.id)).toHaveLength(1);
expect(getAssignments(day1.id)[0].id).toBe(assignment.id);
expect(getNotes(day2.id)).toHaveLength(1);
expect(getNotes(day2.id)[0].id).toBe(note.id);
});
it('TRIP-SVC-011: shrinking range deletes overflow days and their assignments (issue #909)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-07-01', end_date: '2025-07-05' });
const daysBefore = getDays(trip.id);
expect(daysBefore).toHaveLength(5);
const place = createPlace(testDb, trip.id);
createDayAssignment(testDb, daysBefore[3].id, place.id);
createDayAssignment(testDb, daysBefore[4].id, place.id);
// Shrink from 5 to 3 days — surplus days and their content are removed
generateDays(trip.id, '2025-07-01', '2025-07-03');
const daysAfter = getDays(trip.id);
expect(daysAfter).toHaveLength(3);
expect(daysAfter.map(d => d.date)).toEqual(['2025-07-01', '2025-07-02', '2025-07-03']);
});
it('TRIP-SVC-016: shrinking range deletes empty overflow days (issue #909)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-07-01', end_date: '2025-07-07' });
expect(getDays(trip.id)).toHaveLength(7);
// Shrink 7 → 5; days 6 and 7 have no content
generateDays(trip.id, '2025-07-01', '2025-07-05');
const daysAfter = getDays(trip.id);
expect(daysAfter).toHaveLength(5);
expect(daysAfter.map(d => d.date)).toEqual([
'2025-07-01', '2025-07-02', '2025-07-03', '2025-07-04', '2025-07-05',
]);
});
it('TRIP-SVC-012: growing range keeps existing day content and appends new empty days', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-08-01', end_date: '2025-08-03' });
const daysBefore = getDays(trip.id);
expect(daysBefore).toHaveLength(3);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, daysBefore[0].id, place.id);
// Grow to 5 days
generateDays(trip.id, '2025-08-01', '2025-08-05');
const daysAfter = getDays(trip.id);
expect(daysAfter).toHaveLength(5);
expect(daysAfter.map(d => d.date)).toEqual([
'2025-08-01', '2025-08-02', '2025-08-03', '2025-08-04', '2025-08-05',
]);
// Existing day 1 retains its assignment
expect(getAssignments(daysAfter[0].id)).toHaveLength(1);
expect(getAssignments(daysAfter[0].id)[0].id).toBe(assignment.id);
// New days 4 and 5 are empty
expect(getAssignments(daysAfter[3].id)).toHaveLength(0);
expect(getAssignments(daysAfter[4].id)).toHaveLength(0);
});
it('TRIP-SVC-013: clearing dates converts all days to dateless without destroying assignments', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-09-01', end_date: '2025-09-04' });
const daysBefore = getDays(trip.id);
expect(daysBefore).toHaveLength(4);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, daysBefore[1].id, place.id);
// Clear both dates
generateDays(trip.id, null, null);
const daysAfter = getDays(trip.id);
expect(daysAfter).toHaveLength(4);
expect(daysAfter.every(d => d.date === null)).toBe(true);
// The assignment on the former day 2 still exists
const formerDay2 = daysAfter.find(d => d.id === daysBefore[1].id);
expect(formerDay2).toBeDefined();
expect(getAssignments(formerDay2!.id)).toHaveLength(1);
expect(getAssignments(formerDay2!.id)[0].id).toBe(assignment.id);
});
it('TRIP-SVC-014: partial overlap shift remaps by position (day 1→3 kept, 4-5 overflow)', () => {
// Original: Jun 1-5. New: Jun 3-7 (overlap on Jun 3-5, but we map by position)
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-10-01', end_date: '2025-10-05' });
const daysBefore = getDays(trip.id);
const place = createPlace(testDb, trip.id);
// Assign to each of the 5 days
for (const day of daysBefore) createDayAssignment(testDb, day.id, place.id);
// Shift forward 2 days (partial overlap with original range)
generateDays(trip.id, '2025-10-03', '2025-10-07');
const daysAfter = getDays(trip.id);
expect(daysAfter).toHaveLength(5);
expect(daysAfter.map(d => d.date)).toEqual([
'2025-10-03', '2025-10-04', '2025-10-05', '2025-10-06', '2025-10-07',
]);
// All 5 assignments survive
for (const day of daysAfter) {
expect(getAssignments(day.id)).toHaveLength(1);
}
});
it('TRIP-SVC-015: growing into dateless days reuses them; leftover dateless renumber without UNIQUE collision', () => {
// 3 dated days + 2 pre-existing dateless days. Resize to 4 dated days.
// Main loop: dated[0..2] → positions 1-3, dateless[0] → position 4 (consumed).
// Unused dateless: dateless[1] should land at position 5, NOT 4 (collision bug).
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-11-01', end_date: '2025-11-03' });
// Insert 2 dateless days directly
const daysBefore = getDays(trip.id);
testDb.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, NULL)').run(trip.id, 4);
testDb.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, NULL)').run(trip.id, 5);
const allDays = getDays(trip.id);
expect(allDays).toHaveLength(5);
const place = createPlace(testDb, trip.id);
// Put an assignment on the second dateless day (day_number=5) — it should survive
const assignment = createDayAssignment(testDb, allDays[4].id, place.id);
// Grow from 3 to 4 dated days — consumes dateless[0], leaves dateless[1] unused
// This is the scenario that triggered the UNIQUE collision bug
generateDays(trip.id, '2025-11-01', '2025-11-04');
const daysAfter = getDays(trip.id);
expect(daysAfter).toHaveLength(5);
const dated = daysAfter.filter(d => d.date !== null);
const dateless = daysAfter.filter(d => d.date === null);
expect(dated).toHaveLength(4);
expect(dateless).toHaveLength(1);
// The remaining dateless day still has its assignment
expect(getAssignments(dateless[0].id)).toHaveLength(1);
expect(getAssignments(dateless[0].id)[0].id).toBe(assignment.id);
// All day_numbers are unique 1..5
const nums = daysAfter.map(d => d.day_number).sort((a, b) => a - b);
expect(nums).toEqual([1, 2, 3, 4, 5]);
});
it('TRIP-SVC-017: switching a dateless trip to a shorter dated range drops empty leftover days but keeps ones with content (#1083)', () => {
const { user } = createUser(testDb);
// A 7-day trip, then cleared to dateless placeholders (day_count = 7).
const trip = createTrip(testDb, user.id, { start_date: '2025-12-01', end_date: '2025-12-07' });
generateDays(trip.id, null, null);
const dateless = getDays(trip.id);
expect(dateless).toHaveLength(7);
expect(dateless.every(d => d.date === null)).toBe(true);
// Give the LAST dateless day real content so it must be preserved.
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, dateless[6].id, place.id);
// Now set an explicit 2-day range. The first two dateless days are reused for
// the dates; the four empty leftovers must be removed, the one with content kept.
generateDays(trip.id, '2026-01-10', '2026-01-11');
const daysAfter = getDays(trip.id);
const dated = daysAfter.filter(d => d.date !== null);
const stillDateless = daysAfter.filter(d => d.date === null);
expect(dated.map(d => d.date)).toEqual(['2026-01-10', '2026-01-11']);
// day_count is COUNT(*) FROM days: 2 dated + 1 content-bearing dateless = 3 (not the stale 7)
expect(daysAfter).toHaveLength(3);
expect(stillDateless).toHaveLength(1);
expect(getAssignments(stillDateless[0].id)[0].id).toBe(assignment.id);
});
});
describe('exportICS', () => {
it('TRIP-SVC-001: returns VCALENDAR wrapper', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, {
title: 'My Vacation',
start_date: '2025-06-01',
end_date: '2025-06-07',
});
const { ics } = exportICS(trip.id);
expect(ics).toContain('BEGIN:VCALENDAR');
expect(ics).toContain('END:VCALENDAR');
});
it('TRIP-SVC-002: trip with start_date + end_date includes all-day VEVENT', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, {
title: 'Summer Holiday',
start_date: '2025-06-01',
end_date: '2025-06-07',
});
const { ics } = exportICS(trip.id);
expect(ics).toContain('DTSTART;VALUE=DATE:20250601');
// DTEND is exclusive — the day *after* the last day, or the trip loses a day.
expect(ics).toContain('DTEND;VALUE=DATE:20250608');
expect(ics).toContain('SUMMARY:Summer Holiday');
});
describe('#1453 all-day DTEND is timezone-independent', () => {
const originalTz = process.env.TZ;
afterAll(() => {
process.env.TZ = originalTz;
});
// The old code did `new Date(date + 'T00:00:00')` — no Z, so parsed as *server-local*
// midnight — then setDate(+1) and .toISOString(). East of Greenwich that round-trip
// lands a day early, and since DTEND is exclusive the trip's last day was dropped.
// Only invisible in CI because containers default to TZ=UTC.
for (const tz of ['Europe/Berlin', 'Asia/Tokyo', 'Pacific/Kiritimati', 'America/New_York', 'UTC']) {
it(`TRIP-SVC-002b: DTEND is the day after the last day under TZ=${tz}`, () => {
process.env.TZ = tz;
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, {
title: 'TZ Trip',
start_date: '2026-03-28',
end_date: '2026-03-30',
});
const { ics } = exportICS(trip.id);
expect(ics).toContain('DTSTART;VALUE=DATE:20260328');
expect(ics).toContain('DTEND;VALUE=DATE:20260331');
});
}
it('TRIP-SVC-002c: a per-day all-day summary event has the same exclusive DTEND', () => {
process.env.TZ = 'Asia/Tokyo';
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Day Note Trip' });
const day = createDay(testDb, trip.id, { date: '2026-03-30', day_number: 1 });
createDayNote(testDb, day.id, trip.id, { text: 'Pack the bags' });
const { ics } = exportICS(trip.id);
expect(ics).toContain('DTSTART;VALUE=DATE:20260330');
expect(ics).toContain('DTEND;VALUE=DATE:20260331');
});
});
it('TRIP-SVC-003: reservation with full datetime (includes T) → DTSTART without VALUE=DATE', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
const reservation = createReservation(testDb, trip.id, {
title: 'Morning Flight',
type: 'flight',
});
testDb
.prepare('UPDATE reservations SET reservation_time=? WHERE id=?')
.run('2025-06-02T09:00', reservation.id);
const { ics } = exportICS(trip.id);
expect(ics).toContain('DTSTART:20250602T090000');
expect(ics).not.toContain('DTSTART;VALUE=DATE');
});
it('TRIP-SVC-004: reservation with date-only → DTSTART;VALUE=DATE', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
const reservation = createReservation(testDb, trip.id, {
title: 'Hotel Check-in',
type: 'hotel',
});
testDb
.prepare('UPDATE reservations SET reservation_time=? WHERE id=?')
.run('2025-06-02', reservation.id);
const { ics } = exportICS(trip.id);
expect(ics).toContain('DTSTART;VALUE=DATE:20250602');
});
it('TRIP-SVC-005: reservation metadata with flight info appears in DESCRIPTION', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
const reservation = createReservation(testDb, trip.id, {
title: 'CDG to JFK',
type: 'flight',
});
testDb
.prepare('UPDATE reservations SET reservation_time=?, metadata=? WHERE id=?')
.run(
'2025-06-02T09:00',
JSON.stringify({
airline: 'Air Test',
flight_number: 'AT100',
departure_airport: 'CDG',
arrival_airport: 'JFK',
}),
reservation.id
);
const { ics } = exportICS(trip.id);
expect(ics).toContain('Airline: Air Test');
expect(ics).toContain('Flight: AT100');
});
it('TRIP-SVC-006: special characters in title are escaped', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip; First, Best' });
const { ics } = exportICS(trip.id);
expect(ics).toContain('Trip\\; First\\, Best');
});
it('TRIP-SVC-007: throws NotFoundError for non-existent trip', () => {
expect(() => exportICS(99999)).toThrow();
});
it('TRIP-SVC-008: returns a filename derived from trip title', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'My Trip 2025' });
const { filename } = exportICS(trip.id);
expect(filename).toMatch(/My.Trip.2025\.ics/);
});
it('TRIP-SVC-009: reservation with end time includes DTEND', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
const reservation = createReservation(testDb, trip.id, {
title: 'Afternoon Tour',
type: 'activity',
});
testDb
.prepare('UPDATE reservations SET reservation_time=?, reservation_end_time=? WHERE id=?')
.run('2025-06-02T14:00', '2025-06-02T16:00', reservation.id);
const { ics } = exportICS(trip.id);
expect(ics).toContain('DTEND:20250602T160000');
});
it('TRIP-SVC-010: flight with endpoint times but no reservation_time is included', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Paris Trip' });
const reservation = createReservation(testDb, trip.id, {
title: 'CDG → JFK',
type: 'flight',
});
// Confirmed flights store times per endpoint, never as reservation_time.
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL WHERE id=?').run(reservation.id);
const insertEp = testDb.prepare(
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
);
insertEp.run(reservation.id, 'from', 0, 'Paris CDG', 'CDG', 49.0, 2.5, 'Europe/Paris', '09:00', '2025-06-02');
insertEp.run(reservation.id, 'to', 1, 'New York JFK', 'JFK', 40.6, -73.8, 'America/New_York', '12:00', '2025-06-02');
const { ics } = exportICS(trip.id);
expect(ics).toContain('SUMMARY:CDG → JFK');
// Departure endpoint zone drives DTSTART, arrival zone drives DTEND, so the
// subscriber sees TREK's zones instead of their own (#1453).
expect(ics).toContain('DTSTART;TZID=Europe/Paris:20250602T090000');
expect(ics).toContain('DTEND;TZID=America/New_York:20250602T120000');
expect(ics).not.toContain('DTSTART:20250602T090000');
// Each referenced zone gets a VTIMEZONE definition.
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:Europe/Paris');
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:America/New_York');
expect(ics).toContain('Route: CDG → JFK');
});
it('TRIP-SVC-010b: an invalid endpoint timezone degrades to floating time instead of crashing the export', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Bad TZ Trip' });
const reservation = createReservation(testDb, trip.id, { title: 'CDG → JFK', type: 'flight' });
testDb.prepare('UPDATE reservations SET reservation_time=NULL, reservation_end_time=NULL WHERE id=?').run(reservation.id);
const insertEp = testDb.prepare(
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
);
// A stored/plugin-written timezone can be any string; it must never reach Intl.
// The bogus zone takes precedence over the coordinates (first.timezone || resolveZone).
insertEp.run(reservation.id, 'from', 0, 'Paris CDG', 'CDG', 49.0, 2.5, 'Not/AZone', '09:00', '2025-06-02');
insertEp.run(reservation.id, 'to', 1, 'New York JFK', 'JFK', 40.6, -73.8, 'garbage', '12:00', '2025-06-02');
let ics = '';
expect(() => { ics = exportICS(trip.id).ics; }).not.toThrow();
// Falls back to a floating local time (no TZID) and never emits a bogus VTIMEZONE.
expect(ics).toContain('DTSTART:20250602T090000');
expect(ics).not.toContain('TZID=Not/AZone');
expect(ics).not.toContain('garbage');
});
it('TRIP-SVC-011: flight endpoint with no local_date is skipped (relative Day-N trips)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Relative Trip' });
const reservation = createReservation(testDb, trip.id, {
title: 'Timeless Flight',
type: 'flight',
});
testDb.prepare('UPDATE reservations SET reservation_time=NULL WHERE id=?').run(reservation.id);
testDb.prepare(
'INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
).run(reservation.id, 'from', 0, 'Origin', 'AAA', 1.0, 1.0, null, '09:00', null);
const { ics } = exportICS(trip.id);
expect(ics).not.toContain('SUMMARY:Timeless Flight');
});
it('TRIP-SVC-012: timed assignment gets a TZID derived from the place coordinates', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Tokyo Trip' });
const day = createDay(testDb, trip.id, { date: '2025-06-02' });
// Tokyo coordinates → Asia/Tokyo via tz-lookup.
const place = createPlace(testDb, trip.id, { name: 'Senso-ji', lat: 35.7148, lng: 139.7967 });
const assignment = createDayAssignment(testDb, day.id, place.id);
testDb
.prepare('UPDATE day_assignments SET assignment_time=? WHERE id=?')
.run('09:00', assignment.id);
const { ics } = exportICS(trip.id);
expect(ics).toContain('DTSTART;TZID=Asia/Tokyo:20250602T090000');
expect(ics).toContain('BEGIN:VTIMEZONE\r\nTZID:Asia/Tokyo');
expect(ics).not.toContain('DTSTART:20250602T090000');
});
});
// ── deleteOldCover — path containment ──────────────────────────────────────────
describe('deleteOldCover', () => {
it('TRIP-SVC-COVER-001: never unlinks outside uploads/covers for a crafted cover_image', () => {
const existsSpy = vi.spyOn(fs, 'existsSync').mockReturnValue(true);
const unlinkSpy = vi.spyOn(fs, 'unlinkSync').mockImplementation(() => {});
try {
// Attacker-controlled values aimed at auth-gated sibling upload dirs.
deleteOldCover('/uploads/files/victim.pdf');
deleteOldCover('/uploads/covers/../files/secret.pdf');
deleteOldCover('/uploads/avatars/someone.png');
for (const call of unlinkSpy.mock.calls) {
const target = String(call[0]);
expect(target).toMatch(/[\\/]uploads[\\/]covers[\\/]/); // stays in covers
expect(target).not.toMatch(/[\\/]files[\\/]/);
expect(target).not.toMatch(/[\\/]avatars[\\/]/);
}
} finally {
existsSpy.mockRestore();
unlinkSpy.mockRestore();
}
});
it('TRIP-SVC-COVER-002: deletes a legitimate cover file', () => {
const existsSpy = vi.spyOn(fs, 'existsSync').mockReturnValue(true);
const unlinkSpy = vi.spyOn(fs, 'unlinkSync').mockImplementation(() => {});
try {
deleteOldCover('/uploads/covers/abc123.jpg');
expect(unlinkSpy).toHaveBeenCalledTimes(1);
expect(String(unlinkSpy.mock.calls[0][0])).toMatch(/[\\/]covers[\\/]abc123\.jpg$/);
} finally {
existsSpy.mockRestore();
unlinkSpy.mockRestore();
}
});
});
describe('resyncReservationDays (#1288)', () => {
const dayFor = (tripId: number, date: string) =>
(testDb.prepare('SELECT id FROM days WHERE trip_id = ? AND date = ?').get(tripId, date) as { id: number }).id;
const insertDatedReservation = (tripId: number, dayId: number, time: string) =>
Number(testDb.prepare(
"INSERT INTO reservations (trip_id, day_id, title, reservation_time, type, status) VALUES (?, ?, 'Dinner', ?, 'restaurant', 'pending')",
).run(tripId, dayId, time).lastInsertRowid);
it('TRIP-SVC-018: changing the start date re-anchors a dated reservation to the day matching its time', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-06-01', end_date: '2025-06-05' });
const resId = insertDatedReservation(trip.id, dayFor(trip.id, '2025-06-02'), '2025-06-02T19:00:00');
// Shift the whole range one day forward (days become 2025-06-02..06).
updateTrip(trip.id, user.id, { start_date: '2025-06-02', end_date: '2025-06-06' }, 'user');
const res = testDb.prepare('SELECT day_id FROM reservations WHERE id = ?').get(resId) as { day_id: number };
// The booking stays on its absolute date (2025-06-02) instead of shifting with its old day row.
expect(res.day_id).toBe(dayFor(trip.id, '2025-06-02'));
});
it('TRIP-SVC-019: a reservation whose date falls outside the new range keeps its day_id (not nulled)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-06-01', end_date: '2025-06-05' });
const origDayId = dayFor(trip.id, '2025-06-02');
const resId = insertDatedReservation(trip.id, origDayId, '2025-06-02T19:00:00');
// Shift far forward so 2025-06-02 is no longer covered by any day.
updateTrip(trip.id, user.id, { start_date: '2025-06-10', end_date: '2025-06-14' }, 'user');
const res = testDb.prepare('SELECT day_id FROM reservations WHERE id = ?').get(resId) as { day_id: number };
expect(res.day_id).toBe(origDayId);
});
});
describe('resyncAccommodationDays (#1288)', () => {
const dayFor = (tripId: number, date: string) =>
(testDb.prepare('SELECT id FROM days WHERE trip_id = ? AND date = ?').get(tripId, date) as { id: number }).id;
const insertAccommodation = (tripId: number, startDayId: number, endDayId: number) => {
const place = createPlace(testDb, tripId, { name: 'Grand Hotel' });
const acc = createAccommodation(tripId, {
place_id: place.id, start_day_id: startDayId, end_day_id: endDayId,
}) as { id: number };
const linkedRes = testDb.prepare(
'SELECT id FROM reservations WHERE accommodation_id = ?',
).get(acc.id) as { id: number };
return { accId: acc.id, linkedResId: linkedRes.id };
};
const getAcc = (id: number) =>
testDb.prepare('SELECT start_day_id, end_day_id FROM day_accommodations WHERE id = ?').get(id) as
{ start_day_id: number; end_day_id: number };
const getRes = (id: number) =>
testDb.prepare('SELECT day_id, reservation_time FROM reservations WHERE id = ?').get(id) as
{ day_id: number | null; reservation_time: string | null };
it('TRIP-SVC-035: extending the start keeps an accommodation on its absolute dates', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-06-10', end_date: '2025-06-14' });
const { accId, linkedResId } = insertAccommodation(trip.id, dayFor(trip.id, '2025-06-11'), dayFor(trip.id, '2025-06-13'));
// Add a day at the start: days re-date positionally (old 06-11 row becomes 06-10, …).
updateTrip(trip.id, user.id, { start_date: '2025-06-09', end_date: '2025-06-14' }, 'user');
const acc = getAcc(accId);
expect(acc.start_day_id).toBe(dayFor(trip.id, '2025-06-11'));
expect(acc.end_day_id).toBe(dayFor(trip.id, '2025-06-13'));
const res = getRes(linkedResId);
expect(res.day_id).toBe(acc.start_day_id);
expect(res.reservation_time?.slice(0, 10)).toBe('2025-06-11');
});
it('TRIP-SVC-036: moving the whole trip out of the old range keeps the accommodation glued to its days', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-06-01', end_date: '2025-06-05' });
const startDayId = dayFor(trip.id, '2025-06-02');
const endDayId = dayFor(trip.id, '2025-06-03');
const { accId, linkedResId } = insertAccommodation(trip.id, startDayId, endDayId);
updateTrip(trip.id, user.id, { start_date: '2025-07-01', end_date: '2025-07-05' }, 'user');
const acc = getAcc(accId);
expect(acc.start_day_id).toBe(startDayId);
expect(acc.end_day_id).toBe(endDayId);
// The linked reservation follows the (re-dated) start day instead of keeping a stale date snapshot.
const res = getRes(linkedResId);
expect(res.day_id).toBe(startDayId);
expect(res.reservation_time?.slice(0, 10)).toBe('2025-07-02');
});
it("TRIP-SVC-038: date_shift_mode 'shift_all' glues bookings to their days and restamps their times", () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-06-01', end_date: '2025-06-05' });
const origDayId = dayFor(trip.id, '2025-06-02');
const resId = Number(testDb.prepare(
"INSERT INTO reservations (trip_id, day_id, title, reservation_time, type, status) VALUES (?, ?, 'Dinner', '2025-06-02T19:00:00', 'restaurant', 'pending')",
).run(trip.id, origDayId).lastInsertRowid);
const { accId } = insertAccommodation(trip.id, origDayId, dayFor(trip.id, '2025-06-03'));
updateTrip(trip.id, user.id, { start_date: '2025-06-03', end_date: '2025-06-07', date_shift_mode: 'shift_all' }, 'user');
// The booking stays on its day row (now 2025-06-04) and its time follows.
const res = testDb.prepare('SELECT day_id, reservation_time FROM reservations WHERE id = ?').get(resId) as
{ day_id: number; reservation_time: string };
expect(res.day_id).toBe(origDayId);
expect(res.reservation_time).toBe('2025-06-04T19:00:00');
// The accommodation stays glued to its (re-dated) day rows too.
const acc = getAcc(accId);
expect(acc.start_day_id).toBe(origDayId);
});
it('TRIP-SVC-037: a dated hotel reservation without a linked accommodation is re-anchored like other bookings', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2025-06-01', end_date: '2025-06-05' });
const resId = Number(testDb.prepare(
"INSERT INTO reservations (trip_id, day_id, title, reservation_time, type, status) VALUES (?, ?, 'Imported hotel', ?, 'hotel', 'pending')",
).run(trip.id, dayFor(trip.id, '2025-06-02'), '2025-06-02T15:00:00').lastInsertRowid);
updateTrip(trip.id, user.id, { start_date: '2025-06-02', end_date: '2025-06-06' }, 'user');
const res = testDb.prepare('SELECT day_id FROM reservations WHERE id = ?').get(resId) as { day_id: number };
expect(res.day_id).toBe(dayFor(trip.id, '2025-06-02'));
});
});
describe('transferOwnership (#973)', () => {
it('TRIP-SVC-020: hands the trip to a member and demotes the former owner to a member', () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
const result = transferOwnership(trip.id, member.id, owner.id);
expect(result.toEmail).toBe(member.email);
const updated = testDb.prepare('SELECT user_id FROM trips WHERE id = ?').get(trip.id) as { user_id: number };
expect(updated.user_id).toBe(member.id);
// New owner no longer sits in trip_members, former owner now does.
const memberIds = (testDb.prepare('SELECT user_id FROM trip_members WHERE trip_id = ?').all(trip.id) as { user_id: number }[]).map(r => r.user_id);
expect(memberIds).toContain(owner.id);
expect(memberIds).not.toContain(member.id);
});
it('TRIP-SVC-021: rejects a transfer from a non-owner', () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
addTripMember(testDb, trip.id, member.id);
// member (not the owner) attempts the transfer
expect(() => transferOwnership(trip.id, member.id, member.id)).toThrow();
});
it('TRIP-SVC-022: rejects a transfer to someone who is not a member', () => {
const { user: owner } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
expect(() => transferOwnership(trip.id, stranger.id, owner.id)).toThrow('New owner must be a trip member');
});
it('TRIP-SVC-023: rejects transferring to yourself', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
expect(() => transferOwnership(trip.id, owner.id, owner.id)).toThrow('You already own this trip');
});
});
describe('guest members (#1362)', () => {
it('TRIP-SVC-030: createGuest adds a credential-less user joined into the trip', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const { member } = createGuest(trip.id, ' Anna ', owner.id);
expect(member.username).toBe('Anna');
expect(member.is_guest).toBe(true);
const row = testDb.prepare('SELECT username, email, password_hash, is_guest, role FROM users WHERE id = ?').get(member.id) as any;
expect(row.is_guest).toBe(1);
expect(row.password_hash).toBe('');
expect(row.email).toMatch(/@guests\.invalid$/);
expect(row.role).toBe('user');
// Joined as a trip member.
const m = testDb.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(trip.id, member.id);
expect(m).toBeTruthy();
// Surfaces in listMembers with is_guest=true and the typed display name.
const { members } = listMembers(trip.id, owner.id) as any;
const guest = members.find((x: any) => x.id === member.id);
expect(guest.username).toBe('Anna');
expect(guest.is_guest).toBe(true);
});
it('TRIP-SVC-031: the same guest name is allowed, not suffixed (#1446)', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const a = createGuest(trip.id, 'Sam', owner.id);
const b = createGuest(trip.id, 'Sam', owner.id);
// both keep the plain display name; only the internal (uuid) username differs
expect(a.member.username).toBe('Sam');
expect(b.member.username).toBe('Sam');
expect(b.member.id).not.toBe(a.member.id);
const usernames = testDb.prepare('SELECT username FROM users WHERE id IN (?, ?)').all(a.member.id, b.member.id) as { username: string }[];
expect(usernames[0].username).not.toBe(usernames[1].username);
});
it('TRIP-SVC-032: renameGuest updates the display name (trip-scoped, guest-only)', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const otherTrip = createTrip(testDb, other.id);
const trip = createTrip(testDb, owner.id);
const { member } = createGuest(trip.id, 'Bob', owner.id);
expect(renameGuest(trip.id, member.id, 'Robert')).toBe(true);
expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(member.id) as any).display_name).toBe('Robert');
// A real user cannot be renamed through the guest path…
expect(renameGuest(trip.id, owner.id, 'Hacked')).toBe(false);
// …and a guest cannot be renamed from a different trip.
expect(renameGuest(otherTrip.id, member.id, 'Nope')).toBe(false);
});
it('TRIP-SVC-033: deleteGuest removes the user (cascading membership), guest-only + trip-scoped', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const { member } = createGuest(trip.id, 'Carol', owner.id);
// Real members are not deletable via the guest path.
expect(deleteGuest(trip.id, owner.id)).toBe(false);
expect(deleteGuest(trip.id, member.id)).toBe(true);
expect(testDb.prepare('SELECT id FROM users WHERE id = ?').get(member.id)).toBeUndefined();
expect(testDb.prepare('SELECT id FROM trip_members WHERE user_id = ?').get(member.id)).toBeUndefined();
});
it('TRIP-SVC-034: a guest is never invitable (addMember) nor a transfer target', () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const { member } = createGuest(trip.id, 'Dora', owner.id);
// The synthetic username/email must not resolve through the invite box.
expect(() => addMember(trip.id, 'Dora', owner.id, owner.id)).toThrow('User not found');
// Ownership can never be handed to a guest.
expect(() => transferOwnership(trip.id, member.id, owner.id)).toThrow('Cannot transfer ownership to a guest');
});
});
@@ -1,152 +0,0 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import os from 'os';
import fs from 'fs';
import path from 'path';
// safeFetch is mocked so saveUnsplashCover never hits the network.
// db is mocked so getUnsplashKey resolves from a controllable stub, and
// decrypt_api_key is a passthrough so stored values compare as plaintext.
const { safeFetch, mockDbGet } = vi.hoisted(() => ({ safeFetch: vi.fn(), mockDbGet: vi.fn(() => undefined as unknown) }));
vi.mock('../../../src/utils/ssrfGuard', () => ({ safeFetch }));
vi.mock('../../../src/db/database', () => ({
db: { prepare: () => ({ get: mockDbGet, all: vi.fn(() => []), run: vi.fn() }) },
}));
vi.mock('../../../src/services/apiKeyCrypto', () => ({ decrypt_api_key: (v: string | null) => v }));
import { searchUnsplashPhotos, getUnsplashKey, saveUnsplashCover, isUnsplashCoverUrl } from '../../../src/services/unsplashService';
const ORIGINAL_UNSPLASH_ENV = process.env.UNSPLASH_ACCESS_KEY;
afterEach(() => {
vi.clearAllMocks();
vi.unstubAllGlobals();
mockDbGet.mockReturnValue(undefined);
if (ORIGINAL_UNSPLASH_ENV === undefined) delete process.env.UNSPLASH_ACCESS_KEY;
else process.env.UNSPLASH_ACCESS_KEY = ORIGINAL_UNSPLASH_ENV;
});
function fakeRes(init: { ok: boolean; status?: number; type?: string; bytes?: number; json?: unknown }): Response {
return {
ok: init.ok,
status: init.status ?? (init.ok ? 200 : 500),
headers: { get: (h: string) => (h.toLowerCase() === 'content-type' ? init.type ?? '' : null) },
arrayBuffer: async () => new ArrayBuffer(init.bytes ?? 8),
json: async () => init.json ?? {},
} as unknown as Response;
}
describe('unsplashService.isUnsplashCoverUrl', () => {
it('UNSPLASH-001: accepts only the Unsplash image CDN host', () => {
expect(isUnsplashCoverUrl('https://images.unsplash.com/photo-1?w=1080')).toBe(true);
expect(isUnsplashCoverUrl('https://evil.example.com/x.jpg')).toBe(false);
expect(isUnsplashCoverUrl('/uploads/covers/local.jpg')).toBe(false);
expect(isUnsplashCoverUrl(null)).toBe(false);
expect(isUnsplashCoverUrl(undefined)).toBe(false);
});
});
describe('unsplashService.searchUnsplashPhotos', () => {
it('UNSPLASH-002: rejects an empty query without hitting the network', async () => {
expect(await searchUnsplashPhotos(' ')).toEqual({ error: 'Search query is required', status: 400 });
});
it('UNSPLASH-003: maps a non-ok response to an error', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(fakeRes({ ok: false, status: 429, type: 'application/json', json: { errors: ['Rate limited'] } })));
expect(await searchUnsplashPhotos('paris')).toEqual({ error: 'Rate limited', status: 429 });
});
it('UNSPLASH-004: returns normalised photos on success and drops entries missing a url/thumb', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(fakeRes({
ok: true,
type: 'application/json',
json: {
results: [
{ id: 'a', urls: { regular: 'https://images.unsplash.com/a', small: 'https://images.unsplash.com/a-s' }, user: { name: 'Alice' }, links: { html: 'https://unsplash.com/a' } },
{ id: 'b', urls: {} }, // dropped — no url/thumb
],
},
})));
const res = await searchUnsplashPhotos('paris') as { photos: { id: string }[] };
expect(res.photos).toHaveLength(1);
expect(res.photos[0]).toMatchObject({ id: 'a', photographer: 'Alice', link: 'https://unsplash.com/a' });
});
it('UNSPLASH-010: hits the unauthenticated web endpoint when no access key is given', async () => {
const fetchMock = vi.fn().mockResolvedValue(fakeRes({ ok: true, type: 'application/json', json: { results: [] } }));
vi.stubGlobal('fetch', fetchMock);
await searchUnsplashPhotos('paris');
const [url, init] = fetchMock.mock.calls[0];
expect(url).toContain('unsplash.com/napi/search/photos');
expect((init.headers as Record<string, string>).Authorization).toBeUndefined();
});
it('UNSPLASH-011: hits the official API with a Client-ID header when an access key is given', async () => {
const fetchMock = vi.fn().mockResolvedValue(fakeRes({ ok: true, type: 'application/json', json: { results: [] } }));
vi.stubGlobal('fetch', fetchMock);
await searchUnsplashPhotos('paris', 9, 'my-access-key');
const [url, init] = fetchMock.mock.calls[0];
expect(url).toContain('api.unsplash.com/search/photos');
expect((init.headers as Record<string, string>).Authorization).toBe('Client-ID my-access-key');
expect((init.headers as Record<string, string>)['Accept-Version']).toBe('v1');
});
});
describe('unsplashService.getUnsplashKey', () => {
it('UNSPLASH-012: prefers the UNSPLASH_ACCESS_KEY env var over any stored key', () => {
process.env.UNSPLASH_ACCESS_KEY = 'env-key';
mockDbGet.mockReturnValue({ unsplash_api_key: 'user-key' });
expect(getUnsplashKey(1)).toBe('env-key');
expect(mockDbGet).not.toHaveBeenCalled();
});
it('UNSPLASH-013: returns the user key when set and no env var', () => {
delete process.env.UNSPLASH_ACCESS_KEY;
mockDbGet.mockReturnValueOnce({ unsplash_api_key: 'user-key' });
expect(getUnsplashKey(1)).toBe('user-key');
});
it('UNSPLASH-014: falls back to the admin key when the user has none', () => {
delete process.env.UNSPLASH_ACCESS_KEY;
mockDbGet.mockReturnValueOnce({ unsplash_api_key: null });
mockDbGet.mockReturnValueOnce({ unsplash_api_key: 'admin-key' });
expect(getUnsplashKey(1)).toBe('admin-key');
});
it('UNSPLASH-015: returns null when neither env, user, nor admin has a key', () => {
delete process.env.UNSPLASH_ACCESS_KEY;
mockDbGet.mockReturnValue(undefined);
expect(getUnsplashKey(1)).toBeNull();
});
});
describe('unsplashService.saveUnsplashCover', () => {
const dir = path.join(os.tmpdir(), 'trek-unsplash-cover-test');
afterEach(() => { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ } });
it('UNSPLASH-005: rejects a non-Unsplash host before any fetch', async () => {
await expect(saveUnsplashCover('https://evil.example.com/x.jpg', dir)).rejects.toThrow('Not an Unsplash image URL');
expect(safeFetch).not.toHaveBeenCalled();
});
it('UNSPLASH-006: downloads an Unsplash image and writes it locally', async () => {
safeFetch.mockResolvedValue(fakeRes({ ok: true, type: 'image/jpeg', bytes: 1234 }));
const filename = await saveUnsplashCover('https://images.unsplash.com/photo-1?w=1080', dir);
expect(filename).toMatch(/\.jpg$/);
expect(fs.existsSync(path.join(dir, filename))).toBe(true);
});
it('UNSPLASH-007: rejects an unsupported content type', async () => {
safeFetch.mockResolvedValue(fakeRes({ ok: true, type: 'text/html' }));
await expect(saveUnsplashCover('https://images.unsplash.com/photo-1', dir)).rejects.toThrow(/Unsupported cover image type/);
});
it('UNSPLASH-008: rejects an oversized image', async () => {
safeFetch.mockResolvedValue(fakeRes({ ok: true, type: 'image/png', bytes: 16 * 1024 * 1024 }));
await expect(saveUnsplashCover('https://images.unsplash.com/photo-1', dir)).rejects.toThrow('Cover image too large');
});
it('UNSPLASH-009: throws when the download fails', async () => {
safeFetch.mockResolvedValue(fakeRes({ ok: false, status: 404 }));
await expect(saveUnsplashCover('https://images.unsplash.com/photo-1', dir)).rejects.toThrow(/HTTP 404/);
});
});
@@ -1,745 +0,0 @@
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup (real in-memory SQLite) ─────────────────────────────────────────
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: () => null,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
// Mock websocket so notifyPlanUsers doesn't throw
vi.mock('../../../src/websocket', () => ({ broadcastToUser: vi.fn() }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
import {
getOwnPlan,
getActivePlan,
getPlanUsers,
migrateHolidayCalendars,
updatePlan,
addHolidayCalendar,
updateHolidayCalendar,
deleteHolidayCalendar,
setUserColor,
acceptInvite,
declineInvite,
cancelInvite,
getAvailableUsers,
listYears,
addYear,
deleteYear,
getEntries,
toggleEntry,
toggleCompanyHoliday,
getStats,
applyHolidayCalendars,
} from '../../../src/services/vacayService';
// ── Lifecycle ─────────────────────────────────────────────────────────────────
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
// Stub fetch with empty holiday list by default so updatePlan / applyHolidayCalendars
// never makes real network calls.
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => [],
}));
});
afterAll(() => {
vi.unstubAllGlobals();
testDb.close();
});
// ── Helpers ───────────────────────────────────────────────────────────────────
/** Insert a vacay_plan_members row directly (no service factory for it). */
function insertMember(planId: number, userId: number, status: 'pending' | 'accepted'): void {
testDb.prepare(
"INSERT INTO vacay_plan_members (plan_id, user_id, status) VALUES (?, ?, ?)"
).run(planId, userId, status);
}
/** Fast helper: create a user and immediately materialise their own plan. */
function setupUserWithPlan() {
const { user } = createUser(testDb);
const plan = getOwnPlan(user.id);
return { user, plan };
}
// ── getOwnPlan ────────────────────────────────────────────────────────────────
describe('getOwnPlan', () => {
it('VACAY-SVC-001: creates a new plan on first call for a fresh user', () => {
const { user } = createUser(testDb);
const plan = getOwnPlan(user.id);
expect(plan).toBeDefined();
expect(plan.owner_id).toBe(user.id);
expect(plan.id).toBeGreaterThan(0);
});
it('VACAY-SVC-002: returns the same plan on a second call (idempotent)', () => {
const { user } = createUser(testDb);
const first = getOwnPlan(user.id);
const second = getOwnPlan(user.id);
expect(second.id).toBe(first.id);
});
it('VACAY-SVC-003: seeds the current year row in vacay_years after plan creation', () => {
const { user } = createUser(testDb);
const plan = getOwnPlan(user.id);
const yr = new Date().getFullYear();
const row = testDb
.prepare('SELECT * FROM vacay_years WHERE plan_id = ? AND year = ?')
.get(plan.id, yr);
expect(row).toBeDefined();
});
it('VACAY-SVC-004: seeds the current year user_year row with default 30 vacation_days', () => {
const { user } = createUser(testDb);
const plan = getOwnPlan(user.id);
const yr = new Date().getFullYear();
const row = testDb
.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?')
.get(user.id, plan.id, yr) as { vacation_days: number } | undefined;
expect(row).toBeDefined();
expect(row!.vacation_days).toBe(30);
});
});
// ── getActivePlan ─────────────────────────────────────────────────────────────
describe('getActivePlan', () => {
it('VACAY-SVC-005: returns own plan when user has no accepted membership in another plan', () => {
const { user, plan } = setupUserWithPlan();
const active = getActivePlan(user.id);
expect(active.id).toBe(plan.id);
expect(active.owner_id).toBe(user.id);
});
it('VACAY-SVC-006: returns the shared plan when user has an accepted membership in another plan', () => {
const { user: owner, plan: ownerPlan } = setupUserWithPlan();
const { user: member } = createUser(testDb);
// Make sure member also has their own plan materialised first
getOwnPlan(member.id);
insertMember(ownerPlan.id, member.id, 'accepted');
const active = getActivePlan(member.id);
expect(active.id).toBe(ownerPlan.id);
});
it('VACAY-SVC-007: pending membership does NOT override own plan as active', () => {
const { user: owner, plan: ownerPlan } = setupUserWithPlan();
const { user: member } = createUser(testDb);
getOwnPlan(member.id);
insertMember(ownerPlan.id, member.id, 'pending');
const active = getActivePlan(member.id);
// Should still point to member's own plan
expect(active.owner_id).toBe(member.id);
});
});
// ── getPlanUsers ──────────────────────────────────────────────────────────────
describe('getPlanUsers', () => {
it('VACAY-SVC-008: returns [owner] for a solo plan', () => {
const { user, plan } = setupUserWithPlan();
const users = getPlanUsers(plan.id);
expect(users).toHaveLength(1);
expect(users[0].id).toBe(user.id);
});
it('VACAY-SVC-009: returns [owner, member] after an accepted membership is inserted', () => {
const { user: owner, plan } = setupUserWithPlan();
const { user: member } = createUser(testDb);
insertMember(plan.id, member.id, 'accepted');
const users = getPlanUsers(plan.id);
expect(users).toHaveLength(2);
expect(users.map(u => u.id)).toContain(owner.id);
expect(users.map(u => u.id)).toContain(member.id);
});
it('VACAY-SVC-010: pending membership members are NOT included in plan users', () => {
const { plan } = setupUserWithPlan();
const { user: pendingUser } = createUser(testDb);
insertMember(plan.id, pendingUser.id, 'pending');
const users = getPlanUsers(plan.id);
expect(users.map(u => u.id)).not.toContain(pendingUser.id);
});
it('VACAY-SVC-011: returns empty array for a non-existent plan id', () => {
const users = getPlanUsers(99999);
expect(users).toEqual([]);
});
});
// ── migrateHolidayCalendars ───────────────────────────────────────────────────
describe('migrateHolidayCalendars', () => {
it('VACAY-SVC-012: does nothing when holidays_enabled is falsy', async () => {
const { plan } = setupUserWithPlan();
const planRow = { ...plan, holidays_enabled: 0, holidays_region: 'DE' };
await migrateHolidayCalendars(plan.id, planRow);
const rows = testDb
.prepare('SELECT * FROM vacay_holiday_calendars WHERE plan_id = ?')
.all(plan.id);
expect(rows).toHaveLength(0);
});
it('VACAY-SVC-013: inserts a calendar row when holidays_enabled=1 and holidays_region is set', async () => {
const { plan } = setupUserWithPlan();
const planRow = { ...plan, holidays_enabled: 1, holidays_region: 'DE' };
await migrateHolidayCalendars(plan.id, planRow);
const rows = testDb
.prepare('SELECT * FROM vacay_holiday_calendars WHERE plan_id = ?')
.all(plan.id) as { region: string }[];
expect(rows).toHaveLength(1);
expect(rows[0].region).toBe('DE');
});
it('VACAY-SVC-014: does nothing if a calendar row already exists (no duplicate)', async () => {
const { plan } = setupUserWithPlan();
const planRow = { ...plan, holidays_enabled: 1, holidays_region: 'FR' };
await migrateHolidayCalendars(plan.id, planRow);
// Call a second time — should NOT insert another row
await migrateHolidayCalendars(plan.id, planRow);
const rows = testDb
.prepare('SELECT * FROM vacay_holiday_calendars WHERE plan_id = ?')
.all(plan.id);
expect(rows).toHaveLength(1);
});
});
// ── updatePlan ────────────────────────────────────────────────────────────────
describe('updatePlan', () => {
it('VACAY-SVC-015: updates block_weekends flag', async () => {
const { plan } = setupUserWithPlan();
await updatePlan(plan.id, { block_weekends: true }, undefined);
const updated = testDb
.prepare('SELECT block_weekends FROM vacay_plans WHERE id = ?')
.get(plan.id) as { block_weekends: number };
expect(updated.block_weekends).toBe(1);
});
it('VACAY-SVC-016: updates holidays_enabled flag', async () => {
const { plan } = setupUserWithPlan();
await updatePlan(plan.id, { holidays_enabled: true }, undefined);
const updated = testDb
.prepare('SELECT holidays_enabled FROM vacay_plans WHERE id = ?')
.get(plan.id) as { holidays_enabled: number };
expect(updated.holidays_enabled).toBe(1);
});
it('VACAY-SVC-017: returns the updated plan object with boolean-coerced flags', async () => {
const { plan } = setupUserWithPlan();
const result = await updatePlan(plan.id, { block_weekends: false }, undefined);
expect(result.plan.block_weekends).toBe(false);
expect(typeof result.plan.holidays_enabled).toBe('boolean');
});
it('VACAY-SVC-018: resets carried_over to 0 for all user_years when carry_over_enabled is set to false', async () => {
const { user, plan } = setupUserWithPlan();
const yr = new Date().getFullYear();
// Manually set a non-zero carried_over value
testDb
.prepare('UPDATE vacay_user_years SET carried_over = 5 WHERE user_id = ? AND plan_id = ? AND year = ?')
.run(user.id, plan.id, yr);
await updatePlan(plan.id, { carry_over_enabled: false }, undefined);
const row = testDb
.prepare('SELECT carried_over FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?')
.get(user.id, plan.id, yr) as { carried_over: number };
expect(row.carried_over).toBe(0);
});
});
// ── addHolidayCalendar ────────────────────────────────────────────────────────
describe('addHolidayCalendar', () => {
it('VACAY-SVC-019: inserts a new calendar row and returns the calendar object', () => {
const { plan } = setupUserWithPlan();
const cal = addHolidayCalendar(plan.id, 'GB', 'UK Holidays', '#ff0000', 0, undefined);
expect(cal).toBeDefined();
expect(cal.id).toBeGreaterThan(0);
expect(cal.region).toBe('GB');
expect(cal.label).toBe('UK Holidays');
expect(cal.color).toBe('#ff0000');
});
it('VACAY-SVC-020: uses default color #fecaca when no color is provided', () => {
const { plan } = setupUserWithPlan();
const cal = addHolidayCalendar(plan.id, 'US', null, undefined, 0, undefined);
expect(cal.color).toBe('#fecaca');
});
});
// ── updateHolidayCalendar ─────────────────────────────────────────────────────
describe('updateHolidayCalendar', () => {
it('VACAY-SVC-021: changes label and color on an existing calendar', () => {
const { plan } = setupUserWithPlan();
const cal = addHolidayCalendar(plan.id, 'DE', 'Germany', '#aabbcc', 0, undefined);
const updated = updateHolidayCalendar(cal.id, plan.id, { label: 'Deutschland', color: '#112233' }, undefined);
expect(updated).not.toBeNull();
expect(updated!.label).toBe('Deutschland');
expect(updated!.color).toBe('#112233');
});
it('VACAY-SVC-022: returns null when the calendar id does not exist in the plan', () => {
const { plan } = setupUserWithPlan();
const result = updateHolidayCalendar(99999, plan.id, { label: 'Nope' }, undefined);
expect(result).toBeNull();
});
});
// ── deleteHolidayCalendar ─────────────────────────────────────────────────────
describe('deleteHolidayCalendar', () => {
it('VACAY-SVC-023: removes the calendar row and returns true on success', () => {
const { plan } = setupUserWithPlan();
const cal = addHolidayCalendar(plan.id, 'FR', null, undefined, 0, undefined);
const result = deleteHolidayCalendar(cal.id, plan.id, undefined);
expect(result).toBe(true);
const row = testDb.prepare('SELECT id FROM vacay_holiday_calendars WHERE id = ?').get(cal.id);
expect(row).toBeUndefined();
});
it('VACAY-SVC-024: returns false when the calendar does not exist', () => {
const { plan } = setupUserWithPlan();
const result = deleteHolidayCalendar(99999, plan.id, undefined);
expect(result).toBe(false);
});
});
// ── setUserColor ──────────────────────────────────────────────────────────────
describe('setUserColor', () => {
it('VACAY-SVC-025: inserts a color for a user in a plan', () => {
const { user, plan } = setupUserWithPlan();
setUserColor(user.id, plan.id, '#123456', undefined);
const row = testDb
.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?')
.get(user.id, plan.id) as { color: string } | undefined;
expect(row?.color).toBe('#123456');
});
it('VACAY-SVC-026: updates the color when called a second time (upsert)', () => {
const { user, plan } = setupUserWithPlan();
setUserColor(user.id, plan.id, '#aaaaaa', undefined);
setUserColor(user.id, plan.id, '#bbbbbb', undefined);
const row = testDb
.prepare('SELECT color FROM vacay_user_colors WHERE user_id = ? AND plan_id = ?')
.get(user.id, plan.id) as { color: string };
expect(row.color).toBe('#bbbbbb');
});
});
// ── listYears / addYear / deleteYear ──────────────────────────────────────────
describe('listYears', () => {
it('VACAY-SVC-027: returns the seeded current year for a freshly created plan', () => {
const { plan } = setupUserWithPlan();
const yr = new Date().getFullYear();
const years = listYears(plan.id);
expect(years).toContain(yr);
});
});
describe('addYear', () => {
it('VACAY-SVC-028: inserts a new year and creates a user_year record', () => {
const { user, plan } = setupUserWithPlan();
const newYear = new Date().getFullYear() + 2;
addYear(plan.id, newYear, undefined);
const years = listYears(plan.id);
expect(years).toContain(newYear);
const userYear = testDb
.prepare('SELECT * FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?')
.get(user.id, plan.id, newYear) as { vacation_days: number } | undefined;
expect(userYear).toBeDefined();
expect(userYear!.vacation_days).toBe(30);
});
it('VACAY-SVC-029: carries over remaining days to the new year when carry_over_enabled is true', () => {
const { user, plan } = setupUserWithPlan();
const currentYear = new Date().getFullYear();
const nextYear = currentYear + 1;
// Enable carry-over and seed some entries for the current year
testDb.prepare('UPDATE vacay_plans SET carry_over_enabled = 1 WHERE id = ?').run(plan.id);
// Ensure current year row exists with 10 vacation days
testDb.prepare(`
INSERT OR REPLACE INTO vacay_user_years (user_id, plan_id, year, vacation_days, carried_over)
VALUES (?, ?, ?, 10, 0)
`).run(user.id, plan.id, currentYear);
// Add 3 entries (used days) in the current year
for (let day = 1; day <= 3; day++) {
const dateStr = `${currentYear}-06-0${day}`;
testDb.prepare('INSERT OR IGNORE INTO vacay_entries (plan_id, user_id, date, note) VALUES (?, ?, ?, ?)').run(plan.id, user.id, dateStr, '');
}
addYear(plan.id, nextYear, undefined);
const userYear = testDb
.prepare('SELECT carried_over FROM vacay_user_years WHERE user_id = ? AND plan_id = ? AND year = ?')
.get(user.id, plan.id, nextYear) as { carried_over: number } | undefined;
// 10 vacation days - 3 used = 7 carried over
expect(userYear?.carried_over).toBe(7);
});
});
describe('deleteYear', () => {
it('VACAY-SVC-030: removes the year row and its associated entries', () => {
const { user, plan } = setupUserWithPlan();
const targetYear = new Date().getFullYear() + 3;
addYear(plan.id, targetYear, undefined);
// Insert an entry for that year
testDb
.prepare('INSERT INTO vacay_entries (plan_id, user_id, date, note) VALUES (?, ?, ?, ?)')
.run(plan.id, user.id, `${targetYear}-07-15`, '');
deleteYear(plan.id, targetYear, undefined);
const yearRow = testDb
.prepare('SELECT * FROM vacay_years WHERE plan_id = ? AND year = ?')
.get(plan.id, targetYear);
expect(yearRow).toBeUndefined();
const entries = testDb
.prepare("SELECT * FROM vacay_entries WHERE plan_id = ? AND date LIKE ?")
.all(plan.id, `${targetYear}-%`);
expect(entries).toHaveLength(0);
});
});
// ── getEntries / toggleEntry ──────────────────────────────────────────────────
describe('getEntries', () => {
it('VACAY-SVC-031: returns empty entries and companyHolidays for a new plan+year', () => {
const { plan } = setupUserWithPlan();
const yr = new Date().getFullYear().toString();
const result = getEntries(plan.id, yr);
expect(result.entries).toEqual([]);
expect(result.companyHolidays).toEqual([]);
});
});
describe('toggleEntry', () => {
it('VACAY-SVC-032: adds an entry on first call (action: added)', () => {
const { user, plan } = setupUserWithPlan();
const result = toggleEntry(user.id, plan.id, '2025-08-01', undefined);
expect(result.action).toBe('added');
const row = testDb
.prepare('SELECT * FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date = ?')
.get(user.id, plan.id, '2025-08-01');
expect(row).toBeDefined();
});
it('VACAY-SVC-033: removes the entry on second call (action: removed)', () => {
const { user, plan } = setupUserWithPlan();
toggleEntry(user.id, plan.id, '2025-08-02', undefined);
const result = toggleEntry(user.id, plan.id, '2025-08-02', undefined);
expect(result.action).toBe('removed');
const row = testDb
.prepare('SELECT * FROM vacay_entries WHERE user_id = ? AND plan_id = ? AND date = ?')
.get(user.id, plan.id, '2025-08-02');
expect(row).toBeUndefined();
});
});
// ── toggleCompanyHoliday ──────────────────────────────────────────────────────
describe('toggleCompanyHoliday', () => {
it('VACAY-SVC-034: adds a company holiday on first call (action: added)', () => {
const { plan } = setupUserWithPlan();
const result = toggleCompanyHoliday(plan.id, '2025-12-25', 'Christmas', undefined);
expect(result.action).toBe('added');
const row = testDb
.prepare('SELECT * FROM vacay_company_holidays WHERE plan_id = ? AND date = ?')
.get(plan.id, '2025-12-25');
expect(row).toBeDefined();
});
it('VACAY-SVC-035: removes the company holiday on second call (action: removed)', () => {
const { plan } = setupUserWithPlan();
toggleCompanyHoliday(plan.id, '2025-12-26', 'Boxing Day', undefined);
const result = toggleCompanyHoliday(plan.id, '2025-12-26', undefined, undefined);
expect(result.action).toBe('removed');
const row = testDb
.prepare('SELECT * FROM vacay_company_holidays WHERE plan_id = ? AND date = ?')
.get(plan.id, '2025-12-26');
expect(row).toBeUndefined();
});
it('VACAY-SVC-036: adding a company holiday removes any existing vacay_entry on that date', () => {
const { user, plan } = setupUserWithPlan();
// First add a personal entry on that date
toggleEntry(user.id, plan.id, '2025-05-01', undefined);
// Now declare it a company holiday — the personal entry should be wiped
toggleCompanyHoliday(plan.id, '2025-05-01', 'Labour Day', undefined);
const personalEntry = testDb
.prepare('SELECT * FROM vacay_entries WHERE plan_id = ? AND date = ?')
.get(plan.id, '2025-05-01');
expect(personalEntry).toBeUndefined();
});
});
// ── acceptInvite / declineInvite / cancelInvite ───────────────────────────────
describe('acceptInvite', () => {
it('VACAY-SVC-037: changes membership status to accepted', () => {
const { user: owner, plan: ownerPlan } = setupUserWithPlan();
const { user: invitee } = createUser(testDb);
getOwnPlan(invitee.id); // ensure own plan exists for data migration path
insertMember(ownerPlan.id, invitee.id, 'pending');
const result = acceptInvite(invitee.id, ownerPlan.id, undefined);
expect(result.error).toBeUndefined();
const row = testDb
.prepare('SELECT status FROM vacay_plan_members WHERE plan_id = ? AND user_id = ?')
.get(ownerPlan.id, invitee.id) as { status: string } | undefined;
expect(row?.status).toBe('accepted');
});
it('VACAY-SVC-038: returns 404 error when there is no pending invite', () => {
const { user } = createUser(testDb);
const result = acceptInvite(user.id, 99999, undefined);
expect(result.status).toBe(404);
expect(result.error).toBeDefined();
});
it('VACAY-SVC-039: accepted member becomes visible via getActivePlan', () => {
const { user: owner, plan: ownerPlan } = setupUserWithPlan();
const { user: invitee } = createUser(testDb);
getOwnPlan(invitee.id);
insertMember(ownerPlan.id, invitee.id, 'pending');
acceptInvite(invitee.id, ownerPlan.id, undefined);
const active = getActivePlan(invitee.id);
expect(active.id).toBe(ownerPlan.id);
});
});
describe('declineInvite', () => {
it('VACAY-SVC-040: removes the pending invite row', () => {
const { user: owner, plan: ownerPlan } = setupUserWithPlan();
const { user: invitee } = createUser(testDb);
insertMember(ownerPlan.id, invitee.id, 'pending');
declineInvite(invitee.id, ownerPlan.id, undefined);
const row = testDb
.prepare('SELECT * FROM vacay_plan_members WHERE plan_id = ? AND user_id = ?')
.get(ownerPlan.id, invitee.id);
expect(row).toBeUndefined();
});
});
describe('cancelInvite', () => {
it('VACAY-SVC-041: removes the pending invite when owner cancels it', () => {
const { user: owner, plan: ownerPlan } = setupUserWithPlan();
const { user: target } = createUser(testDb);
insertMember(ownerPlan.id, target.id, 'pending');
cancelInvite(ownerPlan.id, target.id);
const row = testDb
.prepare('SELECT * FROM vacay_plan_members WHERE plan_id = ? AND user_id = ?')
.get(ownerPlan.id, target.id);
expect(row).toBeUndefined();
});
});
// ── getAvailableUsers ─────────────────────────────────────────────────────────
describe('getAvailableUsers', () => {
it('VACAY-SVC-042: returns users not already in the plan and not fused elsewhere', () => {
const { user: owner, plan } = setupUserWithPlan();
const { user: unrelated } = createUser(testDb);
getOwnPlan(unrelated.id);
const available = getAvailableUsers(owner.id, plan.id) as { id: number }[];
expect(available.map(u => u.id)).toContain(unrelated.id);
// Owner themselves should NOT appear (excluded by u.id != ?)
expect(available.map(u => u.id)).not.toContain(owner.id);
});
it('VACAY-SVC-043: excludes users who already have an accepted membership in any plan', () => {
const { user: owner, plan } = setupUserWithPlan();
const { user: alreadyFused } = createUser(testDb);
const { plan: otherPlan } = setupUserWithPlan();
insertMember(otherPlan.id, alreadyFused.id, 'accepted');
const available = getAvailableUsers(owner.id, plan.id) as { id: number }[];
expect(available.map(u => u.id)).not.toContain(alreadyFused.id);
});
});
// ── getStats ──────────────────────────────────────────────────────────────────
describe('getStats', () => {
it('VACAY-SVC-044: returns per-user stats with correct fields', () => {
const { user, plan } = setupUserWithPlan();
const yr = new Date().getFullYear();
const stats = getStats(plan.id, yr);
expect(stats).toHaveLength(1);
expect(stats[0]).toMatchObject({
user_id: user.id,
year: yr,
vacation_days: 30,
used: 0,
remaining: 30,
});
});
it('VACAY-SVC-045: used reflects the actual number of entries for that user and year', () => {
const { user, plan } = setupUserWithPlan();
const yr = new Date().getFullYear();
toggleEntry(user.id, plan.id, `${yr}-09-10`, undefined);
toggleEntry(user.id, plan.id, `${yr}-09-11`, undefined);
const stats = getStats(plan.id, yr);
expect(stats[0].used).toBe(2);
expect(stats[0].remaining).toBe(28);
});
});
// ── applyHolidayCalendars ─────────────────────────────────────────────────────
describe('applyHolidayCalendars', () => {
it('VACAY-SVC-046: does nothing when holidays_enabled is 0 (fetch is never called)', async () => {
const { plan } = setupUserWithPlan();
// holidays_enabled defaults to 0
await applyHolidayCalendars(plan.id);
expect(vi.mocked(fetch)).not.toHaveBeenCalled();
});
it('VACAY-SVC-047: deletes matching vacay_entries for a global holiday date returned by the API', async () => {
const { user, plan } = setupUserWithPlan();
const yr = new Date().getFullYear();
// Enable holidays and add a calendar
testDb.prepare('UPDATE vacay_plans SET holidays_enabled = 1 WHERE id = ?').run(plan.id);
addHolidayCalendar(plan.id, 'DE', null, undefined, 0, undefined);
// Add a vacay entry on the holiday date
const holidayDate = `${yr}-01-01`;
testDb
.prepare('INSERT INTO vacay_entries (plan_id, user_id, date, note) VALUES (?, ?, ?, ?)')
.run(plan.id, user.id, holidayDate, '');
// Override fetch to return one global holiday matching that entry
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => [{ date: holidayDate, global: true }],
}));
await applyHolidayCalendars(plan.id);
const remaining = testDb
.prepare('SELECT * FROM vacay_entries WHERE plan_id = ? AND date = ?')
.all(plan.id, holidayDate);
expect(remaining).toHaveLength(0);
});
});
@@ -1,187 +0,0 @@
/**
* Unit tests for checkAndNotifyVersion() in adminService.
* Covers VNOTIF-001 to VNOTIF-007.
*/
import { runMigrations } from '../../../src/db/migrations';
import { createTables } from '../../../src/db/schema';
import { checkAndNotifyVersion, __clearVersionCacheForTests } from '../../../src/services/adminService';
import { createAdmin } from '../../helpers/factories';
import { resetTestDb } from '../../helpers/test-db';
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/websocket', () => ({ broadcastToUser: vi.fn() }));
// Mock MCP to avoid session side-effects
vi.mock('../../../src/mcp', () => ({ revokeUserSessions: vi.fn() }));
// Helper: mock the GitHub releases/latest endpoint
function mockGitHubLatest(tagName: string, ok = true): void {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok,
json: async () => ({ tag_name: tagName, html_url: `https://github.com/liketrek/TREK/releases/tag/${tagName}` }),
}),
);
}
function mockGitHubFetchFailure(): void {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network error')));
}
function getLastNotifiedVersion(): string | undefined {
return (
testDb.prepare('SELECT value FROM app_settings WHERE key = ?').get('last_notified_version') as
| { value: string }
| undefined
)?.value;
}
function getNotificationCount(): number {
return (testDb.prepare('SELECT COUNT(*) as c FROM notifications').get() as { c: number }).c;
}
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
__clearVersionCacheForTests();
vi.unstubAllGlobals();
});
afterAll(() => {
testDb.close();
vi.unstubAllGlobals();
});
// ─────────────────────────────────────────────────────────────────────────────
// checkAndNotifyVersion
// ─────────────────────────────────────────────────────────────────────────────
describe('checkAndNotifyVersion', () => {
it('VNOTIF-001 — does nothing when no update is available', async () => {
createAdmin(testDb);
// GitHub reports same version as package.json (or older) → update_available: false
const { version } = require('../../../package.json');
mockGitHubLatest(`v${version}`);
await checkAndNotifyVersion();
expect(getNotificationCount()).toBe(0);
expect(getLastNotifiedVersion()).toBeUndefined();
});
it('VNOTIF-002 — creates a navigate notification for all admins when update available', async () => {
const { user: admin1 } = createAdmin(testDb);
const { user: admin2 } = createAdmin(testDb);
mockGitHubLatest('v99.0.0');
await checkAndNotifyVersion();
const notifications = testDb.prepare('SELECT * FROM notifications ORDER BY id').all() as Array<{
recipient_id: number;
type: string;
scope: string;
}>;
expect(notifications.length).toBe(2);
const recipientIds = notifications.map((n) => n.recipient_id);
expect(recipientIds).toContain(admin1.id);
expect(recipientIds).toContain(admin2.id);
expect(notifications[0].type).toBe('navigate');
expect(notifications[0].scope).toBe('admin');
});
it('VNOTIF-003 — sets last_notified_version in app_settings after notifying', async () => {
createAdmin(testDb);
mockGitHubLatest('v99.1.0');
await checkAndNotifyVersion();
expect(getLastNotifiedVersion()).toBe('99.1.0');
});
it('VNOTIF-004 — does NOT create duplicate notification if last_notified_version matches', async () => {
createAdmin(testDb);
mockGitHubLatest('v99.2.0');
// First call notifies
await checkAndNotifyVersion();
const countAfterFirst = getNotificationCount();
expect(countAfterFirst).toBe(1);
// Second call with same version — should not create another
await checkAndNotifyVersion();
expect(getNotificationCount()).toBe(countAfterFirst);
});
it('VNOTIF-005 — creates new notification when last_notified_version is an older version', async () => {
createAdmin(testDb);
// Simulate having been notified about an older version
testDb
.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)')
.run('last_notified_version', '98.0.0');
mockGitHubLatest('v99.3.0');
await checkAndNotifyVersion();
expect(getNotificationCount()).toBe(1);
expect(getLastNotifiedVersion()).toBe('99.3.0');
});
it('VNOTIF-006 — notification has correct type, scope, and navigate_target', async () => {
createAdmin(testDb);
mockGitHubLatest('v99.4.0');
await checkAndNotifyVersion();
const notif = testDb.prepare('SELECT * FROM notifications LIMIT 1').get() as {
type: string;
scope: string;
navigate_target: string;
title_key: string;
text_key: string;
navigate_text_key: string;
};
expect(notif.type).toBe('navigate');
expect(notif.scope).toBe('admin');
expect(notif.navigate_target).toBe('/admin');
expect(notif.title_key).toBe('notif.version_available.title');
expect(notif.text_key).toBe('notif.version_available.text');
expect(notif.navigate_text_key).toBe('notif.action.view_admin');
});
it('VNOTIF-007 — silently handles GitHub API fetch failure (no crash, no notification)', async () => {
createAdmin(testDb);
mockGitHubFetchFailure();
// Should not throw
await expect(checkAndNotifyVersion()).resolves.toBeUndefined();
expect(getNotificationCount()).toBe(0);
expect(getLastNotifiedVersion()).toBeUndefined();
});
});
@@ -1,719 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
// Prevent the module-level setInterval from running during tests
vi.useFakeTimers();
// Prevent real HTTP requests
vi.stubGlobal('fetch', vi.fn());
afterAll(() => vi.unstubAllGlobals());
import {
estimateCondition,
cacheKey,
getWeather,
getDetailedWeather,
ApiError,
type WeatherResult,
} from '../../../src/services/weatherService';
// ── estimateCondition ────────────────────────────────────────────────────────
describe('estimateCondition', () => {
describe('heavy precipitation (precipMm > 5)', () => {
it('returns Snow when temp <= 0', () => {
expect(estimateCondition(0, 6)).toBe('Snow');
expect(estimateCondition(-5, 10)).toBe('Snow');
});
it('returns Rain when temp > 0', () => {
expect(estimateCondition(1, 6)).toBe('Rain');
expect(estimateCondition(20, 50)).toBe('Rain');
});
it('boundary: precipMm = 5.01 and temp = 0 -> Snow', () => {
expect(estimateCondition(0, 5.01)).toBe('Snow');
});
it('boundary: precipMm = 5 is NOT heavy (exactly 5, not > 5) -> falls through', () => {
// precipMm = 5 fails the > 5 check, falls to > 1 check -> Snow or Drizzle
expect(estimateCondition(0, 5)).toBe('Snow'); // > 1 and temp <= 0
expect(estimateCondition(5, 5)).toBe('Drizzle'); // > 1 and temp > 0
});
});
describe('moderate precipitation (precipMm > 1)', () => {
it('returns Snow when temp <= 0', () => {
expect(estimateCondition(0, 2)).toBe('Snow');
expect(estimateCondition(-10, 1.5)).toBe('Snow');
});
it('returns Drizzle when temp > 0', () => {
expect(estimateCondition(5, 2)).toBe('Drizzle');
expect(estimateCondition(15, 3)).toBe('Drizzle');
});
});
describe('light precipitation (precipMm > 0.3)', () => {
it('returns Clouds regardless of temperature', () => {
expect(estimateCondition(-5, 0.5)).toBe('Clouds');
expect(estimateCondition(25, 0.5)).toBe('Clouds');
});
it('boundary: precipMm = 0.31 -> Clouds', () => {
expect(estimateCondition(20, 0.31)).toBe('Clouds');
});
it('boundary: precipMm = 0.3 is NOT light precipitation -> falls through', () => {
// precipMm = 0.3 fails the > 0.3 check, falls to temperature check
expect(estimateCondition(20, 0.3)).toBe('Clear'); // temp > 15
expect(estimateCondition(10, 0.3)).toBe('Clouds'); // temp <= 15
});
});
describe('dry conditions (precipMm <= 0.3)', () => {
it('returns Clear when temp > 15', () => {
expect(estimateCondition(16, 0)).toBe('Clear');
expect(estimateCondition(30, 0.1)).toBe('Clear');
});
it('returns Clouds when temp <= 15', () => {
expect(estimateCondition(15, 0)).toBe('Clouds');
expect(estimateCondition(10, 0)).toBe('Clouds');
expect(estimateCondition(-5, 0)).toBe('Clouds');
});
it('boundary: temp = 15 -> Clouds (not > 15)', () => {
expect(estimateCondition(15, 0)).toBe('Clouds');
});
});
});
// ── cacheKey ─────────────────────────────────────────────────────────────────
describe('cacheKey', () => {
it('rounds lat and lng to 2 decimal places', () => {
expect(cacheKey('48.8566', '2.3522', '2024-06-15')).toBe('48.86_2.35_2024-06-15');
});
it('uses "current" when date is undefined', () => {
expect(cacheKey('10.0', '20.0')).toBe('10.00_20.00_current');
});
it('handles negative coordinates', () => {
expect(cacheKey('-33.8688', '151.2093', '2024-01-01')).toBe('-33.87_151.21_2024-01-01');
});
it('pads to 2 decimal places for round numbers', () => {
expect(cacheKey('48', '2', '2024-01-01')).toBe('48.00_2.00_2024-01-01');
});
it('preserves the date string as-is', () => {
expect(cacheKey('0', '0', 'climate')).toBe('0.00_0.00_climate');
});
});
// ── Helpers ───────────────────────────────────────────────────────────────────
/** Build a minimal mock Response for fetch. */
function mockResponse(body: unknown, ok = true, status = 200): Response {
return {
ok,
status,
json: vi.fn().mockResolvedValue(body),
} as unknown as Response;
}
/** ISO date string offset by `days` from now (fake-timer "now"). */
function dateOffset(days: number): string {
const d = new Date(Date.now() + days * 24 * 60 * 60 * 1000);
return d.toISOString().slice(0, 10);
}
// ── getWeather ────────────────────────────────────────────────────────────────
describe('getWeather', () => {
// Use coordinates that are unique per describe block to avoid cross-test cache
// pollution. Each nested describe uses a distinct lat so the module-level Map
// never returns stale data from a sibling test.
beforeEach(() => {
vi.mocked(fetch).mockReset();
});
describe('with date — cache hit', () => {
it('returns cached result without calling fetch', async () => {
const date = dateOffset(2);
const forecastBody = {
daily: {
time: [date],
temperature_2m_max: [20],
temperature_2m_min: [10],
weathercode: [0],
},
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(forecastBody));
// First call populates the cache
const first = await getWeather('10.00', '20.00', date, 'en');
expect(fetch).toHaveBeenCalledTimes(1);
vi.mocked(fetch).mockReset();
// Second call with identical arguments should be served from cache
const second = await getWeather('10.00', '20.00', date, 'en');
expect(fetch).not.toHaveBeenCalled();
expect(second).toEqual(first);
});
});
describe('with date — forecast path (diffDays -1 .. +16)', () => {
it('returns a forecast WeatherResult for a date 3 days away', async () => {
const date = dateOffset(3);
const body = {
daily: {
time: [date],
temperature_2m_max: [25],
temperature_2m_min: [15],
weathercode: [1],
},
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getWeather('11.00', '21.00', date, 'en');
expect(result.type).toBe('forecast');
expect(result.temp).toBe(20); // (25+15)/2
expect(result.temp_max).toBe(25);
expect(result.temp_min).toBe(15);
expect(result.main).toBe('Clear'); // WMO code 1
expect(result.description).toBe('Mainly clear');
});
it('uses German descriptions when lang is "de"', async () => {
const date = dateOffset(4);
const body = {
daily: {
time: [date],
temperature_2m_max: [10],
temperature_2m_min: [5],
weathercode: [3],
},
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getWeather('11.01', '21.01', date, 'de');
expect(result.description).toBe('Bewolkt'); // German for code 3
});
it('falls back to "Clouds" for an unknown WMO code', async () => {
const date = dateOffset(5);
const body = {
daily: {
time: [date],
temperature_2m_max: [10],
temperature_2m_min: [5],
weathercode: [999], // not in WMO_MAP
},
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getWeather('11.02', '21.02', date, 'en');
expect(result.main).toBe('Clouds');
});
it('throws ApiError when response.ok is false', async () => {
const date = dateOffset(2);
const body = { reason: 'rate limited' };
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body, false, 429));
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body, false, 429));
await expect(getWeather('12.00', '22.00', date, 'en')).rejects.toThrow(ApiError);
await expect(getWeather('12.00', '22.00', date, 'en')).rejects.toMatchObject({
status: 429,
message: 'rate limited',
});
});
it('throws ApiError when data.error is true', async () => {
const date = dateOffset(2);
const body = { error: true, reason: 'invalid coordinates' };
// Need a fresh coordinate to avoid the cache from the previous test failure
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body, true, 200));
await expect(getWeather('12.01', '22.01', date, 'en')).rejects.toThrow(ApiError);
});
it('falls through to climate path when date is not found in forecast data', async () => {
// The forecast API returns data but NOT for our target date; the code
// checks idx === -1 and falls into the diffDays > -1 climate branch.
const date = dateOffset(3);
const forecastBody = {
daily: {
time: ['1970-01-01'], // deliberately wrong date
temperature_2m_max: [10],
temperature_2m_min: [5],
weathercode: [0],
},
};
// Archive response for the climate fallback
const refDate = new Date(Date.now() + 3 * 24 * 60 * 60 * 1000);
const archiveBody = {
daily: {
time: ['some-date'],
temperature_2m_max: [18],
temperature_2m_min: [8],
precipitation_sum: [0],
},
};
vi.mocked(fetch)
.mockResolvedValueOnce(mockResponse(forecastBody))
.mockResolvedValueOnce(mockResponse(archiveBody));
const result = await getWeather('13.00', '23.00', date, 'en');
expect(result.type).toBe('climate');
expect(fetch).toHaveBeenCalledTimes(2);
});
});
describe('with date — past date (diffDays < -1)', () => {
it('returns forecast-type WeatherResult from the archive API', async () => {
const date = dateOffset(-5); // 5 days in the past
const archiveBody = {
daily: {
time: [date],
temperature_2m_max: [18],
temperature_2m_min: [10],
weathercode: [2],
precipitation_sum: [0],
},
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(archiveBody));
const result = await getWeather('14.00', '24.00', date, 'en');
expect(result.type).toBe('forecast');
expect(result.temp).toBe(14);
expect(result.temp_max).toBe(18);
expect(result.temp_min).toBe(10);
expect(fetch).toHaveBeenCalledTimes(1);
expect(vi.mocked(fetch).mock.calls[0][0]).toContain('archive-api.open-meteo.com');
});
it('returns no_forecast error when archive has no data for the date', async () => {
const date = dateOffset(-5);
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ daily: { time: [], temperature_2m_max: [], temperature_2m_min: [], weathercode: [] } }));
const result = await getWeather('14.01', '24.01', date, 'en');
expect(result.error).toBe('no_forecast');
});
});
describe('with date — climate / archive path (diffDays > 16)', () => {
it('returns a climate WeatherResult for a far-future date', async () => {
const date = dateOffset(20);
const body = {
daily: {
time: ['2025-01-01', '2025-01-02'],
temperature_2m_max: [22, 24],
temperature_2m_min: [12, 14],
precipitation_sum: [0, 0.1],
},
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getWeather('15.00', '25.00', date, 'en');
expect(result.type).toBe('climate');
expect(result.temp).toBe(18); // avg of (22+12)/2=17 and (24+14)/2=19 -> avg 18
expect(result.temp_max).toBe(23);
expect(result.temp_min).toBe(13);
});
it('throws ApiError when archive API response.ok is false', async () => {
const date = dateOffset(20);
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ reason: 'server error' }, false, 500));
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ reason: 'server error' }, false, 500));
await expect(getWeather('15.01', '25.01', date, 'en')).rejects.toThrow(ApiError);
await expect(getWeather('15.01', '25.01', date, 'en')).rejects.toMatchObject({ status: 500 });
});
it('returns no_forecast when archive daily data is missing', async () => {
const date = dateOffset(20);
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({}));
const result = await getWeather('15.02', '25.02', date, 'en');
expect(result.error).toBe('no_forecast');
});
it('returns no_forecast when archive daily.time is empty', async () => {
const date = dateOffset(20);
const body = { daily: { time: [], temperature_2m_max: [], temperature_2m_min: [], precipitation_sum: [] } };
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getWeather('15.03', '25.03', date, 'en');
expect(result.error).toBe('no_forecast');
});
it('returns no_forecast when all temperature entries are null', async () => {
const date = dateOffset(20);
const body = {
daily: {
time: ['2025-01-01'],
temperature_2m_max: [null],
temperature_2m_min: [null],
precipitation_sum: [0],
},
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getWeather('15.04', '25.04', date, 'en');
expect(result.error).toBe('no_forecast');
});
});
describe('without date — current weather path', () => {
it('returns current WeatherResult', async () => {
const body = {
current: { temperature_2m: 18.7, weathercode: 2 },
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getWeather('16.00', '26.00', undefined, 'en');
expect(result.type).toBe('current');
expect(result.temp).toBe(19); // Math.round(18.7)
expect(result.main).toBe('Clouds'); // WMO code 2
expect(result.description).toBe('Partly cloudy');
});
it('uses German descriptions when lang is "de"', async () => {
const body = { current: { temperature_2m: 10, weathercode: 45 } };
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getWeather('16.01', '26.01', undefined, 'de');
expect(result.description).toBe('Nebel');
});
it('returns cached current weather on second identical call', async () => {
const body = { current: { temperature_2m: 22, weathercode: 0 } };
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const first = await getWeather('16.02', '26.02', undefined, 'en');
vi.mocked(fetch).mockReset();
const second = await getWeather('16.02', '26.02', undefined, 'en');
expect(fetch).not.toHaveBeenCalled();
expect(second).toEqual(first);
});
it('throws ApiError when current weather API returns error', async () => {
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ reason: 'bad request' }, false, 400));
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ reason: 'bad request' }, false, 400));
await expect(getWeather('16.03', '26.03', undefined, 'en')).rejects.toThrow(ApiError);
await expect(getWeather('16.03', '26.03', undefined, 'en')).rejects.toMatchObject({ status: 400 });
});
it('throws ApiError when data.error flag is set on current weather response', async () => {
const body = { error: true, reason: 'quota exceeded' };
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body, true, 200));
await expect(getWeather('16.04', '26.04', undefined, 'en')).rejects.toThrow(ApiError);
});
});
});
// ── getDetailedWeather ────────────────────────────────────────────────────────
describe('getDetailedWeather', () => {
beforeEach(() => {
vi.mocked(fetch).mockReset();
});
describe('cache hit', () => {
it('returns cached result without calling fetch a second time', async () => {
const date = dateOffset(5);
const dailyBody = {
daily: {
time: [date],
temperature_2m_max: [28],
temperature_2m_min: [18],
weathercode: [0],
precipitation_sum: [0],
precipitation_probability_max: [0],
windspeed_10m_max: [10],
sunrise: [`${date}T06:00`],
sunset: [`${date}T20:00`],
},
hourly: { time: [], temperature_2m: [] },
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(dailyBody));
const first = await getDetailedWeather('30.00', '40.00', date, 'en');
vi.mocked(fetch).mockReset();
const second = await getDetailedWeather('30.00', '40.00', date, 'en');
expect(fetch).not.toHaveBeenCalled();
expect(second).toEqual(first);
});
});
describe('forecast path (diffDays <= 16)', () => {
it('returns a detailed forecast WeatherResult with hourly data', async () => {
const date = dateOffset(6);
const body = {
daily: {
time: [date],
temperature_2m_max: [30],
temperature_2m_min: [20],
weathercode: [80],
precipitation_sum: [5],
precipitation_probability_max: [70],
windspeed_10m_max: [15],
sunrise: [`${date}T05:45`],
sunset: [`${date}T21:15`],
},
hourly: {
time: [`${date}T12:00`, `${date}T13:00`],
temperature_2m: [28, 29],
precipitation_probability: [60, 65],
precipitation: [1.2, 0.8],
weathercode: [80, 81],
windspeed_10m: [12, 14],
relativehumidity_2m: [70, 68],
},
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getDetailedWeather('31.00', '41.00', date, 'en');
expect(result.type).toBe('forecast');
expect(result.temp).toBe(25); // (30+20)/2
expect(result.temp_max).toBe(30);
expect(result.temp_min).toBe(20);
expect(result.main).toBe('Rain'); // WMO code 80
expect(result.precipitation_sum).toBe(5);
expect(result.precipitation_probability_max).toBe(70);
expect(result.wind_max).toBe(15);
expect(result.sunrise).toBe('05:45');
expect(result.sunset).toBe('21:15');
expect(result.hourly).toHaveLength(2);
expect(result.hourly![0].temp).toBe(28);
expect(result.hourly![0].precipitation_probability).toBe(60);
expect(result.hourly![1].main).toBe('Rain'); // WMO code 81
});
it('returns no_forecast when daily data is missing', async () => {
const date = dateOffset(7);
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({}));
const result = await getDetailedWeather('31.01', '41.01', date, 'en');
expect(result.error).toBe('no_forecast');
});
it('returns no_forecast when daily.time is empty', async () => {
const date = dateOffset(7);
const body = {
daily: {
time: [],
temperature_2m_max: [],
temperature_2m_min: [],
weathercode: [],
},
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getDetailedWeather('31.02', '41.02', date, 'en');
expect(result.error).toBe('no_forecast');
});
it('throws ApiError when forecast API returns !ok', async () => {
const date = dateOffset(8);
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ reason: 'not found' }, false, 404));
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ reason: 'not found' }, false, 404));
await expect(getDetailedWeather('31.03', '41.03', date, 'en')).rejects.toThrow(ApiError);
await expect(getDetailedWeather('31.03', '41.03', date, 'en')).rejects.toMatchObject({ status: 404 });
});
it('throws ApiError when data.error flag is set', async () => {
const date = dateOffset(9);
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ error: true, reason: 'bad coords' }));
await expect(getDetailedWeather('31.04', '41.04', date, 'en')).rejects.toThrow(ApiError);
});
it('handles missing hourly block gracefully', async () => {
const date = dateOffset(10);
const body = {
daily: {
time: [date],
temperature_2m_max: [20],
temperature_2m_min: [10],
weathercode: [0],
precipitation_sum: [0],
precipitation_probability_max: [0],
windspeed_10m_max: [5],
sunrise: [`${date}T06:00`],
sunset: [`${date}T20:00`],
},
// no hourly field
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getDetailedWeather('31.05', '41.05', date, 'en');
expect(result.type).toBe('forecast');
expect(result.hourly).toEqual([]);
});
});
describe('climate / archive path (diffDays > 16)', () => {
it('returns a detailed climate WeatherResult with hourly data', async () => {
const date = dateOffset(20);
const refDate = new Date(Date.now() + 20 * 24 * 60 * 60 * 1000);
const refYear = refDate.getFullYear() - 1;
const refDateStr = `${refYear}-${String(refDate.getMonth() + 1).padStart(2, '0')}-${String(refDate.getDate()).padStart(2, '0')}`;
const body = {
daily: {
time: [refDateStr],
temperature_2m_max: [26],
temperature_2m_min: [16],
weathercode: [63],
precipitation_sum: [8],
windspeed_10m_max: [20],
sunrise: [`${refDateStr}T06:30`],
sunset: [`${refDateStr}T20:30`],
},
hourly: {
time: [`${refDateStr}T10:00`, `${refDateStr}T11:00`],
temperature_2m: [22, 24],
precipitation: [2, 1],
weathercode: [63, 61],
windspeed_10m: [18, 16],
relativehumidity_2m: [80, 75],
},
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getDetailedWeather('32.00', '42.00', date, 'en');
expect(result.type).toBe('climate');
expect(result.temp).toBe(21); // (26+16)/2
expect(result.temp_max).toBe(26);
expect(result.temp_min).toBe(16);
expect(result.main).toBe('Rain'); // WMO code 63
expect(result.description).toBe('Rain'); // WMO_DESCRIPTION_EN[63]
expect(result.precipitation_sum).toBe(8);
expect(result.wind_max).toBe(20);
expect(result.sunrise).toBe('06:30');
expect(result.sunset).toBe('20:30');
expect(result.hourly).toHaveLength(2);
expect(result.hourly![0].temp).toBe(22);
expect(result.hourly![0].precipitation).toBe(2);
expect(result.hourly![1].main).toBe('Rain'); // WMO code 61
});
it('uses German descriptions when lang is "de"', async () => {
const date = dateOffset(20);
const refDate = new Date(Date.now() + 20 * 24 * 60 * 60 * 1000);
const refYear = refDate.getFullYear() - 1;
const refDateStr = `${refYear}-${String(refDate.getMonth() + 1).padStart(2, '0')}-${String(refDate.getDate()).padStart(2, '0')}`;
const body = {
daily: {
time: [refDateStr],
temperature_2m_max: [20],
temperature_2m_min: [10],
weathercode: [0],
precipitation_sum: [0],
windspeed_10m_max: [5],
},
hourly: { time: [], temperature_2m: [] },
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getDetailedWeather('32.01', '42.01', date, 'de');
expect(result.description).toBe('Klar'); // German WMO_DESCRIPTION_DE[0]
});
it('returns no_forecast when archive daily data is missing', async () => {
const date = dateOffset(20);
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({}));
const result = await getDetailedWeather('32.02', '42.02', date, 'en');
expect(result.error).toBe('no_forecast');
});
it('returns no_forecast when archive daily.time is empty', async () => {
const date = dateOffset(20);
const body = { daily: { time: [], temperature_2m_max: [], temperature_2m_min: [], weathercode: [] } };
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getDetailedWeather('32.03', '42.03', date, 'en');
expect(result.error).toBe('no_forecast');
});
it('throws ApiError when archive API returns !ok', async () => {
const date = dateOffset(20);
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ reason: 'upstream error' }, false, 503));
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ reason: 'upstream error' }, false, 503));
await expect(getDetailedWeather('32.04', '42.04', date, 'en')).rejects.toThrow(ApiError);
await expect(getDetailedWeather('32.04', '42.04', date, 'en')).rejects.toMatchObject({ status: 503 });
});
it('throws ApiError when archive data.error flag is set', async () => {
const date = dateOffset(20);
vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ error: true, reason: 'quota exceeded' }));
await expect(getDetailedWeather('32.05', '42.05', date, 'en')).rejects.toThrow(ApiError);
});
it('falls back to estimateCondition when archive weathercode is undefined', async () => {
// When daily.weathercode[0] is undefined, the code falls back to
// estimateCondition(avgTemp, precipitation_sum)
const date = dateOffset(20);
const refDate = new Date(Date.now() + 20 * 24 * 60 * 60 * 1000);
const refYear = refDate.getFullYear() - 1;
const refDateStr = `${refYear}-${String(refDate.getMonth() + 1).padStart(2, '0')}-${String(refDate.getDate()).padStart(2, '0')}`;
const body = {
daily: {
time: [refDateStr],
temperature_2m_max: [20],
temperature_2m_min: [10],
// weathercode intentionally omitted — will be undefined
precipitation_sum: [10], // > 5 mm and temp > 0 -> 'Rain'
windspeed_10m_max: [5],
},
hourly: { time: [], temperature_2m: [] },
};
vi.mocked(fetch).mockResolvedValueOnce(mockResponse(body));
const result = await getDetailedWeather('32.06', '42.06', date, 'en');
// undefined code -> WMO_MAP[undefined] is undefined -> falls back to estimateCondition
// avgTemp = (20+10)/2 = 15, precip = 10 > 5 and temp 15 > 0 -> 'Rain'
expect(result.main).toBe('Rain');
});
});
});
@@ -1,103 +0,0 @@
/**
* webauthnConfig.test.ts
*
* The RP-ID / allowed-origin resolver is the single highest-risk piece of the
* passkey feature: a wrong RP ID permanently bricks every enrolled credential.
* These tests pin the security-relevant rules — config wins over APP_URL, bare
* IPs are rejected, localhost dev uses the browser (Vite) origin, and the
* resolver NEVER reads request headers.
*/
const { settingsStore, appUrlRef } = vi.hoisted(() => ({
settingsStore: new Map<string, string>(),
appUrlRef: { value: '' },
}));
vi.mock('../../../src/db/database', () => ({
db: {
prepare: (_sql: string) => ({
get: (key: string) => {
const v = settingsStore.get(key);
return v === undefined ? undefined : { value: v };
},
}),
},
}));
vi.mock('../../../src/services/notifications', () => ({
getAppUrl: () => appUrlRef.value,
}));
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { resolveWebauthnConfig, isPasskeyConfigured } from '../../../src/services/webauthnConfig';
beforeEach(() => {
settingsStore.clear();
appUrlRef.value = '';
});
afterEach(() => {
vi.unstubAllEnvs();
});
describe('resolveWebauthnConfig', () => {
it('WAC-001: derives the RP ID and single origin from a real APP_URL domain', () => {
appUrlRef.value = 'https://trek.example.org';
const cfg = resolveWebauthnConfig();
expect(cfg).not.toBeNull();
expect(cfg!.rpID).toBe('trek.example.org');
expect(cfg!.origins).toEqual(['https://trek.example.org']);
expect(isPasskeyConfigured()).toBe(true);
});
it('WAC-002: returns null for a bare-IP host (IPs are not valid RP IDs)', () => {
appUrlRef.value = 'http://192.168.1.50:3001';
expect(resolveWebauthnConfig()).toBeNull();
expect(isPasskeyConfigured()).toBe(false);
});
it('WAC-003: returns null when nothing is configured', () => {
expect(resolveWebauthnConfig()).toBeNull();
expect(isPasskeyConfigured()).toBe(false);
});
it('WAC-004: localhost dev uses the browser (Vite :5173) origin, not just the API port', () => {
appUrlRef.value = 'http://localhost:3001';
const cfg = resolveWebauthnConfig();
expect(cfg!.rpID).toBe('localhost');
expect(cfg!.origins).toContain('http://localhost:5173');
expect(cfg!.origins).toContain('http://localhost:3001');
});
it('WAC-005: an explicit webauthn_rp_id app-setting overrides APP_URL', () => {
appUrlRef.value = 'https://internal.example.org';
settingsStore.set('webauthn_rp_id', 'public.example.org');
settingsStore.set('webauthn_origins', 'https://public.example.org');
const cfg = resolveWebauthnConfig();
expect(cfg!.rpID).toBe('public.example.org');
expect(cfg!.origins).toEqual(['https://public.example.org']);
});
it('WAC-006: webauthn_origins is parsed as a comma-separated, trimmed list', () => {
settingsStore.set('webauthn_rp_id', 'example.org');
settingsStore.set('webauthn_origins', 'https://a.example.org , https://b.example.org/');
const cfg = resolveWebauthnConfig();
expect(cfg!.origins).toEqual(['https://a.example.org', 'https://b.example.org']);
});
it('WAC-007: the WEBAUTHN_RP_ID env var takes priority', () => {
vi.stubEnv('WEBAUTHN_RP_ID', 'env.example.org');
vi.stubEnv('WEBAUTHN_ORIGINS', 'https://env.example.org');
appUrlRef.value = 'https://ignored.example.org';
const cfg = resolveWebauthnConfig();
expect(cfg!.rpID).toBe('env.example.org');
expect(cfg!.origins).toEqual(['https://env.example.org']);
});
it('WAC-008: a configured RP ID with no origins falls back to the APP_URL origin', () => {
appUrlRef.value = 'https://trek.example.org';
settingsStore.set('webauthn_rp_id', 'trek.example.org');
const cfg = resolveWebauthnConfig();
expect(cfg!.origins).toEqual(['https://trek.example.org']);
});
});
@@ -1,197 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import path from 'path';
// wikiService picks its source (local disk vs GitHub) once at module load, so each
// mode needs a fresh import with TREK_WIKI_DIR already set.
const FIXTURE_WIKI = path.join(__dirname, '..', '..', 'fixtures', 'wiki');
const MISSING_WIKI = path.join(__dirname, '..', '..', 'fixtures', 'no-such-wiki');
type WikiModule = typeof import('../../../src/services/wikiService');
async function loadWiki(dir: string | undefined): Promise<WikiModule> {
vi.resetModules();
if (dir === undefined) delete process.env.TREK_WIKI_DIR;
else process.env.TREK_WIKI_DIR = dir;
return import('../../../src/services/wikiService');
}
const fetchSpy = vi.fn();
beforeEach(() => {
fetchSpy.mockReset();
vi.stubGlobal('fetch', fetchSpy);
});
afterEach(() => {
vi.unstubAllGlobals();
delete process.env.TREK_WIKI_DIR;
});
describe('wikiService — local wiki on disk', () => {
it('serves the sidebar from disk and never touches the network', async () => {
const wiki = await loadWiki(FIXTURE_WIKI);
expect(wiki.isLocalWiki()).toBe(true);
const { sections } = await wiki.getWikiIndex();
expect(sections.map((s) => s.title)).toEqual(['Getting Started', 'Planning']); // empty section dropped
expect(sections[0].pages).toEqual([
{ title: 'Home', slug: 'Home' },
{ title: 'Quick Start', slug: 'Quick-Start' },
]);
// `_private` fails SLUG_RE, so it is filtered out of the nav.
expect(sections[1].pages).toEqual([{ title: 'Sample Page', slug: 'Sample' }]);
expect(fetchSpy).not.toHaveBeenCalled();
});
it('renders a page, rewriting wikilinks and relative images', async () => {
const wiki = await loadWiki(FIXTURE_WIKI);
const page = await wiki.getWikiPage('Sample');
expect(page.title).toBe('Sample Page');
expect(page.markdown).toContain('[Quick Start](/help/Quick-Start)');
expect(page.markdown).toContain('[Home](/help/Home)');
expect(page.markdown).toContain('![A picture](/api/help/asset/assets/pic.png)');
expect(page.markdown).toContain('![External](https://example.com/x.png)'); // absolute URLs left alone
expect(page.markdown).not.toContain('TODO: screenshot'); // HTML comments stripped
expect(fetchSpy).not.toHaveBeenCalled();
});
it('rewrites bare relative links, the spelling most wiki pages actually use', async () => {
const wiki = await loadWiki(FIXTURE_WIKI);
const page = await wiki.getWikiPage('Sample');
// These resolve against the wiki root on GitHub but used to fall through to
// HelpPage's external-link branch in-app and open a dead tab.
expect(page.markdown).toContain('[Currencies](/help/Currencies)');
expect(page.markdown).toContain('[Quick Start](/help/Quick-Start#first-steps)');
expect(page.markdown).toContain('[with extension](/help/Home)'); // .md stripped
});
it('leaves links that are already resolvable alone', async () => {
const wiki = await loadWiki(FIXTURE_WIKI);
const page = await wiki.getWikiPage('Sample');
expect(page.markdown).toContain('[external](https://example.com)');
expect(page.markdown).toContain('[absolute](/dashboard)');
expect(page.markdown).toContain('[anchor](#section)');
expect(page.markdown).toContain('[mail](mailto:hi@example.com)');
// Images must not be caught by the link rewriter.
expect(page.markdown).toContain('![A picture](/api/help/asset/assets/pic.png)');
expect(page.markdown).not.toContain('/help/assets/pic.png');
});
it('leaves code samples alone', async () => {
const wiki = await loadWiki(FIXTURE_WIKI);
const page = await wiki.getWikiPage('Sample');
// Plugin-Development.md documents `actions[key](ctx)`, which reads as a
// markdown link. Rewriting it would corrupt a verbatim snippet.
expect(page.markdown).toContain('`actions[key](ctx)`');
expect(page.markdown).toContain('`[x](y)`');
expect(page.markdown).toContain('const link = [label](Currencies)'); // fenced block
expect(page.markdown).not.toContain('/help/ctx');
expect(page.markdown).not.toContain('[label](/help/Currencies)');
});
it('does not render a wikilink anchor as visible link text', async () => {
const wiki = await loadWiki(FIXTURE_WIKI);
const page = await wiki.getWikiPage('Sample');
// `[[Quick Start#first-steps|Quick-Start]]` — the anchor belongs in the href.
expect(page.markdown).toContain('[Quick Start](/help/Quick-Start#first-steps)');
expect(page.markdown).not.toContain('[Quick Start#first-steps]');
});
it('404s an unknown page instead of falling back to GitHub', async () => {
const wiki = await loadWiki(FIXTURE_WIKI);
// A page missing from disk does not exist in *this* version — falling back to
// GitHub here is what would reintroduce version skew.
await expect(wiki.getWikiPage('Nope')).rejects.toBeInstanceOf(wiki.WikiNotFound);
expect(fetchSpy).not.toHaveBeenCalled();
});
it.each([['_Sidebar'], ['../Home'], ['a/b'], ['']])('rejects the invalid slug %j', async (slug) => {
const wiki = await loadWiki(FIXTURE_WIKI);
await expect(wiki.getWikiPage(slug)).rejects.toBeInstanceOf(wiki.WikiNotFound);
});
it('serves an asset from disk with the right content type', async () => {
const wiki = await loadWiki(FIXTURE_WIKI);
const { buf, type } = await wiki.getWikiAsset('assets/pic.png');
expect(type).toBe('image/png');
expect(buf.subarray(1, 4).toString()).toBe('PNG');
expect(fetchSpy).not.toHaveBeenCalled();
});
it.each([
['../../src/config.ts'],
['../../../.env'],
['assets/../../package.json'],
['/etc/passwd'],
['assets/notes.txt'],
])('refuses the asset path %j', async (assetPath) => {
const wiki = await loadWiki(FIXTURE_WIKI);
await expect(wiki.getWikiAsset(assetPath)).rejects.toBeInstanceOf(wiki.WikiNotFound);
expect(fetchSpy).not.toHaveBeenCalled();
});
it('404s a missing asset', async () => {
const wiki = await loadWiki(FIXTURE_WIKI);
await expect(wiki.getWikiAsset('assets/ghost.png')).rejects.toBeInstanceOf(wiki.WikiNotFound);
});
});
describe('wikiService — GitHub fallback when no wiki is on disk', () => {
const ok = (body: string): Response =>
({ ok: true, status: 200, text: async () => body, arrayBuffer: async () => new ArrayBuffer(4) }) as unknown as Response;
it('fetches from GitHub and caches the result', async () => {
const wiki = await loadWiki(MISSING_WIKI);
expect(wiki.isLocalWiki()).toBe(false);
fetchSpy.mockResolvedValue(ok('## Docs\n- [[Home]]\n'));
const first = await wiki.getWikiIndex();
const second = await wiki.getWikiIndex();
expect(first.sections[0].pages).toEqual([{ title: 'Home', slug: 'Home' }]);
expect(second).toEqual(first);
expect(fetchSpy).toHaveBeenCalledTimes(1); // second read served from cache
expect(fetchSpy.mock.calls[0][0]).toContain('raw.githubusercontent.com');
});
it('serves a stale cache entry when GitHub is unreachable', async () => {
const wiki = await loadWiki(MISSING_WIKI);
fetchSpy.mockResolvedValueOnce(ok('# Cached\n'));
const before = await wiki.getWikiPage('Home');
fetchSpy.mockRejectedValue(new Error('network down'));
const after = await wiki.getWikiPage('Home');
expect(after.title).toBe(before.title);
});
it('404s when GitHub is unreachable and nothing is cached', async () => {
const wiki = await loadWiki(MISSING_WIKI);
fetchSpy.mockRejectedValue(new Error('network down'));
await expect(wiki.getWikiPage('Home')).rejects.toBeInstanceOf(wiki.WikiNotFound);
});
});
describe('wikiService — default path resolution', () => {
it("resolves the repo's wiki/ with no override, so a release never ships without docs", async () => {
// Guards the __dirname anchor and the Dockerfile COPY: if either breaks, help
// silently degrades to the GitHub fallback and nobody notices.
const wiki = await loadWiki(undefined);
expect(wiki.isLocalWiki()).toBe(true);
const page = await wiki.getWikiPage('Home');
expect(page.title.length).toBeGreaterThan(0);
expect(fetchSpy).not.toHaveBeenCalled();
});
});