Merge dev into feat/native-apps

Brings the native apps branch up to dev (NestJS-only server, MikroORM
repositories, tracked sessions, per-domain locales, the lint ratchets) and
ports its new code onto that architecture:

- server: /api/auth/native moves onto injected services. The session is
  minted by the auth domain's new LoginSessionService (login bookkeeping and
  SessionsService.issue in one transaction), the one-time codes live behind a
  NativeHandoffStore port with a capped in-memory implementation that drops
  expired codes on write instead of running a timer, both routes declare
  response contracts, and the exchange answers { success: true }. Unit and
  e2e suites run on createTestModule and the ORM factories.
- shared: native strings for az, et, sk and th, native wired into every
  locale, the address placeholder as a full URL.
- client: the account and export changes go into dev's shared hooks
  (useAccountSettings, useTripExport), the native server card is a
  desktop/phone pair on useNativeServer, the hand-off call moves out of the
  page hook into native/, best-effort native failures go through
  reportError instead of the console, and the address screen is known to
  knip and lint:i18n-keys.
- package-lock.json regenerated on Linux.
This commit is contained in:
Maurice
2026-10-25 17:04:15 +01:00
11842 changed files with 1361077 additions and 180501 deletions
+2 -2
View File
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { getAppUrl, getMcpSafeUrl } from '../../../src/app-config/app-url';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
// These tests PIN the exact behavior moved verbatim from
// services/notifications.ts (2026-07-28): the APP_URL → ALLOWED_ORIGINS →
// localhost fallback chain, the strip-ALL-trailing-slashes quirk, the
@@ -0,0 +1,70 @@
import { normalizeEnvAtBoot, readEnv } from '../../../src/app-config/env';
import { describe, it, expect, vi, afterEach } from 'vitest';
/** Everything one normalisation printed as a warning. */
function warnings(raw: Record<string, string | undefined>): string {
const warn = vi.spyOn(process, 'emitWarning').mockImplementation(() => {});
normalizeEnvAtBoot(raw);
const printed = warn.mock.calls.map((c) => String(c[0])).join('\n');
warn.mockRestore();
return printed;
}
describe('normalizeEnvAtBoot (#2565)', () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
vi.resetModules();
});
it('trims a padded NODE_ENV in place and says so', () => {
for (const padded of ['production ', ' production', 'production\r', '\tproduction\n']) {
const raw: Record<string, string | undefined> = { NODE_ENV: padded };
const printed = warnings(raw);
expect(raw.NODE_ENV, JSON.stringify(padded)).toBe('production');
expect(printed).toContain(`NODE_ENV=${JSON.stringify(padded)}`);
expect(printed).toContain('"production"');
}
});
it('trims LOG_LEVEL and DEFAULT_LANGUAGE the same way', () => {
const raw: Record<string, string | undefined> = { LOG_LEVEL: 'debug ', DEFAULT_LANGUAGE: ' de' };
const printed = warnings(raw);
expect(raw.LOG_LEVEL).toBe('debug');
expect(raw.DEFAULT_LANGUAGE).toBe('de');
expect(printed).toContain('LOG_LEVEL="debug "');
expect(printed).toContain('DEFAULT_LANGUAGE=" de"');
});
it('leaves clean, unset and differently cased values alone and stays quiet', () => {
const raw: Record<string, string | undefined> = { NODE_ENV: 'Production', LOG_LEVEL: 'info' };
expect(warnings(raw)).toBe('');
expect(raw).toEqual({ NODE_ENV: 'Production', LOG_LEVEL: 'info' });
});
it('does not turn a padded "test" into the test runtime', () => {
// NODE_ENV=test means an in-memory database and no crons. An instance that
// has been running on "test " with its file database must not wake up on
// an empty one after an update, so this one is only reported.
const raw: Record<string, string | undefined> = { NODE_ENV: 'test ' };
const printed = warnings(raw);
expect(raw.NODE_ENV).toBe('test ');
expect(printed).toContain('NODE_ENV="test "');
});
it('never touches other variables, secrets keep their surrounding spaces', () => {
const raw: Record<string, string | undefined> = { SMTP_PASS: ' pass ', TZ: 'UTC ' };
expect(warnings(raw)).toBe('');
expect(raw).toEqual({ SMTP_PASS: ' pass ', TZ: 'UTC ' });
});
it('runs from the boot import, so everything reading process.env sees the trimmed value', async () => {
vi.stubEnv('NODE_ENV', 'production ');
vi.spyOn(process, 'emitWarning').mockImplementation(() => {});
await import('../../../src/app-config/boot-validate');
expect(process.env.NODE_ENV).toBe('production');
expect(readEnv().app.nodeEnv).toBe('production');
expect(readEnv().app.isProduction).toBe(true);
});
});
@@ -0,0 +1,102 @@
/**
* Every environment variable has exactly one owner: either `readEnv()` (live,
* per call, reachable from anywhere) or one registerAs token (boot-stable,
* injected). A variable read through both drifts the moment one side's
* semantics change, and its dependency is invisible to whoever reads the
* other. These cases record which keys each side actually touches, through a
* Proxy over the raw environment, so a new field in the wrong derive function
* fails here rather than in review.
*/
import { BOOT_DERIVERS, type BootNamespace } from '../../../src/app-config/boot-derive';
import { deriveAll, type RawEnv } from '../../../src/app-config/derive';
import { envSchema } from '../../../src/app-config/env.schema';
import { BOOT_STABLE_TOKENS } from '../../../src/nest/app-config/tokens';
import fs from 'node:fs';
import path from 'node:path';
import { describe, it, expect } from 'vitest';
const SRC = path.join(__dirname, '..', '..', '..', 'src');
const TOKENS_FILE = path.join(SRC, 'nest', 'app-config', 'tokens.ts');
/**
* Variables Node itself and the outbound proxy support read. They are not TREK
* configuration, so the schema does not list them; deriveNet passes them on.
*/
const PLATFORM_VARIABLES = new Set(['HTTP_PROXY', 'http_proxy', 'HTTPS_PROXY', 'https_proxy', 'NO_PROXY', 'no_proxy']);
/** The keys `derive` reads from an empty environment, in the order it reads them. */
function keysReadBy(derive: (raw: RawEnv) => unknown): Set<string> {
const read = new Set<string>();
const raw = new Proxy({} as RawEnv, {
get(_target, key) {
if (typeof key === 'string') read.add(key);
return undefined;
},
});
derive(raw);
return read;
}
function sourceFiles(dir: string): string[] {
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) return sourceFiles(full);
return entry.name.endsWith('.ts') ? [full] : [];
});
}
const namespaces = Object.keys(BOOT_DERIVERS) as BootNamespace[];
const liveKeys = keysReadBy(deriveAll);
describe('config ownership', () => {
it('CONFIG-OWN-001: the recorder sees what readEnv() derives (sanity)', () => {
expect(liveKeys.has('DEMO_MODE')).toBe(true);
expect(liveKeys.has('ALLOWED_ORIGINS')).toBe(true);
expect(keysReadBy(BOOT_DERIVERS.http).has('TRUST_PROXY')).toBe(true);
});
it.each(namespaces)('CONFIG-OWN-002: no variable the %s token owns is also derived by readEnv()', (ns) => {
const both = [...keysReadBy(BOOT_DERIVERS[ns])].filter((key) => liveKeys.has(key));
expect(both).toEqual([]);
});
it('CONFIG-OWN-003: no variable is owned by two tokens', () => {
const owner = new Map<string, string>();
const clashes: string[] = [];
for (const ns of namespaces) {
for (const key of keysReadBy(BOOT_DERIVERS[ns])) {
const previous = owner.get(key);
if (previous) clashes.push(`${key}: ${previous} and ${ns}`);
owner.set(key, ns);
}
}
expect(clashes).toEqual([]);
});
it('CONFIG-OWN-004: every token registers under its namespace and derives with its BOOT_DERIVERS entry', () => {
expect(BOOT_STABLE_TOKENS.map((token) => String(token.KEY)).sort()).toEqual(
namespaces.map((ns) => `CONFIGURATION(${ns})`).sort(),
);
for (const token of BOOT_STABLE_TOKENS) {
const ns = /^CONFIGURATION\((.+)\)$/.exec(String(token.KEY))![1] as BootNamespace;
expect(token()).toEqual(BOOT_DERIVERS[ns](process.env as RawEnv));
}
});
it('CONFIG-OWN-005: every token is injected somewhere, so none is dead scaffolding', () => {
const consumers = sourceFiles(SRC)
.filter((file) => file !== TOKENS_FILE)
.map((file) => fs.readFileSync(file, 'utf8'))
.join('\n');
const unused = namespaces.filter((ns) => !consumers.includes(`${ns}Config.KEY`));
expect(unused).toEqual([]);
});
it('CONFIG-OWN-006: every variable either side reads is in the validated schema', () => {
const schemaKeys = new Set(Object.keys(envSchema.shape));
const read = new Set([...liveKeys, ...namespaces.flatMap((ns) => [...keysReadBy(BOOT_DERIVERS[ns])])]);
const unvalidated = [...read].filter((key) => !schemaKeys.has(key) && !PLATFORM_VARIABLES.has(key));
expect(unvalidated).toEqual([]);
});
});
@@ -6,11 +6,11 @@
* that only the wiki knows about is one the compose file never shows. These
* tests pin the pieces that drifted once.
*/
import { describe, it, expect } from 'vitest';
import { OVERPASS_TIMEOUT_DEFAULT_MS } from '../../../src/nest/maps/maps.helpers';
import fs from 'node:fs';
import path from 'node:path';
import { OVERPASS_TIMEOUT_DEFAULT_MS } from '../../../src/nest/maps/maps.helpers';
import { describe, it, expect } from 'vitest';
const REPO_ROOT = path.join(__dirname, '..', '..', '..', '..');
@@ -38,7 +38,15 @@ describe('OVERPASS_TIMEOUT_MS in the templates', () => {
describe('the Places and Amap switches in the templates', () => {
// The index is asked by default and the only way to stop that is this
// variable, so an operator has to be able to find it where they look.
const documented = ['TREK_PLACES_ENABLED', 'TREK_PLACES_URL', 'AMAP_API_KEY', 'AMAP_API_SECRET', 'AMAP_API_BASE'];
const documented = [
'TREK_PLACES_ENABLED',
'TREK_PLACES_URL',
'GOOGLE_LIST_DATA_BASE',
'PLACES_API_KEY',
'AMAP_API_KEY',
'AMAP_API_SECRET',
'AMAP_API_BASE',
];
it('.env.example documents every one of them', () => {
for (const name of documented) {
@@ -53,7 +61,7 @@ describe('the Places and Amap switches in the templates', () => {
});
it('the Helm ConfigMap passes through the non-secret ones the values file documents', () => {
for (const name of ['TREK_PLACES_ENABLED', 'TREK_PLACES_URL', 'AMAP_API_BASE']) {
for (const name of ['TREK_PLACES_ENABLED', 'TREK_PLACES_URL', 'GOOGLE_LIST_DATA_BASE', 'AMAP_API_BASE']) {
expect(helmValues).toContain(`# ${name}:`);
expect(helmConfigMap).toContain(`${name}: {{ .Values.env.${name} | quote }}`);
}
@@ -66,18 +74,80 @@ describe('the Places and Amap switches in the templates', () => {
expect(helmConfigMap).toContain('{{- if not (kindIs "invalid" .Values.env.TREK_PLACES_ENABLED) }}');
});
it('the Helm chart carries the Amap credentials in the Secret, never in the ConfigMap', () => {
it('the Helm chart carries the Google and Amap credentials in the Secret, never in the ConfigMap', () => {
// A ConfigMap is readable by anyone who can read the namespace; the key and
// its signing secret belong next to the other credentials, in both the
// plain and the generated branch of the Secret, and the pod reads them from
// there like it reads the Unsplash key.
for (const name of ['AMAP_API_KEY', 'AMAP_API_SECRET']) {
for (const name of ['PLACES_API_KEY', 'AMAP_API_KEY', 'AMAP_API_SECRET']) {
expect(helmValues).toContain(` ${name}: ""`);
expect(helmSecret).toContain(`${name}: {{ .Values.secretEnv.${name} | b64enc | quote }}`);
expect(helmSecret).toContain(`${name}: {{ .Values.secretEnv.${name} }}`);
expect(helmSecret).toContain(`${name}: {{ .Values.secretEnv.${name} | quote }}`);
expect(helmDeployment).toContain(`- name: ${name}\n valueFrom:\n secretKeyRef:`);
expect(helmDeployment).toContain(`key: ${name}\n optional: true`);
expect(helmConfigMap).not.toContain(name);
}
});
});
describe('the Web Push keys in the templates', () => {
// All optional, since TREK keeps a generated pair in its database; an
// operator who wants their own pair has to find the names somewhere.
const documented = ['VAPID_PUBLIC_KEY', 'VAPID_PRIVATE_KEY', 'VAPID_SUBJECT'];
it('.env.example and docker-compose.yml document every one of them', () => {
for (const name of documented) {
expect(envExample).toContain(`# ${name}=`);
expect(compose).toContain(`# - ${name}=`);
}
});
it('the Helm ConfigMap passes through the public key and the subject', () => {
for (const name of ['VAPID_PUBLIC_KEY', 'VAPID_SUBJECT']) {
expect(helmValues).toContain(`# ${name}:`);
expect(helmConfigMap).toContain(`${name}: {{ .Values.env.${name} | quote }}`);
}
});
it('no template promises an admin address as the push contact, since TREK never sends one on its own', () => {
const subjectDocs = [
envExample.split(/\r?\n/).find((l) => l.includes('# VAPID_SUBJECT=')),
compose.split(/\r?\n/).find((l) => l.includes('- VAPID_SUBJECT=')),
helmValues.slice(helmValues.indexOf('# VAPID_SUBJECT:')).split(/\r?\n\r?\n/)[0],
];
for (const doc of subjectDocs) {
expect(doc).toContain('APP_URL');
expect(doc).not.toContain('ADMIN_EMAIL');
}
});
it('no template says a broken pair is ignored, since push is off until it is fixed and no stored pair stands in', () => {
// The Helm comment wraps, so its lines are joined back into one sentence first.
const helmPrivateKey = helmValues
.slice(
helmValues.indexOf('# Optional Web Push key pair, private half'),
helmValues.indexOf(' VAPID_PRIVATE_KEY: ""'),
)
.replace(/\s*\n\s*#\s*/g, ' ');
const privateKeyDocs = [
envExample.split(/\r?\n/).find((l) => l.includes('# VAPID_PRIVATE_KEY=')),
compose.split(/\r?\n/).find((l) => l.includes('- VAPID_PRIVATE_KEY=')),
helmPrivateKey,
];
for (const doc of privateKeyDocs) {
expect(doc).toContain('turns push off');
expect(doc).not.toContain('ignored');
expect(doc).not.toContain('keeps working');
}
});
it('the Helm chart carries the private key in the Secret, never in the ConfigMap', () => {
const name = 'VAPID_PRIVATE_KEY';
expect(helmValues).toContain(` ${name}: ""`);
expect(helmSecret).toContain(`${name}: {{ .Values.secretEnv.${name} | b64enc | quote }}`);
expect(helmSecret).toContain(`${name}: {{ .Values.secretEnv.${name} | quote }}`);
expect(helmDeployment).toContain(`- name: ${name}\n valueFrom:\n secretKeyRef:`);
expect(helmDeployment).toContain(`key: ${name}\n optional: true`);
expect(helmConfigMap).not.toContain(name);
});
});
@@ -0,0 +1,78 @@
/**
* The data layout: one anchor for data/, uploads/ and the files inside them,
* shared by the pre-container code (resolveDataPaths) and the Nest classes
* (DataPathsService). These cases pin where each path lands, because a moved
* anchor silently moves the database, the key files or the backups.
*/
import { resolveDataPaths, SERVER_ROOT } from '../../../src/app-config/data-paths';
import { DataPathsService } from '../../../src/nest/app-config/data-paths.service';
import { filesDir } from '../../../src/nest/files/files.constants';
import {
DEFAULT_BACKUPS_ROOT,
DEFAULT_UPLOADS_ROOT,
DATA_ROOT,
GLOBAL_TEMP_DIR,
} from '../../../src/nest/storage/storage-paths';
import path from 'node:path';
import { describe, it, expect, afterEach, vi } from 'vitest';
const SERVER_DIR = path.resolve(__dirname, '..', '..', '..');
afterEach(() => {
vi.unstubAllEnvs();
});
describe('resolveDataPaths', () => {
it('DATAPATHS-001: anchors on the server package directory, not on the working directory', () => {
expect(SERVER_ROOT).toBe(SERVER_DIR);
const paths = resolveDataPaths({ db: { trekDbFile: undefined } });
expect(paths.dataDir).toBe(path.join(SERVER_DIR, 'data'));
expect(paths.uploadsDir).toBe(path.join(SERVER_DIR, 'uploads'));
});
it('DATAPATHS-002: places backups, scratch space, logs and the key files inside data/', () => {
const paths = resolveDataPaths({ db: { trekDbFile: undefined } }, '/srv/trek');
expect(paths).toEqual({
dataDir: path.join('/srv/trek', 'data'),
uploadsDir: path.join('/srv/trek', 'uploads'),
backupsDir: path.join('/srv/trek', 'data', 'backups'),
tmpDir: path.join('/srv/trek', 'data', 'tmp'),
logsDir: path.join('/srv/trek', 'data', 'logs'),
jwtSecretFile: path.join('/srv/trek', 'data', '.jwt_secret'),
encryptionKeyFile: path.join('/srv/trek', 'data', '.encryption_key'),
dbFile: path.join('/srv/trek', 'data', 'travel.db'),
});
});
it('DATAPATHS-003: TREK_DB_FILE moves only the database file', () => {
const paths = resolveDataPaths({ db: { trekDbFile: '/elsewhere/e2e.db' } }, '/srv/trek');
expect(paths.dbFile).toBe('/elsewhere/e2e.db');
expect(paths.dataDir).toBe(path.join('/srv/trek', 'data'));
});
it('DATAPATHS-004: reads TREK_DB_FILE from the live environment by default', () => {
vi.stubEnv('TREK_DB_FILE', '/tmp/live.db');
expect(resolveDataPaths().dbFile).toBe('/tmp/live.db');
vi.stubEnv('TREK_DB_FILE', '');
expect(resolveDataPaths().dbFile).toBe(path.join(SERVER_DIR, 'data', 'travel.db'));
});
});
describe('every consumer resolves the same layout', () => {
it('DATAPATHS-005: the storage defaults and the trip-files directory come from it', () => {
const paths = resolveDataPaths();
expect(DATA_ROOT).toBe(paths.dataDir);
expect(DEFAULT_UPLOADS_ROOT).toBe(paths.uploadsDir);
expect(DEFAULT_BACKUPS_ROOT).toBe(paths.backupsDir);
expect(GLOBAL_TEMP_DIR).toBe(paths.tmpDir);
expect(filesDir).toBe(path.join(paths.uploadsDir, 'files'));
});
it('DATAPATHS-006: DataPathsService hands Nest classes the same answer', () => {
vi.stubEnv('TREK_DB_FILE', '/tmp/service.db');
const service = new DataPathsService();
expect({ ...service }).toEqual(resolveDataPaths());
expect(service.dbFile).toBe('/tmp/service.db');
});
});
+118 -20
View File
@@ -1,7 +1,4 @@
import { describe, it, expect } from 'vitest';
import { OVERPASS_TIMEOUT_DEFAULT_MS } from '../../../src/nest/maps/maps.helpers';
import { deriveHttpBoot, deriveKitinerary, deriveStorage, deriveTransit } from '../../../src/app-config/boot-derive';
import {
deriveApp,
deriveHttp,
@@ -14,10 +11,16 @@ import {
derivePlugins,
deriveIntegrations,
deriveBackup,
deriveDb,
deriveFiles,
deriveNet,
derivePaths,
derivePush,
deriveAll,
} from '../../../src/app-config/derive';
import { OVERPASS_TIMEOUT_DEFAULT_MS } from '../../../src/nest/maps/maps.helpers';
import { describe, it, expect } from 'vitest';
// These tests PIN the exact legacy coercions each derived field replaced.
// If one fails after an edit, the edit changed runtime behavior — fix the
@@ -64,20 +67,25 @@ describe('deriveHttp', () => {
expect(deriveHttp({}).wsOrigins).toBeNull();
});
it('TRUST_PROXY: numeric hop count wins, 1 only as fallback (globalMiddleware)', () => {
expect(deriveHttp({ TRUST_PROXY: '2' }).trustProxy).toBe(2);
it('TRUST_PROXY: numeric hop count wins, 1 only as fallback (globalMiddleware, httpConfig token)', () => {
expect(deriveHttpBoot({ TRUST_PROXY: '2' }).trustProxy).toBe(2);
// 0 is a valid hop count ("trust no proxy"), not a missing value.
expect(deriveHttp({ TRUST_PROXY: '0' }).trustProxy).toBe(0);
expect(deriveHttp({ TRUST_PROXY: 'abc' }).trustProxy).toBe(1);
expect(deriveHttp({}).trustProxy).toBe(1);
expect(deriveHttpBoot({ TRUST_PROXY: '0' }).trustProxy).toBe(0);
expect(deriveHttpBoot({ TRUST_PROXY: 'abc' }).trustProxy).toBe(1);
expect(deriveHttpBoot({}).trustProxy).toBe(1);
});
it("HTTP_KEEP_ALIVE_TIMEOUT_MS: 95 s unless set (above nginx's 60 s and Traefik's 90 s idle timeout)", () => {
expect(deriveHttpBoot({}).keepAliveTimeoutMs).toBe(95_000);
expect(deriveHttpBoot({ HTTP_KEEP_ALIVE_TIMEOUT_MS: '120000' }).keepAliveTimeoutMs).toBe(120_000);
});
it('boolean switches accept the whole boolean-like family (unified semantics)', () => {
expect(deriveHttp({ FORCE_HTTPS: 'TRUE' }).forceHttps).toBe(true);
expect(deriveHttp({ FORCE_HTTPS: 'on' }).forceHttps).toBe(true);
expect(deriveHttp({ HSTS_INCLUDE_SUBDOMAINS: 'TRUE' }).hstsIncludeSubdomains).toBe(true);
expect(deriveHttp({ HSTS_INCLUDE_SUBDOMAINS: '1' }).hstsIncludeSubdomains).toBe(true);
expect(deriveHttp({ HSTS_INCLUDE_SUBDOMAINS: 'off' }).hstsIncludeSubdomains).toBe(false);
expect(deriveHttpBoot({ HSTS_INCLUDE_SUBDOMAINS: 'TRUE' }).hstsIncludeSubdomains).toBe(true);
expect(deriveHttpBoot({ HSTS_INCLUDE_SUBDOMAINS: '1' }).hstsIncludeSubdomains).toBe(true);
expect(deriveHttpBoot({ HSTS_INCLUDE_SUBDOMAINS: 'off' }).hstsIncludeSubdomains).toBe(false);
});
it('COOKIE_SECURE is tri-state: explicit falsy disables, anything else auto-detects', () => {
@@ -145,6 +153,12 @@ describe('deriveOidc', () => {
expect(deriveOidc({ OIDC_ADMIN_CLAIM: 'roles' }).adminClaim).toBe('roles');
});
it('usernameClaim stays unset unless a claim is named (#1677)', () => {
expect(deriveOidc({}).usernameClaim).toBeUndefined();
expect(deriveOidc({ OIDC_USERNAME_CLAIM: ' ' }).usernameClaim).toBeUndefined();
expect(deriveOidc({ OIDC_USERNAME_CLAIM: ' preferred_username ' }).usernameClaim).toBe('preferred_username');
});
it('OIDC_ONLY coerces the boolean-like family', () => {
expect(deriveOidc({ OIDC_ONLY: 'True' }).only).toBe(true);
expect(deriveOidc({ OIDC_ONLY: '1' }).only).toBe(true);
@@ -214,10 +228,8 @@ describe('derivePlugins', () => {
});
describe('deriveIntegrations', () => {
it('pins unsplash trim, transit base strip + default, nominatim trim + default, overpass timeout', () => {
it('pins unsplash trim, nominatim trim + default, overpass timeout', () => {
expect(deriveIntegrations({ UNSPLASH_ACCESS_KEY: ' key ' }).unsplashAccessKey).toBe('key');
expect(deriveIntegrations({}).transitApiBase).toBe('https://api.transitous.org');
expect(deriveIntegrations({ TRANSIT_API_URL: 'https://t.example//' }).transitApiBase).toBe('https://t.example');
expect(deriveIntegrations({}).nominatimUrl).toBe('https://nominatim.openstreetmap.org');
// Padded and whitespace-only both come back from a compose file or a ConfigMap,
// and the schema already called the second one unset.
@@ -236,6 +248,41 @@ describe('deriveIntegrations', () => {
expect(deriveIntegrations({ LLM_TIMEOUT_MS: '-1' }).llmTimeoutMs).toBe(900_000);
expect(deriveIntegrations({ LLM_TIMEOUT_MS: '60000.5' }).llmTimeoutMs).toBe(60_000);
});
it('leaves the LLM answer cap to each client unless one is set (#2677)', () => {
expect(deriveIntegrations({}).llmMaxOutputTokens).toBeUndefined();
expect(deriveIntegrations({ LLM_MAX_OUTPUT_TOKENS: '' }).llmMaxOutputTokens).toBeUndefined();
expect(deriveIntegrations({ LLM_MAX_OUTPUT_TOKENS: '16384' }).llmMaxOutputTokens).toBe(16384);
});
});
describe('deriveTransit (transitConfig token)', () => {
it('TRANSIT_API_URL: trailing slashes stripped, Transitous unless set', () => {
expect(deriveTransit({}).apiBase).toBe('https://api.transitous.org');
expect(deriveTransit({ TRANSIT_API_URL: 'https://t.example//' }).apiBase).toBe('https://t.example');
});
});
describe('deriveKitinerary (kitineraryConfig token)', () => {
const sep = process.platform === 'win32' ? ';' : ':';
it('KITINERARY_EXTRACTOR_PATH passes through as given, unset stays unset', () => {
expect(deriveKitinerary({}).extractorPath).toBeUndefined();
expect(deriveKitinerary({ KITINERARY_EXTRACTOR_PATH: '/opt/ki' }).extractorPath).toBe('/opt/ki');
});
it('splits PATH (or the Windows Path) on the platform delimiter and drops blank entries', () => {
expect(deriveKitinerary({ PATH: ['/a', ' /b ', '', '/c'].join(sep) }).searchPath).toEqual(['/a', '/b', '/c']);
expect(deriveKitinerary({ Path: ['/w1', '/w2'].join(sep) }).searchPath).toEqual(['/w1', '/w2']);
expect(deriveKitinerary({}).searchPath).toEqual([]);
});
});
describe('deriveFiles (#1364)', () => {
it('defaults the upload limit to 50 MB and takes FILE_UPLOAD_LIMIT_MB', () => {
expect(deriveFiles({}).uploadLimitMb).toBe(50);
expect(deriveFiles({ FILE_UPLOAD_LIMIT_MB: '200' }).uploadLimitMb).toBe(200);
});
});
describe('deriveBackup', () => {
@@ -246,6 +293,27 @@ describe('deriveBackup', () => {
expect(deriveBackup({}).maxDecompressedMb).toBe(5 * 1024);
expect(deriveBackup({ ENCRYPTION_KEY: 'x' }).encryptionKeyFromEnv).toBe(true);
});
it('reads RESTORE_FROM_BACKUP as a trimmed path, and blank as unset (#1089)', () => {
expect(deriveBackup({}).restoreFromBackup).toBeNull();
expect(deriveBackup({ RESTORE_FROM_BACKUP: ' ' }).restoreFromBackup).toBeNull();
expect(deriveBackup({ RESTORE_FROM_BACKUP: ' /app/data/b.zip ' }).restoreFromBackup).toBe('/app/data/b.zip');
});
});
describe('deriveDb: the pre-migration snapshot', () => {
it('leaves the switch undefined when unset, so the caller can default it per environment', () => {
expect(deriveDb({}).preMigrateSnapshot).toBeUndefined();
expect(deriveDb({ TREK_DB_PRE_MIGRATE_SNAPSHOT: 'off' }).preMigrateSnapshot).toBe(false);
expect(deriveDb({ TREK_DB_PRE_MIGRATE_SNAPSHOT: 'TRUE' }).preMigrateSnapshot).toBe(true);
});
it('keeps three copies unless told otherwise, at most a hundred', () => {
expect(deriveDb({}).preMigrateSnapshotKeep).toBe(3);
expect(deriveDb({ TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP: '5' }).preMigrateSnapshotKeep).toBe(5);
expect(deriveDb({ TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP: '0' }).preMigrateSnapshotKeep).toBe(3);
expect(deriveDb({ TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP: '500' }).preMigrateSnapshotKeep).toBe(100);
});
});
describe('deriveNet', () => {
@@ -256,7 +324,9 @@ describe('deriveNet', () => {
});
it('ALLOW_LINK_LOCAL_IPS keeps only the addresses that may be used', () => {
expect(deriveNet({ ALLOW_LINK_LOCAL_IPS: '169.254.1.2,169.254.169.254,bogus' }).allowLinkLocalIps).toEqual(['169.254.1.2']);
expect(deriveNet({ ALLOW_LINK_LOCAL_IPS: '169.254.1.2,169.254.169.254,bogus' }).allowLinkLocalIps).toEqual([
'169.254.1.2',
]);
expect(deriveNet({}).allowLinkLocalIps).toEqual([]);
});
});
@@ -264,9 +334,9 @@ describe('deriveNet', () => {
describe('derivePaths', () => {
it('passes the path vars through raw — defaulting stays at the consumer', () => {
expect(derivePaths({ TREK_WIKI_DIR: '/w' }).wikiDir).toBe('/w');
expect(derivePaths({ TREK_PLACE_PHOTO_DIR: '/p' }).placePhotoDir).toBe('/p');
expect(deriveStorage({ TREK_PLACE_PHOTO_DIR: '/p' }).placePhotoDir).toBe('/p');
expect(derivePaths({}).wikiDir).toBeUndefined();
expect(derivePaths({}).placePhotoDir).toBeUndefined();
expect(deriveStorage({}).placePhotoDir).toBeUndefined();
});
});
@@ -276,8 +346,22 @@ describe('deriveAll', () => {
expect(env.app.port).toBe(4000);
expect(env.demo.enabled).toBe(true);
for (const ns of [
'app', 'http', 'session', 'demo', 'adminBootstrap', 'oidc', 'smtp', 'mcp',
'plugins', 'webauthn', 'integrations', 'backup', 'db', 'paths', 'net',
'app',
'http',
'session',
'demo',
'adminBootstrap',
'oidc',
'smtp',
'mcp',
'plugins',
'webauthn',
'integrations',
'backup',
'db',
'paths',
'net',
'push',
] as const) {
expect(env[ns]).toBeDefined();
}
@@ -309,3 +393,17 @@ describe('deriveMaps', () => {
}
});
});
describe('derivePush', () => {
it('passes the VAPID_* values through trimmed, blank counting as unset', () => {
expect(derivePush({})).toEqual({ vapidPublicKey: undefined, vapidPrivateKey: undefined, vapidSubject: undefined });
expect(
derivePush({ VAPID_PUBLIC_KEY: ' BPub ', VAPID_PRIVATE_KEY: 'priv', VAPID_SUBJECT: ' mailto:ops@example.com ' }),
).toEqual({ vapidPublicKey: 'BPub', vapidPrivateKey: 'priv', vapidSubject: 'mailto:ops@example.com' });
expect(derivePush({ VAPID_PUBLIC_KEY: ' ', VAPID_SUBJECT: '' })).toEqual({
vapidPublicKey: undefined,
vapidPrivateKey: undefined,
vapidSubject: undefined,
});
});
});
@@ -0,0 +1,62 @@
/**
* server/.env.example is the env-var reference (root CLAUDE.md), and the Zod
* schema in env.schema.ts is what the server actually validates. Nothing tied
* the two together, so about forty variables the server reads were missing
* from the reference. These cases fail on drift in either direction.
*/
import { envSchema } from '../../../src/app-config/env.schema';
import fs from 'node:fs';
import path from 'node:path';
import { describe, it, expect } from 'vitest';
const ENV_EXAMPLE = path.join(__dirname, '..', '..', '..', '.env.example');
/**
* Schema entries a self-hoster never sets, with the reason. Everything else in
* the schema has a line in .env.example, commented out when it is optional.
* The managed-hosting switches are here on purpose: they stay out of every
* public reference, like TREK_DB_FILE and APP_VERSION.
*/
const NOT_OPERATOR_SETTINGS: Record<string, string> = {
PATH: 'the OS search path, validated only so the kitinerary probe can resolve its binary',
Path: 'the Windows spelling of PATH',
APP_VERSION: 'set by the image build; the VERSION file wins over it',
TREK_DB_FILE: 'points the Playwright harness at a throwaway database',
TREK_MANAGED: 'managed hosting only, deliberately undocumented for self-hosters',
MAPBOX_ACCESS_TOKEN: 'managed hosting only (read with TREK_MANAGED), deliberately undocumented for self-hosters',
CARTO_API_KEY: 'managed hosting only (read with TREK_MANAGED), deliberately undocumented for self-hosters',
PLACES_API_BASE: "managed hosting's egress gateway for the Places calls, deliberately undocumented for self-hosters",
};
/** Every variable named on a `KEY=` line, set or commented out. */
function documentedVariables(): Set<string> {
const names = new Set<string>();
for (const line of fs.readFileSync(ENV_EXAMPLE, 'utf8').split(/\r?\n/)) {
const match = /^#?\s*([A-Za-z][A-Za-z0-9_]*)=/.exec(line);
if (match) names.add(match[1]);
}
return names;
}
const schemaKeys = Object.keys(envSchema.shape);
const documented = documentedVariables();
describe('server/.env.example against the validated schema', () => {
it('ENV-REF-001: documents every variable the schema validates', () => {
const missing = schemaKeys.filter((key) => !documented.has(key) && !(key in NOT_OPERATOR_SETTINGS));
expect(missing).toEqual([]);
});
it('ENV-REF-002: names no variable the server does not validate', () => {
const schema = new Set(schemaKeys);
expect([...documented].filter((key) => !schema.has(key))).toEqual([]);
});
it('ENV-REF-003: the exceptions are real schema entries that the reference leaves out', () => {
for (const key of Object.keys(NOT_OPERATOR_SETTINGS)) {
expect(schemaKeys).toContain(key);
expect(documented.has(key)).toBe(false);
}
});
});
@@ -0,0 +1,52 @@
import { deriveApp } from '../../../src/app-config/derive';
import { imageVersion, resetImageVersion } from '../../../src/app-config/image-version';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
describe('imageVersion', () => {
const dirs: string[] = [];
const versionFile = (content: string): string => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-image-version-'));
dirs.push(dir);
const file = path.join(dir, 'VERSION');
fs.writeFileSync(file, content);
return file;
};
beforeEach(() => resetImageVersion());
afterEach(() => {
resetImageVersion();
for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
});
it('IMGVER-001: reads the version the image was built as, trimmed', () => {
expect(imageVersion(versionFile('4.4.0-pre.3\n'))).toBe('4.4.0-pre.3');
});
it('IMGVER-002: is null outside an image and for an empty file', () => {
expect(imageVersion(path.join(os.tmpdir(), 'trek-no-such-dir', 'VERSION'))).toBeNull();
resetImageVersion();
expect(imageVersion(versionFile(' \n'))).toBeNull();
});
it('IMGVER-003: reads once, because the image does not change under a running process', () => {
const file = versionFile('4.3.3');
expect(imageVersion(file)).toBe('4.3.3');
fs.writeFileSync(file, '9.9.9');
expect(imageVersion(file)).toBe('4.3.3');
});
it("IMGVER-004: the image's version wins over an APP_VERSION a recreated container carried over", () => {
imageVersion(versionFile('4.4.0'));
expect(deriveApp({ APP_VERSION: '4.3.3' }).appVersion).toBe('4.4.0');
});
it('IMGVER-005: without an image file, APP_VERSION still decides', () => {
imageVersion(path.join(os.tmpdir(), 'trek-no-such-dir', 'VERSION'));
expect(deriveApp({ APP_VERSION: '4.3.3' }).appVersion).toBe('4.3.3');
});
});
@@ -0,0 +1,30 @@
import { nestLogLevels } from '../../../src/app-config/nest-log-levels';
import { describe, expect, it } from 'vitest';
describe('nestLogLevels', () => {
it('NESTLOG-001: error keeps only fatal and error, so a test boot prints no route map', () => {
expect(nestLogLevels('error')).toEqual(['fatal', 'error']);
});
it('NESTLOG-002: warn adds warn', () => {
expect(nestLogLevels('warn')).toEqual(['fatal', 'error', 'warn']);
});
it('NESTLOG-003: info adds log but not debug or verbose', () => {
expect(nestLogLevels('info')).toEqual(['fatal', 'error', 'warn', 'log']);
});
it('NESTLOG-004: debug keeps everything', () => {
expect(nestLogLevels('debug')).toEqual(['fatal', 'error', 'warn', 'log', 'debug', 'verbose']);
});
it('NESTLOG-005: unset and unknown values fall back to info, like index.ts', () => {
expect(nestLogLevels(undefined)).toEqual(nestLogLevels('info'));
expect(nestLogLevels('chatty')).toEqual(nestLogLevels('info'));
});
it('NESTLOG-006: the value is matched case-insensitively', () => {
expect(nestLogLevels('ERROR')).toEqual(['fatal', 'error']);
});
});
+65 -4
View File
@@ -1,8 +1,10 @@
import { describe, it, expect } from 'vitest';
import {
csvList,
csvListFiltered,
decodeBase64Url,
isP256PrivateKey,
isUncompressedP256Key,
isVapidSubject,
nonNegativeIntOr,
numberOr,
parseBool,
@@ -15,6 +17,8 @@ import {
stripTrailingSlashes,
} from '../../../src/app-config/parsers';
import { describe, it, expect } from 'vitest';
describe('parseBool', () => {
it('accepts the whole truthy family, any casing, padded', () => {
for (const v of ['true', 'TRUE', 'True', '1', 'on', 'ON', 'yes', 'Yes', ' true ']) {
@@ -159,7 +163,10 @@ describe('resolveKeepaliveMs', () => {
describe('parseLinkLocalAllowList (ALLOW_LINK_LOCAL_IPS)', () => {
it('takes single link-local addresses, trimmed, and ignores empty entries', () => {
expect(parseLinkLocalAllowList(' 169.254.1.2 , ,169.254.0.1')).toEqual({ ips: ['169.254.1.2', '169.254.0.1'], invalid: [] });
expect(parseLinkLocalAllowList(' 169.254.1.2 , ,169.254.0.1')).toEqual({
ips: ['169.254.1.2', '169.254.0.1'],
invalid: [],
});
expect(parseLinkLocalAllowList(undefined)).toEqual({ ips: [], invalid: [] });
expect(parseLinkLocalAllowList('')).toEqual({ ips: [], invalid: [] });
});
@@ -171,8 +178,62 @@ describe('parseLinkLocalAllowList (ALLOW_LINK_LOCAL_IPS)', () => {
});
it('refuses anything that is not one link-local IPv4 in the form a resolver answers with', () => {
for (const bad of ['10.0.0.1', '169.254.1', '169.254.1.2/32', '169.254.01.2', '169.254.1.256', 'fe80::1', 'host.example']) {
for (const bad of [
'10.0.0.1',
'169.254.1',
'169.254.1.2/32',
'169.254.01.2',
'169.254.1.256',
'fe80::1',
'host.example',
]) {
expect(parseLinkLocalAllowList(bad)).toEqual({ ips: [], invalid: [bad] });
}
});
});
describe('Web Push key material', () => {
it('decodeBase64Url refuses anything outside the base64url alphabet instead of skipping it', () => {
expect(decodeBase64Url('AQID')).toEqual(Buffer.from([1, 2, 3]));
expect(decodeBase64Url(' AQID ')).toEqual(Buffer.from([1, 2, 3]));
expect(decodeBase64Url('AQI=')).toEqual(Buffer.from([1, 2]));
expect(decodeBase64Url('-_8')).toEqual(Buffer.from([0xfb, 0xff]));
for (const value of ['', 'AQ+D', 'AQ/D', 'AQ ID', 'AQ=D', 'AQ===']) {
expect(decodeBase64Url(value), value).toBeNull();
}
});
it('isUncompressedP256Key and isP256PrivateKey check the sizes the Web Push tools print', () => {
const point = Buffer.concat([Buffer.from([0x04]), Buffer.alloc(64, 1)]).toString('base64url');
expect(isUncompressedP256Key(point)).toBe(true);
const compressed = Buffer.concat([Buffer.from([0x02]), Buffer.alloc(64, 1)]).toString('base64url');
expect(isUncompressedP256Key(compressed)).toBe(false);
expect(isUncompressedP256Key(Buffer.alloc(33, 4).toString('base64url'))).toBe(false);
expect(isP256PrivateKey(Buffer.alloc(32, 9).toString('base64url'))).toBe(true);
expect(isP256PrivateKey(Buffer.alloc(31, 9).toString('base64url'))).toBe(false);
expect(isP256PrivateKey('not base64url!')).toBe(false);
});
it('isVapidSubject accepts a mailto: address or an https: URL and nothing else', () => {
const accepted = [
'mailto:ops@example.com',
'MAILTO:ops@example.com',
'https://trek.example.com',
' https://x.test/c ',
];
for (const ok of accepted) {
expect(isVapidSubject(ok), ok).toBe(true);
}
const refused = [
'ops@example.com',
'mailto:',
'mailto:no-at-sign',
'mailto:a b@example.com',
'http://x.test',
'not a url',
];
for (const bad of refused) {
expect(isVapidSubject(bad), bad).toBe(false);
}
});
});
@@ -0,0 +1,26 @@
import pkg from '../../../package.json';
import { runningVersion } from '../../../src/app-config';
import { hostVersion } from '../../../src/nest/plugins/install/host-compat';
import { afterEach, describe, expect, it, vi } from 'vitest';
afterEach(() => {
vi.unstubAllEnvs();
});
describe('runningVersion', () => {
it('announces APP_VERSION when it is set', () => {
vi.stubEnv('APP_VERSION', '9.8.7');
expect(runningVersion()).toBe('9.8.7');
});
it('falls back to the server package version', () => {
vi.stubEnv('APP_VERSION', '');
expect(runningVersion()).toBe(pkg.version);
});
it('is what the plugin host-compatibility checks call the host version', () => {
vi.stubEnv('APP_VERSION', '1.2.3');
expect(hostVersion()).toBe(runningVersion());
});
});
+153 -8
View File
@@ -1,6 +1,31 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { validateEnvAtBoot, readEnv, SECRET_ENV_KEYS } from '../../../src/app-config/env';
import { envSchema } from '../../../src/app-config/env.schema';
import { validateEnvAtBoot, readEnv } from '../../../src/app-config/env';
import { describe, it, expect, vi, afterEach } from 'vitest';
import type { z } from 'zod';
const schemaShape: Record<string, z.ZodType> = envSchema.shape;
/**
* A value no check of the schema accepts (not a number, URL, boolean, duration,
* language or base64url key), and one that names its variable, so a leak is
* traceable to the key it came from.
*/
const probe = (key: string): string => `probe+${key}/not valid=`;
/** Everything one boot check printed and threw. */
function bootReport(raw: Record<string, string>): { printed: string; thrown: string } {
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
let thrown = '';
try {
validateEnvAtBoot(raw);
} catch (err) {
thrown = err instanceof Error ? err.message : String(err);
}
const printed = error.mock.calls.map((c) => c.join(' ')).join('\n');
error.mockRestore();
return { printed, thrown };
}
describe('validateEnvAtBoot', () => {
afterEach(() => {
@@ -49,6 +74,14 @@ describe('validateEnvAtBoot', () => {
expect(() => validateEnvAtBoot({ LLM_TIMEOUT_MS: '' })).not.toThrow();
});
it('refuses an LLM answer cap that is no whole token count or too small to hold a booking (#2677)', () => {
expect(() => validateEnvAtBoot({ LLM_MAX_OUTPUT_TOKENS: '8192.5' })).toThrow();
expect(() => validateEnvAtBoot({ LLM_MAX_OUTPUT_TOKENS: '100' })).toThrow();
expect(() => validateEnvAtBoot({ LLM_MAX_OUTPUT_TOKENS: 'lots' })).toThrow();
expect(() => validateEnvAtBoot({ LLM_MAX_OUTPUT_TOKENS: '16384' })).not.toThrow();
expect(() => validateEnvAtBoot({ LLM_MAX_OUTPUT_TOKENS: '' })).not.toThrow();
});
it('refuses an ALLOW_LINK_LOCAL_IPS entry that is not a listable link-local address', () => {
// A metadata address would be dropped silently at runtime; saying so at boot
// is the difference between an OIDC login that works and a puzzling one.
@@ -58,6 +91,98 @@ describe('validateEnvAtBoot', () => {
expect(() => validateEnvAtBoot({ ALLOW_LINK_LOCAL_IPS: '' })).not.toThrow();
});
it('checks the VAPID_* shapes and lets a well-formed set through', () => {
// The application server pair from RFC 8291 Appendix A, in the form the Web Push tools print.
const publicKey = 'BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8';
const privateKey = 'yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw';
expect(() =>
validateEnvAtBoot({
VAPID_PUBLIC_KEY: publicKey,
VAPID_PRIVATE_KEY: privateKey,
VAPID_SUBJECT: 'mailto:ops@example.com',
}),
).not.toThrow();
expect(() => validateEnvAtBoot({ VAPID_SUBJECT: 'https://trek.example.com' })).not.toThrow();
// Whether the halves belong together is checked where they are used, not here.
expect(() => validateEnvAtBoot({ VAPID_PRIVATE_KEY: privateKey })).not.toThrow();
vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() => validateEnvAtBoot({ VAPID_PUBLIC_KEY: privateKey })).toThrow();
expect(() => validateEnvAtBoot({ VAPID_PUBLIC_KEY: `A${publicKey.slice(1)}` })).toThrow();
expect(() => validateEnvAtBoot({ VAPID_PRIVATE_KEY: publicKey })).toThrow();
expect(() => validateEnvAtBoot({ VAPID_PRIVATE_KEY: 'yfWPiYE+n46HLnH0KqZOF1fJJU3MYrct3AELtAQ/oRw' })).toThrow();
expect(() => validateEnvAtBoot({ VAPID_SUBJECT: 'ops@example.com' })).toThrow();
expect(() => validateEnvAtBoot({ VAPID_SUBJECT: 'http://trek.example.com' })).toThrow();
});
it('never prints the value of a secret variable, only its name and the problem', () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
// 43 characters like a real key, with one character base64url does not have.
const leakedPrivateKey = 'yfWPiYE+n46HLnH0KqZOF1fJJU3MYrct3AELtAQ/oRw';
expect(() => validateEnvAtBoot({ VAPID_PRIVATE_KEY: leakedPrivateKey, PORT: 'not-a-port' })).toThrow(/2 problems/);
const report = error.mock.calls.map((c) => c.join(' ')).join('\n');
expect(report).toContain('VAPID_PRIVATE_KEY=***: must be a base64url-encoded P-256 private key');
expect(report).not.toContain(leakedPrivateKey);
expect(report).not.toContain('yfWPiYE');
// Everything else keeps its value, which is what makes a typo findable.
expect(report).toContain('PORT="not-a-port"');
});
it('never prints any secret variable, whether or not its own check refuses the value', () => {
// A broken PORT guarantees a report, so every secret gets its chance to leak into it.
const { printed, thrown } = bootReport({
...Object.fromEntries([...SECRET_ENV_KEYS].map((key) => [key, probe(key)])),
PORT: 'not-a-port',
});
expect(thrown).toMatch(/Invalid environment configuration/);
expect(printed).toContain('PORT="not-a-port"');
let refused = 0;
for (const key of SECRET_ENV_KEYS) {
expect(printed, key).not.toContain(probe(key));
expect(thrown, key).not.toContain(probe(key));
if (!schemaShape[key].safeParse(probe(key)).success) {
refused += 1;
expect(printed, key).toContain(` - ${key}=***: `);
}
}
// The masking only proves itself on a variable the schema refuses.
expect(refused).toBeGreaterThan(0);
});
it('still prints the value of every variable that is not a secret', () => {
const open = Object.keys(schemaShape).filter((key) => !SECRET_ENV_KEYS.has(key));
const { printed } = bootReport(Object.fromEntries(open.map((key) => [key, probe(key)])));
// Free-form variables accept anything, so only the checked ones show up.
const refused = open.filter((key) => !schemaShape[key].safeParse(probe(key)).success);
expect(refused).toContain('VAPID_PUBLIC_KEY');
for (const key of refused) expect(printed, key).toContain(` - ${key}=${JSON.stringify(probe(key))}: `);
expect(printed.split('\n').filter((line) => line.startsWith(' - '))).toHaveLength(refused.length);
});
it('knows every secret-looking variable of the schema as a secret, and nothing the schema does not know', () => {
// A new variable with a word in its name that suggests a credential lands
// here and has to be decided on. Whole words, so OVERPASS_URL and
// WEBAUTHN_RP_ID do not count.
const looksSecret = (key: string): boolean =>
/(^|_)(SECRET|PASS(WORD|PHRASE)?|TOKEN|KEY|APIKEY|CREDENTIALS?|PRIVATE|LICEN[CS]E|WEBHOOK|AUTH|DSN|SALT)(_|$)/.test(
key,
);
const notSecret = new Set([
'VAPID_PUBLIC_KEY', // the public half, which every subscribing browser receives
'TREK_PLUGIN_ALLOW_PRIVATE_EGRESS', // a switch about private networks, not a private value
]);
const schemaKeys = Object.keys(schemaShape);
const flagged = schemaKeys.filter((key) => looksSecret(key) && !notSecret.has(key));
expect(flagged.length).toBeGreaterThan(5);
for (const key of flagged) expect(SECRET_ENV_KEYS.has(key), key).toBe(true);
for (const key of SECRET_ENV_KEYS) expect(schemaKeys, key).toContain(key);
for (const key of notSecret) {
expect(schemaKeys, key).toContain(key);
expect(looksSecret(key), key).toBe(true);
expect(SECRET_ENV_KEYS.has(key), key).toBe(false);
}
});
it('treats blank values as unset (defaults apply, no error)', () => {
expect(() => validateEnvAtBoot({ DEMO_MODE: '', PORT: ' ', TZ: '' })).not.toThrow();
});
@@ -90,6 +215,8 @@ describe('validateEnvAtBoot', () => {
it.each([
['PORT', '70000'],
['TRUST_PROXY', '1.5'],
['HTTP_KEEP_ALIVE_TIMEOUT_MS', '500'],
['HTTP_KEEP_ALIVE_TIMEOUT_MS', '300000'],
['DEFAULT_LANGUAGE', 'klingon'],
['LOG_LEVEL', 'verbose'],
['SESSION_DURATION_REMEMBER', '-1d'],
@@ -155,9 +282,7 @@ describe('validateEnvAtBoot — centrally administered preconditions', () => {
});
it('MANAGED-BOOT-003: passes once the key is supplied', () => {
expect(() =>
validateEnvAtBoot({ TREK_MANAGED: '1', ENCRYPTION_KEY: 'a'.repeat(64) }),
).not.toThrow();
expect(() => validateEnvAtBoot({ TREK_MANAGED: '1', ENCRYPTION_KEY: 'a'.repeat(64) })).not.toThrow();
});
it('MANAGED-BOOT-004: inert without the switch — a self-hoster keeps the file-based key', () => {
@@ -172,9 +297,7 @@ describe('validateEnvAtBoot — centrally administered preconditions', () => {
// Both kinds land in one report: fixing the env should take one pass, not a
// restart per problem.
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() => validateEnvAtBoot({ TREK_MANAGED: '1', PORT: 'not-a-port' })).toThrow(
/2 problems/,
);
expect(() => validateEnvAtBoot({ TREK_MANAGED: '1', PORT: 'not-a-port' })).toThrow(/2 problems/);
expect(err.mock.calls[0][0]).toMatch(/PORT/);
expect(err.mock.calls[0][0]).toMatch(/ENCRYPTION_KEY/);
});
@@ -196,3 +319,25 @@ describe('readEnv', () => {
}
});
});
describe('validateEnvAtBoot: the pre-migration snapshot switches', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('accepts a boolean switch and a keep count from 1 to 100', () => {
expect(() =>
validateEnvAtBoot({ TREK_DB_PRE_MIGRATE_SNAPSHOT: 'false', TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP: '100' }),
).not.toThrow();
});
it('refuses a misspelt switch instead of guessing which way the safety net should go', () => {
expect(bootReport({ TREK_DB_PRE_MIGRATE_SNAPSHOT: 'of' }).thrown).toMatch(/Invalid environment configuration/);
expect(bootReport({ TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP: '0' }).printed).toContain(
'TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP',
);
expect(bootReport({ TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP: '2.5' }).thrown).toMatch(
/Invalid environment configuration/,
);
});
});
+93 -35
View File
@@ -8,8 +8,18 @@
* on another install. The run now goes through backupService.createBackup(),
* which snapshots the DB with VACUUM INTO and bundles the key.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import type { MaintenanceRepository } from '../../src/db/repositories/MaintenanceRepository';
import { AutoBackupJob } from '../../src/nest/backup/auto-backup.job';
import { createBackup } from '../../src/nest/backup/backup.impl';
import type { BackupService } from '../../src/nest/backup/backup.service';
import { SqliteDatabaseBackup } from '../../src/nest/backup/sqlite-database-backup';
import type { DatabaseLifecycle } from '../../src/nest/database/database-lifecycle.service';
import type { CronRegistrarService } from '../../src/nest/scheduling/cron-registrar.service';
import type { StorageService } from '../../src/nest/storage/storage.service';
import type { PathLike } from 'node:fs';
import path from 'node:path';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
const fsMock = vi.hoisted(() => ({
// The parameter is declared so the double carries fs's real signature: the
@@ -47,7 +57,14 @@ const dbMock = vi.hoisted(() => ({
reinitialize: vi.fn(),
}));
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn() }));
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn() }));
// What Nest injects into the backup port: the WAL checkpoint and the VACUUM
// INTO snapshot. Stubbed, because a real VACUUM INTO would bypass the fs mock.
const maintenanceStub = vi.hoisted(() => ({
walCheckpoint: vi.fn(async () => {}),
vacuumInto: vi.fn(async (_target: string) => {}),
}));
vi.mock('fs', () => ({ default: fsMock, ...fsMock }));
vi.mock('node:fs', () => ({ default: fsMock, ...fsMock }));
@@ -55,23 +72,17 @@ vi.mock('archiver', () => ({ default: archiverMock }));
vi.mock('unzipper', () => ({ default: { Extract: vi.fn(), Open: { file: vi.fn() } } }));
vi.mock('../../src/db/database', () => dbMock);
vi.mock('../../src/nest/audit/audit-log.logger', () => logMock);
vi.mock('../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a'.repeat(64),
updateJwtSecret: () => {},
}));
import path from 'node:path';
import { AutoBackupJob } from '../../src/nest/backup/auto-backup.job';
import { createBackup } from '../../src/nest/backup/backup.impl';
import type { BackupService } from '../../src/nest/backup/backup.service';
import type { StorageService } from '../../src/nest/storage/storage.service';
import type { CronRegistrarService } from '../../src/nest/scheduling/cron-registrar.service';
const liveDb = path.join(__dirname, '../../data', 'travel.db');
// createBackup receives StorageService as a parameter (BackupService injects
// it). fs is mocked wholesale here, so a plain stub stands in for the backups
/** The backup port BackupService injects: the real SQLite one over stubs. */
const database = new SqliteDatabaseBackup(
{ file: liveDb, close: vi.fn(), reopen: vi.fn() } as unknown as DatabaseLifecycle,
maintenanceStub as unknown as MaintenanceRepository,
);
// createBackup receives StorageService and the database port as parameters
// (BackupService injects them). fs is mocked wholesale here, so a plain stub stands in for the backups
// backend: staging under /stub/spool, empty category listings, put/stat succeed.
const storageStub = vi.hoisted(() => ({}) as Record<string, unknown>);
function resetStorageStub() {
@@ -108,8 +119,11 @@ function makeJob() {
const job = new AutoBackupJob(
// The same wiring the container does, with the real service function behind
// it — the run below is still the production code path. The forward mirrors
// BackupService: inject the storage stub as the first argument.
{ createBackup: (prefix?: 'backup' | 'auto-backup') => createBackup(storageStub as unknown as StorageService, prefix) } as unknown as BackupService,
// BackupService: the storage stub and the database port go in first.
{
createBackup: (prefix?: 'backup' | 'auto-backup') =>
createBackup({ storage: storageStub as unknown as StorageService, database }, prefix),
} as unknown as BackupService,
registrar as unknown as CronRegistrarService,
storageStub as unknown as StorageService,
);
@@ -121,10 +135,16 @@ function stubArchiver(): Record<string, (arg?: unknown) => void> {
const outputEvents: Record<string, (arg?: unknown) => void> = {};
const archiveEvents: Record<string, (arg?: unknown) => void> = {};
fsMock.createWriteStream.mockReturnValue({
on: vi.fn((event: string, cb: () => void) => { outputEvents[event] = cb; }),
on: vi.fn((event: string, cb: () => void) => {
outputEvents[event] = cb;
}),
} as never);
archiveMock.on.mockImplementation((event: string, cb: (arg?: unknown) => void) => { archiveEvents[event] = cb; });
archiveMock.finalize.mockImplementation(() => { outputEvents['close']?.(); });
archiveMock.on.mockImplementation((event: string, cb: (arg?: unknown) => void) => {
archiveEvents[event] = cb;
});
archiveMock.finalize.mockImplementation(() => {
outputEvents['close']?.();
});
archiverMock.mockReturnValue(archiveMock);
return archiveEvents;
}
@@ -146,7 +166,11 @@ describe('auto-backup run', () => {
// No ENCRYPTION_KEY in the env means the key file is the source of truth and
// has to travel with the backup.
delete process.env.ENCRYPTION_KEY;
fsMock.statSync.mockReturnValue({ size: 4096, birthtime: new Date('2026-04-27T02:00:00Z'), mtimeMs: Date.now() } as never);
fsMock.statSync.mockReturnValue({
size: 4096,
birthtime: new Date('2026-04-27T02:00:00Z'),
mtimeMs: Date.now(),
} as never);
});
afterEach(() => {
@@ -154,28 +178,48 @@ describe('auto-backup run', () => {
});
it('archives a VACUUM INTO snapshot, never the live travel.db', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('travel.db') || String(p).endsWith('backup-settings.json'));
fsMock.existsSync.mockImplementation(
(p: string) => String(p).endsWith('travel.db') || String(p).endsWith('backup-settings.json'),
);
stubArchiver();
await scheduledRun()();
expect(dbMock.db.exec).toHaveBeenCalledWith(expect.stringContaining('VACUUM INTO'));
expect(maintenanceStub.vacuumInto).toHaveBeenCalledWith(
expect.stringContaining('/stub/spool/travel-snap-auto-backup-'),
);
const dbEntry = archiveMock.file.mock.calls.find(([, opts]) => opts?.name === 'travel.db');
expect(dbEntry).toBeDefined();
expect(dbEntry?.[0]).toContain('/stub/spool/travel-snap-auto-backup-');
expect(dbEntry?.[0]).not.toBe(liveDb);
});
it('a snapshot that fails fails the run and archives nothing, instead of zipping the live file', async () => {
fsMock.existsSync.mockImplementation(
(p: string) => String(p).endsWith('travel.db') || String(p).endsWith('backup-settings.json'),
);
stubArchiver();
maintenanceStub.vacuumInto.mockRejectedValueOnce(new Error('database is locked'));
await scheduledRun()();
expect(archiveMock.file).not.toHaveBeenCalled();
expect(storageStub.put).not.toHaveBeenCalled();
expect(logMock.logError).toHaveBeenCalledWith(expect.stringContaining('could not take a snapshot of the database'));
expect(logMock.logError).toHaveBeenCalledWith('Auto-Backup: Database snapshot failed: database is locked');
});
it('bundles the at-rest encryption key', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('.encryption_key') || String(p).endsWith('backup-settings.json'));
fsMock.existsSync.mockImplementation(
(p: string) => String(p).endsWith('.encryption_key') || String(p).endsWith('backup-settings.json'),
);
stubArchiver();
await scheduledRun()();
expect(archiveMock.file).toHaveBeenCalledWith(
expect.stringContaining('.encryption_key'),
{ name: '.encryption_key' },
);
expect(archiveMock.file).toHaveBeenCalledWith(expect.stringContaining('.encryption_key'), {
name: '.encryption_key',
});
});
it('keeps the auto-backup-*.zip naming so retention still prunes it', async () => {
@@ -191,16 +235,22 @@ describe('auto-backup run', () => {
await scheduledRun()();
expect(logMock.logInfo).toHaveBeenCalledWith(expect.stringMatching(/^Auto-Backup created: auto-backup-[\dT-]+\.zip$/));
expect(logMock.logInfo).toHaveBeenCalledWith(
expect.stringMatching(/^Auto-Backup created: auto-backup-[\dT-]+\.zip$/),
);
// cleanupOldBackups(storage, keep_days) still runs after the archive and
// only prunes objects it can match by prefix — through storage.delete
expect(storageStub.delete).toHaveBeenCalledWith('backups', 'auto-backup-2020-01-01T02-00-00.zip');
});
it('logs the failure, drops the partial zip and skips retention', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('.zip') || String(p).endsWith('backup-settings.json'));
fsMock.existsSync.mockImplementation(
(p: string) => String(p).endsWith('.zip') || String(p).endsWith('backup-settings.json'),
);
const archiveEvents = stubArchiver();
archiveMock.finalize.mockImplementation(() => { archiveEvents['error']?.(new Error('disk full')); });
archiveMock.finalize.mockImplementation(() => {
archiveEvents['error']?.(new Error('disk full'));
});
await scheduledRun()();
@@ -289,7 +339,11 @@ describe('auto-backup scheduling (AutoBackupJob.start)', () => {
it('a non-Error rejection from createBackup is stringified into the failure log', async () => {
const broken = { createBackup: vi.fn().mockRejectedValue('plain string') } as unknown as BackupService;
const registrar = { isEnabled: vi.fn(() => true), register: vi.fn(() => true), unregister: vi.fn() };
const job = new AutoBackupJob(broken, registrar as unknown as CronRegistrarService, storageStub as unknown as StorageService);
const job = new AutoBackupJob(
broken,
registrar as unknown as CronRegistrarService,
storageStub as unknown as StorageService,
);
await job.runBackup();
expect(logMock.logError).toHaveBeenCalledWith('Auto-Backup: plain string');
});
@@ -337,11 +391,15 @@ describe('BACKUP-047 updateAutoSettings', () => {
it('BACKUP-047b — re-arms the job only after saving', () => {
const order: string[] = [];
fsMock.writeFileSync.mockImplementation(() => { order.push('save'); });
fsMock.writeFileSync.mockImplementation(() => {
order.push('save');
});
const { job, registrar } = makeJob();
// Saving {enabled:false} sends start() down the disabled path — unregister
// is its scheduling action, so it stands in for the old scheduler.start().
registrar.unregister.mockImplementation(() => { order.push('start'); });
registrar.unregister.mockImplementation(() => {
order.push('start');
});
job.updateAutoSettings({ enabled: false });
+222 -40
View File
@@ -5,47 +5,77 @@
* for costs.listMine. Both orderings are asserted, because swapping them changes
* which refusal a caller sees.
*/
import { describe, it, expect, vi } from 'vitest';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
import { CostsRpc } from '../../../src/nest/budget/costs.rpc';
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
import { PluginGuards } from '../../../src/nest-rpc/plugin-guards.service';
import { createTestPluginRegistry } from '../../../src/nest-rpc/rpc-kit/testing';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { BudgetModule } from '../../../src/nest/budget/budget.module';
import type { BudgetService } from '../../../src/nest/budget/budget.service';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
import { CostsRpc } from '../../../src/nest/budget/costs.rpc';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import type { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { TripAccessService } from '../../../src/nest/trip-membership/trip-access.service';
import type { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { makeDeps } from '../../helpers/rpc-host-deps';
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
import { describe, it, expect, vi } from 'vitest';
/** Trip 1 belongs to user 42, cost 5 sits on it, and the addon is on unless said otherwise. */
function build(opts: { addonOn?: boolean; canEdit?: boolean; missing?: boolean } = {}) {
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({
k: 'req',
id: 'x',
method,
params,
});
/**
* Trip 1 belongs to user 42, cost 5 sits on it, and the addon is on unless said otherwise.
* `refusal` is what BudgetService.linkRefusal answers for the body's links (#2084), and
* `linkedTo` the booking cost 5 is linked to before the write.
*/
function build(
opts: { addonOn?: boolean; canEdit?: boolean; missing?: boolean; refusal?: string; linkedTo?: number | null } = {},
) {
const budget = {
listBudgetItems: vi.fn((tripId: number) => [{ id: 5, trip_id: tripId }]),
create: vi.fn(async (tripId: string, i: Record<string, unknown>) => ({ id: 9, trip_id: tripId, ...i })),
update: vi.fn(async () => (opts.missing ? null : { id: 5, name: 'Hotel' })),
// The row after the write: a link in the body moves it, otherwise it keeps its booking.
update: vi.fn(async (_id: number, _tripId: string, i: Record<string, unknown>) =>
opts.missing
? null
: { id: 5, name: 'Hotel', reservation_id: 'reservation_id' in i ? i.reservation_id : (opts.linkedTo ?? null) },
),
remove: vi.fn(() => !opts.missing),
linkRefusal: vi.fn(() => opts.refusal ?? null),
getBudgetItem: vi.fn(() => (opts.missing ? null : { id: 5, reservation_id: opts.linkedTo ?? null })),
resyncLinkedPrices: vi.fn(),
resyncReservationPrice: vi.fn(),
} as unknown as BudgetService & Record<string, ReturnType<typeof vi.fn>>;
const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };
const db = {
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)),
prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })),
} as unknown as DatabaseService;
findAccessible: vi.fn(async (tripId: number, userId: number) =>
tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined,
),
} as unknown as TripsRepository;
const guards = new PluginGuards(
db,
{ checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => opts.addonOn ?? true) } as unknown as AddonsService,
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
);
// The leaf membership read replaced the deleted trips.bridge for listMine.
const membership = { listAccessibleTripIds: vi.fn(() => [1, 2]) } as unknown as TripMembershipService;
const rpc = new CostsRpc(budget, db, realtime, guards, membership);
const rpc = new CostsRpc(budget, new TripAccessService(db), realtime, guards, membership);
const host = (...grants: string[]) =>
new PluginRpcHost('p', new Set(grants.length ? grants : ['db:read:costs', 'db:write:costs']), makeDeps(), createTestPluginRegistry([rpc]));
new PluginRpcHost(
'p',
new Set(grants.length ? grants : ['db:read:costs', 'db:write:costs']),
makeDeps(),
createTestPluginRegistry([rpc]),
);
return { budget, realtime, host };
}
@@ -53,7 +83,9 @@ describe('CostsRpc reads', () => {
it('COSTS-RPC-001 getByTrip is membership-checked and addon-gated', async () => {
const f = build();
expect((await f.host().dispatch(req('costs.getByTrip', { tripId: 1 }), 42)).ok).toBe(true);
expect(((await f.host().dispatch(req('costs.getByTrip', { tripId: 2 }), 42)) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
expect(((await f.host().dispatch(req('costs.getByTrip', { tripId: 2 }), 42)) as RpcError).error.code).toBe(
'RESOURCE_FORBIDDEN',
);
});
it('COSTS-RPC-002 getByTrip reports the TRIP first when both would fail', async () => {
@@ -74,10 +106,12 @@ describe('CostsRpc reads', () => {
it('COSTS-RPC-004 listMine checks the user first, then the addon', async () => {
const f = build({ addonOn: false });
// No trip to check here, so the userless refusal comes first and the addon second.
expect(((await f.host().dispatch(req('costs.listMine'), undefined)) as RpcError).error.message)
.toBe('cost reads require an authenticated user context');
expect(((await f.host().dispatch(req('costs.listMine'), 42)) as RpcError).error.message)
.toBe('the costs addon is disabled');
expect(((await f.host().dispatch(req('costs.listMine'), undefined)) as RpcError).error.message).toBe(
'cost reads require an authenticated user context',
);
expect(((await f.host().dispatch(req('costs.listMine'), 42)) as RpcError).error.message).toBe(
'the costs addon is disabled',
);
});
it('COSTS-RPC-005 listMine aggregates across every accessible trip', async () => {
@@ -91,13 +125,22 @@ describe('CostsRpc reads', () => {
describe('CostsRpc writes', () => {
it('COSTS-RPC-006 every write needs the addon, trip access and budget_edit', async () => {
const f = build();
expect((await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel', price: 10 } }), 42)).ok).toBe(true);
expect(
(await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel', price: 10 } }), 42)).ok,
).toBe(true);
const off = build({ addonOn: false });
expect(((await off.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError).error.message)
.toBe('the costs addon is disabled');
expect(
((await off.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError)
.error.message,
).toBe('the costs addon is disabled');
const noEdit = build({ canEdit: false });
expect(((await noEdit.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError).error.message)
.toBe('no permission to edit costs on trip 1');
expect(
(
(await noEdit
.host()
.dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError
).error.message,
).toBe('no permission to edit costs on trip 1');
});
it('COSTS-RPC-007 the refusal says "costs on trip", not the generic trip message', async () => {
@@ -109,29 +152,43 @@ describe('CostsRpc writes', () => {
['costs.update', { tripId: 1, itemId: 5, input: { name: 'x' } }],
['costs.delete', { tripId: 1, itemId: 5 }],
] as const) {
expect(((await f.host().dispatch(req(method, params), 42)) as RpcError).error.message)
.toBe('no permission to edit costs on trip 1');
expect(((await f.host().dispatch(req(method, params), 42)) as RpcError).error.message).toBe(
'no permission to edit costs on trip 1',
);
}
});
it('COSTS-RPC-008 a userless write says "cost writes"', async () => {
const f = build();
expect(((await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), undefined)) as RpcError).error.message)
.toBe('cost writes require an authenticated user context');
expect(
(
(await f
.host()
.dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), undefined)) as RpcError
).error.message,
).toBe('cost writes require an authenticated user context');
});
it('COSTS-RPC-009 db:read:costs does not unlock a write', async () => {
const f = build();
expect(((await f.host('db:read:costs').dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError).error.code)
.toBe('PERMISSION_DENIED');
expect(
(
(await f
.host('db:read:costs')
.dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError
).error.code,
).toBe('PERMISSION_DENIED');
});
it('COSTS-RPC-010 a missing item is RESOURCE_FORBIDDEN, naming it', async () => {
const f = build({ missing: true });
expect(((await f.host().dispatch(req('costs.update', { tripId: 1, itemId: 404, input: { name: 'x' } }), 42)) as RpcError).error.message)
.toBe('no cost 404 on trip 1');
expect(((await f.host().dispatch(req('costs.delete', { tripId: 1, itemId: 404 }), 42)) as RpcError).error.message)
.toBe('no cost 404 on trip 1');
expect(
((await f.host().dispatch(req('costs.update', { tripId: 1, itemId: 404, input: { name: 'x' } }), 42)) as RpcError)
.error.message,
).toBe('no cost 404 on trip 1');
expect(
((await f.host().dispatch(req('costs.delete', { tripId: 1, itemId: 404 }), 42)) as RpcError).error.message,
).toBe('no cost 404 on trip 1');
});
it('COSTS-RPC-011 each write broadcasts its event, a refused one broadcasts nothing', async () => {
@@ -139,7 +196,11 @@ describe('CostsRpc writes', () => {
await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel', price: 10 } }), 42);
await f.host().dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { name: 'x' } }), 42);
await f.host().dispatch(req('costs.delete', { tripId: 1, itemId: 5 }), 42);
expect(f.realtime.broadcast.mock.calls.map((c) => c[1])).toEqual(['budget:created', 'budget:updated', 'budget:deleted']);
expect(f.realtime.broadcast.mock.calls.map((c) => c[1])).toEqual([
'budget:created',
'budget:updated',
'budget:deleted',
]);
const off = build({ addonOn: false });
await off.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42);
expect(off.realtime.broadcast).not.toHaveBeenCalled();
@@ -149,3 +210,124 @@ describe('CostsRpc writes', () => {
expectRegisteredProvider(BudgetModule, CostsRpc);
});
});
// #2084: a cost can point at a booking or a place, which has to be on the same trip
// (the REST route answers 400, the MCP tool an error result, the plugin surface
// RESOURCE_FORBIDDEN, all in the same words), and the booking mirrors its costs' total.
describe('CostsRpc links to bookings and places', () => {
it("COSTS-RPC-013 a create linking another trip's booking is refused in linkRefusal's words, before any write", async () => {
const f = build({ refusal: 'reservation_id does not belong to this trip.' });
const res = (await f
.host()
.dispatch(
req('costs.create', { tripId: 1, input: { name: 'Seat', total_price: 15, reservation_id: 4711 } }),
42,
)) as RpcError;
expect(res.error.code).toBe('RESOURCE_FORBIDDEN');
expect(res.error.message).toBe('reservation_id does not belong to this trip.');
expect(f.budget.linkRefusal).toHaveBeenCalledWith(1, expect.objectContaining({ reservation_id: 4711 }));
expect(f.budget.create).not.toHaveBeenCalled();
expect(f.budget.resyncReservationPrice).not.toHaveBeenCalled();
expect(f.realtime.broadcast).not.toHaveBeenCalled();
});
it("COSTS-RPC-014 an update linking another trip's place is refused before it reads, writes or resyncs", async () => {
const f = build({ refusal: 'place_id does not belong to this trip.', linkedTo: 77 });
const res = (await f
.host()
.dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { place_id: 4711 } }), 42)) as RpcError;
expect(res.error.code).toBe('RESOURCE_FORBIDDEN');
expect(res.error.message).toBe('place_id does not belong to this trip.');
expect(f.budget.linkRefusal).toHaveBeenCalledWith(1, { place_id: 4711 });
expect(f.budget.getBudgetItem).not.toHaveBeenCalled();
expect(f.budget.update).not.toHaveBeenCalled();
expect(f.budget.resyncLinkedPrices).not.toHaveBeenCalled();
expect(f.realtime.broadcast).not.toHaveBeenCalled();
});
it('COSTS-RPC-015 the permission refusal still comes first, so a link check never answers a caller without budget_edit', async () => {
const f = build({ canEdit: false, refusal: 'reservation_id does not belong to this trip.' });
for (const [method, params] of [
['costs.create', { tripId: 1, input: { name: 'x', reservation_id: 4711 } }],
['costs.update', { tripId: 1, itemId: 5, input: { reservation_id: 4711 } }],
] as const) {
expect(((await f.host().dispatch(req(method, params), 42)) as RpcError).error.message).toBe(
'no permission to edit costs on trip 1',
);
}
expect(f.budget.linkRefusal).not.toHaveBeenCalled();
});
it("COSTS-RPC-016 a cost created on a booking resyncs that booking's price; an unlinked one resyncs nothing", async () => {
const f = build();
expect(
(
await f
.host()
.dispatch(
req('costs.create', { tripId: 1, input: { name: 'Seat', total_price: 15, reservation_id: 77 } }),
42,
)
).ok,
).toBe(true);
expect(f.budget.resyncReservationPrice).toHaveBeenCalledWith(1, 77);
expect(f.realtime.broadcast.mock.calls.map((c) => c[1])).toEqual(['budget:created']);
const g = build();
await g.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'Coffee', total_price: 3 } }), 42);
expect(g.budget.resyncReservationPrice).not.toHaveBeenCalled();
});
it('COSTS-RPC-017 an update moving the cost hands the booking it left and the row it wrote to resyncLinkedPrices', async () => {
const f = build({ linkedTo: 77 });
const res = await f
.host()
.dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { reservation_id: 78 } }), 42);
expect(res.ok).toBe(true);
// The row is read before the write, so the booking it leaves is still known.
expect(f.budget.getBudgetItem).toHaveBeenCalledWith(5, 1);
expect(vi.mocked(f.budget.getBudgetItem).mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(f.budget.update).mock.invocationCallOrder[0],
);
expect(f.budget.resyncLinkedPrices).toHaveBeenCalledWith(
1,
77,
{ id: 5, name: 'Hotel', reservation_id: 78 },
{ reservation_id: 78 },
);
});
it('COSTS-RPC-018 an unlink (null) snapshots too and passes the booking it leaves', async () => {
const f = build({ linkedTo: 77 });
await f.host().dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { reservation_id: null } }), 42);
expect(f.budget.resyncLinkedPrices).toHaveBeenCalledWith(
1,
77,
{ id: 5, name: 'Hotel', reservation_id: null },
{ reservation_id: null },
);
});
it('COSTS-RPC-019 an update that names no booking reads nothing first, yet still lets the linked booking resync', async () => {
// A new total or currency moves the price of the booking the cost stays on.
const f = build({ linkedTo: 77 });
await f.host().dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { total_price: 40 } }), 42);
expect(f.budget.getBudgetItem).not.toHaveBeenCalled();
expect(f.budget.resyncLinkedPrices).toHaveBeenCalledWith(
1,
undefined,
{ id: 5, name: 'Hotel', reservation_id: 77 },
{ total_price: 40 },
);
});
it('COSTS-RPC-020 a missing cost resyncs nothing', async () => {
const f = build({ missing: true });
const res = (await f
.host()
.dispatch(req('costs.update', { tripId: 1, itemId: 404, input: { reservation_id: 78 } }), 42)) as RpcError;
expect(res.error.message).toBe('no cost 404 on trip 1');
expect(f.budget.resyncLinkedPrices).not.toHaveBeenCalled();
expect(f.realtime.broadcast).not.toHaveBeenCalled();
});
});
+70 -2
View File
@@ -2,6 +2,10 @@ import fs from 'node:fs';
import path from 'node:path';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// The subject here is config.ts itself, so this suite takes the real module
// rather than the fixed values the global setup puts in its place.
vi.unmock('../../src/config');
// config.ts resolves its key material at import time, so every case here has to
// reset the module registry and re-import it with the file system stubbed out.
const ENC_KEY_FILE = path.resolve(__dirname, '../../data/.encryption_key');
@@ -82,7 +86,9 @@ describe('config — encryption key resolution', () => {
}) as never);
const write = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
vi.spyOn(console, 'error').mockImplementation(() => undefined);
vi.spyOn(fs, 'existsSync').mockImplementation(((file: fs.PathLike) => String(file) === ENC_KEY_FILE) as typeof fs.existsSync);
vi.spyOn(fs, 'existsSync').mockImplementation(
((file: fs.PathLike) => String(file) === ENC_KEY_FILE) as typeof fs.existsSync,
);
stubKeyFileRead(() => ' \n');
await expect(import('../../src/config')).rejects.toThrow('process.exit called');
@@ -97,7 +103,9 @@ describe('config — encryption key resolution', () => {
vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
vi.spyOn(console, 'log').mockImplementation(() => undefined);
// The key file is genuinely absent, so the empty-file guard must not fire.
vi.spyOn(fs, 'existsSync').mockImplementation(((file: fs.PathLike) => String(file) !== ENC_KEY_FILE) as typeof fs.existsSync);
vi.spyOn(fs, 'existsSync').mockImplementation(
((file: fs.PathLike) => String(file) !== ENC_KEY_FILE) as typeof fs.existsSync,
);
stubKeyFileRead(() => {
throw enoent();
});
@@ -106,4 +114,64 @@ describe('config — encryption key resolution', () => {
expect(exit).not.toHaveBeenCalled();
expect(config.ENCRYPTION_KEY).toMatch(/^[0-9a-f]{64}$/);
});
describe('an explicit ENCRYPTION_KEY outside the test suite', () => {
const realNodeEnv = process.env.NODE_ENV;
beforeEach(() => {
process.env.NODE_ENV = 'production';
});
afterEach(() => {
process.env.NODE_ENV = realNodeEnv;
});
it('CFGKEY-004: refuses to boot when it disagrees with the key file, and leaves the file alone', async () => {
process.env.ENCRYPTION_KEY = 'a-new-key';
const exit = vi.spyOn(process, 'exit').mockImplementation((() => {
throw new Error('process.exit called');
}) as never);
const write = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);
stubKeyFileRead(() => 'the-original-key\n');
await expect(import('../../src/config')).rejects.toThrow('process.exit called');
expect(exit).toHaveBeenCalledWith(1);
expect(write).not.toHaveBeenCalledWith(ENC_KEY_FILE, expect.anything(), expect.anything());
expect(error.mock.calls.flat().join(' ')).toContain('migrate-encryption.ts');
});
it('CFGKEY-005: boots and keeps the file in step when both agree', async () => {
process.env.ENCRYPTION_KEY = 'the-original-key';
const exit = vi.spyOn(process, 'exit').mockImplementation((() => {
throw new Error('process.exit called');
}) as never);
const write = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
stubKeyFileRead(() => 'the-original-key\n');
const config = await import('../../src/config');
expect(exit).not.toHaveBeenCalled();
expect(config.ENCRYPTION_KEY).toBe('the-original-key');
expect(write).toHaveBeenCalledWith(ENC_KEY_FILE, 'the-original-key', { mode: 0o600 });
});
it('CFGKEY-006: writes the key file on the first start that has one in the environment', async () => {
process.env.ENCRYPTION_KEY = 'first-key';
const write = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
stubKeyFileRead(() => {
throw enoent();
});
await import('../../src/config');
expect(write).toHaveBeenCalledWith(ENC_KEY_FILE, 'first-key', { mode: 0o600 });
});
});
it('CFGKEY-007: under test, an explicit key neither checks nor overwrites the developer key file', async () => {
process.env.ENCRYPTION_KEY = 'suite-key';
const write = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
stubKeyFileRead(() => 'a-developer-key');
const config = await import('../../src/config');
expect(config.ENCRYPTION_KEY).toBe('suite-key');
expect(write).not.toHaveBeenCalledWith(ENC_KEY_FILE, expect.anything(), expect.anything());
});
});
@@ -0,0 +1,238 @@
/**
* contracts:dto-open: the contracts the server really binds may only get tighter.
*
* shared's contracts:open counts the open shapes in every export named
* *RequestSchema, but the name is a convention, not what the server binds:
* dozens of DTOs wrap a schema named *BodySchema, *InputSchema or just
* *Schema, and some wrap a schema declared in the dto file itself. This walks
* the other way round. It finds every `class X extends createZodDto(...)` under
* src/, imports the file, and counts the open shapes (the same walk as
* shared/scripts/open-request-schemas.mjs) in the schema that class hands the
* global ZodValidationPipe. The count per class is held against
* scripts/dto-open-shapes-baseline.json: a new DTO may hold none, an existing
* one no more than its entry.
*
* npm run contracts:dto-open this file, as CI runs it in the unit tests
* npm run contracts:dto-open -- --update lower the baseline to today's counts; it
* never raises or adds an entry
*
* It fails closed: a missing or malformed baseline, a createZodDto call that is
* not an exported class, two DTO classes with one name, or a tree without a
* single DTO stop it instead of passing with nothing checked.
*/
import { createZodDto } from 'nestjs-zod';
import { isZodDto } from 'nestjs-zod/dto';
import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { beforeAll, describe, expect, it } from 'vitest';
import { z } from 'zod';
const SERVER_ROOT = path.resolve(__dirname, '../../..');
const SRC = path.join(SERVER_ROOT, 'src');
const BASELINE = path.join(SERVER_ROOT, 'scripts/dto-open-shapes-baseline.json');
const OPEN_SHAPES_SCRIPT = path.resolve(SERVER_ROOT, '../shared/scripts/open-request-schemas.mjs');
type Counts = Record<string, number>;
interface OpenShapesModule {
openShapes(root: unknown): string[];
compare(baseline: Counts, counts: Counts): { grown: [string, number][]; lowerable: [string, number][] };
lowerBaseline(baseline: Counts, counts: Counts): Counts;
}
interface DtoDeclaration {
file: string;
name: string;
}
const DTO_CLASS = /\b(export\s+)?class\s+(\w+)\s+extends\s+createZodDto\s*\(/g;
const DTO_CALL = /\bcreateZodDto\s*\(/g;
function sourceFiles(dir: string, files: string[] = []): string[] {
for (const name of readdirSync(dir)) {
const full = path.join(dir, name);
if (statSync(full).isDirectory()) sourceFiles(full, files);
else if (name.endsWith('.ts') && !name.endsWith('.d.ts')) files.push(full);
}
return files;
}
/** The source without its comments, so a createZodDto named in prose is not counted as a call. */
function stripComments(text: string): string {
return text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
}
/**
* Every DTO class declared under `root`, and the problems that keep the walk
* from seeing one: a createZodDto call that is not `export class X extends
* createZodDto(...)` (its schema could not be reached through the module), or
* a class name used twice (the baseline is keyed by name).
*/
function findDtoClasses(root: string): { dtos: DtoDeclaration[]; problems: string[] } {
const dtos: DtoDeclaration[] = [];
const problems: string[] = [];
const firstFile = new Map<string, string>();
for (const full of sourceFiles(root)) {
const code = stripComments(readFileSync(full, 'utf8'));
const file = path.relative(SERVER_ROOT, full).split(path.sep).join('/');
const calls = code.match(DTO_CALL)?.length ?? 0;
const classes = [...code.matchAll(DTO_CLASS)];
if (calls !== classes.length) {
problems.push(
`${file}: ${calls - classes.length} createZodDto call(s) outside \`export class X extends createZodDto(...)\``,
);
}
for (const [, exported, name] of classes) {
if (!exported) problems.push(`${file}: ${name} is not exported, so its schema cannot be counted`);
const seen = firstFile.get(name);
if (seen) problems.push(`${name} is declared in ${seen} and ${file}: DTO class names must be unique`);
firstFile.set(name, file);
dtos.push({ file, name });
}
}
return { dtos, problems };
}
/** The baseline as committed. Missing, unreadable or malformed is an error, never an empty baseline. */
function readBaseline(file = BASELINE): Counts {
let parsed: unknown;
try {
parsed = JSON.parse(readFileSync(file, 'utf8'));
} catch (err) {
throw new Error(`scripts/dto-open-shapes-baseline.json cannot be read: ${(err as Error).message}`, { cause: err });
}
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('scripts/dto-open-shapes-baseline.json must be an object of DTO class names to counts');
}
for (const [name, n] of Object.entries(parsed)) {
if (!Number.isInteger(n) || (n as number) < 1) {
throw new Error(
`scripts/dto-open-shapes-baseline.json: ${name} holds ${JSON.stringify(n)}, expected a whole number above 0`,
);
}
}
return parsed as Counts;
}
/** Open-shape counts for every ZodDto class among a module's exports. */
function countDtoExports(namespace: Record<string, unknown>, names: string[], shapes: OpenShapesModule): Counts {
const counts: Counts = {};
for (const name of names) {
const dto = namespace[name];
if (typeof dto !== 'function' || !isZodDto(dto)) {
throw new Error(`${name} is not an exported createZodDto class`);
}
counts[name] = shapes.openShapes(dto.schema).length;
}
return counts;
}
let shapes: OpenShapesModule;
beforeAll(async () => {
shapes = (await import(pathToFileURL(OPEN_SHAPES_SCRIPT).href)) as OpenShapesModule;
});
describe('open shapes in the DTO contracts', () => {
let counts: Counts;
let problems: string[];
beforeAll(async () => {
const found = findDtoClasses(SRC);
problems = found.problems;
counts = {};
const byFile = new Map<string, string[]>();
for (const { file, name } of found.dtos) byFile.set(file, [...(byFile.get(file) ?? []), name]);
for (const [file, names] of byFile) {
const namespace = (await import(pathToFileURL(path.join(SERVER_ROOT, file)).href)) as Record<string, unknown>;
for (const name of names) {
try {
Object.assign(counts, countDtoExports(namespace, [name], shapes));
} catch (err) {
// Reported once by DTO-001, together with the reason the scan found.
if (!problems.some((p) => p.includes(` ${name} `))) problems.push(`${file}: ${(err as Error).message}`);
}
}
}
}, 120_000);
it('DTO-001: every createZodDto call is an exported, uniquely named class, and there are some', () => {
expect(problems).toEqual([]);
expect(
Object.keys(counts).length,
'no DTO class found under src/: the check would look at nothing',
).toBeGreaterThan(0);
});
it('DTO-002: no DTO holds more open shapes than the baseline allows', () => {
const { grown } = shapes.compare(readBaseline(), counts);
expect(
grown,
'type the fields instead of accepting any object (shared/CLAUDE.md, "Rules for new contracts")',
).toEqual([]);
});
it('DTO-003: the baseline names only DTOs that exist and are still open', () => {
let baseline = readBaseline();
if (process.env.DTO_OPEN_SHAPES_UPDATE === '1') {
baseline = shapes.lowerBaseline(baseline, counts);
writeFileSync(BASELINE, JSON.stringify(baseline, null, 2) + '\n');
}
const { lowerable } = shapes.compare(baseline, counts);
expect(lowerable, 'run `npm run contracts:dto-open -- --update` after narrowing a schema').toEqual([]);
});
});
describe('the DTO walk itself', () => {
it('DTO-004: counts an open body whatever its schema is called and fails on a new one', () => {
// A body named like most of the tree (fooBodySchema, pluginConfigSchema), not *RequestSchema.
const pluginConfigSchema = z.record(z.string(), z.unknown());
const fooBodySchema = z.looseObject({ name: z.string(), extra: z.unknown() });
class PluginConfigDto extends createZodDto(pluginConfigSchema) {}
class FooBodyDto extends createZodDto(fooBodySchema) {}
class ClosedDto extends createZodDto(z.strictObject({ a: z.string() })) {}
const counts = countDtoExports(
{ PluginConfigDto, FooBodyDto, ClosedDto },
['PluginConfigDto', 'FooBodyDto', 'ClosedDto'],
shapes,
);
expect(counts).toEqual({ PluginConfigDto: 1, FooBodyDto: 2, ClosedDto: 0 });
expect(shapes.compare({}, counts).grown).toEqual([
['PluginConfigDto', 1],
['FooBodyDto', 2],
]);
expect(shapes.compare({ FooBodyDto: 1, PluginConfigDto: 1 }, counts).grown).toEqual([['FooBodyDto', 2]]);
expect(() => countDtoExports({}, ['GoneDto'], shapes)).toThrow(/not an exported createZodDto class/);
});
it('DTO-005: refuses a DTO it cannot reach and a name used twice', () => {
const root = path.join(tmpdir(), `trek-dto-walk-${process.pid}-${Date.now()}`);
const nested = path.join(root, 'b');
try {
mkdirSync(nested, { recursive: true });
writeFileSync(
path.join(root, 'a.dto.ts'),
[
'// createZodDto( in a comment is not a call',
'export class ADto extends createZodDto(a) {}',
'class HiddenDto extends createZodDto(b) {}',
'const Loose = createZodDto(c);',
].join('\r\n'),
);
writeFileSync(path.join(nested, 'b.dto.ts'), 'export class ADto extends createZodDto(d) {}\n');
const { dtos, problems } = findDtoClasses(root);
expect(dtos.map((d) => d.name).sort()).toEqual(['ADto', 'ADto', 'HiddenDto']);
expect(problems.some((p) => p.includes('1 createZodDto call(s) outside'))).toBe(true);
expect(problems.some((p) => p.includes('HiddenDto is not exported'))).toBe(true);
expect(problems.some((p) => p.includes('ADto is declared in'))).toBe(true);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it('DTO-006: a missing or malformed baseline is an error, never an empty baseline', () => {
expect(() => readBaseline(path.join(SERVER_ROOT, 'scripts/definitely-not-here.json'))).toThrow(/cannot be read/);
expect(() => readBaseline(path.join(SERVER_ROOT, 'package.json'))).toThrow(/expected a whole number/);
});
});
@@ -0,0 +1,69 @@
import { readdirSync } from 'node:fs';
import path from 'node:path';
import { beforeAll, describe, expect, it } from 'vitest';
/**
* The coverage gate is a ratchet per src/nest domain (vitest.config.ts). A
* domain without its own entry falls into the pooled `src/nest/**` catch-all,
* where its coverage is averaged with app.module.ts and the like and can drop
* twenty points unseen; eleven domains had landed that way. This keeps every
* domain folder on its own floor, and every entry pointing at a folder that
* still exists.
*/
const NEST = path.resolve(__dirname, '../../src/nest');
// Loaded at runtime rather than imported: an import would pull vitest.config.ts
// into the tests' tsc program, which compiles it as CommonJS and rejects its
// import.meta.
const CONFIG_PATH = '../../vitest.config';
let thresholds: Record<string, Record<string, number>> = {};
beforeAll(async () => {
const config = ((await import(CONFIG_PATH)) as { default: { test?: { coverage?: unknown } } }).default;
thresholds = (config.test?.coverage as { thresholds?: typeof thresholds } | undefined)?.thresholds ?? {};
});
function domains(): string[] {
return readdirSync(NEST, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort();
}
function domainKeys(): string[] {
return Object.keys(thresholds)
.map((key) => key.match(/^src\/nest\/([^/*]+)\/\*\*\/\*\.ts$/)?.[1])
.filter((name): name is string => Boolean(name))
.sort();
}
describe('per-domain coverage thresholds', () => {
it('COVT-001: the config holds the per-domain block at all', () => {
expect(domainKeys().length).toBeGreaterThan(50);
expect(domains().length).toBeGreaterThan(50);
});
it('COVT-002: every directory under src/nest has its own threshold entry', () => {
const pinned = new Set(domainKeys());
expect(
domains().filter((d) => !pinned.has(d)),
"add `'src/nest/<domain>/**/*.ts'` to vitest.config.ts, from `node scripts/coverage-thresholds.mjs` after a coverage run",
).toEqual([]);
});
it('COVT-003: every domain entry names a directory that exists', () => {
const present = new Set(domains());
expect(domainKeys().filter((d) => !present.has(d))).toEqual([]);
});
it('COVT-004: no domain entry sits above 100 or below 0', () => {
for (const domain of domainKeys()) {
const entry = thresholds[`src/nest/${domain}/**/*.ts`];
for (const metric of ['statements', 'branches', 'functions', 'lines']) {
expect(entry?.[metric], `${domain}.${metric}`).toBeGreaterThanOrEqual(0);
expect(entry?.[metric], `${domain}.${metric}`).toBeLessThanOrEqual(100);
}
}
});
});
+52 -22
View File
@@ -4,22 +4,29 @@
* the stub identity; the rest cover the per-handler paths the router-level test had
* no room for.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
import { DayNotesRpc } from '../../../src/nest/day-notes/day-notes.rpc';
import { DayNotesModule } from '../../../src/nest/day-notes/day-notes.module';
import type { DayNotesService } from '../../../src/nest/day-notes/day-notes.service';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
import { PluginGuards } from '../../../src/nest-rpc/plugin-guards.service';
import { createTestPluginRegistry } from '../../../src/nest-rpc/rpc-kit/testing';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { DayNotesModule } from '../../../src/nest/day-notes/day-notes.module';
import { DayNotesRpc } from '../../../src/nest/day-notes/day-notes.rpc';
import type { DayNotesService } from '../../../src/nest/day-notes/day-notes.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { makeDeps } from '../../helpers/rpc-host-deps';
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
import { describe, it, expect, vi, beforeEach } from 'vitest';
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({
k: 'req',
id: 'x',
method,
params,
});
/** Trip 1 belongs to user 42; day 5 and note 50 sit on it. Nothing else does. */
function build(canEdit = true) {
@@ -35,13 +42,15 @@ function build(canEdit = true) {
} as unknown as DayNotesService & Record<string, ReturnType<typeof vi.fn>>;
const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };
const db = {
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)),
prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })),
} as unknown as DatabaseService;
findAccessible: vi.fn(async (tripId: number, userId: number) =>
tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined,
),
} as unknown as TripsRepository;
const guards = new PluginGuards(
db,
{ checkPermission: vi.fn(() => canEdit) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
);
const rpc = new DayNotesRpc(notes, realtime, guards);
const host = (...grants: string[]) =>
@@ -65,7 +74,9 @@ describe('DayNotesRpc through the router', () => {
it('DAYNOTES-RPC-002 create needs db:write:daynotes + day_edit, membership-checked, text required', async () => {
const host = f.host('db:write:daynotes');
expect((await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'Pack sunscreen' } }), 42)).ok).toBe(true);
expect(
(await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'Pack sunscreen' } }), 42)).ok,
).toBe(true);
expect(f.notes.create).toHaveBeenCalledWith(5, 1, 'Pack sunscreen', undefined, undefined, undefined);
const bad = await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: ' ' } }), 42);
expect((bad as RpcError).error.code).toBe('BAD_PARAMS');
@@ -83,19 +94,32 @@ describe('DayNotesRpc through the router', () => {
it('DAYNOTES-RPC-004 the read grant does not unlock a write', async () => {
const host = f.host('db:read:daynotes');
const res = (await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'x' } }), 42)) as RpcError;
const res = (await host.dispatch(
req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'x' } }),
42,
)) as RpcError;
expect(res.error.code).toBe('PERMISSION_DENIED');
});
it('DAYNOTES-RPC-005 update broadcasts and returns the updated note', async () => {
const host = f.host('db:write:daynotes');
expect((await host.dispatch(req('daynotes.update', { tripId: 1, dayId: 5, noteId: 50, input: { text: 'new' } }), 42)).ok).toBe(true);
expect(f.realtime.broadcast).toHaveBeenCalledWith(1, 'dayNote:updated', expect.objectContaining({ dayId: 5 }), undefined);
expect(
(await host.dispatch(req('daynotes.update', { tripId: 1, dayId: 5, noteId: 50, input: { text: 'new' } }), 42)).ok,
).toBe(true);
expect(f.realtime.broadcast).toHaveBeenCalledWith(
1,
'dayNote:updated',
expect.objectContaining({ dayId: 5 }),
undefined,
);
});
it('DAYNOTES-RPC-006 a note on another day is refused, naming it', async () => {
const host = f.host('db:write:daynotes');
const res = (await host.dispatch(req('daynotes.update', { tripId: 1, dayId: 5, noteId: 404, input: {} }), 42)) as RpcError;
const res = (await host.dispatch(
req('daynotes.update', { tripId: 1, dayId: 5, noteId: 404, input: {} }),
42,
)) as RpcError;
expect(res.error.code).toBe('RESOURCE_FORBIDDEN');
expect(res.error.message).toBe('no note 404 on day 5');
});
@@ -103,14 +127,20 @@ describe('DayNotesRpc through the router', () => {
it('DAYNOTES-RPC-007 without the edit permission the write is refused before it touches the service', async () => {
const noEdit = build(false);
const host = noEdit.host('db:write:daynotes');
const res = (await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'x' } }), 42)) as RpcError;
const res = (await host.dispatch(
req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'x' } }),
42,
)) as RpcError;
expect(res.error.message).toBe('no permission to edit trip 1');
expect(noEdit.notes.create).not.toHaveBeenCalled();
});
it('DAYNOTES-RPC-008 a day outside the trip is refused, naming it', async () => {
const host = f.host('db:write:daynotes');
const res = (await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 99, input: { text: 'x' } }), 42)) as RpcError;
const res = (await host.dispatch(
req('daynotes.create', { tripId: 1, dayId: 99, input: { text: 'x' } }),
42,
)) as RpcError;
expect(res.error.message).toBe('no day 99 on trip 1');
});
+114 -45
View File
@@ -5,26 +5,38 @@
* counts as a DAY edit in the app, so itinerary.* runs under day_edit rather than a
* permission of its own, and both halves scope their rows to the trip before writing.
*/
import { describe, it, expect, vi } from 'vitest';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
import { DaysRpc } from '../../../src/nest/days/days.rpc';
import { DaysModule } from '../../../src/nest/days/days.module';
import { ItineraryRpc } from '../../../src/nest/assignments/itinerary.rpc';
import { AssignmentsModule } from '../../../src/nest/assignments/assignments.module';
import { DayAppendError, NO_DATES_MESSAGE, type DatedDayAppend, type DaysService } from '../../../src/nest/days/days.service';
import { DayDeleteError, type DayRemoval, type DayRemovalService } from '../../../src/nest/days/day-removal.service';
import type { AssignmentsService } from '../../../src/nest/assignments/assignments.service';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
import { PluginGuards } from '../../../src/nest-rpc/plugin-guards.service';
import { createTestPluginRegistry } from '../../../src/nest-rpc/rpc-kit/testing';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { AssignmentsModule } from '../../../src/nest/assignments/assignments.module';
import type { AssignmentsService } from '../../../src/nest/assignments/assignments.service';
import { ItineraryRpc } from '../../../src/nest/assignments/itinerary.rpc';
import { DayDeleteError, type DayRemoval, type DayRemovalService } from '../../../src/nest/days/day-removal.service';
import { DaysModule } from '../../../src/nest/days/days.module';
import { DaysRpc } from '../../../src/nest/days/days.rpc';
import {
DayAppendError,
NO_DATES_MESSAGE,
type DatedDayAppend,
type DaysService,
} from '../../../src/nest/days/days.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { makeDeps } from '../../helpers/rpc-host-deps';
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
import { describe, it, expect, vi } from 'vitest';
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({
k: 'req',
id: 'x',
method,
params,
});
/** Trip 1 belongs to user 42; day 3, place 7 and assignment 30 sit on it. */
function build(opts: { canEdit?: boolean } = {}) {
@@ -33,8 +45,17 @@ function build(opts: { canEdit?: boolean } = {}) {
getDay: vi.fn((dayId: number, tripId: number) => (dayId === 3 && tripId === 1 ? { id: 3 } : undefined)),
update: vi.fn((id: number) => ({ id })),
appendDated: vi.fn((tripId: number): DatedDayAppend => ({
day: { id: 21, trip_id: tripId, day_number: 3, date: '2027-01-03', assignments: [], notes_items: [] } as DatedDayAppend['day'],
endDate: '2027-01-03', boundaries: null, trip: { id: tripId, end_date: '2027-01-03' },
day: {
id: 21,
trip_id: tripId,
day_number: 3,
date: '2027-01-03',
assignments: [],
notes_items: [],
} as DatedDayAppend['day'],
endDate: '2027-01-03',
boundaries: null,
trip: { id: tripId, end_date: '2027-01-03' },
})),
// The service's own fan-out is DAY-SVC-099; the stub sends one event through each sender.
announceDatedAppend: vi.fn((append: DatedDayAppend, send: Parameters<DaysService['announceDatedAppend']>[1]) => {
@@ -43,8 +64,15 @@ function build(opts: { canEdit?: boolean } = {}) {
}),
} as unknown as DaysService & Record<string, ReturnType<typeof vi.fn>>;
const removed: DayRemoval = {
dayId: 3, orderedIds: [4], stayIds: [], reservationIds: [], budgetItemIds: [], mirrors: [],
boundaries: null, endDate: null, trip: { id: 1 },
dayId: 3,
orderedIds: [4],
stayIds: [],
reservationIds: [],
budgetItemIds: [],
mirrors: [],
boundaries: null,
endDate: null,
trip: { id: 1 },
};
// announce() is the removal service's own fan-out (DAY-DEL-014); the stub sends
// one event through each sender so the case can see where they lead.
@@ -59,20 +87,27 @@ function build(opts: { canEdit?: boolean } = {}) {
dayExists: vi.fn((dayId: number, tripId: number) => dayId === 3 && tripId === 1),
placeExists: vi.fn((placeId: number, tripId: number) => placeId === 7 && tripId === 1),
createAssignment: vi.fn(() => ({ id: 30, day_id: 3, place_id: 7 })),
getAssignmentForTrip: vi.fn((id: number, tripId: number) => (id === 30 && tripId === 1 ? { id: 30, day_id: 3 } : undefined)),
getAssignmentForTrip: vi.fn((id: number, tripId: number) =>
id === 30 && tripId === 1 ? { id: 30, day_id: 3 } : undefined,
),
deleteAssignment: vi.fn(),
reconcile: vi.fn(),
} as unknown as AssignmentsService & Record<string, ReturnType<typeof vi.fn>>;
const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };
const guards = new PluginGuards(
{
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)),
prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })),
} as unknown as DatabaseService,
findAccessible: vi.fn(async (tripId: number, userId: number) =>
tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined,
),
} as unknown as TripsRepository,
{ checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
);
const registry = createTestPluginRegistry([new DaysRpc(days, realtime, guards, removal), new ItineraryRpc(assignments, realtime, guards)]);
const registry = createTestPluginRegistry([
new DaysRpc(days, realtime, guards, removal),
new ItineraryRpc(assignments, realtime, guards),
]);
const host = (...grants: string[]) => new PluginRpcHost('p', new Set(grants), makeDeps(), registry);
return { days, assignments, realtime, host, removal, removed };
}
@@ -82,7 +117,9 @@ describe('DaysRpc', () => {
const f = build();
const host = f.host('db:write:days');
expect((await host.dispatch(req('days.create', { tripId: 1, input: { date: '2027-01-01' } }), 42)).ok).toBe(true);
expect(((await host.dispatch(req('days.create', { tripId: 2, input: {} }), 42)) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
expect(((await host.dispatch(req('days.create', { tripId: 2, input: {} }), 42)) as RpcError).error.code).toBe(
'RESOURCE_FORBIDDEN',
);
const noUser = (await host.dispatch(req('days.create', { tripId: 1, input: {} }), undefined)) as RpcError;
expect(noUser.error.message).toBe('day writes require an authenticated user context');
});
@@ -90,10 +127,12 @@ describe('DaysRpc', () => {
it('DAYS-RPC-002 a day on another trip is refused for update and delete alike', async () => {
const f = build();
const host = f.host('db:write:days');
expect(((await host.dispatch(req('days.update', { tripId: 1, dayId: 404, input: {} }), 42)) as RpcError).error.message)
.toBe('no day 404 on trip 1');
expect(((await host.dispatch(req('days.delete', { tripId: 1, dayId: 404 }), 42)) as RpcError).error.message)
.toBe('no day 404 on trip 1');
expect(
((await host.dispatch(req('days.update', { tripId: 1, dayId: 404, input: {} }), 42)) as RpcError).error.message,
).toBe('no day 404 on trip 1');
expect(((await host.dispatch(req('days.delete', { tripId: 1, dayId: 404 }), 42)) as RpcError).error.message).toBe(
'no day 404 on trip 1',
);
expect(f.removal.remove).not.toHaveBeenCalled();
});
@@ -103,7 +142,12 @@ describe('DaysRpc', () => {
await host.dispatch(req('days.create', { tripId: 1, input: {} }), 42);
await host.dispatch(req('days.update', { tripId: 1, dayId: 3, input: { notes: 'x' } }), 42);
await host.dispatch(req('days.delete', { tripId: 1, dayId: 3 }), 42);
expect(f.realtime.broadcast.mock.calls.map((c) => c[1])).toEqual(['day:created', 'day:updated', 'day:deleted', 'day:reordered']);
expect(f.realtime.broadcast.mock.calls.map((c) => c[1])).toEqual([
'day:created',
'day:updated',
'day:deleted',
'day:reordered',
]);
});
it('DAYS-RPC-004 the class is listed in its module providers', () => {
@@ -112,7 +156,9 @@ describe('DaysRpc', () => {
it('DAYS-RPC-005 the last day of a trip is BAD_PARAMS with the sentence REST and MCP give, and nothing is announced', async () => {
const f = build();
vi.mocked(f.removal.remove).mockImplementation(() => { throw new DayDeleteError('A trip needs at least one day.'); });
vi.mocked(f.removal.remove).mockImplementation(() => {
throw new DayDeleteError('A trip needs at least one day.');
});
const res = (await f.host('db:write:days').dispatch(req('days.delete', { tripId: 1, dayId: 3 }), 42)) as RpcError;
expect(res.error).toMatchObject({ code: 'BAD_PARAMS', message: 'A trip needs at least one day.' });
expect(f.removal.announce).not.toHaveBeenCalled();
@@ -135,14 +181,18 @@ describe('DaysRpc', () => {
it('DAYS-RPC-006b anything but the last-day refusal is not dressed up as bad params', async () => {
const f = build();
vi.mocked(f.removal.remove).mockImplementation(() => { throw new Error('db is down'); });
vi.mocked(f.removal.remove).mockImplementation(() => {
throw new Error('db is down');
});
const res = (await f.host('db:write:days').dispatch(req('days.delete', { tripId: 1, dayId: 3 }), 42)) as RpcError;
expect(res.error.code).not.toBe('BAD_PARAMS');
});
it('DAYS-RPC-007 a dated create appends as the bound user, answers with the day and fans out to every socket', async () => {
const f = build();
const res = await f.host('db:write:days').dispatch(req('days.create', { tripId: 1, input: { dated: true, notes: 'Late checkout' } }), 42);
const res = await f
.host('db:write:days')
.dispatch(req('days.create', { tripId: 1, input: { dated: true, notes: 'Late checkout' } }), 42);
expect(res).toMatchObject({ ok: true, result: { id: 21, date: '2027-01-03' } });
expect(f.days.appendDated).toHaveBeenCalledWith(1, 42, 'Late checkout');
expect(f.days.create).not.toHaveBeenCalled();
@@ -153,18 +203,25 @@ describe('DaysRpc', () => {
it('DAYS-RPC-008 a dated create on a trip without dates, or next to a position, is BAD_PARAMS and announces nothing', async () => {
const f = build();
vi.mocked(f.days.appendDated).mockImplementation(() => { throw new DayAppendError(NO_DATES_MESSAGE); });
vi.mocked(f.days.appendDated).mockImplementation(() => {
throw new DayAppendError(NO_DATES_MESSAGE);
});
const host = f.host('db:write:days');
const noDates = (await host.dispatch(req('days.create', { tripId: 1, input: { dated: true } }), 42)) as RpcError;
expect(noDates.error).toMatchObject({ code: 'BAD_PARAMS', message: NO_DATES_MESSAGE });
const mixed = (await host.dispatch(req('days.create', { tripId: 1, input: { dated: true, position: 2 } }), 42)) as RpcError;
const mixed = (await host.dispatch(
req('days.create', { tripId: 1, input: { dated: true, position: 2 } }),
42,
)) as RpcError;
expect(mixed.error.code).toBe('BAD_PARAMS');
expect(mixed.error.message).toContain('dated cannot be combined with date or position');
expect(f.days.appendDated).toHaveBeenCalledTimes(1);
// Anything else is not dressed up as bad params.
vi.mocked(f.days.appendDated).mockImplementation(() => { throw new Error('db is down'); });
vi.mocked(f.days.appendDated).mockImplementation(() => {
throw new Error('db is down');
});
const broken = (await host.dispatch(req('days.create', { tripId: 1, input: { dated: true } }), 42)) as RpcError;
expect(broken.error.code).not.toBe('BAD_PARAMS');
expect(f.realtime.broadcast).not.toHaveBeenCalled();
@@ -174,7 +231,9 @@ describe('DaysRpc', () => {
describe('ItineraryRpc', () => {
it('ITIN-RPC-001 assign links a day and a place that both belong to the trip', async () => {
const f = build();
const res = await f.host('db:write:itinerary').dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 7 }), 42);
const res = await f
.host('db:write:itinerary')
.dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 7 }), 42);
expect(res.ok).toBe(true);
expect(f.assignments.createAssignment).toHaveBeenCalledWith(3, 7, null);
});
@@ -182,22 +241,30 @@ describe('ItineraryRpc', () => {
it('ITIN-RPC-002 a day or place from another trip is refused, so nothing cross-links', async () => {
const f = build();
const host = f.host('db:write:itinerary');
expect(((await host.dispatch(req('itinerary.assign', { tripId: 1, dayId: 404, placeId: 7 }), 42)) as RpcError).error.message)
.toBe('no day 404 on trip 1');
expect(((await host.dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 404 }), 42)) as RpcError).error.message)
.toBe('no place 404 on trip 1');
expect(
((await host.dispatch(req('itinerary.assign', { tripId: 1, dayId: 404, placeId: 7 }), 42)) as RpcError).error
.message,
).toBe('no day 404 on trip 1');
expect(
((await host.dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 404 }), 42)) as RpcError).error
.message,
).toBe('no place 404 on trip 1');
expect(f.assignments.createAssignment).not.toHaveBeenCalled();
});
it('ITIN-RPC-003 it runs under day_edit, not an itinerary permission of its own', async () => {
const f = build({ canEdit: false });
const res = (await f.host('db:write:itinerary').dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 7 }), 42)) as RpcError;
const res = (await f
.host('db:write:itinerary')
.dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 7 }), 42)) as RpcError;
expect(res.error.message).toBe('no permission to edit trip 1');
});
it('ITIN-RPC-004 notes are optional and pass through as null when absent', async () => {
const f = build();
await f.host('db:write:itinerary').dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 7, notes: 'lunch' }), 42);
await f
.host('db:write:itinerary')
.dispatch(req('itinerary.assign', { tripId: 1, dayId: 3, placeId: 7, notes: 'lunch' }), 42);
expect(f.assignments.createAssignment).toHaveBeenCalledWith(3, 7, 'lunch');
});
@@ -217,7 +284,9 @@ describe('ItineraryRpc', () => {
it('ITIN-RPC-007 an assignment on another trip is refused and nothing is deleted', async () => {
const f = build();
const res = (await f.host('db:write:itinerary').dispatch(req('itinerary.unassign', { tripId: 1, assignmentId: 404 }), 42)) as RpcError;
const res = (await f
.host('db:write:itinerary')
.dispatch(req('itinerary.unassign', { tripId: 1, assignmentId: 404 }), 42)) as RpcError;
expect(res.error.message).toBe('no assignment 404 on trip 1');
expect(f.assignments.deleteAssignment).not.toHaveBeenCalled();
});
@@ -0,0 +1,148 @@
/**
* `Migration20200101046280_an_assistant_conversation_can_be_about_no_one_trip`:
* `assistant_threads` is rebuilt so a thread of the home chat can name neither
* a trip nor a journey, with `assistant_messages` and `assistant_tool_calls`
* rebuilt beside it, without losing a row of any of the three; a thread still
* never names both, and each goes with what it is about.
*/
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import { describe, expect, it } from 'vitest';
const TARGET = 'Migration20200101046280_an_assistant_conversation_can_be_about_no_one_trip';
async function ormBeforeTarget(): Promise<MikroORM> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const index = names.indexOf(TARGET);
expect(index).toBeGreaterThan(0);
await migrateTo(orm, names[index - 1]);
return orm;
}
async function seed(orm: MikroORM): Promise<void> {
await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')");
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Kyoto')");
await rawExec(
orm,
"INSERT INTO journeys (id, user_id, title, created_at, updated_at) VALUES (20, 1, 'Portugal', 0, 0)",
);
await rawExec(
orm,
`INSERT INTO assistant_threads (id, user_id, trip_id, title, created_at, last_message_at)
VALUES (1, 1, 10, 'Kyoto day', '2026-10-20 10:00:00', '2026-10-20 11:00:00')`,
);
await rawExec(
orm,
`INSERT INTO assistant_threads (id, user_id, journey_id, title, created_at, last_message_at)
VALUES (2, 1, 20, 'Cover', '2026-10-21 10:00:00', '2026-10-21 11:00:00')`,
);
await rawExec(
orm,
`INSERT INTO assistant_messages (id, thread_id, role, parts, provider_state, status, model, created_at)
VALUES (5, 1, 'assistant', '[]', '{"items":[]}', 'awaiting_approval', 'claude', '2026-10-20 10:00:00')`,
);
await rawExec(
orm,
`INSERT INTO assistant_tool_calls (id, thread_id, message_id, provider_call_id, tool_name, args, preview, state,
result, undo_until, created_at, decided_at)
VALUES ('c1', 1, 5, 'toolu_1', 'create_place', '{"name":"A"}', '{}', 'executed', '{"place":{"id":3}}',
'2026-10-20 10:15:00', '2026-10-20 10:00:00', '2026-10-20 10:01:00')`,
);
}
describe('Assistant home threads migration', () => {
it('HTHRMIG-001: keeps every trip and journey thread, message and proposed change as it was', async () => {
const orm = await ormBeforeTarget();
try {
await seed(orm);
await migrateTo(orm, TARGET);
expect(await rawQuery(orm, 'SELECT * FROM assistant_threads ORDER BY id')).toEqual([
{
id: 1,
user_id: 1,
trip_id: 10,
journey_id: null,
title: 'Kyoto day',
created_at: '2026-10-20 10:00:00',
last_message_at: '2026-10-20 11:00:00',
},
{
id: 2,
user_id: 1,
trip_id: null,
journey_id: 20,
title: 'Cover',
created_at: '2026-10-21 10:00:00',
last_message_at: '2026-10-21 11:00:00',
},
]);
expect(await rawQuery(orm, 'SELECT id, thread_id, status, provider_state FROM assistant_messages')).toEqual([
{ id: 5, thread_id: 1, status: 'awaiting_approval', provider_state: '{"items":[]}' },
]);
expect(
await rawQuery(orm, 'SELECT id, thread_id, message_id, state, undo_until FROM assistant_tool_calls'),
).toEqual([{ id: 'c1', thread_id: 1, message_id: 5, state: 'executed', undo_until: '2026-10-20 10:15:00' }]);
expect(await rawQuery(orm, 'SELECT * FROM pragma_foreign_key_check')).toEqual([]);
} finally {
await orm.close(true);
}
}, 30000);
it('HTHRMIG-002: a thread may name neither a trip nor a journey, still never both', async () => {
const orm = await ormBeforeTarget();
try {
await seed(orm);
await migrateTo(orm, TARGET);
await rawExec(orm, "INSERT INTO assistant_threads (id, user_id, title) VALUES (3, 1, 'Home')");
expect(await rawQuery(orm, 'SELECT trip_id, journey_id FROM assistant_threads WHERE id = 3')).toEqual([
{ trip_id: null, journey_id: null },
]);
await expect(
rawExec(orm, "INSERT INTO assistant_threads (user_id, trip_id, journey_id, title) VALUES (1, 10, 20, 'Both')"),
).rejects.toThrow(/CHECK/);
await expect(
rawExec(orm, "INSERT INTO assistant_threads (user_id, trip_id, title) VALUES (1, 999, 'Nowhere')"),
).rejects.toThrow(/FOREIGN KEY/);
} finally {
await orm.close(true);
}
}, 30000);
it('HTHRMIG-003: the keys point at the new tables, the indexes come back, and each thread goes with what it is about', async () => {
const orm = await ormBeforeTarget();
try {
await seed(orm);
await migrateTo(orm, TARGET);
await rawExec(orm, "INSERT INTO assistant_threads (id, user_id, title) VALUES (3, 1, 'Home')");
const parents = await rawQuery<{ table: string }>(
orm,
`SELECT "table" FROM pragma_foreign_key_list('assistant_tool_calls') ORDER BY "table"`,
);
expect(parents.map((row) => row.table)).toEqual(['assistant_messages', 'assistant_threads']);
const indexes = await rawQuery<{ name: string }>(
orm,
"SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'assistant_threads' AND sql IS NOT NULL ORDER BY name",
);
expect(indexes.map((row) => row.name)).toEqual([
'idx_assistant_threads_journey',
'idx_assistant_threads_trip',
'idx_assistant_threads_user_journey',
'idx_assistant_threads_user_trip',
]);
await rawExec(orm, 'DELETE FROM trips WHERE id = 10');
await rawExec(orm, 'DELETE FROM journeys WHERE id = 20');
expect(await rawQuery(orm, 'SELECT id FROM assistant_threads')).toEqual([{ id: 3 }]);
expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM assistant_messages')).toEqual([{ n: 0 }]);
await rawExec(orm, 'DELETE FROM users WHERE id = 1');
expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM assistant_threads')).toEqual([{ n: 0 }]);
} finally {
await orm.close(true);
}
}, 30000);
});
@@ -0,0 +1,165 @@
/**
* `Migration20200101046250_an_assistant_conversation_can_be_about_a_journey`:
* `assistant_threads` is rebuilt so a thread can be about a journey instead of
* a trip, with `assistant_messages` and `assistant_tool_calls` rebuilt beside
* it, without losing a row of any of the three; every thread is about exactly
* one of the two, and each goes with what it is about.
*/
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import { describe, expect, it } from 'vitest';
const TARGET = 'Migration20200101046250_an_assistant_conversation_can_be_about_a_journey';
async function ormBeforeTarget(): Promise<MikroORM> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const index = names.indexOf(TARGET);
expect(index).toBeGreaterThan(0);
await migrateTo(orm, names[index - 1]);
return orm;
}
async function seedOwner(orm: MikroORM): Promise<void> {
await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')");
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Kyoto')");
await rawExec(
orm,
"INSERT INTO journeys (id, user_id, title, created_at, updated_at) VALUES (20, 1, 'Portugal', 0, 0)",
);
}
async function seedTripConversation(orm: MikroORM): Promise<void> {
await rawExec(
orm,
`INSERT INTO assistant_threads (id, user_id, trip_id, title, created_at, last_message_at)
VALUES (1, 1, 10, 'Kyoto day', '2026-10-20 10:00:00', '2026-10-20 11:00:00')`,
);
await rawExec(
orm,
`INSERT INTO assistant_messages (id, thread_id, role, parts, provider_state, status, model, created_at)
VALUES (5, 1, 'assistant', '[]', '{"items":[]}', 'awaiting_approval', 'claude', '2026-10-20 10:00:00')`,
);
await rawExec(
orm,
`INSERT INTO assistant_tool_calls (id, thread_id, message_id, provider_call_id, tool_name, args, preview, state,
result, undo_until, created_at, decided_at)
VALUES ('c1', 1, 5, 'toolu_1', 'create_place', '{"name":"A"}', '{}', 'executed', '{"place":{"id":3}}',
'2026-10-20 10:15:00', '2026-10-20 10:00:00', '2026-10-20 10:01:00')`,
);
}
describe('Assistant journey threads migration', () => {
it('JTHRMIG-001: keeps every thread, message and proposed change as it was', async () => {
const orm = await ormBeforeTarget();
try {
await seedOwner(orm);
await seedTripConversation(orm);
await migrateTo(orm, TARGET);
expect(await rawQuery(orm, 'SELECT * FROM assistant_threads')).toEqual([
{
id: 1,
user_id: 1,
trip_id: 10,
journey_id: null,
title: 'Kyoto day',
created_at: '2026-10-20 10:00:00',
last_message_at: '2026-10-20 11:00:00',
},
]);
expect(await rawQuery(orm, 'SELECT * FROM assistant_messages')).toEqual([
{
id: 5,
thread_id: 1,
role: 'assistant',
parts: '[]',
provider_state: '{"items":[]}',
status: 'awaiting_approval',
model: 'claude',
created_at: '2026-10-20 10:00:00',
},
]);
expect(await rawQuery(orm, 'SELECT * FROM assistant_tool_calls')).toEqual([
{
id: 'c1',
thread_id: 1,
message_id: 5,
provider_call_id: 'toolu_1',
tool_name: 'create_place',
args: '{"name":"A"}',
preview: '{}',
state: 'executed',
result: '{"place":{"id":3}}',
undo_until: '2026-10-20 10:15:00',
created_at: '2026-10-20 10:00:00',
decided_at: '2026-10-20 10:01:00',
},
]);
expect(await rawQuery(orm, 'SELECT * FROM pragma_foreign_key_check')).toEqual([]);
} finally {
await orm.close(true);
}
}, 30000);
it('JTHRMIG-002: a thread is about a trip or a journey, never both and never neither', async () => {
const orm = await ormBeforeTarget();
try {
await seedOwner(orm);
await migrateTo(orm, TARGET);
await rawExec(orm, "INSERT INTO assistant_threads (id, user_id, journey_id, title) VALUES (2, 1, 20, 'Book')");
expect(await rawQuery(orm, 'SELECT trip_id, journey_id FROM assistant_threads WHERE id = 2')).toEqual([
{ trip_id: null, journey_id: 20 },
]);
await expect(
rawExec(orm, "INSERT INTO assistant_threads (user_id, trip_id, journey_id, title) VALUES (1, 10, 20, 'Both')"),
).rejects.toThrow(/CHECK/);
await expect(
rawExec(orm, "INSERT INTO assistant_threads (user_id, title) VALUES (1, 'Neither')"),
).rejects.toThrow(/CHECK/);
await expect(
rawExec(orm, "INSERT INTO assistant_threads (user_id, journey_id, title) VALUES (1, 999, 'Nowhere')"),
).rejects.toThrow(/FOREIGN KEY/);
} finally {
await orm.close(true);
}
}, 30000);
it('JTHRMIG-003: each goes with its journey or its trip, children included, and the keys point at the new tables', async () => {
const orm = await ormBeforeTarget();
try {
await seedOwner(orm);
await seedTripConversation(orm);
await migrateTo(orm, TARGET);
await rawExec(orm, "INSERT INTO assistant_threads (id, user_id, journey_id, title) VALUES (2, 1, 20, 'Book')");
const parents = await rawQuery<{ table: string }>(
orm,
`SELECT "table" FROM pragma_foreign_key_list('assistant_tool_calls') ORDER BY "table"`,
);
expect(parents.map((row) => row.table)).toEqual(['assistant_messages', 'assistant_threads']);
const indexes = await rawQuery<{ name: string }>(
orm,
"SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'assistant_threads' AND sql IS NOT NULL ORDER BY name",
);
expect(indexes.map((row) => row.name)).toEqual([
'idx_assistant_threads_journey',
'idx_assistant_threads_trip',
'idx_assistant_threads_user_journey',
'idx_assistant_threads_user_trip',
]);
await rawExec(orm, 'DELETE FROM journeys WHERE id = 20');
expect(await rawQuery(orm, 'SELECT id FROM assistant_threads')).toEqual([{ id: 1 }]);
await rawExec(orm, 'DELETE FROM trips WHERE id = 10');
expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM assistant_threads')).toEqual([{ n: 0 }]);
expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM assistant_messages')).toEqual([{ n: 0 }]);
expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM assistant_tool_calls')).toEqual([{ n: 0 }]);
} finally {
await orm.close(true);
}
}, 30000);
});
@@ -2,122 +2,147 @@
* Unit test for the Atlas region-code reconciliation migration (#1119).
*
* After Atlas swapped Natural Earth for geoBoundaries, manually-marked regions
* (`visited_regions`) held the old Natural Earth ISO-3166-2 codes. The final migration
* reconciles each row against the shipped admin-1 bundle: valid codes are kept, codes
* whose region NAME still matches are re-coded, renamed-merge cases use a curated
* crosswalk, and anything else is left untouched. We exercise the real migration by
* running all migrations, seeding rows, rewinding schema_version by one, and re-running
* so only the last (reconciliation) migration fires.
* (`visited_regions`) held the old Natural Earth ISO-3166-2 codes. The
* migration reconciles each row against the shipped admin-1 bundle: valid
* codes are kept, codes whose region NAME still matches are re-coded,
* renamed-merge cases use a curated crosswalk, and anything else is left
* untouched. Ported off the legacy runner (Task 0 triage: PORT — the numbered
* MikroORM migration below has its own class but no dedicated test) onto the
* real `Migration20200101021500_atlas_dropped_natural_earth_for_geoboundaries`:
* migrate to the step immediately before it, seed rows with raw SQL, apply
* just that one migration, assert.
*/
import { describe, it, expect } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { createUser } from '../../helpers/factories';
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
function freshDb() {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
runMigrations(db);
return db;
import { describe, it, expect, afterEach } from 'vitest';
const TARGET = 'Migration20200101021500_atlas_dropped_natural_earth_for_geoboundaries';
let seq = 0;
let orm: MikroORM;
/** A fresh ORM migrated to the step immediately before the reconciliation. */
async function ormBeforeTarget(): Promise<MikroORM> {
const o = await createMigrationOrm();
const names = await pendingNames(o);
const idx = names.indexOf(TARGET);
expect(idx).toBeGreaterThan(0); // sanity: the migration must exist in the chain
await migrateTo(o, names[idx - 1]);
return o;
}
function mark(db: Database.Database, userId: number, code: string, name: string, country = 'NO') {
db.prepare(
'INSERT INTO visited_regions (user_id, region_code, region_name, country_code) VALUES (?, ?, ?, ?)'
).run(userId, code, name, country);
async function createUser(): Promise<number> {
const username = `u${++seq}`;
await rawExec(orm, 'INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)', [
username,
`${username}@example.test`,
'x',
'user',
]);
const rows = await rawQuery<{ id: number }>(orm, 'SELECT last_insert_rowid() as id');
return rows[0].id;
}
// The visited_regions reconciliation (#1119) is pinned at schema version 135.
// Migrations added afterwards are appended AFTER it (append-only), so it is no
// longer the last migration. Rewind to just before the reconciliation and
// re-run: the later migrations are idempotent, so only the reconciliation has
// any effect on the seeded rows here.
const RECONCILIATION_VERSION = 135;
function rerunLastMigration(db: Database.Database) {
db.prepare('UPDATE schema_version SET version = ?').run(RECONCILIATION_VERSION - 1);
runMigrations(db);
async function mark(userId: number, code: string, name: string, country = 'NO'): Promise<void> {
await rawExec(
orm,
'INSERT INTO visited_regions (user_id, region_code, region_name, country_code) VALUES (?, ?, ?, ?)',
[userId, code, name, country],
);
}
async function runReconciliation(): Promise<void> {
await migrateTo(orm, TARGET);
}
afterEach(async () => {
await orm?.close(true);
});
describe('Atlas region-code reconciliation migration', () => {
it('CROSSWALK-001: remaps a renamed-merge county via the curated crosswalk', () => {
const db = freshDb();
const { user } = createUser(db);
mark(db, user.id, 'NO-05', 'Oppland'); // merged into Innlandet, name changed
it('CROSSWALK-001: remaps a renamed-merge county via the curated crosswalk', async () => {
orm = await ormBeforeTarget();
const userId = await createUser();
await mark(userId, 'NO-05', 'Oppland'); // merged into Innlandet, name changed
rerunLastMigration(db);
await runReconciliation();
const rows = db.prepare('SELECT region_code, region_name FROM visited_regions WHERE user_id = ?').all(user.id);
const rows = await rawQuery(orm, 'SELECT region_code, region_name FROM visited_regions WHERE user_id = ?', [
userId,
]);
expect(rows).toEqual([{ region_code: 'NO-34', region_name: 'Innlandet' }]);
db.close();
});
it('CROSSWALK-002: merges two old counties that map to the same new region (no UNIQUE clash)', () => {
const db = freshDb();
const { user } = createUser(db);
mark(db, user.id, 'NO-04', 'Hedmark'); // → Innlandet
mark(db, user.id, 'NO-05', 'Oppland'); // → Innlandet
it('CROSSWALK-002: merges two old counties that map to the same new region (no UNIQUE clash)', async () => {
orm = await ormBeforeTarget();
const userId = await createUser();
await mark(userId, 'NO-04', 'Hedmark'); // → Innlandet
await mark(userId, 'NO-05', 'Oppland'); // → Innlandet
rerunLastMigration(db);
await runReconciliation();
const rows = db.prepare('SELECT region_code FROM visited_regions WHERE user_id = ?').all(user.id);
const rows = await rawQuery(orm, 'SELECT region_code FROM visited_regions WHERE user_id = ?', [userId]);
expect(rows).toEqual([{ region_code: 'NO-34' }]);
db.close();
});
it('CROSSWALK-003: leaves a still-valid code untouched', () => {
const db = freshDb();
const { user } = createUser(db);
mark(db, user.id, 'NO-03', 'Oslo'); // present in the new bundle
it('CROSSWALK-003: leaves a still-valid code untouched', async () => {
orm = await ormBeforeTarget();
const userId = await createUser();
await mark(userId, 'NO-03', 'Oslo'); // present in the new bundle
rerunLastMigration(db);
await runReconciliation();
const rows = db.prepare('SELECT region_code, region_name FROM visited_regions WHERE user_id = ?').all(user.id);
const rows = await rawQuery(orm, 'SELECT region_code, region_name FROM visited_regions WHERE user_id = ?', [
userId,
]);
expect(rows).toEqual([{ region_code: 'NO-03', region_name: 'Oslo' }]);
db.close();
});
it('CROSSWALK-004: re-codes a stale code whose region NAME still matches the bundle', () => {
it('CROSSWALK-004: re-codes a stale code whose region NAME still matches the bundle', async () => {
// Not in any crosswalk: a bogus code but a name ("Oslo") that the bundle still carries
// for NO → reconciled to the bundle's code for that name (NO-03) by the name-match path.
const db = freshDb();
const { user } = createUser(db);
mark(db, user.id, 'NO-99', 'Oslo');
orm = await ormBeforeTarget();
const userId = await createUser();
await mark(userId, 'NO-99', 'Oslo');
rerunLastMigration(db);
await runReconciliation();
const rows = db.prepare('SELECT region_code, region_name FROM visited_regions WHERE user_id = ?').all(user.id);
const rows = await rawQuery(orm, 'SELECT region_code, region_name FROM visited_regions WHERE user_id = ?', [
userId,
]);
expect(rows).toEqual([{ region_code: 'NO-03', region_name: 'Oslo' }]);
db.close();
});
it('CROSSWALK-005: leaves an unresolvable row as-is (no code, no name, no crosswalk match)', () => {
const db = freshDb();
const { user } = createUser(db);
mark(db, user.id, 'ZZ-99', 'Nowhere', 'ZZ');
it('CROSSWALK-005: leaves an unresolvable row as-is (no code, no name, no crosswalk match)', async () => {
orm = await ormBeforeTarget();
const userId = await createUser();
await mark(userId, 'ZZ-99', 'Nowhere', 'ZZ');
rerunLastMigration(db);
await runReconciliation();
const rows = db.prepare('SELECT region_code, region_name FROM visited_regions WHERE user_id = ?').all(user.id);
const rows = await rawQuery(orm, 'SELECT region_code, region_name FROM visited_regions WHERE user_id = ?', [
userId,
]);
expect(rows).toEqual([{ region_code: 'ZZ-99', region_name: 'Nowhere' }]);
db.close();
});
it('CROSSWALK-006: does not touch bucket_list or visited_countries (no region identifier there)', () => {
const db = freshDb();
const { user } = createUser(db);
db.prepare('INSERT INTO bucket_list (user_id, name, country_code) VALUES (?, ?, ?)').run(user.id, 'Oppland', 'NO');
db.prepare('INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(user.id, 'NO');
mark(db, user.id, 'NO-05', 'Oppland'); // ensure the migration actually runs its body
it('CROSSWALK-006: does not touch bucket_list or visited_countries (no region identifier there)', async () => {
orm = await ormBeforeTarget();
const userId = await createUser();
await rawExec(orm, 'INSERT INTO bucket_list (user_id, name, country_code) VALUES (?, ?, ?)', [
userId,
'Oppland',
'NO',
]);
await rawExec(orm, 'INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)', [userId, 'NO']);
await mark(userId, 'NO-05', 'Oppland'); // ensure the migration actually runs its body
rerunLastMigration(db);
await runReconciliation();
const bucket = db.prepare('SELECT name, country_code FROM bucket_list WHERE user_id = ?').all(user.id);
const bucket = await rawQuery(orm, 'SELECT name, country_code FROM bucket_list WHERE user_id = ?', [userId]);
expect(bucket).toEqual([{ name: 'Oppland', country_code: 'NO' }]); // free-text name untouched
const countries = db.prepare('SELECT country_code FROM visited_countries WHERE user_id = ?').all(user.id);
const countries = await rawQuery(orm, 'SELECT country_code FROM visited_countries WHERE user_id = ?', [userId]);
expect(countries).toEqual([{ country_code: 'NO' }]);
db.close();
});
});
+151 -52
View File
@@ -8,23 +8,27 @@
*
* The rules live in reseat-booked-nights.ts and are tested there directly on a fully
* migrated database: the columns the step reads (assignment_time, accommodation_id)
* and the vias table come from migrations, so seeding before runMigrations is not an
* option, and rewinding schema_version would tie this file to the tail of the
* append-only array.
* and the vias table come from migrations, so seeding before the schema is fully
* migrated is not an option.
*
* As the numbered migration (step 242, `Migration20200101040300`): ported off the
* legacy `createTables`+`runMigrations` builder onto the real `Migrator`, same shape
* as `tests/unit/db/trip-days-backfill-migration.test.ts` — migrate to the step
* immediately before it, seed rows with raw SQL, apply just that one migration, assert.
*/
import { describe, it, expect } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { reseatBookedNights } from '../../../src/db/reseat-booked-nights';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import Database from 'better-sqlite3';
import { describe, it, expect } from 'vitest';
function freshDb() {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
runMigrations(db);
db.prepare("INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'u', 'u@test.local', 'x', 'user')").run();
const db = createSnapshotTestDb();
db.prepare(
"INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'u', 'u@test.local', 'x', 'user')",
).run();
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run();
db.prepare("INSERT INTO days (id, trip_id, day_number, date) VALUES (1, 1, 1, '2026-10-02')").run();
return db;
@@ -33,33 +37,65 @@ function freshDb() {
let nextPlace = 1;
function place(db: Database.Database, name: string, time: string | null = null, located = true) {
const id = nextPlace++;
db.prepare('INSERT INTO places (id, trip_id, name, lat, lng, place_time) VALUES (?, 1, ?, ?, ?, ?)')
.run(id, name, located ? 50 + id / 100 : null, located ? 10 : null, time);
db.prepare('INSERT INTO places (id, trip_id, name, lat, lng, place_time) VALUES (?, 1, ?, ?, ?, ?)').run(
id,
name,
located ? 50 + id / 100 : null,
located ? 10 : null,
time,
);
return id;
}
let nextStop = 1;
function stop(db: Database.Database, placeId: number, orderIndex: number, time: string | null = null, accommodationId: number | null = null) {
function stop(
db: Database.Database,
placeId: number,
orderIndex: number,
time: string | null = null,
accommodationId: number | null = null,
) {
const id = nextStop++;
db.prepare('INSERT INTO day_assignments (id, day_id, place_id, order_index, assignment_time, accommodation_id) VALUES (?, 1, ?, ?, ?, ?)')
.run(id, placeId, orderIndex, time, accommodationId);
db.prepare(
'INSERT INTO day_assignments (id, day_id, place_id, order_index, assignment_time, accommodation_id) VALUES (?, 1, ?, ?, ?, ?)',
).run(id, placeId, orderIndex, time, accommodationId);
return id;
}
function night(db: Database.Database, placeId: number, checkIn: string | null) {
return Number(db.prepare('INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in) VALUES (1, ?, 1, 1, ?)')
.run(placeId, checkIn).lastInsertRowid);
return Number(
db
.prepare(
'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in) VALUES (1, ?, 1, 1, ?)',
)
.run(placeId, checkIn).lastInsertRowid,
);
}
const order = (db: Database.Database) =>
(db.prepare('SELECT place_id FROM day_assignments WHERE day_id = 1 ORDER BY order_index').all() as { place_id: number }[]).map((r) => r.place_id);
(
db.prepare('SELECT place_id FROM day_assignments WHERE day_id = 1 ORDER BY order_index').all() as {
place_id: number;
}[]
).map((r) => r.place_id);
const indexes = (db: Database.Database) =>
(db.prepare('SELECT order_index FROM day_assignments WHERE day_id = 1 ORDER BY order_index').all() as { order_index: number }[]).map((r) => r.order_index);
(
db.prepare('SELECT order_index FROM day_assignments WHERE day_id = 1 ORDER BY order_index').all() as {
order_index: number;
}[]
).map((r) => r.order_index);
const vias = (db: Database.Database) =>
db.prepare('SELECT id, after_order_index, sequence FROM roadtrip_vias WHERE day_id = 1 ORDER BY after_order_index, sequence, id').all() as
{ id: number; after_order_index: number; sequence: number }[];
db
.prepare(
'SELECT id, after_order_index, sequence FROM roadtrip_vias WHERE day_id = 1 ORDER BY after_order_index, sequence, id',
)
.all() as { id: number; after_order_index: number; sequence: number }[];
const via = (db: Database.Database, afterOrderIndex: number, sequence = 0) =>
Number(db.prepare('INSERT INTO roadtrip_vias (day_id, after_order_index, sequence, lat, lng) VALUES (1, ?, ?, 50, 10)').run(afterOrderIndex, sequence).lastInsertRowid);
Number(
db
.prepare('INSERT INTO roadtrip_vias (day_id, after_order_index, sequence, lat, lng) VALUES (1, ?, ?, 50, 10)')
.run(afterOrderIndex, sequence).lastInsertRowid,
);
describe('booked night reseat', () => {
it('RESEAT-001: a night appended behind stops without an hour leads the day', () => {
@@ -88,7 +124,12 @@ describe('booked night reseat', () => {
it('RESEAT-003: a stop with its own hour at or before the check-in stays ahead', () => {
const db = freshDb();
const [early, loose, late, hotel] = [place(db, 'Aral'), place(db, 'Hafen'), place(db, 'Museum'), place(db, 'Rostock')];
const [early, loose, late, hotel] = [
place(db, 'Aral'),
place(db, 'Hafen'),
place(db, 'Museum'),
place(db, 'Rostock'),
];
stop(db, early, 0, '08:00');
stop(db, loose, 1);
// The place's own hour counts as much as the visit's.
@@ -189,7 +230,7 @@ describe('booked night reseat', () => {
expect(reseatBookedNights(db)).toBe(0);
});
it('RESEAT-011: two nights with the same check-in, booked in that order, stay put with their roads', () => {
it('RESEAT-012: two nights with the same check-in, booked in that order, stay put with their roads', () => {
// Each used to count the other as "at or before" its check-in, so the step reported
// two moves it never made and the reanchor dropped the road between them.
const db = freshDb();
@@ -209,7 +250,7 @@ describe('booked night reseat', () => {
expect(reseatBookedNights(db)).toBe(0);
});
it('RESEAT-012: two nights with the same check-in settle by their booking, and only once', () => {
it('RESEAT-013: two nights with the same check-in settle by their booking, and only once', () => {
const db = freshDb();
const [fuel, first, second] = [place(db, 'Aral'), place(db, 'Adlon'), place(db, 'Mercure')];
const firstNight = night(db, first, '15:00');
@@ -226,7 +267,7 @@ describe('booked night reseat', () => {
expect(order(db)).toEqual([first, second, fuel]);
});
it('RESEAT-013: two nights without a check-in settle by their booking too', () => {
it('RESEAT-014: two nights without a check-in settle by their booking too', () => {
// Both used to want the front, and every pass swapped them.
const db = freshDb();
const [first, second] = [place(db, 'Adlon'), place(db, 'Mercure')];
@@ -242,7 +283,7 @@ describe('booked night reseat', () => {
expect(order(db)).toEqual([first, second]);
});
it('RESEAT-014: a night without a check-in leads one with a clock', () => {
it('RESEAT-015: a night without a check-in leads one with a clock', () => {
const db = freshDb();
const [fuel, clocked, open] = [place(db, 'Aral'), place(db, 'Adlon'), place(db, 'Mercure')];
stop(db, fuel, 0);
@@ -256,7 +297,7 @@ describe('booked night reseat', () => {
expect(order(db)).toEqual([open, clocked, fuel]);
});
it('RESEAT-015: an hour pinned on a night own stop is not what the other nights read it by', () => {
it('RESEAT-016: an hour pinned on a night own stop is not what the other nights read it by', () => {
// The stop carries eight, the booking carries three, and a night seats itself by
// its check-in. Read the pinned hour off the row instead and the two of them
// answer the same question differently: each counts the other as ahead, the step
@@ -276,7 +317,7 @@ describe('booked night reseat', () => {
expect(reseatBookedNights(db)).toBe(0);
});
it('RESEAT-016: a night without a check-in leads on its booking, whatever hour its place carries', () => {
it('RESEAT-017: a night without a check-in leads on its booking, whatever hour its place carries', () => {
const db = freshDb();
const [first, second] = [place(db, 'Adlon', '09:00'), place(db, 'Mercure')];
const firstNight = night(db, first, null);
@@ -302,24 +343,82 @@ describe('booked night reseat', () => {
expect(reseatBookedNights(db)).toBe(0);
expect(order(db)).toEqual(once);
});
it('RESEAT-009: the migration runs the step on a database being upgraded', () => {
// Seeded through the tables the base schema has, so the step fires on its normal
// pass: the backfill for older bookings appends the night last first, then the
// reseat brings it to the front.
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
db.prepare("INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'u', 'u@test.local', 'x', 'user')").run();
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run();
db.prepare("INSERT INTO days (id, trip_id, day_number, date) VALUES (1, 1, 1, '2026-10-02')").run();
db.prepare("INSERT INTO places (id, trip_id, name, lat, lng) VALUES (901, 1, 'Aral', 50.1, 10), (902, 1, 'Rostock', 50.2, 10)").run();
db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (1, 901, 0)').run();
db.prepare("INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in) VALUES (1, 902, 1, 1, '10:00')").run();
runMigrations(db);
expect(order(db)).toEqual([902, 901]);
});
});
describe('booked night reseat — as the numbered migration (step 242)', () => {
// Plan 4 Task 6 item 1: ruling 7 assumed `reseatBookedNights` was already
// invoked from a shipped migration; Task 5c found it wasn't (only the
// legacy `db/migrations.ts` array called it, as its last step, #242). This
// is that missing numbered migration, appended at the end of the chain.
const MIGRATION = 'Migration20200101040300_a_booked_night_finally_took_the_seat_a_new';
async function ormBefore(): Promise<MikroORM> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const idx = names.indexOf(MIGRATION);
expect(idx).toBeGreaterThan(0);
await migrateTo(orm, names[idx - 1]);
return orm;
}
it('RESEAT-009: an install upgrading through the chain gets an out-of-order night reseated', async () => {
const orm = await ormBefore();
try {
await rawExec(
orm,
"INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'u', 'u@test.local', 'x', 'user')",
);
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')");
await rawExec(orm, "INSERT INTO days (id, trip_id, day_number, date) VALUES (1, 1, 1, '2026-10-02')");
await rawExec(
orm,
"INSERT INTO places (id, trip_id, name, lat, lng) VALUES (901, 1, 'Aral', 50.1, 10), (902, 1, 'Rostock', 50.2, 10)",
);
await rawExec(
orm,
"INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in) VALUES (1, 902, 1, 1, '10:00')",
);
const accRow = await rawQuery<{ id: number }>(orm, 'SELECT last_insert_rowid() as id');
const accId = accRow[0]!.id;
// The stop step 229/230 (Migration20200101034900/035000) puts on a
// booked night's check-in day already ran by the time `ormBefore()`
// returns, so it must be seeded here rather than left for that earlier
// migration to create — same convention `stop()`/`night()` above use.
await rawExec(orm, 'INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (1, 901, 0)');
await rawExec(
orm,
'INSERT INTO day_assignments (day_id, place_id, order_index, accommodation_id) VALUES (1, 902, 1, ?)',
[accId],
);
await migrateTo(orm, MIGRATION);
const rows = await rawQuery<{ place_id: number }>(
orm,
'SELECT place_id FROM day_assignments WHERE day_id = 1 ORDER BY order_index',
);
expect(rows.map((r) => r.place_id)).toEqual([902, 901]);
} finally {
await orm.close(true);
}
}, 30000);
it('RESEAT-011: a fresh install with no booked nights out of order migrates through cleanly', async () => {
const orm = await ormBefore();
try {
await rawExec(
orm,
"INSERT INTO users (id, username, email, password_hash, role) VALUES (1, 'u', 'u@test.local', 'x', 'user')",
);
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')");
await rawExec(orm, "INSERT INTO days (id, trip_id, day_number, date) VALUES (1, 1, 1, '2026-10-02')");
await expect(migrateTo(orm, MIGRATION)).resolves.toBeUndefined();
const rows = await rawQuery(orm, 'SELECT * FROM day_assignments WHERE day_id = 1');
expect(rows).toHaveLength(0);
} finally {
await orm.close(true);
}
}, 30000);
});
@@ -9,119 +9,134 @@
* The second half covers the databases that ran the LIKE version before it was
* repaired — a fixed step never replays, so the damage is undone by a migration
* of its own at the end of the array.
*
* Ported off the legacy runner (Task 0 triage: PORT — both migrations) onto the
* real `Migration20200101030600_free_the_note_column_on_budget_items` (forward)
* and `Migration20200101031700_give_back_the_notes_the_ticketjson_step`
* (recovery): migrate to the step immediately before each, seed rows with raw
* SQL, apply just that one migration, assert.
*/
import { describe, it, expect } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
function makeDbWithNotes(): Database.Database {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA busy_timeout = 5000');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
// Minimal FK chain: user -> trip -> budget_items rows.
db.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')").run();
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run();
db.prepare(
'INSERT INTO budget_items (id, trip_id, name, note) VALUES (1, 1, ?, ?), (2, 1, ?, ?)',
).run('Dinner', 'TICKETJSON:{"items":[]}', 'Museum', 'ticketjson: buy at the door');
return db;
import { describe, it, expect } from 'vitest';
const FORWARD = 'Migration20200101030600_free_the_note_column_on_budget_items';
const RECOVERY = 'Migration20200101031700_give_back_the_notes_the_ticketjson_step';
async function ormBefore(target: string): Promise<{ orm: MikroORM; names: string[]; idx: number }> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const idx = names.indexOf(target);
expect(idx).toBeGreaterThan(0);
await migrateTo(orm, names[idx - 1]);
return { orm, names, idx };
}
describe('budget_items ticket_json migration', () => {
it('moves a real receipt into ticket_json and clears the note', () => {
const db = makeDbWithNotes();
try {
runMigrations(db);
const row = db.prepare('SELECT note, ticket_json FROM budget_items WHERE id = 1').get() as {
note: string | null;
ticket_json: string | null;
};
expect(row).toEqual({ note: null, ticket_json: '{"items":[]}' });
} finally {
db.close();
}
});
const readRow = (orm: MikroORM, id: number) =>
rawQuery<{ note: string | null; ticket_json: string | null }>(
orm,
'SELECT note, ticket_json FROM budget_items WHERE id = ?',
[id],
).then((r) => r[0]);
it('leaves a lowercase note alone (LIKE would have eaten it)', () => {
const db = makeDbWithNotes();
describe('budget_items ticket_json migration', () => {
async function ormWithNotes(): Promise<MikroORM> {
const { orm } = await ormBefore(FORWARD);
// Minimal FK chain: user -> trip -> budget_items rows.
await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')");
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')");
await rawExec(orm, 'INSERT INTO budget_items (id, trip_id, name, note) VALUES (1, 1, ?, ?), (2, 1, ?, ?)', [
'Dinner',
'TICKETJSON:{"items":[]}',
'Museum',
'ticketjson: buy at the door',
]);
return orm;
}
it('moves a real receipt into ticket_json and clears the note', async () => {
const orm = await ormWithNotes();
try {
runMigrations(db);
const row = db.prepare('SELECT note, ticket_json FROM budget_items WHERE id = 2').get() as {
note: string | null;
ticket_json: string | null;
};
expect(row).toEqual({ note: 'ticketjson: buy at the door', ticket_json: null });
await migrateTo(orm, FORWARD);
expect(await readRow(orm, 1)).toEqual({ note: null, ticket_json: '{"items":[]}' });
} finally {
db.close();
await orm.close(true);
}
});
}, 30000);
it('leaves a lowercase note alone (LIKE would have eaten it)', async () => {
const orm = await ormWithNotes();
try {
await migrateTo(orm, FORWARD);
expect(await readRow(orm, 2)).toEqual({ note: 'ticketjson: buy at the door', ticket_json: null });
} finally {
await orm.close(true);
}
}, 30000);
});
describe('recovering what the case-insensitive match destroyed', () => {
/**
* A database that already ran the buggy step: migrated to the tip, then wound
* back to just before the recovery step so it runs again — which is exactly
* what an existing install does on the next boot. The wind-back target is the
* recovery step's ABSOLUTE version (the array is append-only and
* index-addressed, so it never moves); anything appended after it replays too,
* which every later migration must tolerate anyway.
* A database that already ran the buggy step: migrate to just before the
* recovery migration, then seed rows in the SHAPE the buggy LIKE-based step
* would have left behind — exactly what an existing install carries into the
* recovery step on its next boot.
*/
function makeDamagedDb(): Database.Database {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA busy_timeout = 5000');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
runMigrations(db);
db.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')").run();
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run();
async function ormWithDamage(): Promise<MikroORM> {
const { orm } = await ormBefore(RECOVERY);
await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')");
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')");
// Row 1: what the LIKE match left behind for "ticketjson: buy at the door".
// Row 2: an actual receipt. Row 3: a receipt on a row whose owner has since
// written a note.
db.prepare('INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)')
.run(1, 1, 'Museum', null, ' buy at the door');
db.prepare('INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)')
.run(2, 1, 'Dinner', null, '{"items":[{"name":"Beer","price":"4.50","parts":[1]}]}');
db.prepare('INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)')
.run(3, 1, 'Taxi', 'split at the hotel', '{"items":[]}');
// 196 = the version just before the recovery step (migration #197).
db.prepare('UPDATE schema_version SET version = ?').run(196);
return db;
await rawExec(orm, 'INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)', [
1,
1,
'Museum',
null,
' buy at the door',
]);
await rawExec(orm, 'INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)', [
2,
1,
'Dinner',
null,
'{"items":[{"name":"Beer","price":"4.50","parts":[1]}]}',
]);
await rawExec(orm, 'INSERT INTO budget_items (id, trip_id, name, note, ticket_json) VALUES (?, ?, ?, ?, ?)', [
3,
1,
'Taxi',
'split at the hotel',
'{"items":[]}',
]);
return orm;
}
const read = (db: Database.Database, id: number) =>
db.prepare('SELECT note, ticket_json FROM budget_items WHERE id = ?').get(id) as {
note: string | null;
ticket_json: string | null;
};
it('puts a chopped note back where it came from', () => {
const db = makeDamagedDb();
it('puts a chopped note back where it came from', async () => {
const orm = await ormWithDamage();
try {
runMigrations(db);
expect(read(db, 1)).toEqual({ note: ' buy at the door', ticket_json: null });
await migrateTo(orm, RECOVERY);
expect(await readRow(orm, 1)).toEqual({ note: ' buy at the door', ticket_json: null });
} finally {
db.close();
await orm.close(true);
}
});
}, 30000);
it('leaves a genuine receipt alone', () => {
const db = makeDamagedDb();
it('leaves a genuine receipt alone', async () => {
const orm = await ormWithDamage();
try {
runMigrations(db);
expect(read(db, 2)).toEqual({
await migrateTo(orm, RECOVERY);
expect(await readRow(orm, 2)).toEqual({
note: null,
ticket_json: '{"items":[{"name":"Beer","price":"4.50","parts":[1]}]}',
});
// A note written since the damage means the row was not chopped, so it is
// not a candidate at all.
expect(read(db, 3)).toEqual({ note: 'split at the hotel', ticket_json: '{"items":[]}' });
expect(await readRow(orm, 3)).toEqual({ note: 'split at the hotel', ticket_json: '{"items":[]}' });
} finally {
db.close();
await orm.close(true);
}
});
}, 30000);
});
+218
View File
@@ -0,0 +1,218 @@
import { openDatabase } from '../../../src/db/connection';
import { Places } from '../../../src/db/entities/Places.entity';
import { Trips } from '../../../src/db/entities/Trips.entity';
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
import { TripsService } from '../../../src/nest/trips/trips.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import {
createDayAssignment,
createDayNote,
createPackingItem,
createPlace,
createTrip,
createUser,
} from '../../helpers/factories';
import { countRows } from '../../helpers/factories/rows';
import { readTripDays } from '../../helpers/factories/trips';
import { createTestOrm } from '../../helpers/test-orm';
import Database from 'better-sqlite3';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
// #2518: a container with a read-only root filesystem and no tmpfs on /tmp
// gives SQLite nowhere to put a temp file, so deleting a trip failed with
// SQLITE_IOERR_GETTEMPPATH. Every connection TREK opens keeps its temp storage
// in memory now, and these tests pin that down.
const SERVER_ROOT = path.resolve(__dirname, '../../..');
const MEMORY = 2; // PRAGMA temp_store: 0 default, 1 file, 2 memory
let tmpDir: string;
let schemaFile: string;
beforeAll(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-connection-'));
// Real schema, built once and copied per test: the delete below has to
// cascade through the same tables and foreign keys a live install has.
// The schema is the migrated snapshot the vitest global setup built, written
// out as a file so every copy is a real on-disk database.
schemaFile = path.join(tmpDir, 'schema.db');
const snapshot = createSnapshotTestDb();
fs.writeFileSync(schemaFile, snapshot.serialize());
snapshot.close();
const db = openDatabase(schemaFile);
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
db.close();
});
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
function freshCopy(name: string): string {
const file = path.join(tmpDir, `${name}.db`);
fs.copyFileSync(schemaFile, file);
return file;
}
describe('openDatabase', () => {
it('keeps temp storage in memory on a read-write handle', () => {
const db = openDatabase(freshCopy('rw'));
try {
expect(db.pragma('temp_store', { simple: true })).toBe(MEMORY);
} finally {
db.close();
}
});
it('keeps temp storage in memory on a read-only handle', () => {
const db = openDatabase(freshCopy('ro'), { readonly: true });
try {
expect(db.readonly).toBe(true);
expect(db.pragma('temp_store', { simple: true })).toBe(MEMORY);
} finally {
db.close();
}
});
it('is what the server opens its main database with', async () => {
const { db } = await import('../../../src/db/database');
expect(db.pragma('temp_store', { simple: true })).toBe(MEMORY);
});
});
// SQLite names every temp file etilqs_<random>. Linux unlinks the file the
// moment it is opened, so it only shows among the process's open descriptors;
// Windows keeps it in the temp directory until it is closed. macOS offers
// neither view, which is why the test below does not run there.
const canSeeTempFiles = process.platform === 'linux' || process.platform === 'win32';
function sqliteTempFiles(): string[] {
if (process.platform === 'linux') {
return fs
.readdirSync('/proc/self/fd')
.flatMap((fd) => {
try {
return [fs.readlinkSync(`/proc/self/fd/${fd}`)];
} catch {
return [];
}
})
.filter((target) => target.includes('etilqs_'));
}
return fs.readdirSync(os.tmpdir()).filter((name) => name.startsWith('etilqs_'));
}
/**
* Builds a trip the size of a real one on `db`, deletes it through
* TripsService.remove and reports which SQLite temp files were open while the
* delete ran. A trigger calls back into the test after the cascade, still
* inside the statement, which is when a spilled statement journal is open.
*/
async function deleteTripAndWatchTempFiles(db: Database.Database): Promise<{
tempFiles: string[];
tripLeft: number;
placesLeft: number;
}> {
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
const { user } = createUser(db);
const trip = createTrip(db, user.id, {
title: 'Niederlande Hoofddorp',
start_date: '2026-06-01',
end_date: '2026-06-14',
});
const t = await createTestOrm(db);
const days = await readTripDays(t, trip.id);
for (let i = 0; i < 25; i++) {
const place = createPlace(db, trip.id, { name: `Ort ${i}`, description: 'Grachten und Tulpen. '.repeat(10) });
createDayAssignment(db, days[i % days.length].id, place.id);
}
days.forEach((day) => createDayNote(db, day.id, trip.id));
for (let i = 0; i < 20; i++) createPackingItem(db, trip.id, { name: `Teil ${i}` });
const before = new Set(sqliteTempFiles());
const seen = new Set<string>();
db.function('trek_watch_temp_files', () => {
for (const file of sqliteTempFiles()) if (!before.has(file)) seen.add(file);
return null;
});
db.exec('CREATE TRIGGER trek_watch_trip_delete AFTER DELETE ON trips BEGIN SELECT trek_watch_temp_files(); END');
const none = undefined as never;
try {
const trips = new TripsService(none, none, none, none, none, none, none, none, new UnitOfWork(t.em), t.em, none);
await trips.remove(trip.id, user.id, 'user');
return {
tempFiles: [...seen],
tripLeft: await countRows(t, Trips, { id: trip.id }),
placesLeft: await countRows(t, Places, { trip: trip.id }),
};
} finally {
await t.close();
}
}
describe.runIf(canSeeTempFiles)('deleting a trip with content (#2518)', () => {
it('needs a temp file on a connection left at the SQLite default', async () => {
// The control: proves the watcher sees temp files, and that this delete is
// one SQLite cannot finish without one where no temp directory is writable.
const db = new Database(freshCopy('default'));
try {
const result = await deleteTripAndWatchTempFiles(db);
expect(result.tempFiles.length).toBeGreaterThan(0);
expect(result.tripLeft).toBe(0);
} finally {
db.close();
}
});
it('never touches a temp file on a connection TREK opens', async () => {
const db = openDatabase(freshCopy('trek'));
try {
const result = await deleteTripAndWatchTempFiles(db);
expect(result.tempFiles).toEqual([]);
expect(result.tripLeft).toBe(0);
expect(result.placesLeft).toBe(0);
} finally {
db.close();
}
});
});
describe('every SQLite connection goes through openDatabase', () => {
function sourceFiles(dir: string): string[] {
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) return sourceFiles(full);
return entry.name.endsWith('.ts') ? [full] : [];
});
}
it('leaves no other place in src/ constructing a better-sqlite3 handle', () => {
const offenders = sourceFiles(path.join(SERVER_ROOT, 'src')).filter((file) => {
if (file === path.join(SERVER_ROOT, 'src', 'db', 'connection.ts')) return false;
const source = fs.readFileSync(file, 'utf8');
// A value import (not `import type`) under whatever local name, then `new` on it.
const imported = /import\s+(?!type\b)(\w+)[^;]*?from\s+['"]better-sqlite3['"]/.exec(source)?.[1];
const required = /(\w+)\s*=\s*require\(\s*['"]better-sqlite3['"]\s*\)/.exec(source)?.[1];
return [imported, required].some((name) => name && new RegExp(`new\\s+${name}\\s*\\(`).test(source));
});
expect(offenders.map((file) => path.relative(SERVER_ROOT, file))).toEqual([]);
});
it('is mirrored by the standalone scripts that cannot import it', () => {
// reset-admin.js and the key rotation run in the container without src/,
// so they set the pragma themselves.
for (const script of ['reset-admin.js', 'scripts/migrate-encryption.ts']) {
const source = fs.readFileSync(path.join(SERVER_ROOT, script), 'utf8');
expect(source, script).toMatch(/PRAGMA temp_store = MEMORY|pragma\('temp_store = MEMORY'\)/);
}
});
});
@@ -0,0 +1,88 @@
/**
* db/database.ts opens the connection on first use, not at import.
*
* It used to call initDb() at module load, so importing anything that reached
* it opened the database: index.ts had to defer loading the app until a
* first-boot restore had put the backup's file in place. The connection is now
* opened by its first reader (the ORM's first connect inside buildApp(), driven
* by DatabaseLifecycle), and a connection closed on purpose for a restore stays
* closed until it is reopened.
*
* The cases share the module's one connection and run in order.
*/
import {
closeDb,
db,
getRawConnection,
openDb,
registerReinitializeHook,
reinitialize,
} from '../../../src/db/database';
import { describe, expect, it, vi } from 'vitest';
const opened = vi.hoisted(() => ({ count: 0 }));
vi.mock('../../../src/db/connection', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../../src/db/connection')>();
return {
...actual,
openDatabase: (...args: Parameters<typeof actual.openDatabase>) => {
opened.count++;
return actual.openDatabase(...args);
},
};
});
describe('db/database.ts connection lifecycle', () => {
it('DBOPEN-001: importing the module opens nothing', () => {
expect(opened.count).toBe(0);
});
it('DBOPEN-002: the first reader opens it once, with the pragmas applied', () => {
const handle = getRawConnection();
expect(getRawConnection()).toBe(handle);
expect(opened.count).toBe(1);
expect(handle.pragma('foreign_keys', { simple: true })).toBe(1);
expect(handle.pragma('busy_timeout', { simple: true })).toBe(5000);
// The Proxy reads through to the same handle.
expect(db.open).toBe(true);
});
it('DBOPEN-003: a connection closed on purpose stays closed instead of quietly reopening', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
try {
closeDb();
} finally {
log.mockRestore();
}
expect(() => getRawConnection()).toThrow('Database connection is not available (restore in progress?)');
// test-sql-allow: tests that the raw db proxy itself refuses a statement while the connection is closed; no ORM is involved.
expect(() => db.prepare('SELECT 1')).toThrow('Database connection is not available (restore in progress?)');
expect(opened.count).toBe(1);
});
it('DBOPEN-004: openDb() reopens it, and opening an open connection is a no-op', () => {
openDb();
openDb();
expect(opened.count).toBe(2);
expect(getRawConnection().open).toBe(true);
});
it('DBOPEN-005: reinitialize() swaps in a fresh handle and then runs the registered hook', async () => {
const before = getRawConnection();
const seen: boolean[] = [];
registerReinitializeHook(async () => {
seen.push(getRawConnection() !== before && getRawConnection().open);
});
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
try {
await reinitialize();
} finally {
log.mockRestore();
}
expect(before.open).toBe(false);
expect(seen).toEqual([true]);
expect(opened.count).toBe(3);
});
});
@@ -0,0 +1,274 @@
import {
castIntegerKysely,
concatKysely,
currentTimestampKysely,
nowPlusSecondsKysely,
startsWithIsoDateKysely,
substringKysely,
unixEpochToIsoKysely,
} from '../../../../src/db/dialect/kysely-functions';
import {
isKnownPlatform,
isPostgres,
isSqlite,
pgDateText,
pgTimestampText,
} from '../../../../src/db/dialect/platform';
import {
absDifference,
caseWhenEquals,
caseWhenNotNull,
castInteger,
coalesce,
coalesceOverride,
coalesceOverrideWhileSame,
coalesceParam,
collateNoCase,
columnIncrementedBy,
columnRef,
concat,
countAll,
countAllRef,
currentTimestamp,
dateAdd,
dateOf,
dayDistance,
foundAgainState,
lower,
lowerParam,
lowerTrim,
lowerTrimParam,
maxOf,
minOf,
nowDateOffset,
nowMinusDays,
nowMinusHours,
nowPlusSeconds,
startsWithIsoDate,
substring,
trim,
} from '../../../../src/db/dialect/sql-functions';
import { Platform } from '@mikro-orm/core';
import { BasePostgreSqlPlatform, SqlitePlatform } from '@mikro-orm/sql';
import {
DummyDriver,
expressionBuilder,
Kysely,
PostgresAdapter,
PostgresIntrospector,
PostgresQueryCompiler,
} from 'kysely';
import { describe, expect, it } from 'vitest';
/**
* The Postgres branches of the dialect layer, pinned as compiled text. Nothing
* here talks to a Postgres server: the CI `postgres-probe` job
* (`scripts/pg-probe.ts`) runs every one of these spellings against a real
* one and compares the values with what SQLite returns. This file holds the
* text, so a change to a spelling is a visible diff in review.
*/
const pg = new BasePostgreSqlPlatform();
const NOW = "(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')";
interface ProbeDB {
users: { id: number; username: string; display_name: string | null; created_at: number };
}
const db = new Kysely<ProbeDB>({
dialect: {
createAdapter: () => new PostgresAdapter(),
createDriver: () => new DummyDriver(),
createIntrospector: (kysely) => new PostgresIntrospector(kysely),
createQueryCompiler: () => new PostgresQueryCompiler(),
},
});
describe('dialect platform checks', () => {
it('SQLFPG-001: tells SQLite, Postgres and anything else apart', () => {
class FakePlatform extends Platform {}
expect(isSqlite(new SqlitePlatform())).toBe(true);
expect(isPostgres(new SqlitePlatform())).toBe(false);
expect(isPostgres(pg)).toBe(true);
expect(isSqlite(pg)).toBe(false);
expect(isKnownPlatform(pg)).toBe(true);
expect(isKnownPlatform(new SqlitePlatform())).toBe(true);
expect(isKnownPlatform(new FakePlatform())).toBe(false);
});
it("SQLFPG-002: renders a timestamp expression as SQLite's timestamp and date text", () => {
expect(pgTimestampText('x')).toBe("to_char(x, 'YYYY-MM-DD HH24:MI:SS')");
expect(pgDateText('x')).toBe("to_char(x, 'YYYY-MM-DD')");
});
});
describe('sql-functions (postgres)', () => {
it("SQLFPG-010: the clock helpers render SQLite's UTC text", () => {
expect(currentTimestamp(pg).sql).toBe(`to_char(${NOW}, 'YYYY-MM-DD HH24:MI:SS')`);
expect(nowMinusDays(pg, 30).sql).toBe(`to_char(${NOW} - INTERVAL '30 days', 'YYYY-MM-DD HH24:MI:SS')`);
expect(nowMinusHours(pg, 20).sql).toBe(`to_char(${NOW} - INTERVAL '20 hours', 'YYYY-MM-DD HH24:MI:SS')`);
expect(nowPlusSeconds(pg, 90).sql).toBe(`to_char(${NOW} + INTERVAL '90 seconds', 'YYYY-MM-DD HH24:MI:SS')`);
expect(nowDateOffset(pg, -400).sql).toBe(`to_char(${NOW} + INTERVAL '-400 days', 'YYYY-MM-DD')`);
expect(nowDateOffset(pg, 1).sql).toBe(`to_char(${NOW} + INTERVAL '1 days', 'YYYY-MM-DD')`);
});
it('SQLFPG-011: the column date helpers cast the stored text to a timestamp', () => {
expect(dateOf(pg, 'u.created_at').sql).toBe("to_char(CAST(u.created_at AS timestamp), 'YYYY-MM-DD')");
expect(dateAdd(pg, 'u.created_at', 10).sql).toBe(
"to_char(CAST(u.created_at AS timestamp) + INTERVAL '10 days', 'YYYY-MM-DD')",
);
expect(dateAdd(pg, 'u.created_at', -3).sql).toBe(
"to_char(CAST(u.created_at AS timestamp) + INTERVAL '-3 days', 'YYYY-MM-DD')",
);
const distance = dayDistance(pg, 'date', '2026-01-01');
expect(distance.sql).toBe('ABS(EXTRACT(EPOCH FROM (CAST(date AS timestamp) - CAST(? AS timestamp))) / 86400)');
expect(distance.params).toEqual(['2026-01-01']);
});
it('SQLFPG-012: the validation guards hold on Postgres as they do on SQLite', () => {
expect(() => dateOf(pg, 'u.created_at); DROP TABLE users; --')).toThrow(/not a column reference/);
expect(() => dateAdd(pg, 'u.created_at', 1.5)).toThrow(/integer day count/);
expect(() => nowMinusDays(pg, -1)).toThrow(/non-negative integer day count/);
expect(() => nowMinusHours(pg, 0.5)).toThrow(/non-negative integer hour count/);
expect(() => nowPlusSeconds(pg, -1)).toThrow(/non-negative integer second count/);
expect(() => nowDateOffset(pg, 0.5)).toThrow(/integer day count/);
expect(() => substring(pg, 'r.t', 0)).toThrow(/1-based integer start/);
expect(() => concat(pg, { column: 'a.b' })).toThrow(/at least two parts/);
});
it('SQLFPG-013: the spellings both engines read alike stay byte-identical', () => {
expect(columnRef(pg, 'u.max_uses').sql).toBe('u.max_uses');
expect(columnIncrementedBy(pg, 'u.used_count', -2).sql).toBe('u.used_count - 2');
expect(columnIncrementedBy(pg, 'u.used_count', 1).sql).toBe('u.used_count + 1');
expect(lower(pg, 'u.email').sql).toBe('LOWER(u.email)');
expect(lowerParam(pg, 'JOSÉ@x.com').params).toEqual(['JOSÉ@x.com']);
expect(lowerParam(pg, 'x').sql).toBe('LOWER(?)');
expect(trim(pg, 'p.name').sql).toBe('TRIM(p.name)');
expect(lowerTrim(pg, 'p.name').sql).toBe('LOWER(TRIM(p.name))');
expect(lowerTrimParam(pg, ' X ').sql).toBe('LOWER(TRIM(?))');
expect(coalesce(pg, 'a.x', 'a.y').sql).toBe('COALESCE(a.x, a.y)');
expect(coalesceParam(pg, 'a.x', 3).sql).toBe('COALESCE(a.x, ?)');
expect(coalesceOverride(pg, 'v', 'a.x').sql).toBe('COALESCE(?, a.x)');
expect(absDifference(pg, 'p.lat', 1.5).sql).toBe('ABS(p.lat - ?)');
expect(countAll(pg, 'total').sql).toBe('COUNT(*) as total');
expect(minOf(pg, 'p.at', 'first').sql).toBe('MIN(p.at) as first');
expect(maxOf(pg, 'p.at', 'last').sql).toBe('MAX(p.at) as last');
expect(countAllRef(pg).sql).toBe('COUNT(*)');
expect(caseWhenEquals(pg, 'u.id', 1, 'owner', 'member').sql).toBe('CASE WHEN u.id = ? THEN ? ELSE ? END');
expect(caseWhenNotNull(pg, 'p.tour_id', 'p.route').sql).toBe('CASE WHEN p.tour_id IS NOT NULL THEN p.route END');
expect(foundAgainState(pg, 's.state', 's.file_id').sql).toBe(
"CASE WHEN s.state = 'remote_missing' AND s.file_id IS NOT NULL THEN 'synced' ELSE s.state END",
);
expect(substring(pg, 'r.t', 1, 10).sql).toBe('substr(r.t, 1, 10)');
expect(substring(pg, 'r.t', 12).sql).toBe('substr(r.t, 12)');
const joined = concat(pg, { column: 'd.date' }, { value: 'T' }, { column: 'a.check_in' });
expect(joined.sql).toBe('d.date || ? || a.check_in');
expect(joined.params).toEqual(['T']);
});
it('SQLFPG-014: GLOB, the integer cast, NOCASE and the null-safe IS get their Postgres forms', () => {
expect(startsWithIsoDate(pg, 'r.reservation_time').sql).toBe(
"CAST(r.reservation_time AS text) ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}'",
);
expect(castInteger(pg, 'vr.accommodation_id').sql).toBe(
'CAST(trunc(CAST(vr.accommodation_id AS numeric)) AS integer)',
);
expect(collateNoCase(pg, 'name').sql).toBe('name COLLATE "nocase"');
const whileSame = coalesceOverrideWhileSame(pg, null, 'u.tls', 'u.url', 'https://a');
expect(whileSame.sql).toBe(
'CASE WHEN u.url IS NOT DISTINCT FROM ? THEN COALESCE(?, u.tls) ELSE COALESCE(?, 0) END',
);
expect(whileSame.params).toEqual(['https://a', null, null]);
});
});
describe('kysely-functions (postgres)', () => {
it('SQLFPG-020: startsWithIsoDateKysely is an anchored regular expression over the text', () => {
const compiled = db
.selectFrom('users')
.select((eb) => startsWithIsoDateKysely(pg, eb, 'username').as('v'))
.compile();
expect(compiled.sql).toBe('select cast("username" as text) ~ $1 as "v" from "users"');
expect(compiled.parameters).toEqual(['^[0-9]{4}-[0-9]{2}-[0-9]{2}']);
});
it('SQLFPG-021: substringKysely and concatKysely compose, a bound part cast to text', () => {
const compiled = db
.selectFrom('users')
.select((eb) =>
concatKysely(
pg,
eb,
{ column: 'username' },
{ value: 'T' },
{ expression: substringKysely(pg, eb, 'username', 12) },
).as('v'),
)
.compile();
expect(compiled.sql).toBe('select "username" || cast($1 as text) || substr("username", $2) as "v" from "users"');
expect(compiled.parameters).toEqual(['T', 12]);
const sliced = db
.selectFrom('users')
.select((eb) => substringKysely(pg, eb, 'username', 1, 10).as('v'))
.compile();
expect(sliced.sql).toBe('select substr("username", $1, $2) as "v" from "users"');
expect(sliced.parameters).toEqual([1, 10]);
});
it('SQLFPG-022: castIntegerKysely truncates through numeric', () => {
const compiled = db
.selectFrom('users')
.select((eb) => castIntegerKysely(pg, eb, 'display_name').as('v'))
.compile();
expect(compiled.sql).toBe('select cast(trunc(cast("display_name" as numeric)) as integer) as "v" from "users"');
expect(compiled.parameters).toEqual([]);
});
it('SQLFPG-023: unixEpochToIsoKysely renders UTC ISO text from epoch milliseconds', () => {
const compiled = db
.selectFrom('users')
.select((eb) => unixEpochToIsoKysely(pg, eb, 'created_at').as('v'))
.compile();
expect(compiled.sql).toBe(
'select to_char(timezone(cast($1 as text), to_timestamp("created_at" / $2)), cast($3 as text)) as "v" from "users"',
);
expect(compiled.parameters).toEqual(['UTC', 1000, 'YYYY-MM-DD"T"HH24:MI:SS"Z"']);
});
it("SQLFPG-024: the Kysely clock helpers render SQLite's timestamp text", () => {
const later = db
.selectFrom('users')
.select((eb) => nowPlusSecondsKysely(pg, eb, 45).as('v'))
.compile();
expect(later.sql).toBe(`select to_char(${NOW} + make_interval(secs => 45), cast($1 as text)) as "v" from "users"`);
expect(later.parameters).toEqual(['YYYY-MM-DD HH24:MI:SS']);
const now = db
.selectFrom('users')
.select(() => currentTimestampKysely(pg).as('v'))
.compile();
expect(now.sql).toBe(`select to_char(${NOW}, 'YYYY-MM-DD HH24:MI:SS') as "v" from "users"`);
expect(now.parameters).toEqual([]);
});
it('SQLFPG-025: an unknown platform still fails closed in the Kysely twins', () => {
class FakePlatform extends Platform {}
const foreign = new FakePlatform();
const eb = expressionBuilder<ProbeDB, 'users'>();
expect(() => startsWithIsoDateKysely(foreign, eb, 'username')).toThrow(
/no implementation for platform FakePlatform/,
);
expect(() => substringKysely(foreign, eb, 'username', 1)).toThrow(/no implementation for platform FakePlatform/);
expect(() => concatKysely(foreign, eb, { value: 'a' }, { value: 'b' })).toThrow(
/no implementation for platform FakePlatform/,
);
expect(() => castIntegerKysely(foreign, eb, 'display_name')).toThrow(/no implementation for platform FakePlatform/);
expect(() => unixEpochToIsoKysely(foreign, eb, 'created_at')).toThrow(
/no implementation for platform FakePlatform/,
);
expect(() => nowPlusSecondsKysely(foreign, eb, 1)).toThrow(/no implementation for platform FakePlatform/);
expect(() => currentTimestampKysely(foreign)).toThrow(/no implementation for platform FakePlatform/);
});
});
File diff suppressed because it is too large Load Diff
+36 -6
View File
@@ -1,13 +1,13 @@
import { resolveDurability } from '../../../src/app-config/parsers';
import { applyDurabilityPragmas } from '../../../src/db/durability';
import Database from 'better-sqlite3';
import { execFileSync } from 'child_process';
import fs from 'fs';
import os from 'os';
import path from 'path';
import Database from 'better-sqlite3';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { resolveDurability } from '../../../src/app-config/parsers';
import { applyDurabilityPragmas } from '../../../src/db/durability';
// journal_mode is written into the database file header, so it outlives the
// connection that set it. Anything asserting a mode here therefore reopens the
// file: that is the property operators on SMB/NFS volumes actually depend on.
@@ -184,6 +184,7 @@ describe('standalone scripts honour the same configuration', () => {
password_hash TEXT,
role TEXT,
must_change_password INTEGER DEFAULT 0,
password_version INTEGER NOT NULL DEFAULT 0,
mfa_secret TEXT,
maps_api_key TEXT,
openweather_api_key TEXT,
@@ -219,13 +220,42 @@ describe('standalone scripts honour the same configuration', () => {
expect(readModes(dbPath)).toEqual({ journalMode: 'DELETE', synchronous: 2 });
const db = new Database(dbPath);
// test-sql-allow: the file reset-admin.js just rewrote has no ORM bound to it; it is read as the script left it.
const admin = db.prepare('SELECT role FROM users WHERE email = ?').get('locked-out@example.com') as
| { role: string }
| undefined;
{ role: string } | undefined;
db.close();
expect(admin?.role).toBe('admin');
}, 60000);
it('reset-admin.js finds the account whatever the case, and ends its sessions', () => {
seedWalDb();
const seed = new Database(dbPath);
// test-sql-allow: the database file reset-admin.js works on has no ORM bound to it.
seed
.prepare(
"INSERT INTO users (username, email, password_hash, role, password_version) VALUES ('boss', 'Boss@Example.com', 'x', 'user', 3)",
)
.run();
seed.close();
execFileSync(process.execPath, ['reset-admin.js'], {
cwd: SERVER_ROOT,
env: {
...process.env,
TREK_DB_FILE: dbPath,
RESET_ADMIN_EMAIL: 'boss@example.com',
RESET_ADMIN_PASSWORD: 'Recovery12345!',
},
stdio: 'pipe',
});
const db = new Database(dbPath);
// test-sql-allow: the file reset-admin.js just rewrote has no ORM bound to it; it is read as the script left it.
const rows = db.prepare('SELECT email, role, password_version, must_change_password FROM users').all();
db.close();
expect(rows).toEqual([{ email: 'Boss@Example.com', role: 'admin', password_version: 4, must_change_password: 1 }]);
}, 60000);
it('migrate-encryption.ts no longer forces the database back to WAL', () => {
seedWalDb();
@@ -0,0 +1,105 @@
/**
* `Migration20200101042400_one_account_per_email_whatever_its_case` and the
* boot step that finishes its job (`src/db/email-case-index.ts`): one account
* per email address whatever its case, without ever failing the boot of an
* install that already holds such a pair.
*/
import { ensureEmailCaseIndex } from '../../../src/db/email-case-index';
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import { afterEach, describe, expect, it, vi } from 'vitest';
const TARGET = 'Migration20200101042400_one_account_per_email_whatever_its_case';
let orm: MikroORM | null = null;
async function ormBeforeTarget(): Promise<MikroORM> {
orm = await createMigrationOrm();
const names = await pendingNames(orm);
const idx = names.indexOf(TARGET);
expect(idx).toBeGreaterThan(0);
await migrateTo(orm, names[idx - 1]);
return orm;
}
async function addUser(db: MikroORM, id: number, email: string): Promise<void> {
await rawExec(db, 'INSERT INTO users (id, username, email, password_hash) VALUES (?, ?, ?, ?)', [
id,
`user${id}`,
email,
'x',
]);
}
const hasIndex = async (db: MikroORM) =>
(await rawQuery(db, `SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'idx_users_email_lower'`))
.length === 1;
const pendingFlag = async (db: MikroORM) =>
rawQuery<{ value: string }>(db, `SELECT value FROM app_settings WHERE key = 'email_case_index_pending'`);
afterEach(async () => {
vi.restoreAllMocks();
await orm?.close(true);
orm = null;
});
describe('one account per email address, whatever its case', () => {
it('EMAILCI-001: without case duplicates the index is created and refuses a second account in other case', async () => {
const db = await ormBeforeTarget();
await addUser(db, 1, 'Anna@Example.test');
await addUser(db, 2, 'bob@example.test');
await migrateTo(db, TARGET);
expect(await hasIndex(db)).toBe(true);
expect(await pendingFlag(db)).toEqual([]);
await expect(addUser(db, 3, 'anna@example.TEST')).rejects.toThrow(/UNIQUE constraint failed/);
// Mixed case itself is fine: only a second account for the same address is not.
expect(await rawQuery(db, 'SELECT email FROM users ORDER BY id')).toEqual([
{ email: 'Anna@Example.test' },
{ email: 'bob@example.test' },
]);
}, 30000);
it('EMAILCI-002: with case duplicates the boot goes on, names the accounts, and the index waits', async () => {
const db = await ormBeforeTarget();
await addUser(db, 1, 'anna@example.test');
await addUser(db, 2, 'Anna@Example.test');
await addUser(db, 3, 'carl@example.test');
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
await expect(migrateTo(db, TARGET)).resolves.toBeUndefined();
expect(await hasIndex(db)).toBe(false);
expect(await pendingFlag(db)).toEqual([{ value: 'true' }]);
const message = String(warn.mock.calls[0]?.[0]);
expect(message).toContain('1 email address(es) belong to more than one account');
expect(message).toContain('user ids 1, 2');
expect(message).not.toContain('anna@example.test');
}, 30000);
it('EMAILCI-003: the boot step repeats the warning while the pair remains, then creates the index once it is gone', async () => {
const db = await ormBeforeTarget();
await addUser(db, 1, 'anna@example.test');
await addUser(db, 2, 'ANNA@example.test');
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.spyOn(console, 'log').mockImplementation(() => {});
await migrateTo(db, TARGET);
warn.mockClear();
await ensureEmailCaseIndex(db.em.getConnection());
expect(await hasIndex(db)).toBe(false);
expect(String(warn.mock.calls[0]?.[0])).toContain('still belong to more than one account');
await rawExec(db, `UPDATE users SET email = 'anna.work@example.test' WHERE id = 2`);
await ensureEmailCaseIndex(db.em.getConnection());
expect(await hasIndex(db)).toBe(true);
expect(await pendingFlag(db)).toEqual([]);
// Nothing owed any more: a later boot does nothing.
warn.mockClear();
await ensureEmailCaseIndex(db.em.getConnection());
expect(warn).not.toHaveBeenCalled();
}, 30000);
});
@@ -0,0 +1,94 @@
/**
* `Migration20200101042800_an_email_the_account_typed_in_itself`: every
* existing account starts out trusted (0), except one whose address provably
* moved away from the one it registered with while no admin ever edited its
* email. A broken audit row is skipped, and a second run changes nothing.
*/
import { Migration20200101042800_an_email_the_account_typed_in_itself } from '../../../src/db/migrations/Migration20200101042800_an_email_the_account_typed_in_itself';
import {
createMigrationOrm,
migrateTo,
pendingNames,
rawExec,
rawQuery,
runMigrationDirect,
} from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import { describe, expect, it } from 'vitest';
const TARGET = 'Migration20200101042800_an_email_the_account_typed_in_itself';
async function ormBeforeTarget(): Promise<MikroORM> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const idx = names.indexOf(TARGET);
expect(idx).toBeGreaterThan(0);
await migrateTo(orm, names[idx - 1]);
return orm;
}
async function seed(orm: MikroORM): Promise<void> {
// 1 registered and kept the address; 2 registered and changed it itself;
// 3 registered, changed it, and an admin set an email later; 4 was made by
// an admin (no register row); 5 registered in another case only; 6 has a
// broken register row.
await rawExec(
orm,
`INSERT INTO users (id, username, email, password_hash) VALUES
(1, 'kept', 'kept@test', 'x'),
(2, 'moved', 'colleague@test', 'x'),
(3, 'fixed', 'fixed-by-admin@test', 'x'),
(4, 'made', 'made@test', 'x'),
(5, 'cased', 'Cased@Test', 'x'),
(6, 'broken', 'broken-now@test', 'x')`,
);
await rawExec(
orm,
`INSERT INTO audit_log (user_id, action, resource, details) VALUES
(1, 'user.register', NULL, '{"username":"kept","email":"kept@test","role":"user"}'),
(2, 'user.register', NULL, '{"username":"moved","email":"moved@test","role":"user"}'),
(3, 'user.register', NULL, '{"username":"fixed","email":"fixed@test","role":"user"}'),
(4, 'admin.user_update', '3', '{"targetUser":"fixed-self@test","fields":["username","email","role"]}'),
(4, 'admin.user_update', '2', '{"targetUser":"colleague@test","fields":["role"]}'),
(5, 'user.register', NULL, '{"username":"cased","email":"cased@test","role":"user"}'),
(6, 'user.register', NULL, 'not json')`,
);
}
const flags = (orm: MikroORM) =>
rawQuery<{ id: number; email_self_asserted: number }>(orm, 'SELECT id, email_self_asserted FROM users ORDER BY id');
const EXPECTED = [
{ id: 1, email_self_asserted: 0 },
{ id: 2, email_self_asserted: 1 },
{ id: 3, email_self_asserted: 0 },
{ id: 4, email_self_asserted: 0 },
{ id: 5, email_self_asserted: 0 },
{ id: 6, email_self_asserted: 0 },
];
describe('email self-asserted migration', () => {
it('EMAILSELF-MIG-001: only an address the account provably changed itself is marked', async () => {
const orm = await ormBeforeTarget();
try {
await seed(orm);
await migrateTo(orm, TARGET);
expect(await flags(orm)).toEqual(EXPECTED);
} finally {
await orm.close(true);
}
}, 30000);
it('EMAILSELF-MIG-002: running it again changes nothing', async () => {
const orm = await ormBeforeTarget();
try {
await seed(orm);
await migrateTo(orm, TARGET);
await runMigrationDirect(orm, Migration20200101042800_an_email_the_account_typed_in_itself);
expect(await flags(orm)).toEqual(EXPECTED);
} finally {
await orm.close(true);
}
}, 30000);
});
+140
View File
@@ -0,0 +1,140 @@
import { ALL_ENTITIES } from '../../../src/db/entities';
import { TrekRepository } from '../../../src/db/repositories/_shared/trek-repository';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { EntitySchema, type EntityRepository } from '@mikro-orm/core';
import fs from 'node:fs';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
const ENTITIES_DIR = path.join(__dirname, '../../../src/db/entities');
const REPOSITORIES_DIR = path.join(__dirname, '../../../src/db/repositories');
describe('ALL_ENTITIES', () => {
it('ENT-001: lists exactly one schema per *.entity.ts file', () => {
const files = fs
.readdirSync(ENTITIES_DIR)
.filter((f) => f.endsWith('.entity.ts'))
.sort();
const names = ALL_ENTITIES.map((s) => s.name).sort();
const expected = files.map((f) => f.replace(/\.entity\.ts$/, '')).sort();
expect(names).toEqual(expected);
});
it('ENT-002: every entry is an EntitySchema with a class', () => {
for (const schema of ALL_ENTITIES) {
expect(schema).toBeInstanceOf(EntitySchema);
expect(typeof schema.meta.class).toBe('function');
}
});
/**
* Plan 2 Task 3: every one of the 135 entities the migrated schema
* describes (120 rewritten + the 5 document-sync tables added this task,
* + push_subscriptions and google_api_usage from legacy steps 245 and 254,
* + tour_types, tours and tour_waypoints from the Tours migration,
* + scheduler_leases from the cron lease migration
* + user_sessions, the session rows behind revocable session tokens
* + ferrata_tiles, the stored via ferrata grid cells
* + paddle_regions, paddle_features and tour_obstacle_reviews, the paddle obstacle data and decisions
* + trip_journal_links and trip_journal_link_members, the journal a trip shows and who it is open to
* + paddle_water_graphs and paddle_region_requests, a region's water network and the regions that wait for an admin
* + tour_station_visits, how far a city walk got on one of its days
* + tour_change_steps, the changes to a tour saved from a confirmed proposal
* + tour_activities, the recorded tracks assigned to a tour
* + tour_activity_exclusions, the tours a user left out of their own activity sums
* + collection_tours, the whole tours a collection keeps
* + tour_packing_links, the packing list or category a tour points at
* + tour_source_hints, what the wanderer watch found about a snapshot's source
* + journey_recorded_days, the recorded route a journey keeps per day
* + journey_entry_stays, the recorded stays a journey entry was taken over from
* + journey_recording_prep, how far preparing a journey's recorded days got for each person
* + tour_drafts, the Tours planner's unsaved draft per user and trip
* + ai_connections, the AI assistant's connections to a language model
* + assistant_threads, assistant_messages, assistant_tool_calls and assistant_usage,
* the trip assistant's conversations, the changes it proposed and what it used
* + trek_photo_signals, what a photo's pixels say, for picking photos for a book
* + journey_book_revisions, the books a whole-book design replaced, for its undo
* + trip_member_removals, who another member took off a trip, so its invite link refuses them
* + assistant_attachments, the files attached in the trip chat, kept with their conversation)
* is registered, and no two share a class name (a silent duplicate would
* shadow one of them in `orm.getMetadata()`, exactly the kind of drift
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
* which de-duplicates by class name).
*/
it('ENT-003: exactly 162 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(162);
const names = ALL_ENTITIES.map((s) => s.meta.className);
expect(new Set(names).size).toBe(names.length);
});
/**
* Task 1's review flagged this binding as otherwise unpinned: dropping an
* entity's `repository: () => XRepository` mutation stayed green in every
* gate up to here (task-1-review.md, minor 1). `em.getRepository(X)` must
* return an instance of the exact repository class
* `src/db/repositories/<Name>.repository.ts` exports, for every entity —
* the 120 the generator wrote a stub for this task plus the 5 pre-existing,
* hand-written ones (`Days`, `DayNotes`, `Trips`, `BudgetCategoryOrder`,
* `VacayUserSettings`) it left untouched.
*/
describe('ENT-004: em.getRepository(X) is an instance of X.repository.ts', () => {
let t: TestOrm;
const testDb = createSnapshotTestDb();
beforeAll(async () => {
t = await createTestOrm(testDb);
});
afterAll(async () => {
await t.close();
testDb.close();
});
it('every entity resolves to its own repository class', async () => {
const failures: string[] = [];
for (const schema of ALL_ENTITIES) {
const className = schema.meta.className;
const repoFile = path.join(REPOSITORIES_DIR, `${className}.repository.ts`);
if (!fs.existsSync(repoFile)) {
failures.push(`${className}: no src/db/repositories/${className}.repository.ts file`);
continue;
}
const mod: Record<string, unknown> = await import(
/* @vite-ignore */ `../../../src/db/repositories/${className}.repository`
);
const RepoClass = mod[`${className}Repository`];
if (typeof RepoClass !== 'function') {
failures.push(`${className}: repository module has no exported ${className}Repository class`);
continue;
}
const repo: EntityRepository<object> = t.em.getRepository(schema.class as new () => object);
if (!(repo instanceof (RepoClass as abstract new (...args: never[]) => unknown))) {
failures.push(`${className}: em.getRepository() did not return a ${className}Repository instance`);
}
// Task 7 review, H2 carry-list item 1: the `extends EntityRepository`
// ratchet made self-enforcing — every bound repository must also be
// a TrekRepository (validateRequestContext + the disableIdentityMap
// read default), not just an instance of its own named class.
if (!(repo instanceof TrekRepository)) {
failures.push(`${className}: em.getRepository() did not return a TrekRepository instance`);
}
}
expect(failures).toEqual([]);
});
// Task 7 review, H2: a source-scan companion to the instanceof check
// above — belt and suspenders against a repository that extends
// TrekRepository indirectly (or not through this loop's import path).
it('SCAN-001: exactly one repository file extends EntityRepository directly — the base class itself', () => {
const files = fs.readdirSync(REPOSITORIES_DIR).filter((f) => f.endsWith('.repository.ts'));
const hits: string[] = [];
for (const file of files) {
const content = fs.readFileSync(path.join(REPOSITORIES_DIR, file), 'utf-8');
if (/\bextends\s+EntityRepository\b/.test(content)) hits.push(file);
}
expect(hits).toEqual([]); // the base class lives in _shared/, not matched by *.repository.ts
});
});
});
@@ -0,0 +1,178 @@
import { AppSettings } from '../../../../src/db/entities/AppSettings.entity';
import { BudgetCategoryOrder } from '../../../../src/db/entities/BudgetCategoryOrder.entity';
import { VacayUserSettings } from '../../../../src/db/entities/VacayUserSettings.entity';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createTrip, createUser } from '../../../helpers/factories';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { defineEntity, p, wrap, type Ref } from '@mikro-orm/core';
import { MikroORM } from '@mikro-orm/sqlite';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
/**
* Plan 2 (ORM entity rewrite) Task 1 — the primary-relation spike.
*
* `BudgetCategoryOrder`/`VacayUserSettings` are the first entities to carry
* the Phase 0 shape (hidden relation + `persist(false)` scalar twin,
* snake_case scalars) on a relation that is (part of) the PRIMARY KEY. Before
* Task 3's bulk rewrite relies on that shape for the ~15 other
* primary-relation entities, this file pins that it actually works: a hidden
* PRIMARY relation still hydrates its twin, `findOne`/`find` accept the
* composite/one-to-one PK condition, and `toObject()` keeps emitting the twin
* column and omitting the relation — exactly as it does for a non-PRIMARY
* hidden relation (`DayNotes.day`/`DayNotes.trip`).
*
* Also pins the `.name()` vs `.joinColumn()` semantics Task 0 found on
* `SchoolHolidayRegions.country` (target PK is not `id`): `.name()` is an
* alias for `.fieldName()`, which a *relation* ignores when computing its FK
* column (the naming strategy still derives it from the property name + the
* target's PK) — only `.joinColumn()` overrides the column MikroORM emits.
*/
const testDb = createSnapshotTestDb();
let t: TestOrm;
beforeAll(async () => {
t = await createTestOrm(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('primary-relation entities (Task 1 spike)', () => {
it('SPIKE-001: BudgetCategoryOrder — composite PK (trip relation + category text) round-trips create, findOne, find and toObject', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const created = t.em.create(BudgetCategoryOrder, { trip: trip.id, category: 'Food', sort_order: 2 });
await t.em.persist(created).flush();
t.em.clear();
const rawInsert = testDb
// test-sql-allow: the raw row is the oracle the ORM's toObject() is held against.
.prepare('SELECT * FROM budget_category_order WHERE trip_id = ? AND category = ?')
.get(trip.id, 'Food');
expect(rawInsert).toEqual({ trip_id: trip.id, category: 'Food', sort_order: 2 });
const found = await t.repo(BudgetCategoryOrder).findOne({ trip: trip.id, category: 'Food' });
expect(found).not.toBeNull();
t.em.clear();
const [hydrated] = await t.repo(BudgetCategoryOrder).find({ trip: trip.id });
expect(hydrated.trip_id).toBe(trip.id);
expect(hydrated.trip.isInitialized()).toBe(false);
expect(wrap(hydrated).toObject()).toStrictEqual(rawInsert);
});
it('SPIKE-002: VacayUserSettings — one-to-one PRIMARY relation (user) round-trips the same four facts', async () => {
const { user } = createUser(testDb);
const created = t.em.create(VacayUserSettings, {
user: user.id,
year_type: 'fiscal',
year_start_month: 4,
year_start_day: 1,
hire_date: '2020-01-01',
});
await t.em.persist(created).flush();
t.em.clear();
// test-sql-allow: the raw row is the oracle the ORM's toObject() is held against.
const rawInsert = testDb.prepare('SELECT * FROM vacay_user_settings WHERE user_id = ?').get(user.id);
expect(rawInsert).toEqual({
user_id: user.id,
year_type: 'fiscal',
year_start_month: 4,
year_start_day: 1,
hire_date: '2020-01-01',
});
const found = await t.repo(VacayUserSettings).findOne({ user: user.id });
expect(found).not.toBeNull();
t.em.clear();
const [hydrated] = await t.repo(VacayUserSettings).find({ user: user.id });
expect(hydrated.user_id).toBe(user.id);
expect(hydrated.user?.isInitialized()).toBe(false);
expect(wrap(hydrated).toObject()).toStrictEqual(rawInsert);
});
it("SPIKE-003: .name() sets the property's fieldName, but a relation's FK column is only overridden by .joinColumn()", async () => {
// A throwaway target whose PK is NOT `id` — the exact shape that made
// SchoolHolidayRegions.country_code (Task 0) a real bug: the naming
// strategy composes the FK column from the property name plus the
// target's PK name (`<prop>_<targetPk>`), independent of `.name()`.
class SpikeTarget {
code!: string;
}
const SpikeTargetSchema = defineEntity({
class: SpikeTarget,
properties: {
code: p.text().primary(),
},
});
class SpikeSourceName {
id?: number;
country!: Ref<SpikeTarget>;
}
const SpikeSourceNameSchema = defineEntity({
class: SpikeSourceName,
properties: {
id: p.integer().primary().autoincrement(),
country: () => p.manyToOne(SpikeTarget).ref().name('country'),
},
});
class SpikeSourceJoinColumn {
id?: number;
country!: Ref<SpikeTarget>;
}
const SpikeSourceJoinColumnSchema = defineEntity({
class: SpikeSourceJoinColumn,
properties: {
id: p.integer().primary().autoincrement(),
country: () => p.manyToOne(SpikeTarget).ref().joinColumn('country'),
},
});
const spikeOrm = await MikroORM.init({
entities: [SpikeTargetSchema, SpikeSourceNameSchema, SpikeSourceJoinColumnSchema],
dbName: ':memory:',
discovery: { warnWhenNoEntities: false },
});
try {
const namedMeta = spikeOrm.getMetadata().get(SpikeSourceName);
const joinColumnMeta = spikeOrm.getMetadata().get(SpikeSourceJoinColumn);
// `.name('country')` is an alias for `.fieldName('country')` (per
// node_modules/@mikro-orm/core/entity/defineEntity.d.ts) — it does not
// reach the FK-column computation for a relation, so the naming
// strategy still derives `<prop>_<targetPk>`.
expect(namedMeta.properties.country.fieldNames).toEqual(['country_code']);
// `.joinColumn('country')` overrides the computed FK column directly.
expect(joinColumnMeta.properties.country.fieldNames).toEqual(['country']);
} finally {
await spikeOrm.close(true);
}
});
it('SPIKE-004: a nullable text PRIMARY KEY (AppSettings.key) round-trips create → findOne unchanged, and toObject keeps the key', async () => {
const created = t.em.create(AppSettings, { key: 'spike_setting', value: 'on' });
await t.em.persist(created).flush();
t.em.clear();
const found = await t.repo(AppSettings).findOne({ key: 'spike_setting' });
expect(found?.key).toBe('spike_setting');
expect(found?.value).toBe('on');
// test-sql-allow: the raw row is the oracle the ORM's toObject() is held against.
const raw = testDb.prepare('SELECT * FROM app_settings WHERE key = ?').get('spike_setting');
expect(wrap(found).toObject()).toStrictEqual(raw);
});
});
@@ -0,0 +1,229 @@
import { ALL_ENTITIES } from '../../../src/db/entities';
import { BudgetItems } from '../../../src/db/entities/BudgetItems.entity';
import { IdempotencyKeys } from '../../../src/db/entities/IdempotencyKeys.entity';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createUser, createTrip } from '../../helpers/factories';
import { resetTestDb } from '../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { EntityRepositoryType, ReferenceKind } from '@mikro-orm/core';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
/**
* Permanent guard for `task-4-review-shape.md` Important finding 1: a
* numeric class-field initialiser must never render `NaN` (see
* `scripts/generate-entities.ts`'s `RULE1d_fixNaNNumericDefaults` and
* `tests/unit/db/generate-entities.test.ts`'s `RULE1D-*` fixture tests for
* the mechanism). This file pins the OUTPUT of that rule against the real,
* committed entities (every one of the 133, not a sample) and reproduces
* the reviewer's own insert probe so a future regenerate/hand-edit that
* reintroduces a `NaN` initialiser fails loudly here, not silently at a
* caller's first `em.create()`.
*/
/** NOT NULL scalars with neither a column default nor a class-field initialiser (legitimate: the caller must supply them). */
// 424 + push_subscriptions (legacy step 245): id, user_id, endpoint, p256dh, auth, vapid_public_key.
// + Tours: tour_types label_key, icon, color; tours.tour_type; tour_waypoints id, place_id, lat, lng, role, sequence.
// + scheduler_leases: name, owner, expires_at (the scheduler always writes all three).
// + user_sessions: id, user_id, expires_at.
// + ferrata_tiles: tile_key, payload, fetched_at (a fetched tile always carries all three).
// + paddle_regions: id, name; paddle_features: id, region_id, osm_ref, kind, geometry, tags, tag_hash and
// its bounding box (a feature is only ever written whole, from one read of its region).
// + tour_obstacle_reviews: place_id, obstacle_key, decision, both fingerprints, obstacle_snapshot, decided_at.
// + trip_journal_links: id, trip_id, journey_id, created_at; trip_journal_link_members: link_id, user_id,
// added_at (a link and its members are always written whole).
// + paddle_water_graphs: file, rev, bytes, built_at, stats and its bounding box (a network is only ever written
// whole, from one build of its region).
// + paddle_region_requests: region_id, name, reason (a request is only ever filed whole).
// + tour_station_visits: assignment_id, station_key, status (a visit is only ever written whole, by the
// day plan that checks a city walk's station off).
// + tour_change_steps: id, place_id, proposal_id, base_revision, revision, changes, before_state (a step is
// only ever written whole, by the save of a confirmed change).
// + tour_activities: id, place_id, track_place_id (an assignment always names its tour and its recording).
// + tour_activity_exclusions: id, user_id, place_id (an exclusion always names its user and its tour).
// + collection_tours: id, collection_id, name, waypoints, tour_type, origin, source_trip_title, source_tour_name
// (a kept tour is only ever written whole, from the tour it was saved from).
// + tour_source_hints: user_id (a hint is only ever written for the user whose snapshot it is about).
// + journey_recorded_days: id, journey_id, local_date, source_kind, utc_offset_minutes, window_from,
// window_to, segments, point_count, content_hash, fetched_at (a kept day is only ever written whole).
// + journey_entry_stays: id, journey_id, entry_id, source_visit_id, name, started_at, ended_at (a stay is
// only ever written whole, by the take-over of its day).
// + journey_recording_prep: id, journey_id, user_id (a status row always names its journey and its person).
// + tour_drafts: id, trip_id, user_id, payload (a draft is only ever written whole, by the planner that keeps it).
// + ai_connections: id, scope, kind, model; assistant_threads: id, user_id, trip_id, title;
// assistant_messages: id, thread_id, role, parts; assistant_tool_calls: id, thread_id, message_id,
// provider_call_id, tool_name, args, preview; assistant_usage: user_id, day, paid_by (each row is
// written whole by the assistant, which always knows all of them).
// + trek_photo_signals: id, photo_id, algo (a measurement always names its photo and how it was made).
// - assistant_threads.trip_id: a thread may be about a journey instead, so it is nullable now.
// + journey_book_revisions: id, journey_id, version, document (a revision is only ever written whole).
// + trip_member_removals: id, trip_id, user_id (a removal note always names its trip and its person).
// + assistant_attachments: id, thread_id, user_id, trip_id, name, mime, size, sha256, storage_key, text_status
// (an attached file is only ever written whole, by the turn it was attached in).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 585;
describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {
it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 133 entities', () => {
const failures: string[] = [];
for (const schema of ALL_ENTITIES) {
const Ctor = schema.class as new () => Record<string, unknown>;
const instance = new Ctor();
for (const [key, value] of Object.entries(instance)) {
if (typeof value === 'number' && Number.isNaN(value)) {
failures.push(`${schema.meta.className}.${key}`);
}
}
}
expect(failures).toEqual([]);
});
/**
* Report-only (per the brief): a NOT NULL scalar property with no
* `default`/`defaultRaw` at all legitimately has no class-field
* initialiser — the caller is expected to supply it (`name!: string`, for
* example). That is normal and not a bug, so this never asserts the list
* is empty; it exists so a reviewer can see the shape at a glance and so a
* suspicious spike in the count (e.g. every numeric property in an entity
* suddenly losing its default) shows up in test output without failing
* the suite on a false positive.
*/
it('CLASSFIELD-002: exactly the known NOT NULL, no-default scalar properties have no class-field initialiser', async () => {
const testDb = createSnapshotTestDb();
try {
const t = await createTestOrm(testDb);
try {
const report: string[] = [];
for (const schema of ALL_ENTITIES) {
const meta = t.orm.getMetadata().get(schema.class);
const Ctor = schema.class as new () => Record<string, unknown>;
const instance = new Ctor();
for (const prop of meta.props) {
if (prop.kind !== undefined && prop.kind !== ReferenceKind.SCALAR) continue;
if (prop.nullable) continue;
if (prop.default !== undefined || prop.defaultRaw !== undefined) continue;
if (!(prop.name in instance)) continue;
if (instance[prop.name] === undefined) {
report.push(`${meta.className}.${prop.name}`);
}
}
}
// Informational only — see the doc comment above. `console.info` (not
// a `console.log` vitest might buffer away) so it survives a run.
// A ratchet, not a census: the failure mode this file guards (a regeneration
// handing every numeric property a bogus default) makes this number DROP;
// a new NOT NULL column without a default bumps it by one — update the
// constant with the migration that adds the column.
expect(report.length, report.join(', ')).toBe(KNOWN_UNINITIALISED_NOT_NULL_SCALARS);
} finally {
await t.close();
}
} finally {
testDb.close();
}
});
});
/**
* Plan 3b pre-task (`scripts/generate-entities.ts`'s `RULE10_repositoryTypeMarker`
* / `injectRepositoryTypeMarker`): `[EntityRepositoryType]?: XRepository;` is
* a type-only class member, never routed through `meta.addProperty` — this
* pins that it stays that way, so CLASSFIELD-002's census above (and its
* pinned count, 423) can never silently start counting it.
*/
describe('[EntityRepositoryType] marker is excluded from the class-field census (RULE10)', () => {
it('CLASSFIELD-003: every entity has an own [EntityRepositoryType] symbol property that is never a real metadata property and never leaks as a string key', async () => {
const testDb = createSnapshotTestDb();
try {
const t = await createTestOrm(testDb);
try {
const failures: string[] = [];
for (const schema of ALL_ENTITIES) {
const meta = t.orm.getMetadata().get(schema.class);
const Ctor = schema.class as new () => Record<string, unknown>;
const instance = new Ctor();
if (!Object.getOwnPropertySymbols(instance).includes(EntityRepositoryType)) {
failures.push(`${meta.className}: missing an own [EntityRepositoryType] symbol property`);
}
if (Object.keys(instance).includes('EntityRepositoryType')) {
failures.push(`${meta.className}: [EntityRepositoryType] leaked as a string-keyed own property`);
}
if (meta.props.some((prop) => prop.name === 'EntityRepositoryType')) {
failures.push(`${meta.className}: [EntityRepositoryType] was registered as a real metadata property`);
}
}
expect(failures).toEqual([]);
} finally {
await t.close();
}
} finally {
testDb.close();
}
});
});
/**
* The reviewer's exact repro (`task-4-review-shape.md`, Important finding
* 1): before the fix, `em.create(BudgetItems, …)` and
* `em.create(IdempotencyKeys, …)` both threw `SqliteError: no such column:
* NaN` at `flush()` — Kysely rendered the `NaN` class-field initialiser as a
* bare SQL identifier. Neither probe names the broken columns
* (`persons`/`days`/`place_id`/`reservation_id` on `BudgetItems`,
* `created_at` on `IdempotencyKeys`) — the whole point is that a caller
* should never have to.
*/
describe("insert probes (task-4-review-shape.md, the reviewer's exact repro)", () => {
const testDb = createSnapshotTestDb();
let t: TestOrm;
beforeAll(async () => {
t = await createTestOrm(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
it('INSERT-PROBE-001: em.create(BudgetItems, { trip, name, total_price, exchange_rate }) + flush succeeds', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const created = t.em.create(BudgetItems, {
trip: trip.id,
name: 'Dinner',
total_price: 4200,
exchange_rate: 1,
});
await t.em.persist(created).flush();
// test-sql-allow: reads the stored columns behind the ORM to prove what its own insert wrote.
const row = testDb
.prepare('SELECT persons, days, place_id, reservation_id FROM budget_items WHERE id = ?')
.get(created.id);
expect(row).toEqual({ persons: null, days: null, place_id: null, reservation_id: null });
});
it('INSERT-PROBE-002: em.create(IdempotencyKeys, { key, user, method, path, status_code, response_body }) + flush succeeds', async () => {
const { user } = createUser(testDb);
const created = t.em.create(IdempotencyKeys, {
key: 'idem-key-probe-1',
user: user.id,
method: 'POST',
path: '/api/trips',
status_code: 201,
response_body: '{}',
});
await t.em.persist(created).flush();
const row = testDb
// test-sql-allow: reads the stored column behind the ORM to prove the database default filled it.
.prepare('SELECT created_at FROM idempotency_keys WHERE key = ? AND user_id = ? AND method = ? AND path = ?')
.get('idem-key-probe-1', user.id, 'POST', '/api/trips') as { created_at: number };
// The DB's own defaultRaw (strftime('%s','now')) filled it in — never NaN, never null.
expect(row.created_at).toEqual(expect.any(Number));
expect(Number.isNaN(row.created_at)).toBe(false);
});
});
@@ -0,0 +1,645 @@
import { ALL_ENTITIES } from '../../../src/db/entities';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { ReferenceKind, type EntityMetadata, type EntityProperty } from '@mikro-orm/core';
import type Database from 'better-sqlite3';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
/**
* The blocking entry gate for Plan 2 (the entity rewrite, see
* docs/superpowers/plans/2026-09-22-orm-phase2-entity-rewrite.md, Task 0):
* every entity's MikroORM metadata must describe exactly the schema the
* migrations built, column for column. `orm.schema.getUpdateSchemaSQL()` was
* tried first and rejected — on SQLite it produces 883 statements of pure
* naming-convention noise (index names, `__temp_alter` table rebuilds), which
* the MikroORM docs (7.2, schema comparator) say not to use as a test. This
* compares `PRAGMA table_info(<table>)` against `getMetadata().getAll()`
* column by column instead, which is precise: on today's entities it reports
* exactly 24 tables with issues, of which only 4 are real drifts (fixed
* alongside this test) and the rest is type-name spelling MikroORM's SQLite
* platform leaves abstract (`double`, `json` — see `normaliseColumnType`
* below) plus 5 tables Plan 2 Task 3 still has to add entities for.
*/
const testDb = createSnapshotTestDb();
let t: TestOrm;
beforeAll(async () => {
t = await createTestOrm(testDb);
});
afterAll(async () => {
await t.close();
testDb.close();
});
/**
* Tables with no entity yet. Plan 2 Task 0 named the 5 document-sync tables
* here; Task 3 added their entities (`DocumentProviders`,
* `DocumentProviderFields`, `DocumentConnections`, `TripDocumentLinks`,
* `DocumentSyncItems`), so the set is empty. PARITY-007's "every db table
* has an entity" assertion reports anything listed here as expected missing
* instead of failing on it; PARITY-008 fails the moment a listed table
* actually gains an entity, so a future author has to empty this set again
* rather than silently leaving a stale entry behind.
*/
const ENTITIES_STILL_MISSING: string[] = [];
interface DbColumn {
cid: number;
name: string;
type: string;
notnull: number;
dflt_value: string | null;
pk: number;
}
/** Tables SQLite itself creates (`sqlite_sequence` for AUTOINCREMENT bookkeeping) — never a domain table, never an entity. */
function dbTables(db: Database.Database): Set<string> {
const rows = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`).all() as {
name: string;
}[];
return new Set(rows.map((r) => r.name));
}
function tableInfo(db: Database.Database, table: string): DbColumn[] {
return db.prepare(`PRAGMA table_info("${table}")`).all() as DbColumn[];
}
/**
* Spells a column type the way both sides can agree on. MikroORM's SQLite
* platform normalises most abstract type names to their real SQLite storage
* class (`boolean` -> `integer`, `string` -> `text`) but leaves a few as the
* ORM's own abstract name because it never overrides the base `Platform`
* declaration for them (`getDoubleDeclarationSQL`, `getJsonDeclarationSQL` —
* verified against `node_modules/@mikro-orm/sql/dialects/sqlite/SqlitePlatform.js`
* and `node_modules/@mikro-orm/core/platforms/Platform.js`), so those need an
* explicit map. `varchar` only ever appears on the db side (the hand-written
* migration SQL for `migrations.name`); the entity's `p.string()` already
* reports `text` on SQLite.
*/
function normaliseColumnType(type: string): string {
const stripped = type
.trim()
.toLowerCase()
.replace(/\(\d+(,\s*\d+)?\)/, '');
if (stripped === 'double') return 'real';
if (stripped === 'varchar' || stripped === 'json') return 'text';
return stripped;
}
/**
* `datetime` and `text` are accepted as equal in either direction: a
* `DbTimestampType` column reports `datetime` (SQLite's
* `getDateTimeTypeDeclarationSQL`), and every migration that created a
* timestamp column also declared it `DATETIME`, so in practice both sides
* already say `datetime` — but a future entity or migration is free to spell
* a timestamp column `TEXT` (SQLite gives it the same storage class either
* way), and that must not be a drift.
*/
function columnTypesEqual(entityType: string, dbType: string): boolean {
const a = normaliseColumnType(entityType);
const b = normaliseColumnType(dbType);
if (a === b) return true;
const datetimeTextPair = new Set([a, b]);
return datetimeTextPair.has('datetime') && datetimeTextPair.has('text');
}
/** A property this test holds against the migrated schema: it owns a real, persisted column. */
function isPersistedColumnProperty(prop: EntityProperty): boolean {
if (prop.persist === false) return false;
if (prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY) return false;
if (prop.kind === ReferenceKind.EMBEDDED) return false;
if (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner) return false;
return true;
}
/**
* MikroORM flags a declared `pivotEntity` (`PackingItemContributors`, which
* carries `status`/`created_at` payload columns) with `pivotTable: true` just
* like the synthetic pivots it invents for a bare `manyToMany`. Only the
* synthetic ones have no class of their own — a declared pivot entity is a
* real table-backed entity and is held to the schema like any other.
*/
const DECLARED_ENTITY_CLASSES = new Set(ALL_ENTITIES.map((schema) => schema.meta.className));
function isSyntheticPivot(meta: EntityMetadata): boolean {
return Boolean(meta.pivotTable) && !DECLARED_ENTITY_CLASSES.has(meta.className);
}
/** Entity metadata this test holds against a table: skips MikroORM's own synthetic/non-table entries. */
function isTableBackedMeta(meta: EntityMetadata): boolean {
return !isSyntheticPivot(meta) && !meta.embeddable && !meta.virtual && !meta.abstract;
}
function tableBackedMetas(): EntityMetadata[] {
return [...t.orm.getMetadata().getAll().values()].filter(isTableBackedMeta);
}
/** Table names of the SYNTHETIC pivots MikroORM registers for a bare `manyToMany` + `pivotTable` — covered by the owning relation, never their own entity. */
function pivotTableNames(): Set<string> {
const names = new Set<string>();
for (const meta of t.orm.getMetadata().getAll().values()) {
if (isSyntheticPivot(meta)) names.add(meta.tableName);
}
return names;
}
describe('entity ↔ migrated-schema parity', () => {
it('PARITY-001: every entity maps to a table that exists', () => {
const tables = dbTables(testDb);
const failures: string[] = [];
for (const meta of tableBackedMetas()) {
if (!tables.has(meta.tableName)) {
failures.push(`${meta.className}: entity table "${meta.tableName}" does not exist in the migrated schema`);
}
}
expect(failures).toEqual([]);
});
it('PARITY-002: every persisted property has a matching column', () => {
const failures: string[] = [];
for (const meta of tableBackedMetas()) {
const table = meta.tableName;
if (!dbTables(testDb).has(table)) continue; // reported by PARITY-001
const columns = new Map(tableInfo(testDb, table).map((c) => [c.name, c]));
for (const prop of meta.props) {
if (!isPersistedColumnProperty(prop)) continue;
for (const fieldName of prop.fieldNames) {
if (!columns.has(fieldName)) {
failures.push(`${table}.${fieldName}: entity property "${meta.className}.${prop.name}" has no db column`);
}
}
}
}
expect(failures).toEqual([]);
});
it('PARITY-003: column types agree after normalisation', () => {
const failures: string[] = [];
for (const meta of tableBackedMetas()) {
const table = meta.tableName;
const columns = new Map(tableInfo(testDb, table).map((c) => [c.name, c]));
for (const prop of meta.props) {
if (!isPersistedColumnProperty(prop)) continue;
for (const [i, fieldName] of prop.fieldNames.entries()) {
const column = columns.get(fieldName);
if (!column) continue; // reported by PARITY-002
const entityType = prop.columnTypes[i];
if (!entityType) {
failures.push(
`${table}.${fieldName}: entity property "${meta.className}.${prop.name}" declares no column type`,
);
continue;
}
if (!columnTypesEqual(entityType, column.type)) {
failures.push(
`${table}.${fieldName}: entity ${normaliseColumnType(entityType)} vs db ${normaliseColumnType(column.type)}`,
);
}
}
}
}
expect(failures).toEqual([]);
});
it('PARITY-004: nullability agrees on every non-primary-key column', () => {
const failures: string[] = [];
for (const meta of tableBackedMetas()) {
const table = meta.tableName;
const columns = new Map(tableInfo(testDb, table).map((c) => [c.name, c]));
for (const prop of meta.props) {
if (!isPersistedColumnProperty(prop)) continue;
for (const fieldName of prop.fieldNames) {
const column = columns.get(fieldName);
if (!column) continue; // reported by PARITY-002
if (column.pk) continue; // SQLite's INTEGER PRIMARY KEY reports notnull=0 regardless; text PKs are legitimately nullable (no `NOT NULL` in the migration) — confirmed in inputs.md.
const entityNullable = Boolean(prop.nullable);
const dbNullable = column.notnull === 0;
if (entityNullable !== dbNullable) {
failures.push(`${table}.${fieldName}: nullable entity=${entityNullable} vs db=${dbNullable}`);
}
}
}
}
expect(failures).toEqual([]);
});
/**
* Column defaults, now a real gate: Task 2/3's generator rewrite removed
* every `onCreate(() => new Date())` hook in favour of `DbTimestampType` +
* `defaultRaw('CURRENT_TIMESTAMP')` (Plan 2's D2), which is what unblocked
* this test — Task 0 left it `it.skip`'d and report-only with 93 of 994
* columns "mismatching," all of them that same onCreate-vs-CURRENT_TIMESTAMP
* gap or a quoting spelling difference carrying no schema information.
* `normaliseDefault` below folds those spellings together (quote style, a
* wrapping paren SQLite adds around a non-literal `DEFAULT (expr)` that
* `PRAGMA table_info` sometimes strips and the generator's own
* `prop.defaultRaw` sometimes doesn't, `datetime('now')`/`CURRENT_TIMESTAMP`,
* and `p.boolean()`'s literal `true`/`false` class-field default against
* SQLite's `0`/`1` — the only boolean column in the schema today,
* `addons.enabled`). Only real schema drift survives that.
*/
it('PARITY-005: column defaults agree after normalisation', () => {
const failures: string[] = [];
for (const meta of tableBackedMetas()) {
const table = meta.tableName;
const columns = new Map(tableInfo(testDb, table).map((c) => [c.name, c]));
for (const prop of meta.props) {
if (!isPersistedColumnProperty(prop)) continue;
for (const fieldName of prop.fieldNames) {
const column = columns.get(fieldName);
if (!column) continue;
const entityDefault = normaliseDefault(
prop.defaultRaw ?? (prop.default != null ? String(prop.default) : null),
);
const dbDefault = normaliseDefault(column.dflt_value);
if (entityDefault !== dbDefault) {
failures.push(
`${table}.${fieldName}: default entity=${entityDefault ?? 'null'} vs db=${dbDefault ?? 'null'}`,
);
}
}
}
}
expect(failures).toEqual([]);
});
it('PARITY-006: every db column is covered by a persisted property', () => {
const failures: string[] = [];
for (const meta of tableBackedMetas()) {
const table = meta.tableName;
if (!dbTables(testDb).has(table)) continue; // reported by PARITY-001
const covered = new Set<string>();
for (const prop of meta.props) {
if (!isPersistedColumnProperty(prop)) continue;
for (const fieldName of prop.fieldNames) covered.add(fieldName);
}
for (const column of tableInfo(testDb, table)) {
if (!covered.has(column.name)) {
failures.push(`${table}.${column.name}: db column has no entity property (${meta.className})`);
}
}
}
expect(failures).toEqual([]);
});
it('PARITY-007: every db table has an entity, except mikro_orm_migrations, declared pivots and ENTITIES_STILL_MISSING', () => {
const tables = dbTables(testDb);
const entityTables = new Set(tableBackedMetas().map((m) => m.tableName));
const pivots = pivotTableNames();
const stillMissing = new Set(ENTITIES_STILL_MISSING);
const failures: string[] = [];
for (const table of tables) {
if (table === 'mikro_orm_migrations') continue;
if (entityTables.has(table)) continue;
if (pivots.has(table)) continue;
if (stillMissing.has(table)) continue; // reported separately below
failures.push(`${table}: db table has no entity and is not in ENTITIES_STILL_MISSING`);
}
expect(failures).toEqual([]);
});
it('PARITY-008: ENTITIES_STILL_MISSING stays accurate — none of them may already have an entity', () => {
const entityTables = new Set(tableBackedMetas().map((m) => m.tableName));
const failures: string[] = [];
const tables = dbTables(testDb);
for (const table of ENTITIES_STILL_MISSING) {
if (!tables.has(table)) failures.push(`${table}: listed in ENTITIES_STILL_MISSING but is not a db table`);
if (entityTables.has(table)) {
failures.push(`${table}: has an entity now — remove it from ENTITIES_STILL_MISSING`);
}
}
expect(failures).toEqual([]);
});
/**
* FK targets, against `PRAGMA foreign_key_list` — the plan's second,
* allow-listed check (Task 0, Step 3), the REFERENCED-COLUMN half. Task 0
* left the whole check (referenced column + deleteRule + index names)
* `it.skip`'d and report-only. This half is un-skipped as of Plan 3b
* interlude A: `RULE11_referencedColumns` (`scripts/generate-entities.ts`)
* closed the one gap that made it fail — `OauthTokens.client`/
* `OauthConsents.client` targeted `oauth_clients.id` (the generator's
* default assumption for an owning to-one relation) instead of the schema's
* real FK target, the UNIQUE natural key `oauth_clients.client_id`
* (`Migration20200101012500_oauth_2.ts`). Every other owning relation in
* the schema already agreed with `PRAGMA foreign_key_list`'s `to` column,
* `school_holiday_regions.country -> school_holiday_countries.code`
* included (`code` IS that table's primary key, so the generator's default
* assumption was already correct there — unchanged by Rule 11, confirmed
* by this same test). The deleteRule half is un-skipped by Plan 4 Task 7 —
* see `PARITY-009b` immediately below.
*
* `school_holiday_regions.country` re-verified one more time at Task 7's
* own HEAD, directly against the live migration DDL (not the entity, not
* an earlier report): `Migration20200101033600_create_school_holiday_countries.ts`
* declares `country TEXT NOT NULL REFERENCES school_holiday_countries(code)`
* — a real, DB-enforced FK, confirmed here by this very test passing for
* that column too (`SchoolHolidayRegions.countryRef`'s `.joinColumn('country')`,
* Plan 2 Task 3). 3f's inventory was right; there is no schema gap here to
* document for the user.
*/
it('PARITY-009: FK referenced columns agree with PRAGMA foreign_key_list', () => {
const failures: string[] = [];
for (const meta of tableBackedMetas()) {
const table = meta.tableName;
const fkRows = testDb.prepare(`PRAGMA foreign_key_list("${table}")`).all() as {
from: string;
table: string;
to: string;
}[];
const fkByColumn = new Map(fkRows.map((row) => [row.from, row]));
for (const prop of meta.props) {
const isOwningToOne =
prop.kind === ReferenceKind.MANY_TO_ONE || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner);
if (!isOwningToOne) continue;
const fieldName = prop.fieldNames[0];
const fk = fkByColumn.get(fieldName);
if (!fk) {
failures.push(`${table}.${fieldName}: entity relation has no matching db foreign key`);
continue;
}
const entityReferencedColumn = prop.referencedColumnNames?.[0];
if (entityReferencedColumn !== fk.to) {
failures.push(
`${table}.${fieldName}: referencedColumn entity=${String(entityReferencedColumn)} vs db=${fk.to}`,
);
}
}
}
expect(failures).toEqual([]);
});
/**
* The deleteRule half of the same check (Task 0, Step 3), un-skipped by
* Plan 4 Task 7. Task 0 found deleteRule disagreeing on 11 of 180 owning
* relations; Task 3's rewrite fixed one of those eleven as a side effect
* (`school_holiday_regions.country`) and re-measured the other 124
* rewritten/added entities at 10. Task 7 re-measured again at its own HEAD
* (program rule: re-measure, never assume a prior count) and found the
* same 10, unchanged: `trip_members.invited_by`, `oauth_tokens.
* parent_token_id`, `budget_settlements.created_by_user_id`, `budget_items.
* paid_by_user_id` (a nullable relation whose column has no `ON DELETE` at
* all in its migration — SQLite ⇒ `no action` — while the entity's bare
* `.nullable()` defaults to MikroORM's own `'set null'`), `roadtrip_day_
* tracks.day_id` (nullable AND the table's sole PK — migration says
* `ON DELETE CASCADE`, entity defaulted to `'set null'` the same way),
* `journey_contributors.user_id` (a composite-PK member whose migration
* has no `ON DELETE`, while the entity's FK-as-PK shape defaults to
* `'cascade'`), and `reservation_travelers.reservation_id`/`.user_id` +
* `assignment_participants.assignment_id`/`.user_id` (migrations say
* `ON DELETE CASCADE`; the entity had no default at all for that shape,
* landing on `'no action'`).
*
* All 10 are the ENTITY side never having matched its migration's physical
* FK to begin with (never a migration defect — program rule: migrations
* are append-only, and every one of the 10 migrations above is verified
* correct against its own table's real production behavior). Fixed via a
* new generator rule, `RULE13_pinDeleteRuleDrift` (`scripts/generate-
* entities.ts`), which pins an explicit `.deleteRule(...)` wherever
* leaving the relation implicit would produce the wrong effective rule —
* see that rule's own doc comment for the full mechanism, including one
* more wrinkle it found empirically: `DawarichConnections.user`,
* `PlaceRegions.place` and `VacayUserSettings.user` share the exact same
* "nullable AND sole FK-as-PK" shape as `roadtrip_day_tracks.day_id` but
* were NOT among the 10 — their runtime default already happens to land on
* `'cascade'` (matching physical) purely because of `ALL_ENTITIES`
* discovery order, not because the shape is safe. `RULE13` pins all four
* explicitly rather than trust that order to hold.
*/
it('PARITY-009b: FK deleteRule agrees with PRAGMA foreign_key_list', () => {
const failures: string[] = [];
for (const meta of tableBackedMetas()) {
const table = meta.tableName;
const fkRows = testDb.prepare(`PRAGMA foreign_key_list("${table}")`).all() as {
from: string;
table: string;
on_delete: string;
}[];
const fkByColumn = new Map(fkRows.map((row) => [row.from, row]));
for (const prop of meta.props) {
const isOwningToOne =
prop.kind === ReferenceKind.MANY_TO_ONE || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner);
if (!isOwningToOne) continue;
const fieldName = prop.fieldNames[0];
const fk = fkByColumn.get(fieldName);
if (!fk) {
failures.push(`${table}.${fieldName}: entity relation has no matching db foreign key`);
continue;
}
const entityRule = (prop.deleteRule ?? 'no action').toLowerCase();
const dbRule = fk.on_delete.toLowerCase();
if (entityRule !== dbRule) {
failures.push(`${table}.${fieldName}: deleteRule entity=${entityRule} vs db=${dbRule}`);
}
}
}
expect(failures).toEqual([]);
});
/**
* The index-name half of the same PRAGMA-allow-listed check (Task 0, Step
* 3) — per 3a's own ledger note, "PARITY-009's index half was never
* implemented (only deleteRule)." Task 7 writes it fresh.
*
* `PRAGMA index_list(<table>)` names every index SQLite actually built —
* a plain `CREATE INDEX <name> ON ...` or `CREATE UNIQUE INDEX <name>
* ON ...`, one row each — MINUS the unnamed `sqlite_autoindex_<table>_<n>`
* entries a bare `PRIMARY KEY`/inline `UNIQUE(...)` constraint gets for
* free (excluded the same way `collectImplicitUniqueIndexes` in
* `scripts/generate-entities.ts` excludes them — those are RULE9's
* `uniques:` territory, a DIFFERENT, already-covered check, not a named
* index this one can compare against). The entity side collects every
* NAMED index a `defineEntity` call can declare: a property-level
* `.index('name')`/`.unique('name')` (`prop.index`/`prop.unique`, a string
* when named — the codebase never uses the unnamed `boolean` form, see the
* `grep` a future author can re-run: `grep -rn '\.index()\|\.unique()' src/db/entities/*.entity.ts`
* finds nothing), and every entity-level `indexes:`/`uniques:` block's own
* `.name` (composite indexes, e.g. `Notifications.idx_notifications_target_scope`).
* The two sets must be equal — a name in one and not the other means
* either a migration added/renamed/dropped an index without the entity
* following, or the reverse. Measured clean on today's schema (the
* generator's own introspection already names every entity index after
* its real DB index, RULE9's unnamed `uniques:` entries excluded by
* construction from both sides) — this is a drift GUARD for a future
* migration, not a fix for a found gap.
*/
it('PARITY-009c: index names agree with PRAGMA index_list', () => {
const failures: string[] = [];
for (const meta of tableBackedMetas()) {
const table = meta.tableName;
const dbIndexRows = testDb.prepare(`PRAGMA index_list("${table}")`).all() as { name: string; unique: number }[];
const dbNames = new Set(
dbIndexRows.filter((row) => !row.name.startsWith('sqlite_autoindex_')).map((row) => row.name),
);
const entityNames = new Set<string>();
for (const prop of meta.props) {
if (typeof prop.index === 'string') entityNames.add(prop.index);
if (typeof prop.unique === 'string') entityNames.add(prop.unique);
}
for (const idx of meta.indexes) if (idx.name) entityNames.add(idx.name);
for (const uniq of meta.uniques) if (uniq.name) entityNames.add(uniq.name);
for (const name of dbNames) {
if (!entityNames.has(name))
failures.push(`${table}: db index "${name}" has no matching entity index declaration`);
}
for (const name of entityNames) {
if (!dbNames.has(name)) failures.push(`${table}: entity declares index "${name}" with no matching db index`);
}
}
expect(failures).toEqual([]);
});
/**
* D1's own rule (the naming strategy derives the same column from a
* camelCase or a snake_case property, so a column-level check can never
* see the difference): every persisted scalar property's name must equal
* its single column name. Relations are exempt by kind (an owning
* relation legitimately renames itself away from its column, e.g.
* `SchoolHolidayRegions.countryRef` + `.joinColumn('country')` — Task 2's
* rule 5); their FK twin scalars are `kind === SCALAR` and stay covered
* here. The same test asserts every single-column integer primary key is
* `autoincrement` in the discovered metadata — Task 2's Rule 3 doesn't
* spell `.autoincrement()` in the builder chain for every case (relying on
* `MetadataDiscovery#initAutoincrement`'s own `??= true` default for an
* integer PK with no explicit value), so nothing until now pinned that the
* default actually fires. Composite and text primary keys are untouched by
* design (Task 0/1) and excluded here by construction (more than one
* primary prop, or a non-integer type).
*/
it('PARITY-010: persisted scalar property names equal their single column name; integer id PKs are autoincrement', () => {
const failures: string[] = [];
for (const meta of tableBackedMetas()) {
for (const prop of meta.props) {
const isRelation = prop.kind !== undefined && prop.kind !== ReferenceKind.SCALAR;
if (isRelation) continue;
if (prop.persist === false && prop.fieldNames.length === 0) continue; // an embeddable/virtual scalar with no column at all
if (prop.fieldNames.length !== 1 || prop.name !== prop.fieldNames[0]) {
failures.push(
`${meta.className}.${prop.name}: property name does not equal its single column name (fieldNames=${JSON.stringify(prop.fieldNames)})`,
);
}
}
// A genuinely single-column primary key only — a composite PK (e.g.
// RoadtripDayBoundaries' PRIMARY KEY (trip_id, day_number)) can have an
// all-integer shape without ever being SQLite's single-column
// `INTEGER PRIMARY KEY` rowid alias, so it must never autoincrement;
// `getPrimaryProps()` must report exactly one prop, unfiltered, before
// this check applies at all.
const primaryProps = meta.getPrimaryProps();
if (primaryProps.length === 1) {
const pk = primaryProps[0];
const isIntegerScalarPk =
(pk.kind === undefined || pk.kind === ReferenceKind.SCALAR) &&
normaliseColumnType(pk.columnTypes[0] ?? '') === 'integer';
if (isIntegerScalarPk && pk.autoincrement !== true) {
failures.push(`${meta.className}.${pk.name}: integer primary key is not autoincrement`);
}
}
}
expect(failures).toEqual([]);
});
});
/**
* Strips SQL string-literal quoting and a single wrapping paren pair (SQLite
* requires `DEFAULT (expr)` for a non-literal expression in the migration's
* own DDL; `PRAGMA table_info` and the generator's introspected
* `prop.defaultRaw` don't always agree on keeping that outer pair), folds
* SQLite's `CURRENT_TIMESTAMP`/`datetime('now')` spellings together, and
* folds a `p.boolean()` property's literal `true`/`false` default onto
* SQLite's `1`/`0` (SQLite has no boolean storage class — see
* `BOOLEAN_COLUMNS` in `scripts/generate-entities.ts`). Used by PARITY-005.
*
* M1 (task-4-review-gates.md): only the SQL keywords/functions above are
* folded case-insensitively — a quoted string literal's PAYLOAD is data, not
* a keyword, and is compared verbatim, case included. A blanket
* `s.toLowerCase()` on the whole string (the previous shape) silently
* equated `'#10b981'` and `'#10B981'`, proved by the gate reviewer's mutation
* (d2): flipping `Tags.color`'s class-field default's case left every test
* green. The entity side and the db side aren't even symmetric about
* quoting to begin with (`prop.default` arrives as a bare JS string, e.g.
* `#10b981`; `column.dflt_value` arrives SQL-quoted, `'#10b981'`) — quotes
* are stripped from whichever side has them, then BOTH sides are compared
* verbatim, never lowercased, unless they match a known keyword.
*/
function normaliseDefault(value: string | null): string | null {
if (value == null) return null;
let s = value.trim();
if (s.startsWith('(') && s.endsWith(')')) s = s.slice(1, -1).trim();
if (s.startsWith("'") && s.endsWith("'")) s = s.slice(1, -1); // SQL quoting stripped; payload kept verbatim below
const lower = s.toLowerCase();
if (lower === "datetime('now')" || lower === 'current_timestamp') return '__now__';
if (lower === 'true') return '1';
if (lower === 'false') return '0';
return s;
}
describe('normaliseColumnType', () => {
it('TYPE-001: maps the abstract names MikroORM leaves untranslated on SQLite', () => {
expect(normaliseColumnType('double')).toBe('real');
expect(normaliseColumnType('json')).toBe('text');
expect(normaliseColumnType('varchar')).toBe('text');
});
it('TYPE-002: strips a length/precision suffix and lowercases', () => {
expect(normaliseColumnType('VARCHAR(255)')).toBe('text');
expect(normaliseColumnType('DECIMAL(10,2)')).toBe('decimal');
expect(normaliseColumnType('INTEGER')).toBe('integer');
});
it('TYPE-003: passes through types that already agree', () => {
expect(normaliseColumnType('text')).toBe('text');
expect(normaliseColumnType('real')).toBe('real');
expect(normaliseColumnType('datetime')).toBe('datetime');
expect(normaliseColumnType('bigint')).toBe('bigint');
});
});
describe('normaliseDefault', () => {
it('DEFAULT-NORM-001: a case-only difference in a quoted string literal payload is a real mismatch (M1)', () => {
expect(normaliseDefault("'#10b981'")).not.toBe(normaliseDefault("'#10B981'"));
});
it('DEFAULT-NORM-002: an identical quoted string literal payload matches, case preserved', () => {
expect(normaliseDefault("'#10b981'")).toBe(normaliseDefault("'#10b981'"));
expect(normaliseDefault("'#10b981'")).toBe('#10b981');
});
it('DEFAULT-NORM-003: an unquoted default (as PARITY-005 passes the entity side, String(prop.default)) compares verbatim too', () => {
expect(normaliseDefault('#10B981')).toBe('#10B981');
expect(normaliseDefault('#10B981')).not.toBe(normaliseDefault("'#10b981'"));
});
it('DEFAULT-NORM-004: SQL keyword/function spellings still fold case-insensitively', () => {
expect(normaliseDefault('CURRENT_TIMESTAMP')).toBe('__now__');
expect(normaliseDefault('current_timestamp')).toBe('__now__');
expect(normaliseDefault("datetime('now')")).toBe('__now__');
expect(normaliseDefault("DATETIME('NOW')")).toBe('__now__');
expect(normaliseDefault('TRUE')).toBe('1');
expect(normaliseDefault('FALSE')).toBe('0');
});
it('DEFAULT-NORM-005: a wrapping paren pair around a non-literal expression is stripped once', () => {
expect(normaliseDefault("(strftime('%s','now'))")).toBe("strftime('%s','now')");
});
it('DEFAULT-NORM-006: null passes through as null', () => {
expect(normaliseDefault(null)).toBeNull();
});
});
describe('columnTypesEqual', () => {
it('TYPE-004: accepts datetime on one side and text on the other, either direction', () => {
expect(columnTypesEqual('datetime', 'text')).toBe(true);
expect(columnTypesEqual('text', 'datetime')).toBe(true);
expect(columnTypesEqual('DATETIME', 'TEXT')).toBe(true);
});
it('TYPE-005: still rejects a genuine mismatch', () => {
expect(columnTypesEqual('integer', 'text')).toBe(false);
expect(columnTypesEqual('real', 'integer')).toBe(false);
});
});
@@ -0,0 +1,67 @@
/**
* `Migration20200101043200_via_ferrata_tiles_outlive_a_restart`: the table
* that keeps the via ferrata grid cells exists only from this step on, keyed
* by the cell, with every column required.
*/
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import { describe, expect, it } from 'vitest';
const TARGET = 'Migration20200101043200_via_ferrata_tiles_outlive_a_restart';
async function ormBeforeTarget(): Promise<MikroORM> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const index = names.indexOf(TARGET);
expect(index).toBeGreaterThan(0);
await migrateTo(orm, names[index - 1]);
return orm;
}
const tables = (orm: MikroORM) =>
rawQuery<{ name: string }>(orm, "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'ferrata_tiles'");
describe('Via ferrata tiles migration', () => {
it('FERTILEMIG-001: creates ferrata_tiles with a required key, payload and fetch time', async () => {
const orm = await ormBeforeTarget();
try {
expect(await tables(orm)).toEqual([]);
await migrateTo(orm, TARGET);
expect(await tables(orm)).toEqual([{ name: 'ferrata_tiles' }]);
const columns = await rawQuery<{ name: string; type: string; notnull: number; pk: number }>(
orm,
'SELECT name, type, "notnull", pk FROM pragma_table_info(\'ferrata_tiles\') ORDER BY cid',
);
expect(columns).toEqual([
{ name: 'tile_key', type: 'TEXT', notnull: 1, pk: 1 },
{ name: 'payload', type: 'TEXT', notnull: 1, pk: 0 },
{ name: 'fetched_at', type: 'INTEGER', notnull: 1, pk: 0 },
]);
} finally {
await orm.close(true);
}
}, 30000);
it('FERTILEMIG-002: holds one row per cell and refuses a row without a payload', async () => {
const orm = await ormBeforeTarget();
try {
await migrateTo(orm, TARGET);
await rawExec(orm, "INSERT INTO ferrata_tiles (tile_key, payload, fetched_at) VALUES ('942,224', '{}', 1)");
await expect(
rawExec(orm, "INSERT INTO ferrata_tiles (tile_key, payload, fetched_at) VALUES ('942,224', '{}', 2)"),
).rejects.toThrow(/UNIQUE|PRIMARY KEY/);
await expect(
rawExec(orm, "INSERT INTO ferrata_tiles (tile_key, payload, fetched_at) VALUES ('942,225', NULL, 2)"),
).rejects.toThrow(/NOT NULL/);
await expect(
rawExec(orm, "INSERT INTO ferrata_tiles (tile_key, payload, fetched_at) VALUES (NULL, '{}', 2)"),
).rejects.toThrow(/NOT NULL/);
} finally {
await orm.close(true);
}
}, 30000);
});
@@ -0,0 +1,202 @@
import { createSnapshotTestDb } from '../../helpers/db-mock';
import type Database from 'better-sqlite3';
import { afterAll, describe, expect, it } from 'vitest';
/**
* Migration20200101042200 added 86 indexes by hand so that deleting a trip or a
* user stops scanning every child table while it holds the one connection. A
* hand-written list is a one-off, though: the next table with a trip_id or a
* user_id foreign key would bring the full scans back without a signal, and
* gen:entities regenerates entities without an @Index just as happily.
*
* This runs against the database the migrations build (the same snapshot every
* test opens) and requires that the columns of every foreign key lead some
* index or the primary key, in order, so SQLite can find the child rows of a
* parent by seeking instead of scanning. A foreign key that deliberately goes
* without one is listed in UNINDEXED_ALLOWED with the reason.
*/
/** `table.column` (comma-joined for a composite key) that may stay unindexed, each with its reason. */
const UNINDEXED_ALLOWED: Record<string, string> = {};
interface ForeignKeyRow {
id: number;
seq: number;
table: string;
from: string;
}
interface IndexListRow {
name: string;
partial: number;
}
interface IndexInfoRow {
seqno: number;
name: string | null;
}
interface TableInfoRow {
name: string;
pk: number;
}
const testDb = createSnapshotTestDb();
afterAll(() => {
testDb.close();
});
function tables(db: Database.Database): string[] {
const rows = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`).all() as {
name: string;
}[];
return rows.map((r) => r.name).sort();
}
/** Each foreign key of a table as its ordered child columns. */
function foreignKeys(db: Database.Database, table: string): string[][] {
const rows = db.prepare(`PRAGMA foreign_key_list("${table}")`).all() as ForeignKeyRow[];
const byId = new Map<number, ForeignKeyRow[]>();
for (const row of rows) byId.set(row.id, [...(byId.get(row.id) ?? []), row]);
return [...byId.values()].map((group) => group.sort((a, b) => a.seq - b.seq).map((r) => r.from));
}
/** The leading columns of an index, and the columns its WHERE clause requires to be non-null. */
interface IndexPrefix {
cols: string[];
notNull: string[];
}
/**
* The columns a partial index's predicate requires to be non-null, or null when
* the predicate says anything else. SQLite proves `col = ?` implies `col IS NOT
* NULL`, so only such an index serves the parent's cascade lookup; one filtered
* on another predicate (`WHERE state = 'open'`) leaves the lookup scanning.
*/
function notNullPredicate(sql: string | null): string[] | null {
const where = /\bWHERE\b([\s\S]*)$/i.exec(sql ?? '');
if (!where) return null;
const cols: string[] = [];
for (const term of where[1].trim().split(/\s+AND\s+/i)) {
const m = /^\(?\s*["`[]?(\w+)["`\]]?\s+IS\s+NOT\s+NULL\s*\)?$/i.exec(term.trim());
if (!m) return null;
cols.push(m[1]);
}
return cols;
}
/** Every index of a table, and its primary key, as ordered column lists. */
function indexedPrefixes(db: Database.Database, table: string): IndexPrefix[] {
const lists: IndexPrefix[] = [];
for (const { name, partial } of db.prepare(`PRAGMA index_list("${table}")`).all() as IndexListRow[]) {
let notNull: string[] = [];
if (partial) {
const row = db.prepare(`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?`).get(name) as
{ sql: string | null } | undefined;
const required = notNullPredicate(row?.sql ?? null);
// A predicate other than IS NOT NULL on key columns hides rows from the lookup.
if (required === null) continue;
notNull = required;
}
const cols = (db.prepare(`PRAGMA index_info("${name}")`).all() as IndexInfoRow[])
.sort((a, b) => a.seqno - b.seqno)
// An expression column has no name and ends the usable prefix.
.map((c) => c.name);
const usable: string[] = [];
for (const c of cols) {
if (c === null) break;
usable.push(c);
}
lists.push({ cols: usable, notNull });
}
const pk = (db.prepare(`PRAGMA table_info("${table}")`).all() as TableInfoRow[])
.filter((c) => c.pk > 0)
.sort((a, b) => a.pk - b.pk)
.map((c) => c.name);
if (pk.length) lists.push({ cols: pk, notNull: [] });
return lists;
}
/**
* True when the foreign key's columns, in any order, are the leading columns of
* one index, and a partial index filters only on those columns being non-null.
*/
function isLedByIndex(fk: string[], indexes: IndexPrefix[]): boolean {
const want = [...fk].sort().join(',');
return indexes.some(
({ cols, notNull }) =>
cols.length >= fk.length &&
[...cols.slice(0, fk.length)].sort().join(',') === want &&
notNull.every((c) => fk.includes(c)),
);
}
function unindexed(db: Database.Database): string[] {
const missing: string[] = [];
for (const table of tables(db)) {
const indexes = indexedPrefixes(db, table);
for (const fk of foreignKeys(db, table)) {
if (!isLedByIndex(fk, indexes)) missing.push(`${table}.${fk.join(',')}`);
}
}
return missing;
}
describe('foreign key indexes', () => {
it('FKIDX-001: every foreign key in the migrated schema leads an index or the primary key', () => {
const missing = unindexed(testDb).filter((key) => !(key in UNINDEXED_ALLOWED));
expect(missing, 'add a CREATE INDEX for each in a new migration, and an @Index on the entity').toEqual([]);
});
it('FKIDX-002: UNINDEXED_ALLOWED holds only keys that exist and are still unindexed', () => {
const now = new Set(unindexed(testDb));
expect(Object.keys(UNINDEXED_ALLOWED).filter((key) => !now.has(key))).toEqual([]);
});
it('FKIDX-003: the check fails on an unindexed foreign key and passes once it is indexed', () => {
const Sqlite = testDb.constructor as unknown as new (path: string) => Database.Database;
const db = new Sqlite(':memory:');
try {
db.exec(`
CREATE TABLE parent (id INTEGER PRIMARY KEY, a INTEGER, b INTEGER, UNIQUE (a, b));
CREATE TABLE child (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES parent(id), note TEXT);
CREATE TABLE pair (x INTEGER, y INTEGER, z INTEGER, FOREIGN KEY (x, y) REFERENCES parent(a, b));
CREATE TABLE owned (parent_id INTEGER REFERENCES parent(id), slot INTEGER, PRIMARY KEY (parent_id, slot));
`);
// owned is covered by its primary key; child and pair are not.
expect(unindexed(db)).toEqual(['child.parent_id', 'pair.x,y']);
// An index that holds the column second does not help a lookup by it.
db.exec('CREATE INDEX idx_child_note_parent ON child(note, parent_id)');
expect(unindexed(db)).toContain('child.parent_id');
// A partial index on another predicate leaves the cascade lookup scanning.
db.exec(`CREATE INDEX idx_child_parent_open ON child(parent_id) WHERE note = 'open'`);
expect(db.prepare('EXPLAIN QUERY PLAN SELECT 1 FROM child WHERE parent_id = ?').get(1)).toMatchObject({
detail: 'SCAN child',
});
expect(unindexed(db)).toContain('child.parent_id');
// One filtered only on the key being non-null still serves `parent_id = ?`.
db.exec('CREATE INDEX idx_child_parent ON child(parent_id) WHERE parent_id IS NOT NULL');
expect(
(db.prepare('EXPLAIN QUERY PLAN SELECT 1 FROM child WHERE parent_id = ?').get(1) as { detail: string }).detail,
).toContain('idx_child_parent');
db.exec('CREATE INDEX idx_pair_yx ON pair(y, x, z)');
expect(unindexed(db)).toEqual([]);
} finally {
db.close();
}
});
it('FKIDX-004: a partial index counts only when its predicate is IS NOT NULL on its columns', () => {
expect(notNullPredicate('CREATE INDEX i ON c(p_id) WHERE p_id IS NOT NULL')).toEqual(['p_id']);
expect(notNullPredicate('CREATE INDEX i ON c(a, b) WHERE "a" IS NOT NULL AND (b IS NOT NULL)')).toEqual(['a', 'b']);
expect(notNullPredicate("CREATE INDEX i ON c(p_id) WHERE state = 'open'")).toBeNull();
expect(notNullPredicate('CREATE INDEX i ON c(p_id) WHERE p_id IS NOT NULL OR x = 1')).toBeNull();
expect(notNullPredicate('CREATE INDEX i ON c(p_id) WHERE p_id IS NULL')).toBeNull();
expect(notNullPredicate(null)).toBeNull();
});
});
@@ -0,0 +1,195 @@
import {
checkDbTypes,
generateDbTypes,
interfaceName,
KYSELY_DIR,
pascalCase,
renderAll,
renderColumns,
renderDb,
renderTable,
tsTypeFor,
writeDbTypes,
type ColumnInfo,
type TableInfo,
} from '../../../scripts/generate-db-types';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
function column(overrides: Partial<ColumnInfo> & { name: string }): ColumnInfo {
return { type: 'TEXT', notnull: true, hasDefault: false, pk: 0, hidden: 0, ...overrides };
}
const ITEMS: TableInfo = {
name: 'budget_items',
columns: [
column({ name: 'id', type: 'INTEGER', notnull: false, pk: 1 }),
column({ name: 'trip_id', type: 'INTEGER' }),
column({ name: 'name' }),
column({ name: 'note', notnull: false }),
column({ name: 'created_at', type: 'DATETIME', notnull: false, hasDefault: true }),
column({ name: 'exchange_rate', type: 'REAL', hasDefault: true }),
],
};
function tempDir(prefix: string): string {
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
}
describe('tsTypeFor', () => {
it('DBTYPES-001: maps the declared types the schema uses by SQLite affinity', () => {
expect(tsTypeFor('INTEGER')).toBe('number');
expect(tsTypeFor('bigint')).toBe('number');
expect(tsTypeFor('TEXT')).toBe('string');
expect(tsTypeFor('varchar(255)')).toBe('string');
expect(tsTypeFor('REAL')).toBe('number');
expect(tsTypeFor('DATETIME')).toBe('string');
expect(tsTypeFor('BLOB')).toBe('Buffer');
expect(tsTypeFor('BOOLEAN')).toBe('number');
expect(tsTypeFor('')).toBe('unknown');
});
it('DBTYPES-002: refuses a declared type it has no mapping for, naming it', () => {
expect(() => tsTypeFor('GEOMETRY')).toThrow(/"GEOMETRY"/);
});
});
describe('names', () => {
it('DBTYPES-003: snake_case tables become PascalCase files and <Name>Table interfaces', () => {
expect(pascalCase('budget_items')).toBe('BudgetItems');
expect(pascalCase('users')).toBe('Users');
expect(interfaceName('trip_files')).toBe('TripFilesTable');
});
});
describe('renderTable', () => {
it('DBTYPES-004: a rowid, a defaulted and a nullable column are InsertOptional, the rest required', () => {
const source = renderTable(ITEMS);
expect(source).toContain("import type { InsertOptional } from './columns';");
expect(source).toContain('export interface BudgetItemsTable {');
expect(source).toContain(' id: InsertOptional<number>;');
expect(source).toContain(' trip_id: number;');
expect(source).toContain(' name: string;');
expect(source).toContain(' note: InsertOptional<string | null>;');
expect(source).toContain(' created_at: InsertOptional<string | null>;');
expect(source).toContain(' exchange_rate: InsertOptional<number>;');
});
it('DBTYPES-005: a composite primary key is required on insert, not a rowid', () => {
const source = renderTable({
name: 'place_tags',
columns: [
column({ name: 'place_id', type: 'INTEGER', pk: 1 }),
column({ name: 'tag_id', type: 'INTEGER', pk: 2 }),
],
});
expect(source).toContain(' place_id: number;');
expect(source).toContain(' tag_id: number;');
expect(source).not.toContain('import type');
});
it('DBTYPES-006: a generated (computed) column is GeneratedAlways, so no insert or update can name it', () => {
const source = renderTable({ name: 't', columns: [column({ name: 'total', type: 'INTEGER', hidden: 2 })] });
expect(source).toContain("import type { GeneratedAlways } from 'kysely';");
expect(source).toContain(' total: GeneratedAlways<number>;');
});
it('DBTYPES-007: a column name that is not an identifier is quoted', () => {
const source = renderTable({ name: 't', columns: [column({ name: 'group-name' })] });
expect(source).toContain(" 'group-name': string;");
});
});
describe('renderDb / renderColumns / renderAll', () => {
it('DBTYPES-008: db.ts imports every table interface and maps the table name to it', () => {
const source = renderDb([ITEMS, { name: 'users', columns: [column({ name: 'id', type: 'INTEGER', pk: 1 })] }]);
expect(source).toContain("import type { BudgetItemsTable } from './BudgetItems.table';");
expect(source).toContain("import type { UsersTable } from './Users.table';");
expect(source).toContain('export interface DB {\n budget_items: BudgetItemsTable;\n users: UsersTable;\n}');
});
it('DBTYPES-009: InsertOptional widens the insert type with void, which survives a non-strict compile', () => {
expect(renderColumns()).toContain('export type InsertOptional<T> = ColumnType<T, T | void, T>;');
});
it('DBTYPES-010: renderAll emits one file per table plus columns.ts and db.ts, and refuses an empty schema', () => {
const files = renderAll([ITEMS]);
expect([...files.keys()].sort()).toEqual(['BudgetItems.table.ts', 'columns.ts', 'db.ts']);
expect(() => renderAll([])).toThrow(/no tables/);
});
});
describe('checkDbTypes / writeDbTypes', () => {
it('DBTYPES-011: reports a changed, a missing and an extra file, and nothing once written', () => {
const files = renderAll([ITEMS]);
const dir = tempDir('gen-db-types-');
try {
expect(checkDbTypes(dir, files)).toEqual(['BudgetItems.table.ts', 'columns.ts', 'db.ts']);
writeDbTypes(dir, files);
expect(checkDbTypes(dir, files)).toEqual([]);
fs.writeFileSync(path.join(dir, 'db.ts'), 'export interface DB {}\n');
fs.writeFileSync(path.join(dir, 'Stale.table.ts'), 'export interface StaleTable {}\n');
expect(checkDbTypes(dir, files)).toEqual(['Stale.table.ts (not produced by the generator)', 'db.ts']);
writeDbTypes(dir, files);
expect(fs.existsSync(path.join(dir, 'Stale.table.ts'))).toBe(false);
expect(checkDbTypes(dir, files)).toEqual([]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it('DBTYPES-012: a CRLF checkout of an unchanged file is not drift', () => {
const files = renderAll([ITEMS]);
const dir = tempDir('gen-db-types-crlf-');
try {
writeDbTypes(dir, files);
const target = path.join(dir, 'db.ts');
fs.writeFileSync(target, fs.readFileSync(target, 'utf8').replace(/\n/g, '\r\n'));
expect(checkDbTypes(dir, files)).toEqual([]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
describe('the committed src/db/kysely/', () => {
it('DBTYPES-013: matches what the migrated schema generates (the check:db-types gate)', async () => {
const files = await generateDbTypes();
expect(files.get('db.ts')).toContain(' budget_items: BudgetItemsTable;');
expect(checkDbTypes(KYSELY_DIR, files)).toEqual([]);
}, 60_000);
});
describe('formatting', () => {
it('DBTYPES-014: every generated file is already Prettier-clean, so lint:format and check:db-types agree', async () => {
const prettier = await import('prettier');
// Sorted by name, as readSchema hands them over.
const files = renderAll([
ITEMS,
{
name: 'place_tags',
columns: [
column({ name: 'place_id', type: 'INTEGER', pk: 1 }),
column({ name: 'tag_id', type: 'INTEGER', pk: 2 }),
],
},
{
name: 't',
columns: [column({ name: 'total', type: 'INTEGER', hidden: 2 }), column({ name: 'note', notnull: false })],
},
]);
const verdicts = await Promise.all(
[...files].map(async ([fileName, content]) => {
const filepath = path.join(KYSELY_DIR, fileName);
const options = await prettier.resolveConfig(filepath);
return { fileName, clean: await prettier.check(content, { ...options, filepath }) };
}),
);
expect(verdicts).toEqual([...files.keys()].map((fileName) => ({ fileName, clean: true })));
});
});
File diff suppressed because it is too large Load Diff
@@ -1,100 +1,151 @@
import { runMigrations } from '../../../src/db/migrations';
import { createTables } from '../../../src/db/schema';
import { runSeeds } from '../../../src/db/seeds';
/**
* The Immich self-signed switch and the two settings rows (#2475), legacy step
* 243, on the real `Migration20200101040400_immich_learns_the_switch_synology_airtrail_and`.
*
* The legacy test rewound `schema_version` to just before the step and ran the
* runner again. Here a replay runs the migration class directly a second time
* (bypassing the Migrator's "already applied, skip" bookkeeping), and a fresh
* install is the whole chain followed by the `PhotoProviderSeeder`, the order
* `db/orm.ts` runs them in at boot.
*/
import { Migration20200101040400_immich_learns_the_switch_synology_airtrail_and as TargetMigration } from '../../../src/db/migrations/Migration20200101040400_immich_learns_the_switch_synology_airtrail_and';
import { PhotoProviderSeeder } from '../../../src/db/seeders/PhotoProviderSeeder';
import {
createMigrationOrm,
migrateTo,
migratorOf,
pendingNames,
rawExec,
rawQuery,
runMigrationDirect,
} from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import Database from 'better-sqlite3';
import { afterEach, describe, expect, it } from 'vitest';
// The Immich self-signed switch and the two settings rows are pinned at schema
// version 243 (#2475). Later migrations are appended after it, so a case that
// replays it rewinds to just before it; the steps after it are idempotent.
const IMMICH_TLS_VERSION = 243;
const TARGET = 'Migration20200101040400_immich_learns_the_switch_synology_airtrail_and';
type FieldRow = { field_key: string; input_type: string; settings_key: string | null; payload_key: string | null; sort_order: number };
type FieldRow = {
field_key: string;
input_type: string;
settings_key: string | null;
payload_key: string | null;
sort_order: number;
};
function immichFields(db: Database.Database): FieldRow[] {
return db
.prepare(
"SELECT field_key, input_type, settings_key, payload_key, sort_order FROM photo_provider_fields WHERE provider_id = 'immich' ORDER BY sort_order",
)
.all() as FieldRow[];
function immichFields(orm: MikroORM): Promise<FieldRow[]> {
return rawQuery<FieldRow>(
orm,
"SELECT field_key, input_type, settings_key, payload_key, sort_order FROM photo_provider_fields WHERE provider_id = 'immich' ORDER BY sort_order",
);
}
const EXPECTED_FIELDS: FieldRow[] = [
{ field_key: 'immich_url', input_type: 'url', settings_key: 'immich_url', payload_key: 'immich_url', sort_order: 0 },
{ field_key: 'immich_api_key', input_type: 'password', settings_key: null, payload_key: 'immich_api_key', sort_order: 1 },
{ field_key: 'immich_allow_insecure_tls', input_type: 'checkbox', settings_key: 'allow_insecure_tls', payload_key: 'allow_insecure_tls', sort_order: 2 },
{ field_key: 'immich_auto_upload', input_type: 'checkbox', settings_key: 'auto_upload', payload_key: 'auto_upload', sort_order: 5 },
{
field_key: 'immich_api_key',
input_type: 'password',
settings_key: null,
payload_key: 'immich_api_key',
sort_order: 1,
},
{
field_key: 'immich_allow_insecure_tls',
input_type: 'checkbox',
settings_key: 'allow_insecure_tls',
payload_key: 'allow_insecure_tls',
sort_order: 2,
},
{
field_key: 'immich_auto_upload',
input_type: 'checkbox',
settings_key: 'auto_upload',
payload_key: 'auto_upload',
sort_order: 5,
},
];
function replay(db: Database.Database): void {
db.prepare('UPDATE schema_version SET version = ?').run(IMMICH_TLS_VERSION - 1);
runMigrations(db);
async function migrateToJustBefore(orm: MikroORM): Promise<void> {
const names = await pendingNames(orm);
const idx = names.indexOf(TARGET);
expect(idx).toBeGreaterThan(0);
await migrateTo(orm, names[idx - 1]);
}
describe('Immich provider fields and the self-signed switch (#2475)', () => {
let db: Database.Database;
let orm: MikroORM | undefined;
afterEach(() => db?.close());
afterEach(async () => {
await orm?.close(true);
orm = undefined;
});
it('a fresh install shows every Immich setting, the auto-upload toggle included', () => {
// database.ts runs schema, migrations, seeds in that order. On an empty
// database the migrations find no Immich provider row yet, so the seeds
// are what has to bring the rows along.
db = new Database(':memory:');
createTables(db);
runMigrations(db);
it('a fresh install shows every Immich setting, the auto-upload toggle included', async () => {
// Boot runs the migrations, then the seeders. On an empty database the
// migration finds no Immich provider row yet, so the seeder is what has to
// bring the rows along.
orm = await createMigrationOrm();
await migratorOf(orm).up();
// An existing user keeps the admin seeding out of this.
db.exec("INSERT INTO users (username, email, password_hash) VALUES ('someone', 'someone@example.test', 'x')");
runSeeds(db);
await rawExec(
orm,
"INSERT INTO users (username, email, password_hash) VALUES ('someone', 'someone@example.test', 'x')",
);
await new PhotoProviderSeeder().run(orm.em);
expect(immichFields(db)).toEqual(EXPECTED_FIELDS);
const label = db
.prepare("SELECT label FROM photo_provider_fields WHERE provider_id = 'immich' AND field_key = 'immich_allow_insecure_tls'")
.get();
expect(await immichFields(orm)).toEqual(EXPECTED_FIELDS);
const label = await rawQuery(
orm,
"SELECT label FROM photo_provider_fields WHERE provider_id = 'immich' AND field_key = 'immich_allow_insecure_tls'",
);
// The Synology label, so every locale already has the words.
expect(label).toEqual({ label: 'skipSSLVerification' });
});
expect(label).toEqual([{ label: 'skipSSLVerification' }]);
}, 30000);
it('the switch is off for every user until they turn it on', () => {
db = new Database(':memory:');
createTables(db);
runMigrations(db);
db.exec("INSERT INTO users (username, email, password_hash) VALUES ('someone', 'someone@example.test', 'x')");
it('the switch is off for every user until they turn it on', async () => {
orm = await createMigrationOrm();
await migratorOf(orm).up();
await rawExec(
orm,
"INSERT INTO users (username, email, password_hash) VALUES ('someone', 'someone@example.test', 'x')",
);
expect(db.prepare('SELECT immich_allow_insecure_tls AS v FROM users').get()).toEqual({ v: 0 });
});
expect(await rawQuery(orm, 'SELECT immich_allow_insecure_tls AS v FROM users')).toEqual([{ v: 0 }]);
}, 30000);
it('an install that already had the Immich provider gets both rows once, and a replay changes nothing', () => {
db = new Database(':memory:');
createTables(db);
runMigrations(db);
it('an install that already had the Immich provider gets both rows once, and a replay changes nothing', async () => {
orm = await createMigrationOrm();
await migrateToJustBefore(orm);
// What an upgraded fresh install looked like: the seeds of an older release
// added the provider with only its URL and key.
db.exec(`
INSERT INTO photo_providers (id, name, description, icon, enabled, sort_order) VALUES ('immich', 'Immich', 'Immich photo provider', 'Image', 0, 0);
INSERT INTO photo_provider_fields (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order) VALUES
await rawExec(
orm,
"INSERT INTO photo_providers (id, name, description, icon, enabled, sort_order) VALUES ('immich', 'Immich', 'Immich photo provider', 'Image', 0, 0)",
);
await rawExec(
orm,
`INSERT INTO photo_provider_fields (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order) VALUES
('immich', 'immich_url', 'providerUrl', 'url', 'https://immich.example.com', 1, 0, 'immich_url', 'immich_url', 0),
('immich', 'immich_api_key', 'providerApiKey', 'password', 'API Key', 1, 1, NULL, 'immich_api_key', 1);
`);
('immich', 'immich_api_key', 'providerApiKey', 'password', 'API Key', 1, 1, NULL, 'immich_api_key', 1)`,
);
replay(db);
expect(immichFields(db)).toEqual(EXPECTED_FIELDS);
await migrateTo(orm, TARGET);
expect(await immichFields(orm)).toEqual(EXPECTED_FIELDS);
replay(db);
expect(immichFields(db)).toEqual(EXPECTED_FIELDS);
});
await runMigrationDirect(orm, TargetMigration);
expect(await immichFields(orm)).toEqual(EXPECTED_FIELDS);
}, 30000);
it('a replay keeps what a user already chose', () => {
db = new Database(':memory:');
createTables(db);
runMigrations(db);
db.exec(
it('a replay keeps what a user already chose', async () => {
orm = await createMigrationOrm();
await migrateTo(orm, TARGET);
await rawExec(
orm,
"INSERT INTO users (username, email, password_hash, immich_allow_insecure_tls) VALUES ('someone', 'someone@example.test', 'x', 1)",
);
replay(db);
await runMigrationDirect(orm, TargetMigration);
expect(db.prepare('SELECT immich_allow_insecure_tls AS v FROM users').get()).toEqual({ v: 1 });
});
expect(await rawQuery(orm, 'SELECT immich_allow_insecure_tls AS v FROM users')).toEqual([{ v: 1 }]);
}, 30000);
});
@@ -10,132 +10,156 @@
* promotion is skipped, because the instance row outranks everybody's own
* column and nobody may be moved onto a stranger's key by an upgrade.
*
* Seeded before runMigrations rather than by rewinding schema_version
* afterwards: createTables already brings users.role and both key columns, so
* the backfill fires on its normal pass and finds the rows. That keeps this
* file independent of where the entry sits in the append-only array, so
* appending the next migration does not drag it along. The one guard that does
* have to track the tail is tests/integration/leg-mode-incoming.test.ts, which
* says so in place.
* Ported off the legacy runner (Task 0 triage: PORT) onto the real
* `Migration20200101031100_1939`: migrate to the step immediately before it,
* seed rows with raw SQL, apply just that one migration, assert.
*/
import { describe, it, expect } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
function freshDb() {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
return db;
import { describe, it, expect } from 'vitest';
const TARGET = 'Migration20200101031100_1939';
async function ormBeforeTarget(): Promise<MikroORM> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const idx = names.indexOf(TARGET);
expect(idx).toBeGreaterThan(0);
await migrateTo(orm, names[idx - 1]);
return orm;
}
function seedUser(
db: Database.Database,
async function seedUser(
orm: MikroORM,
id: number,
role: 'admin' | 'user',
keys: { maps?: string; unsplash?: string } = {},
) {
db.prepare(
): Promise<void> {
await rawExec(
orm,
`INSERT INTO users (id, username, email, password_hash, role, maps_api_key, unsplash_api_key)
VALUES (?, ?, ?, 'x', ?, ?, ?)`
).run(id, `u${id}`, `u${id}@test.local`, role, keys.maps ?? null, keys.unsplash ?? null);
VALUES (?, ?, ?, 'x', ?, ?, ?)`,
[id, `u${id}`, `u${id}@test.local`, role, keys.maps ?? null, keys.unsplash ?? null],
);
}
const setting = (db: Database.Database, key: string) =>
(db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value;
async function setting(orm: MikroORM, key: string): Promise<string | undefined> {
const rows = await rawQuery<{ value: string }>(orm, 'SELECT value FROM app_settings WHERE key = ?', [key]);
return rows[0]?.value;
}
describe('instance API-key backfill migration', () => {
it('KEYFILL-001: copies the one key the install was searching with and keeps the column', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'the-admin-google', unsplash: 'the-admin-unsplash' });
seedUser(db, 2, 'user');
it('KEYFILL-001: copies the one key the install was searching with and keeps the column', async () => {
const orm = await ormBeforeTarget();
try {
await seedUser(orm, 1, 'admin', { maps: 'the-admin-google', unsplash: 'the-admin-unsplash' });
await seedUser(orm, 2, 'user');
runMigrations(db);
await migrateTo(orm, TARGET);
expect(setting(db, 'maps_api_key')).toBe('the-admin-google');
expect(setting(db, 'unsplash_api_key')).toBe('the-admin-unsplash');
// Nothing is taken away: the columns are still the per-user fallback.
const row = db.prepare('SELECT maps_api_key FROM users WHERE id = 1').get() as { maps_api_key: string };
expect(row.maps_api_key).toBe('the-admin-google');
db.close();
});
expect(await setting(orm, 'maps_api_key')).toBe('the-admin-google');
expect(await setting(orm, 'unsplash_api_key')).toBe('the-admin-unsplash');
// Nothing is taken away: the columns are still the per-user fallback.
const rows = await rawQuery<{ maps_api_key: string }>(orm, 'SELECT maps_api_key FROM users WHERE id = 1');
expect(rows[0].maps_api_key).toBe('the-admin-google');
} finally {
await orm.close(true);
}
}, 30000);
it('KEYFILL-002: skips an admin whose column is empty and takes the next one', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: '' });
seedUser(db, 2, 'admin', { maps: 'the-only-real-key' });
it('KEYFILL-002: skips an admin whose column is empty and takes the next one', async () => {
const orm = await ormBeforeTarget();
try {
await seedUser(orm, 1, 'admin', { maps: '' });
await seedUser(orm, 2, 'admin', { maps: 'the-only-real-key' });
runMigrations(db);
await migrateTo(orm, TARGET);
expect(setting(db, 'maps_api_key')).toBe('the-only-real-key');
db.close();
});
expect(await setting(orm, 'maps_api_key')).toBe('the-only-real-key');
} finally {
await orm.close(true);
}
}, 30000);
it('KEYFILL-003: never overwrites a value the admin has already saved instance-wide', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'old-column-key' });
db.prepare("INSERT INTO app_settings (key, value) VALUES ('maps_api_key', 'already-instance-wide')").run();
it('KEYFILL-003: never overwrites a value the admin has already saved instance-wide', async () => {
const orm = await ormBeforeTarget();
try {
await seedUser(orm, 1, 'admin', { maps: 'old-column-key' });
await rawExec(orm, "INSERT INTO app_settings (key, value) VALUES ('maps_api_key', 'already-instance-wide')");
runMigrations(db);
await migrateTo(orm, TARGET);
expect(setting(db, 'maps_api_key')).toBe('already-instance-wide');
db.close();
});
expect(await setting(orm, 'maps_api_key')).toBe('already-instance-wide');
} finally {
await orm.close(true);
}
}, 30000);
it('KEYFILL-004: ignores a non-admin key and writes no row at all', () => {
const db = freshDb();
seedUser(db, 1, 'user', { maps: 'members-own-key' });
it('KEYFILL-004: ignores a non-admin key and writes no row at all', async () => {
const orm = await ormBeforeTarget();
try {
await seedUser(orm, 1, 'user', { maps: 'members-own-key' });
runMigrations(db);
await migrateTo(orm, TARGET);
// A member's key stays theirs — the resolver still finds it for them, and
// promoting it would hand their billing to the whole instance.
expect(setting(db, 'maps_api_key')).toBeUndefined();
db.close();
});
// A member's key stays theirs — the resolver still finds it for them, and
// promoting it would hand their billing to the whole instance.
expect(await setting(orm, 'maps_api_key')).toBeUndefined();
} finally {
await orm.close(true);
}
}, 30000);
it('KEYFILL-005: writes nothing on an install that never had a key', () => {
const db = freshDb();
seedUser(db, 1, 'admin');
it('KEYFILL-005: writes nothing on an install that never had a key', async () => {
const orm = await ormBeforeTarget();
try {
await seedUser(orm, 1, 'admin');
runMigrations(db);
await migrateTo(orm, TARGET);
expect(setting(db, 'maps_api_key')).toBeUndefined();
expect(setting(db, 'unsplash_api_key')).toBeUndefined();
db.close();
});
expect(await setting(orm, 'maps_api_key')).toBeUndefined();
expect(await setting(orm, 'unsplash_api_key')).toBeUndefined();
} finally {
await orm.close(true);
}
}, 30000);
it('KEYFILL-006: leaves a column alone once a member holds a key of their own', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'admins-own-google', unsplash: 'admins-own-unsplash' });
seedUser(db, 7, 'user', { maps: 'members-own-google' });
it('KEYFILL-006: leaves a column alone once a member holds a key of their own', async () => {
const orm = await ormBeforeTarget();
try {
await seedUser(orm, 1, 'admin', { maps: 'admins-own-google', unsplash: 'admins-own-unsplash' });
await seedUser(orm, 7, 'user', { maps: 'members-own-google' });
runMigrations(db);
await migrateTo(orm, TARGET);
// Member 7 pays for their own Google key. Promoting the admin's would put
// every one of their searches on his key and his bill, because the instance
// row is resolved before their own column.
expect(setting(db, 'maps_api_key')).toBeUndefined();
// Decided per column: nobody else has an Unsplash key, so that one really
// was the whole install's and stays it.
expect(setting(db, 'unsplash_api_key')).toBe('admins-own-unsplash');
const row = db.prepare('SELECT maps_api_key FROM users WHERE id = 7').get() as { maps_api_key: string };
expect(row.maps_api_key).toBe('members-own-google');
db.close();
});
// Member 7 pays for their own Google key. Promoting the admin's would put
// every one of their searches on his key and his bill, because the instance
// row is resolved before their own column.
expect(await setting(orm, 'maps_api_key')).toBeUndefined();
// Decided per column: nobody else has an Unsplash key, so that one really
// was the whole install's and stays it.
expect(await setting(orm, 'unsplash_api_key')).toBe('admins-own-unsplash');
const rows = await rawQuery<{ maps_api_key: string }>(orm, 'SELECT maps_api_key FROM users WHERE id = 7');
expect(rows[0].maps_api_key).toBe('members-own-google');
} finally {
await orm.close(true);
}
}, 30000);
it('KEYFILL-007: two admins with their own keys both keep them', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'first-admin-google' });
seedUser(db, 2, 'admin', { maps: 'second-admin-google' });
it('KEYFILL-007: two admins with their own keys both keep them', async () => {
const orm = await ormBeforeTarget();
try {
await seedUser(orm, 1, 'admin', { maps: 'first-admin-google' });
await seedUser(orm, 2, 'admin', { maps: 'second-admin-google' });
runMigrations(db);
await migrateTo(orm, TARGET);
expect(setting(db, 'maps_api_key')).toBeUndefined();
const rows = db.prepare('SELECT maps_api_key FROM users ORDER BY id').all() as { maps_api_key: string }[];
expect(rows.map((r) => r.maps_api_key)).toEqual(['first-admin-google', 'second-admin-google']);
db.close();
});
expect(await setting(orm, 'maps_api_key')).toBeUndefined();
const rows = await rawQuery<{ maps_api_key: string }>(orm, 'SELECT maps_api_key FROM users ORDER BY id');
expect(rows.map((r) => r.maps_api_key)).toEqual(['first-admin-google', 'second-admin-google']);
} finally {
await orm.close(true);
}
}, 30000);
});
@@ -0,0 +1,52 @@
import { knownMigrationNames, unknownMigrations } from '../../../src/db/known-migrations';
import { refuseNewerDatabase } from '../../../src/db/legacy-baseline';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
describe('known migrations', () => {
it('KNOWNMIG-001: lists every migration this build ships, by its recorded name', () => {
const known = knownMigrationNames();
expect(known.has('Migration20200101000000_baseline_schema')).toBe(true);
expect(known.has('Migration20200101042000_tours')).toBe(true);
expect(known.has('Migration20200101042900_tour_planned_total_duration')).toBe(true);
expect(known.has('Migration20200101043000_tour_break_additional_duration')).toBe(true);
expect(known.has('Migration20200101043100_an_imported_tour_has_no_hiking_difficulty')).toBe(true);
expect(known.has('Migration20200101043200_via_ferrata_tiles_outlive_a_restart')).toBe(true);
expect(known.has('Migration20200101043300_a_tour_leg_can_follow_a_via_ferrata')).toBe(true);
expect(known.has('Migration20200101043400_wanderer_connection_and_tour_sources')).toBe(true);
expect(known.has('Migration20200101043500_wanderer_difficulty_on_the_sac_scale')).toBe(true);
expect(known.has('Migration20200101043600_a_tour_remembers_the_import_it_was_derived_from')).toBe(true);
expect(known.has('Migration20200101043700_an_import_planned_over_keeps_its_recorded_track')).toBe(true);
expect(known.has('Migration20200101043800_a_tour_records_where_it_came_from')).toBe(true);
expect(known.has('Migration20200101043900_a_tour_can_be_paddled')).toBe(true);
expect(known.size).toBe(fs.readdirSync(path.join(__dirname, '../../../src/db/migrations')).length);
});
it('KNOWNMIG-002: reads compiled files too, and ignores maps, declarations and strangers', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-known-migrations-'));
try {
for (const file of [
'Migration20200101000000_a.js',
'Migration20200101000000_a.js.map',
'Migration20200101000100_b.d.ts',
'README.md',
]) {
fs.writeFileSync(path.join(dir, file), '');
}
expect([...knownMigrationNames(dir)]).toEqual(['Migration20200101000000_a']);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it('KNOWNMIG-003: names only what this build does not ship, and refuses on it', () => {
const known = new Set(['Migration1_a', 'Migration2_b']);
expect(unknownMigrations(['Migration1_a', 'Migration3_c'], known)).toEqual(['Migration3_c']);
expect(() => refuseNewerDatabase(['Migration1_a', 'Migration2_b'], known)).not.toThrow();
expect(() => refuseNewerDatabase(['Migration1_a', 'Migration3_c'], known)).toThrow(/newer TREK/);
expect(() => refuseNewerDatabase(['Migration1_a', 'Migration3_c'], known)).toThrow(/or by a development build/);
});
});
@@ -0,0 +1,336 @@
/**
* The legacy step → migration map and the baseline that uses it
* (`src/db/legacy-baseline.ts`, Plan 4 final review B1).
*
* The map is derived from the migrations' own `Legacy migration step N`
* docstrings; LEGACYMAP-001/002 pin that derivation against the files on disk
* so a new migration that mis-numbers, duplicates or drops a step fails here
* rather than on somebody's upgrade. The rest pin the fail-closed paths.
* The end-to-end upgrade of real legacy databases is
* `tests/integration/legacy-upgrade-v*.test.ts`.
*/
import { buildLegacyStepMap, migrateToHead, planLegacyBaseline } from '../../../src/db/legacy-baseline';
import {
createMigrationOrm,
migrateTo,
migratorOf,
pendingNames,
rawExec,
rawQuery,
} from '../../helpers/migration-step';
import type { MigrationInfo } from '@mikro-orm/core';
import type { MikroORM } from '@mikro-orm/sqlite';
import fs from 'node:fs';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
const MIGRATIONS = path.join(__dirname, '../../../src/db/migrations');
const BASELINE = 'Migration20200101000000_baseline_schema';
/** The migrations that carry no legacy step: the baseline, and the post-legacy ones every upgrade runs. */
const UNNUMBERED = [
BASELINE,
'Migration20200101040200_trek_photo_cache_meta_cache_key_not_null',
'Migration20200101042000_tours',
'Migration20200101042100_a_trip_reminder_remembers_it_was_sent',
'Migration20200101042200_an_index_on_every_foreign_key',
'Migration20200101042300_every_tour_type_the_contract_names',
'Migration20200101042400_one_account_per_email_whatever_its_case',
'Migration20200101042500_a_cron_tick_runs_in_one_process',
'Migration20200101042600_a_session_row_per_sign_in',
'Migration20200101042700_timestamps_stored_in_one_spelling',
'Migration20200101042800_an_email_the_account_typed_in_itself',
'Migration20200101042900_tour_planned_total_duration',
'Migration20200101043000_tour_break_additional_duration',
'Migration20200101043100_an_imported_tour_has_no_hiking_difficulty',
'Migration20200101043200_via_ferrata_tiles_outlive_a_restart',
'Migration20200101043300_a_tour_leg_can_follow_a_via_ferrata',
'Migration20200101043400_wanderer_connection_and_tour_sources',
'Migration20200101043500_wanderer_difficulty_on_the_sac_scale',
'Migration20200101043600_a_tour_remembers_the_import_it_was_derived_from',
'Migration20200101043700_an_import_planned_over_keeps_its_recorded_track',
'Migration20200101043800_a_tour_records_where_it_came_from',
'Migration20200101043900_a_tour_can_be_paddled',
'Migration20200101044000_a_paddle_tour_plans_its_portages_and_locks',
'Migration20200101044100_paddle_obstacles_from_openstreetmap',
'Migration20200101044200_a_paddle_tour_records_its_obstacle_decisions',
'Migration20200101044300_a_trip_links_a_journal',
'Migration20200101044400_a_paddle_region_builds_its_water_network',
'Migration20200101044500_a_tour_waypoint_can_shape_the_route',
'Migration20200101044600_a_paddle_tour_remembers_how_it_crosses_lakes',
'Migration20200101044700_paddle_water_data_loads_where_a_paddler_plans',
'Migration20200101044800_a_tour_counts_its_revisions',
'Migration20200101044900_a_tour_waypoint_can_be_a_place_of_the_trip',
'Migration20200101045000_a_hike_keeps_its_routing_preferences',
'Migration20200101045100_a_tour_remembers_the_trip_it_was_taken_from',
'Migration20200101045200_a_tour_can_be_ridden',
'Migration20200101045300_a_tour_can_be_a_city_walk',
'Migration20200101045400_a_tour_waypoint_remembers_the_kind_of_place_it_was_found_as',
'Migration20200101045500_a_hike_can_be_marked_as_a_winter_activity',
'Migration20200101045510_a_tour_can_be_a_run',
'Migration20200101045520_a_tour_can_be_a_ski_track',
'Migration20200101045600_a_tour_can_be_ridden_on_horseback',
'Migration20200101045700_a_tour_records_the_changes_saved_from_a_proposal',
'Migration20200101045710_a_saved_tour_change_can_be_taken_back',
'Migration20200101045900_a_tour_keeps_the_track_it_was_done_with',
'Migration20200101045910_a_tour_can_be_left_out_of_ones_activities',
'Migration20200101046000_a_tour_waypoint_can_end_a_stage',
'Migration20200101046010_a_day_can_hold_one_stage_of_a_tour',
'Migration20200101046100_a_collection_keeps_whole_tours',
'Migration20200101046110_a_tour_points_at_its_packing_list',
'Migration20200101046120_a_wanderer_connection_can_watch_its_sources',
'Migration20200101046130_snowshoeing_and_winter_hiking_are_ski_disciplines',
'Migration20200101046140_tours_are_on_for_every_install',
'Migration20200101046150_a_ski_tour_keeps_its_piste_router_options',
'Migration20200101046160_a_journey_keeps_its_recorded_days',
'Migration20200101046170_a_journey_entry_remembers_the_stays_it_came_from',
'Migration20200101046180_journeys_can_prepare_recorded_days',
'Migration20200101046190_a_journey_share_can_show_its_plan_and_recordings',
'Migration20200101046200_a_tour_draft_lives_on_the_account',
'Migration20200101046200_a_user_can_connect_an_ai_provider',
'Migration20200101046210_the_trip_assistant_remembers_its_conversations',
'Migration20200101046220_a_chat_message_can_say_it_came_from_the_assistant',
'Migration20200101046230_an_admin_can_share_a_chatgpt_plan',
'Migration20200101046240_a_photo_keeps_its_quality_signals',
'Migration20200101046250_an_assistant_conversation_can_be_about_a_journey',
'Migration20200101046260_a_book_keeps_its_last_revisions',
'Migration20200101046270_a_photo_knows_its_colours_and_calm_areas',
'Migration20200101046280_an_assistant_conversation_can_be_about_no_one_trip',
'Migration20200101046290_a_removed_member_cannot_rejoin_by_invite_link',
'Migration20200101046300_an_attached_file_stays_with_its_conversation',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
const LEGACY_FINAL_STEP = 258;
/** Synthetic migrations whose "source" is the text given, for the fail-closed cases. */
function fake(sources: Array<[string, string]>): { list: MigrationInfo[]; read: (p: string) => string } {
const byPath = new Map(sources.map(([name, text]) => [`/fake/${name}.ts`, text]));
return {
list: sources.map(([name]) => ({ name, path: `/fake/${name}.ts` })),
read: (p) => byPath.get(p) ?? '',
};
}
describe('the legacy step map', () => {
it('LEGACYMAP-001: every numbered migration maps to exactly one step, steps 1..258 are all present, in order, behind the baseline', async () => {
const orm = await createMigrationOrm();
try {
const all = await migratorOf(orm).getPending();
const map = buildLegacyStepMap(all);
expect(map.finalStep).toBe(LEGACY_FINAL_STEP);
expect([...map.steps.keys()]).toEqual(Array.from({ length: LEGACY_FINAL_STEP }, (_, i) => i + 1));
expect(new Set(map.steps.values()).size).toBe(LEGACY_FINAL_STEP);
expect(map.baseline).toEqual([BASELINE]);
// The unnumbered ones: the baseline, and the post-legacy migrations that
// must always run on an upgraded install.
const numbered = new Set(map.steps.values());
expect(all.map((m) => m.name).filter((name) => !numbered.has(name))).toEqual(UNNUMBERED);
expect(map.steps.get(242)).toBe('Migration20200101040300_a_booked_night_finally_took_the_seat_a_new');
expect(map.steps.get(243)).toBe('Migration20200101040400_immich_learns_the_switch_synology_airtrail_and');
expect(map.steps.get(258)).toBe('Migration20200101041900_a_journey_that_puts_an_entry_on');
expect(map.steps.get(26)).toBe('Migration20200101002600_day_assignments_add_assignment_time');
} finally {
await orm.close(true);
}
});
it('LEGACYMAP-002: the map agrees with an independent read of the files on disk', async () => {
const onDisk = new Map<string, number>();
for (const file of fs.readdirSync(MIGRATIONS).filter((f) => f.endsWith('.ts'))) {
const steps = [
...fs.readFileSync(path.join(MIGRATIONS, file), 'utf8').matchAll(/Legacy migration step (\d+)\b/g),
];
expect(steps.length, file).toBeLessThanOrEqual(1);
if (steps.length === 1) onDisk.set(file.replace(/\.ts$/, ''), Number(steps[0]![1]));
}
const orm = await createMigrationOrm();
try {
const map = buildLegacyStepMap(await migratorOf(orm).getPending());
expect(new Map([...map.steps].map(([step, name]) => [name, step]))).toEqual(onDisk);
} finally {
await orm.close(true);
}
});
it('LEGACYMAP-003: refuses a step claimed twice', () => {
const { list, read } = fake([
['M0_base', ''],
['M1', 'Legacy migration step 1'],
['M2', 'Legacy migration step 1'],
]);
expect(() => buildLegacyStepMap(list, read)).toThrow(/legacy step 1 is claimed by both M1 and M2/);
});
it('LEGACYMAP-004: refuses a gap in the steps', () => {
const { list, read } = fake([
['M0_base', ''],
['M1', 'Legacy migration step 1'],
['M3', 'Legacy migration step 3'],
]);
expect(() => buildLegacyStepMap(list, read)).toThrow(/no migration carries legacy step 2/);
});
it('LEGACYMAP-005: refuses a migration naming two steps, and steps applied out of order', () => {
const two = fake([
['M0_base', ''],
['M1', 'Legacy migration step 1, formerly Legacy migration step 2'],
]);
expect(() => buildLegacyStepMap(two.list, two.read)).toThrow(/M1 names more than one legacy step \(1, 2\)/);
const swapped = fake([
['M0_base', ''],
['M1', 'Legacy migration step 2'],
['M2', 'Legacy migration step 1'],
]);
expect(() => buildLegacyStepMap(swapped.list, swapped.read)).toThrow(
/M2 \(legacy step 1\) sorts after legacy step 2/,
);
});
it('LEGACYMAP-006: refuses no baseline, no numbered step at all, and a migration without a source file', () => {
const noBase = fake([['M1', 'Legacy migration step 1']]);
expect(() => buildLegacyStepMap(noBase.list, noBase.read)).toThrow(
/no baseline migration sorts ahead of legacy step 1/,
);
const none = fake([['M0_base', '']]);
expect(() => buildLegacyStepMap(none.list, none.read)).toThrow(/no migration names a legacy step/);
expect(() => buildLegacyStepMap([{ name: 'M0_classOnly' }])).toThrow(/M0_classOnly has no source file/);
});
});
describe('planLegacyBaseline / migrateToHead', () => {
let orm: MikroORM;
beforeEach(async () => {
orm = await createMigrationOrm();
});
afterEach(async () => {
await orm.close(true);
});
const baseline = () => planLegacyBaseline(orm.em.getConnection(), migratorOf(orm));
const migrate = () => migrateToHead(orm.em.getConnection(), migratorOf(orm));
const recorded = async () =>
(await rawQuery<{ name: string }>(orm, 'SELECT name FROM mikro_orm_migrations ORDER BY id')).map((r) => r.name);
it('LEGACYBASE-001: a fresh database (no schema_version) is left alone', async () => {
await expect(baseline()).resolves.toEqual([]);
expect(await recorded()).toEqual([]);
});
it('LEGACYBASE-002: a database the migrator already knows is left alone, even though it carries schema_version', async () => {
await migrateTo(orm, 'Migration20200101020900_create_schema_version_new');
await rawExec(orm, 'INSERT INTO schema_version (version) VALUES (241)');
const before = await recorded();
await expect(baseline()).resolves.toEqual([]);
expect(await recorded()).toEqual(before);
});
it('LEGACYBASE-003: a legacy database at step N plans steps 1..N in application order — never the baseline — and writes nothing', async () => {
const all = await pendingNames(orm);
await rawExec(orm, 'CREATE TABLE schema_version (version INTEGER NOT NULL)');
await rawExec(orm, 'INSERT INTO schema_version (version) VALUES (10)');
// Review N1: the legacy runner ran createTables() before its steps on every
// boot, and ~30 tables exist only in the baseline, so it must run, not be marked.
await expect(baseline()).resolves.toEqual(all.slice(1, 11));
expect(all[0]).toBe(BASELINE);
expect(await recorded()).toEqual([]);
});
it('LEGACYBASE-004: refuses a schema_version newer than the last legacy step, and records nothing', async () => {
await rawExec(orm, 'CREATE TABLE schema_version (version INTEGER NOT NULL)');
await rawExec(orm, `INSERT INTO schema_version (version) VALUES (${LEGACY_FINAL_STEP + 1})`);
await expect(baseline()).rejects.toThrow(
`[DB] Refusing to boot: schema_version 259 is newer than the last legacy step this release knows (258)`,
);
expect(await recorded()).toEqual([]);
});
it.each([
['0', '(0)', /schema_version 0 is not a legacy step/],
['a text value', "('205')", /schema_version 205 is not a legacy step/],
['a fraction', '(20.5)', /schema_version 20.5 is not a legacy step/],
['two rows', '(205), (206)', /schema_version holds 2 rows/],
['no row', null, /schema_version holds 0 rows/],
])(
'LEGACYBASE-005: refuses an unmappable schema_version (%s), and records nothing',
async (_label, values, error) => {
await rawExec(orm, 'CREATE TABLE schema_version (version)');
if (values) await rawExec(orm, `INSERT INTO schema_version (version) VALUES ${values}`);
await expect(baseline()).rejects.toThrow(error);
expect(await recorded()).toEqual([]);
},
);
it('LEGACYBASE-006: the baseline rows commit with the run — a failed first run leaves nothing recorded, so the next boot baselines again', async () => {
const all = await pendingNames(orm);
await rawExec(orm, 'CREATE TABLE schema_version (version INTEGER NOT NULL)');
await rawExec(orm, 'INSERT INTO schema_version (version) VALUES (241)');
// An obstacle for Migration20200101040200's rebuild, which runs after the baseline.
await rawExec(orm, 'CREATE TABLE trek_photo_cache_meta_new (x INTEGER)');
await expect(migrate()).rejects.toThrow();
expect(await recorded()).toEqual([]);
// Nothing half-done: the next boot still sees a legacy install and plans the same steps.
await expect(baseline()).resolves.toEqual(all.filter((name) => name !== BASELINE).slice(0, 241));
expect(await recorded()).toEqual([]);
});
it('LEGACYBASE-007: an install the positional runner left past step 242 is baselined to its step, never refused or replayed', async () => {
const all = await pendingNames(orm);
const numbered = all.filter((name) => !UNNUMBERED.includes(name));
await rawExec(orm, 'CREATE TABLE schema_version (version INTEGER NOT NULL)');
await rawExec(orm, 'INSERT INTO schema_version (version) VALUES (250)');
const planned = await baseline();
expect(planned).toEqual(numbered.slice(0, 250));
expect(planned.at(-1)).toBe('Migration20200101041100_half_company_holidays_0_5_covers_the');
expect(await recorded()).toEqual([]);
});
it('LEGACYBASE-008: refuses a database a newer TREK migrated, before applying anything', async () => {
await migrate();
await rawExec(
orm,
"INSERT INTO mikro_orm_migrations (name, executed_at) VALUES ('Migration20990101000000_from_a_newer_release', CURRENT_TIMESTAMP)",
);
const before = await recorded();
await expect(migrate()).rejects.toThrow(
/Refusing to boot: the database was migrated by a newer TREK \(1 unknown migration\(s\), latest Migration20990101000000_from_a_newer_release\)/,
);
expect(await recorded()).toEqual(before);
});
it('LEGACYBASE-009: a database at head of this build boots again without complaint', async () => {
await migrate();
await expect(migrate()).resolves.toBeUndefined();
});
it.each([
[246, 242],
[243, 242],
[217, 215],
])(
'LEGACYBASE-010: a pre-ORM Tours branch database at schema_version %i is baselined to upstream step %i',
async (version, upstream) => {
const all = await pendingNames(orm);
const numbered = all.filter((name) => !UNNUMBERED.includes(name));
await rawExec(orm, 'CREATE TABLE schema_version (version INTEGER NOT NULL)');
await rawExec(orm, `INSERT INTO schema_version (version) VALUES (${version})`);
await rawExec(orm, 'CREATE TABLE tour_types (key TEXT PRIMARY KEY)');
expect(await baseline()).toEqual(numbered.slice(0, upstream));
},
);
it('LEGACYBASE-011: the same schema_version without the Tours tables is an upstream database and keeps its step', async () => {
const all = await pendingNames(orm);
const numbered = all.filter((name) => !UNNUMBERED.includes(name));
await rawExec(orm, 'CREATE TABLE schema_version (version INTEGER NOT NULL)');
await rawExec(orm, 'INSERT INTO schema_version (version) VALUES (244)');
expect(await baseline()).toEqual(numbered.slice(0, 244));
});
});
@@ -10,22 +10,20 @@
* key, decrypt_api_key returns null on the next read, and the instance quietly
* behaves as if no key were configured. This pins the copy instead.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { INSTANCE_API_KEY_NAMES } from '../../../src/nest/settings/instance-api-keys';
import { storageSecretFields } from '@trek/shared';
import Database from 'better-sqlite3';
import { execFileSync } from 'node:child_process';
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
import { INSTANCE_API_KEY_NAMES } from '../../../src/nest/settings/instance-api-keys';
import { storageSecretFields } from '@trek/shared';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
const SERVER_ROOT = path.join(__dirname, '..', '..', '..');
const script = fs.readFileSync(
path.join(__dirname, '..', '..', '..', 'scripts', 'migrate-encryption.ts'),
'utf8',
);
const script = fs.readFileSync(path.join(__dirname, '..', '..', '..', 'scripts', 'migrate-encryption.ts'), 'utf8');
// The app_settings loop only, so a name that happens to appear elsewhere in the
// script (a users column of the same name, a comment) cannot satisfy the test.
@@ -95,6 +93,19 @@ describe('migrate-encryption.ts app_settings parity', () => {
}
});
// VapidKeysService stores the Web Push signing key with encrypt_api_key.
// Missed by a rotation it no longer decrypts, and push stays off on every
// device until the old key is back.
it('ROTPAR-012: rotates the stored Web Push private key', () => {
const vapid = fs.readFileSync(
path.join(SERVER_ROOT, 'src', 'nest', 'notifications', 'push', 'vapid-keys.service.ts'),
'utf8',
);
expect(vapid).toContain("VAPID_PRIVATE_KEY_SETTING = 'web_push_vapid_private_key'");
expect(vapid).toContain('encrypt_api_key(keys.privateKey)');
expect(appSettingsLoop).toContain("'web_push_vapid_private_key'");
});
it('ROTPAR-003: the canonical list is not empty, so ROTPAR-001 cannot pass vacuously', () => {
expect(INSTANCE_API_KEY_NAMES.length).toBeGreaterThan(0);
});
@@ -133,7 +144,7 @@ describe('migrate-encryption.ts app_settings parity', () => {
expect(script).toContain('access_token');
expect(script).toContain('refresh_token');
expect(script).toContain('plugin_settings_fields');
expect(script).toContain("UPDATE plugins SET config = ?");
expect(script).toContain('UPDATE plugins SET config = ?');
expect(script).toContain('plugin_user_config');
});
@@ -152,6 +163,16 @@ describe('migrate-encryption.ts app_settings parity', () => {
expect(script).toContain('SELECT id, webhook_secret FROM trip_document_links');
expect(script).toContain('UPDATE trip_document_links SET webhook_secret = ?');
});
// ai-secrets.ts seals every AI connection credential (an API key, a ChatGPT
// sign-in's tokens) in one blob. Missed by a rotation, the instance's
// connection needs its key again and every ChatGPT user a new sign-in.
it('ROTPAR-014: rotates the AI connection secrets blob', () => {
const aiSecrets = fs.readFileSync(path.join(SERVER_ROOT, 'src', 'nest', 'ai-connections', 'ai-secrets.ts'), 'utf8');
expect(aiSecrets).toContain('maybe_encrypt_api_key');
expect(script).toContain('SELECT id, secrets FROM ai_connections');
expect(script).toContain('UPDATE ai_connections SET secrets = ?');
});
});
describe('migrate-encryption.ts storage.backends: malformed shape', () => {
@@ -183,10 +204,9 @@ describe('migrate-encryption.ts storage.backends: malformed shape', () => {
`);
// Valid JSON, but not an array — the malformed shape the fix must not
// silently skip.
seed.prepare('INSERT INTO app_settings (key, value) VALUES (?, ?)').run(
'storage.backends',
JSON.stringify({ not: 'an array' }),
);
seed
.prepare('INSERT INTO app_settings (key, value) VALUES (?, ?)')
.run('storage.backends', JSON.stringify({ not: 'an array' }));
seed.close();
let output: string;
@@ -275,24 +295,24 @@ describe('migrate-encryption.ts rotates the stores the app writes', () => {
const seed = new Database(dbPath);
seed.exec(BASE_SCHEMA);
seed.prepare('INSERT INTO users (id, airtrail_api_key) VALUES (1, ?)').run(encryptWith('old-key', 'at-token'));
seed.prepare('INSERT INTO settings (user_id, key, value) VALUES (1, ?, ?)').run('llm_api_key', encryptWith('old-key', 'sk-llm'));
seed.prepare('INSERT INTO plugins (id, config) VALUES (?, ?)').run(
'koffi',
JSON.stringify({ api_key: encryptWith('old-key', 'plugin-secret'), server: 'https://h' }),
);
seed.prepare('INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES (?, ?, ?, ?)').run('koffi', 'api_key', 'instance', 1);
seed.prepare('INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES (?, ?, ?, ?)').run('koffi', 'token', 'user', 1);
seed.prepare('INSERT INTO plugin_user_config (plugin_id, user_id, config) VALUES (?, ?, ?)').run(
'koffi',
1,
JSON.stringify({ token: encryptWith('old-key', 'user-secret') }),
);
seed.prepare('INSERT INTO plugin_oauth_tokens (plugin_id, user_id, access_token, refresh_token) VALUES (?, ?, ?, ?)').run(
'koffi',
1,
encryptWith('old-key', 'access'),
encryptWith('old-key', 'refresh'),
);
seed
.prepare('INSERT INTO settings (user_id, key, value) VALUES (1, ?, ?)')
.run('llm_api_key', encryptWith('old-key', 'sk-llm'));
seed
.prepare('INSERT INTO plugins (id, config) VALUES (?, ?)')
.run('koffi', JSON.stringify({ api_key: encryptWith('old-key', 'plugin-secret'), server: 'https://h' }));
seed
.prepare('INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES (?, ?, ?, ?)')
.run('koffi', 'api_key', 'instance', 1);
seed
.prepare('INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES (?, ?, ?, ?)')
.run('koffi', 'token', 'user', 1);
seed
.prepare('INSERT INTO plugin_user_config (plugin_id, user_id, config) VALUES (?, ?, ?)')
.run('koffi', 1, JSON.stringify({ token: encryptWith('old-key', 'user-secret') }));
seed
.prepare('INSERT INTO plugin_oauth_tokens (plugin_id, user_id, access_token, refresh_token) VALUES (?, ?, ?, ?)')
.run('koffi', 1, encryptWith('old-key', 'access'), encryptWith('old-key', 'refresh'));
seed.close();
execFileSync(process.execPath, ['--import', 'tsx', 'scripts/migrate-encryption.ts'], {
@@ -317,12 +337,16 @@ describe('migrate-encryption.ts rotates the stores the app writes', () => {
expect(decryptWith('new-key', tokens.access_token)).toBe('access');
expect(decryptWith('new-key', tokens.refresh_token)).toBe('refresh');
const pluginConfig = JSON.parse((after.prepare("SELECT config AS v FROM plugins WHERE id = 'koffi'").get() as { v: string }).v);
const pluginConfig = JSON.parse(
(after.prepare("SELECT config AS v FROM plugins WHERE id = 'koffi'").get() as { v: string }).v,
);
expect(decryptWith('new-key', pluginConfig.api_key)).toBe('plugin-secret');
// A non-secret field is left exactly as it was.
expect(pluginConfig.server).toBe('https://h');
const userConfig = JSON.parse((after.prepare('SELECT config AS v FROM plugin_user_config').get() as { v: string }).v);
const userConfig = JSON.parse(
(after.prepare('SELECT config AS v FROM plugin_user_config').get() as { v: string }).v,
);
expect(decryptWith('new-key', userConfig.token)).toBe('user-secret');
after.close();
}, 30000);
@@ -339,15 +363,17 @@ describe('migrate-encryption.ts rotates the stores the app writes', () => {
seed.exec(BASE_SCHEMA);
seed.exec(DOC_SYNC_SCHEMA);
const connectionBlob = JSON.stringify({ token: 'paperless-token', deviceId: 'dsm-device' });
seed.prepare('INSERT INTO document_connections (id, secrets) VALUES (1, ?)').run(encryptWith('old-key', connectionBlob));
seed
.prepare('INSERT INTO document_connections (id, secrets) VALUES (1, ?)')
.run(encryptWith('old-key', connectionBlob));
// A second run over a half-rotated database must not touch a row that is
// already readable under the new key, let alone re-encrypt it under the old.
const alreadyRotated = encryptWith('new-key', JSON.stringify({ token: 'nextcloud-app-password' }));
seed.prepare('INSERT INTO document_connections (id, secrets) VALUES (2, ?)').run(alreadyRotated);
seed.prepare('INSERT INTO document_connections (id, secrets) VALUES (3, NULL)').run();
seed.prepare('INSERT INTO trip_document_links (id, webhook_secret) VALUES (1, ?)').run(
encryptWith('old-key', JSON.stringify({ webhook: 'hook-secret' })),
);
seed
.prepare('INSERT INTO trip_document_links (id, webhook_secret) VALUES (1, ?)')
.run(encryptWith('old-key', JSON.stringify({ webhook: 'hook-secret' })));
seed.close();
const output = execFileSync(process.execPath, ['--import', 'tsx', 'scripts/migrate-encryption.ts'], {
@@ -359,17 +385,27 @@ describe('migrate-encryption.ts rotates the stores the app writes', () => {
});
const after = new Database(dbPath, { readonly: true });
const rotated = (after.prepare('SELECT secrets AS v FROM document_connections WHERE id = 1').get() as { v: string }).v;
const rotated = (after.prepare('SELECT secrets AS v FROM document_connections WHERE id = 1').get() as { v: string })
.v;
expect(decryptWith('old-key', rotated)).toBeNull();
expect(JSON.parse(decryptWith('new-key', rotated) ?? 'null')).toEqual({ token: 'paperless-token', deviceId: 'dsm-device' });
expect(JSON.parse(decryptWith('new-key', rotated) ?? 'null')).toEqual({
token: 'paperless-token',
deviceId: 'dsm-device',
});
const untouched = (after.prepare('SELECT secrets AS v FROM document_connections WHERE id = 2').get() as { v: string }).v;
const untouched = (
after.prepare('SELECT secrets AS v FROM document_connections WHERE id = 2').get() as { v: string }
).v;
expect(untouched).toBe(alreadyRotated);
const empty = (after.prepare('SELECT secrets AS v FROM document_connections WHERE id = 3').get() as { v: string | null }).v;
const empty = (
after.prepare('SELECT secrets AS v FROM document_connections WHERE id = 3').get() as { v: string | null }
).v;
expect(empty).toBeNull();
const webhook = (after.prepare('SELECT webhook_secret AS v FROM trip_document_links WHERE id = 1').get() as { v: string }).v;
const webhook = (
after.prepare('SELECT webhook_secret AS v FROM trip_document_links WHERE id = 1').get() as { v: string }
).v;
expect(JSON.parse(decryptWith('new-key', webhook) ?? 'null')).toEqual({ webhook: 'hook-secret' });
after.close();
@@ -378,4 +414,37 @@ describe('migrate-encryption.ts rotates the stores the app writes', () => {
expect(output).toMatch(/Already on new key:\s+1\b/);
expect(output).toContain('All secrets successfully re-encrypted.');
}, 30000);
it('ROTPAR-013: re-encrypts the AI Parsing addon key and moves the key file to the new key', () => {
const seed = new Database(dbPath);
seed.exec(BASE_SCHEMA);
seed.exec('CREATE TABLE addons (id TEXT PRIMARY KEY, config TEXT)');
seed
.prepare('INSERT INTO addons (id, config) VALUES (?, ?)')
.run('llm_parse', JSON.stringify({ provider: 'openai', apiKey: encryptWith('old-key', 'sk-addon') }));
seed.prepare('INSERT INTO addons (id, config) VALUES (?, ?)').run('packing', '{"x":1}');
seed.close();
const keyFile = path.join(path.dirname(dbPath), '.encryption_key');
fs.writeFileSync(keyFile, 'old-key');
execFileSync(process.execPath, ['--import', 'tsx', 'scripts/migrate-encryption.ts'], {
cwd: SERVER_ROOT,
env: { ...process.env, DB_PATH: dbPath },
input: ['old-key', 'new-key', 'yes', ''].join(String.fromCharCode(10)),
stdio: 'pipe',
encoding: 'utf8',
});
const after = new Database(dbPath, { readonly: true });
const llm = JSON.parse(
(after.prepare("SELECT config AS v FROM addons WHERE id = 'llm_parse'").get() as { v: string }).v,
);
expect(decryptWith('new-key', llm.apiKey)).toBe('sk-addon');
expect(llm.provider).toBe('openai');
const other = (after.prepare("SELECT config AS v FROM addons WHERE id = 'packing'").get() as { v: string }).v;
expect(other).toBe('{"x":1}');
after.close();
// The server refuses an ENCRYPTION_KEY that disagrees with this file.
expect(fs.readFileSync(keyFile, 'utf8')).toBe('new-key');
}, 30000);
});
@@ -1,200 +0,0 @@
/**
* Migration hygiene guardrails.
*
* These tests scan the migration source statically and fail when a NEW
* destructive operation (DROP TABLE / DROP COLUMN / TRUNCATE / DELETE FROM /
* ALTER ... DROP) is introduced, or when an empty/silent `catch` block creeps
* back into the migration runner.
*
* Migrations 1..N are append-only and immutable once shipped (the live schema
* has already applied them; rewriting an applied migration is a breaking
* change). The destructive statements that already exist were each reviewed
* and are legitimate — almost all are the standard SQLite "table rebuild"
* pattern (create *_new, copy rows, DROP old, RENAME), plus a handful of
* deliberate, data-preserving cleanups. They are recorded in
* ALLOWED_DESTRUCTIVE below with the reason. Anything not on that list is
* treated as a regression.
*/
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { createTestDb } from '../../helpers/test-db';
const MIGRATIONS_PATH = resolve(__dirname, '../../../src/db/migrations.ts');
const migrationsSource = readFileSync(MIGRATIONS_PATH, 'utf8');
/**
* Strip line and block comments so commented-out SQL (or prose mentioning
* "DROP TABLE") is never flagged. String/template contents are preserved —
* that is exactly where the real SQL lives.
*/
function stripComments(src: string): string {
return src
.replace(/\/\*[\s\S]*?\*\//g, ' ')
.replace(/(^|[^:])\/\/[^\n]*/g, '$1');
}
const scannableSource = stripComments(migrationsSource);
interface DestructiveHit {
/** Normalised signature used as the allowlist key, e.g. "DROP TABLE budget_items". */
signature: string;
/** The raw matched fragment, kept for diagnostics. */
fragment: string;
}
/**
* Detects destructive DDL/DML. For each match we build a normalised signature
* of "<OPERATION> <TARGET>" so cosmetic whitespace/quoting changes don't churn
* the allowlist, while a genuinely new target (or operation) shows up as a new
* signature.
*/
function findDestructiveStatements(src: string): DestructiveHit[] {
const hits: DestructiveHit[] = [];
const norm = (s: string) => s.replace(/[`"'\[\]]/g, '').replace(/\s+/g, ' ').trim();
// DROP TABLE [IF EXISTS] <name>
for (const m of src.matchAll(/DROP\s+TABLE\s+(IF\s+EXISTS\s+)?[`"'\[]?([A-Za-z_][\w]*)/gi)) {
hits.push({ signature: `DROP TABLE ${m[2]}`, fragment: norm(m[0]) });
}
// ALTER TABLE <t> DROP COLUMN <c> (and bare ALTER ... DROP <c>)
for (const m of src.matchAll(/ALTER\s+TABLE\s+[`"'\[]?([A-Za-z_][\w]*)[`"'\]]?\s+DROP\s+(COLUMN\s+)?[`"'\[]?([A-Za-z_][\w]*)/gi)) {
hits.push({ signature: `ALTER TABLE ${m[1]} DROP COLUMN ${m[3]}`, fragment: norm(m[0]) });
}
// TRUNCATE <t> (not valid SQLite, but guard anyway)
for (const m of src.matchAll(/TRUNCATE\s+(TABLE\s+)?[`"'\[]?([A-Za-z_][\w]*)/gi)) {
hits.push({ signature: `TRUNCATE ${m[2]}`, fragment: norm(m[0]) });
}
// DELETE FROM <t>
for (const m of src.matchAll(/DELETE\s+FROM\s+[`"'\[]?([A-Za-z_][\w]*)/gi)) {
hits.push({ signature: `DELETE FROM ${m[1]}`, fragment: norm(m[0]) });
}
return hits;
}
/**
* Allowlist of destructive statements already present and reviewed as
* legitimate. Keyed by normalised signature. NEVER add to this without a
* code-review-level justification — that is the whole point of the guard.
*
* Rebuild = standard SQLite 12-step ALTER emulation: CREATE <t>_new,
* INSERT ... SELECT to copy rows, DROP old <t>, ALTER ... RENAME <t>_new TO <t>.
* Rows are preserved across the rebuild.
*/
const ALLOWED_DESTRUCTIVE: Record<string, string> = {
// ── table rebuilds (data preserved) ──────────────────────────────────────
'DROP TABLE budget_items':
'Migration 12: rebuild to drop a stale NOT NULL DEFAULT on persons/days. Rows copied first.',
'DROP TABLE oauth_clients':
'Make oauth_clients.user_id nullable for anonymous DCR clients. Rebuild, rows copied.',
'DROP TABLE idempotency_keys':
'Widen PK to (key,user_id,method,path). Rebuild, rows copied (old PK is a subset).',
'DROP TABLE day_accommodations':
'Make place_id nullable + ON DELETE SET NULL. Rebuild, rows copied.',
'DROP TABLE schema_version':
'Add surrogate id PK to schema_version. Rebuild, version row copied.',
// ── photo/journey table rebuilds (data preserved) ────────────────────────
'DROP TABLE trip_photos':
'trip_photos normalisation + later photo_id FK refactor. Rebuilds, rows copied.',
'DROP TABLE trip_album_links':
'Normalise trip_album_links to provider+album_id schema. Rebuild, rows copied.',
'DROP TABLE journey_photos':
'Journey photo provider support + photo_id FK refactor. Rebuilds, rows copied.',
'DROP TABLE journey_photos_old':
'Migration 121 gallery refactor: drops the temporary *_old backup after backfill.',
'DROP TABLE journey_location_trail':
'Migration 87 journey rebuild: old data SELECTed into memory and re-inserted into new schema.',
'DROP TABLE journey_entries':
'Migration 87 journey rebuild: old data SELECTed into memory and re-inserted into new schema.',
'DROP TABLE journey_checkins':
'Migration 87 journey rebuild: old data SELECTed into memory and re-inserted into new schema.',
'DROP TABLE journey_members':
'Migration 87 journey rebuild: old data SELECTed into memory and re-inserted into new schema.',
'DROP TABLE journey_trips':
'Migration 87 journey rebuild: old data SELECTed into memory and re-inserted into new schema.',
'DROP TABLE journeys':
'Migration 87 journey rebuild: old data SELECTed into memory and re-inserted into new schema.',
'DROP TABLE roadtrip_day_boundaries':
'Rebuild to lift the day_number CHECK that mirrored the old 365-day trip limit (#2403). Rows copied first.',
// ── template/cache scaffolding drops (no user content lost) ──────────────
'DROP TABLE packing_template_items':
'IF EXISTS drop to recreate the template-items table with a category_id FK. Template scaffolding.',
'DROP TABLE notification_preferences':
'IF EXISTS drop AFTER migration 71 copied the data into notification_channel_preferences.',
// ── guarded column drop ──────────────────────────────────────────────────
'ALTER TABLE photo_providers DROP COLUMN config':
'Drop generated-only config column; guarded by a PRAGMA table_info check that it exists.',
// ── targeted, bounded DELETEs ────────────────────────────────────────────
'DELETE FROM oauth_tokens':
'SEC-H6: DELETE ... WHERE audience IS NULL — purge pre-audience-binding tokens that the MCP server now rejects.',
'DELETE FROM journey_entries':
"Migration 121: DELETE ... WHERE title IN ('Gallery','[Trip Photos]') — remove synthetic wrapper entries replaced by the gallery model.",
'DELETE FROM place_regions':
'Atlas enclave fix: DELETE ... WHERE place_id IN (places inside specific enclave boxes) — invalidate stale region cache; re-resolved on next request.',
'DELETE FROM visited_regions':
'Atlas geoBoundaries swap (#1119): DELETE ... WHERE id = ? — after UPDATE OR IGNORE re-codes a manually-marked region to its current code, drop only the single leftover row whose UNIQUE(user_id, region_code) collision caused the update to be skipped (a duplicate of a region the user already has).',
'DELETE FROM hidden_regions':
'Guangdong rename (#2284): DELETE ... WHERE region_code = the retired CN-GUANGZHOUPROVINCE, run right after an UPDATE OR IGNORE re-codes the tombstone. Only a row the update had to skip survives to here, and it can only be skipped because UNIQUE(user_id, region_code) already holds the same tombstone under the correct code, so the user keeps the region hidden either way.',
'DELETE FROM reservation_day_positions':
'DELETE ... WHERE the row joins a reservation and a day sitting on different trips. The table has no trip_id and its two foreign keys only require the ids to exist, so a pair that never belonged together was storable; the writer scopes to the trip now and this clears what earlier builds allowed. Bounded by the join — a row whose reservation and day agree on their trip is untouched.',
};
describe('migration hygiene — destructive operation guard', () => {
it('introduces no destructive migration statement outside the reviewed allowlist', () => {
const hits = findDestructiveStatements(scannableSource);
const offenders = hits.filter((h) => !(h.signature in ALLOWED_DESTRUCTIVE));
if (offenders.length > 0) {
const detail = offenders
.map((o) => ` • ${o.signature} (matched: "${o.fragment}")`)
.join('\n');
throw new Error(
`Found ${offenders.length} destructive migration statement(s) that are not on the ` +
`reviewed allowlist in tests/unit/db/migration-hygiene.test.ts.\n` +
`Migrations are append-only and destructive DDL/DML risks data loss on upgrade.\n` +
`If the statement is genuinely safe (e.g. a SQLite table rebuild that copies rows ` +
`first, or a tightly-bounded cache/cleanup DELETE), add its signature to ` +
`ALLOWED_DESTRUCTIVE with a justification.\n\nOffending statement(s):\n${detail}`,
);
}
expect(offenders).toEqual([]);
});
it('every allowlist entry still corresponds to a real statement (no dead allowlist rows)', () => {
const present = new Set(findDestructiveStatements(scannableSource).map((h) => h.signature));
const dead = Object.keys(ALLOWED_DESTRUCTIVE).filter((sig) => !present.has(sig));
expect(dead, `Allowlist entries no longer found in migrations.ts: ${dead.join(', ')}`).toEqual([]);
});
});
describe('migration hygiene — no silently swallowed errors', () => {
it('contains no empty catch block (catch must at least log)', () => {
// Matches `catch {}` and `catch (e) {}` where the body is only whitespace.
const emptyCatch = scannableSource.match(/catch\s*(\([^)]*\))?\s*\{\s*\}/g) ?? [];
expect(
emptyCatch,
`migrations.ts must not swallow errors silently. Give each catch a log line ` +
`(e.g. console.warn('[migrations] ...', err)). Found: ${emptyCatch.length}`,
).toEqual([]);
});
});
describe('migration hygiene — full chain smoke', () => {
it('migrates a fresh in-memory database from zero to the latest version', () => {
// createTestDb() runs createTables() + the entire runMigrations() chain.
// This proves the logging edits in the previously-empty catch blocks do
// not change control flow / break the migration runner.
const db = createTestDb();
try {
const row = db.prepare('SELECT version FROM schema_version').get() as { version: number };
expect(row.version).toBeGreaterThan(0);
} finally {
db.close();
}
});
});
@@ -1,55 +0,0 @@
/**
* The schema_version bump must commit with the migration that earned it.
*
* If it lands in a statement of its own, a crash between the two leaves the
* schema advanced and the version stale, and the next boot replays a step that
* is not idempotent (an INSERT INTO app_settings, say) and exits 1 forever.
*/
import { describe, it, expect, vi } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
function migratedDb(): Database.Database {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA busy_timeout = 5000');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
runMigrations(db);
return db;
}
describe('migration version bump atomicity', () => {
it('MIGRATE-ATOMIC-001: writes schema_version inside the migration transaction', () => {
const db = migratedDb();
try {
const { version } = db.prepare('SELECT version FROM schema_version LIMIT 1').get() as { version: number };
// Rewind one slot so exactly the last migration replays.
db.prepare('UPDATE schema_version SET version = ?').run(version - 1);
const realPrepare = db.prepare.bind(db);
const inTransaction: boolean[] = [];
vi.spyOn(db, 'prepare').mockImplementation(((sql: string) => {
const stmt = realPrepare(sql);
if (sql.includes('UPDATE schema_version SET version')) {
const realRun = stmt.run.bind(stmt);
stmt.run = ((...args: unknown[]) => {
inTransaction.push(db.inTransaction);
return realRun(...(args as never[]));
}) as typeof stmt.run;
}
return stmt;
}) as typeof db.prepare);
runMigrations(db);
expect(inTransaction).toEqual([true]);
const after = db.prepare('SELECT version FROM schema_version LIMIT 1').get() as { version: number };
expect(after.version).toBe(version);
} finally {
vi.restoreAllMocks();
db.close();
}
});
});
+190
View File
@@ -0,0 +1,190 @@
/**
* Unit tests for migration 69/71 — normalized per-user per-channel
* notification preferences. Covers MIGR-001 to MIGR-004b.
*
* Previously a hand-inlined reimplementation of the migration's SQL over a
* bespoke minimal schema, entirely decoupled from both the legacy runner and
* the real migration (its `createTables` import was unused dead code). Ported
* (Task 0/Task 5c triage: PORT — a genuine numbered-migration equivalent
* exists but had no dedicated test) onto the real
* `Migration20200101011800_normalized_per_user_per_channel_notification_preferences`:
* migrate to the step immediately before it, seed rows with raw SQL, apply
* just that one migration, assert.
*/
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import { describe, it, expect } from 'vitest';
const TARGET = 'Migration20200101011800_normalized_per_user_per_channel_notification_preferences';
async function ormBeforeTarget(): Promise<MikroORM> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const idx = names.indexOf(TARGET);
expect(idx).toBeGreaterThan(0);
await migrateTo(orm, names[idx - 1]);
return orm;
}
async function seedUser(orm: MikroORM, username: string): Promise<number> {
await rawExec(orm, "INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, 'x', 'user')", [
username,
`${username}@example.test`,
]);
const rows = await rawQuery<{ id: number }>(orm, 'SELECT last_insert_rowid() as id');
return rows[0].id;
}
describe('Migration 69/71 — normalized notification_channel_preferences', () => {
it('MIGR-001 — notification_channel_preferences table exists after migration', async () => {
const orm = await ormBeforeTarget();
try {
await migrateTo(orm, TARGET);
const table = await rawQuery(
orm,
`SELECT name FROM sqlite_master WHERE type='table' AND name='notification_channel_preferences'`,
);
expect(table[0]).toBeDefined();
} finally {
await orm.close(true);
}
}, 30000);
it('MIGR-002 — old notification_preferences rows with disabled events migrated as enabled=0', async () => {
const orm = await ormBeforeTarget();
try {
const userId = await seedUser(orm, 'testuser');
// Simulate user who has disabled trip_invite and booking_change email
await rawExec(
orm,
`
INSERT INTO notification_preferences
(user_id, notify_trip_invite, notify_booking_change, notify_trip_reminder,
notify_vacay_invite, notify_photos_shared, notify_collab_message, notify_packing_tagged, notify_webhook)
VALUES (?, 0, 0, 1, 1, 1, 1, 1, 1)
`,
[userId],
);
await migrateTo(orm, TARGET);
const read = (eventType: string) =>
rawQuery<{ enabled: number }>(
orm,
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?',
[userId, eventType, 'email'],
).then((r) => r[0]);
const tripInviteEmail = await read('trip_invite');
const bookingEmail = await read('booking_change');
const reminderEmail = await read('trip_reminder');
// Disabled events should have enabled=0 rows
expect(tripInviteEmail).toBeDefined();
expect(tripInviteEmail!.enabled).toBe(0);
expect(bookingEmail).toBeDefined();
expect(bookingEmail!.enabled).toBe(0);
// Enabled events should have no row (no-row = enabled)
expect(reminderEmail).toBeUndefined();
} finally {
await orm.close(true);
}
}, 30000);
it('MIGR-003 — old notify_webhook=0 creates disabled webhook rows for all 7 events', async () => {
const orm = await ormBeforeTarget();
try {
const userId = await seedUser(orm, 'webhookuser');
// User has all email enabled but webhook disabled
await rawExec(
orm,
`
INSERT INTO notification_preferences
(user_id, notify_trip_invite, notify_booking_change, notify_trip_reminder,
notify_vacay_invite, notify_photos_shared, notify_collab_message, notify_packing_tagged, notify_webhook)
VALUES (?, 1, 1, 1, 1, 1, 1, 1, 0)
`,
[userId],
);
await migrateTo(orm, TARGET);
const allEvents = [
'trip_invite',
'booking_change',
'trip_reminder',
'vacay_invite',
'photos_shared',
'collab_message',
'packing_tagged',
];
for (const eventType of allEvents) {
const row = (
await rawQuery<{ enabled: number }>(
orm,
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?',
[userId, eventType, 'webhook'],
)
)[0];
expect(row).toBeDefined();
expect(row!.enabled).toBe(0);
// Email rows should NOT exist (all email was enabled → no row needed)
const emailRow = (
await rawQuery(
orm,
'SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?',
[userId, eventType, 'email'],
)
)[0];
expect(emailRow).toBeUndefined();
}
} finally {
await orm.close(true);
}
}, 30000);
it('MIGR-004 — notification_channels key is created in app_settings from notification_channel value', async () => {
const orm = await ormBeforeTarget();
try {
// Simulate existing single-channel setting
await rawExec(orm, 'INSERT INTO app_settings (key, value) VALUES (?, ?)', ['notification_channel', 'email']);
await migrateTo(orm, TARGET);
const plural = (
await rawQuery<{ value: string }>(orm, 'SELECT value FROM app_settings WHERE key = ?', [
'notification_channels',
])
)[0];
expect(plural).toBeDefined();
expect(plural!.value).toBe('email');
} finally {
await orm.close(true);
}
}, 30000);
it('MIGR-004b — notification_channels is not duplicated if already exists', async () => {
const orm = await ormBeforeTarget();
try {
// Both keys already set (e.g. partial migration or manual edit)
await rawExec(orm, 'INSERT INTO app_settings (key, value) VALUES (?, ?)', ['notification_channel', 'email']);
await rawExec(orm, 'INSERT INTO app_settings (key, value) VALUES (?, ?)', [
'notification_channels',
'email,webhook',
]);
await migrateTo(orm, TARGET);
// The existing notification_channels value should be preserved (INSERT OR IGNORE)
const plural = (
await rawQuery<{ value: string }>(orm, 'SELECT value FROM app_settings WHERE key = ?', [
'notification_channels',
])
)[0];
expect(plural!.value).toBe('email,webhook');
} finally {
await orm.close(true);
}
}, 30000);
});
@@ -0,0 +1,201 @@
import { Trips } from '../../../src/db/entities/Trips.entity';
import { NulSafeSqlitePlatform } from '../../../src/db/nul-safe-sqlite-platform';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTrip, createUser } from '../../helpers/factories';
import { resetTestDb } from '../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import Database from 'better-sqlite3';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
/**
* Plan 3c Task 4 review M1 / program rule 22: MikroORM 7 inlines every bound
* value into the SQL text via `platform.quoteValue`/`escape` (see
* `NulSafeSqlitePlatform`'s own docstring for the full mechanism). These
* tests prove the override round-trips a NUL byte at every position SQLite
* itself will accept, by handing the platform's own generated SQL literal to
* a REAL `better-sqlite3` connection and reading the value back — not a
* string-shape assertion, an actual SQLite round-trip.
*/
describe('NulSafeSqlitePlatform', () => {
const platform = new NulSafeSqlitePlatform();
const db = new Database(':memory:');
function roundTrip(value: string): string {
const literal = platform.escape(value);
const row = db.prepare(`SELECT ${literal} as v`).get() as { v: string };
return row.v;
}
it('round-trips a string with no NUL unchanged (baseline: unaffected by the override)', () => {
expect(roundTrip('plain string')).toBe('plain string');
});
it('round-trips a NUL in the middle of a string', () => {
const value = 'nul\u0000name';
expect(roundTrip(value)).toBe(value);
});
it('round-trips a NUL at the very start of a string', () => {
const value = '\u0000leading';
expect(roundTrip(value)).toBe(value);
});
it('round-trips a NUL at the very end of a string', () => {
const value = 'trailing\u0000';
expect(roundTrip(value)).toBe(value);
});
it('round-trips a string made ENTIRELY of NUL bytes', () => {
expect(roundTrip('\u0000')).toBe('\u0000');
expect(roundTrip('\u0000\u0000\u0000')).toBe('\u0000\u0000\u0000');
});
it('round-trips a NUL next to a single quote (the string-literal escape character)', () => {
const value = "o'brien\u0000's café";
expect(roundTrip(value)).toBe(value);
});
it('round-trips a NUL next to a backslash (not special in a SQLite string literal)', () => {
const value = 'back\\slash\u0000end\\';
expect(roundTrip(value)).toBe(value);
});
it('round-trips multiple NULs mixed with quotes and backslashes', () => {
const value = "a'\u0000b\\\u0000c''\u0000\\\\d";
expect(roundTrip(value)).toBe(value);
});
it('fuzzes every 0x00-0x1F control character: none corrupt the round-trip and none throw', () => {
for (let code = 0x00; code <= 0x1f; code++) {
const ch = String.fromCharCode(code);
const value = `before${ch}after`;
expect(() => roundTrip(value)).not.toThrow();
expect(roundTrip(value)).toBe(value);
}
});
it('leaves non-string values to the base platform (numbers, null, dates, buffers untouched)', () => {
expect(platform.escape(42)).toBe('42');
expect(platform.escape(null)).toBe('null');
expect(platform.escape(true)).toBe('true');
});
it('formatQuery (the real call path AbstractSqlConnection.execute uses: formatQuery -> quoteValue -> escape) inlines a NUL-safe literal for a bound `?`, matched via a real table', () => {
db.exec('CREATE TABLE probe (name TEXT)');
const value = 'search\u0000term';
const insertSql = platform.formatQuery('insert into probe (name) values (?)', [value]);
db.exec(insertSql);
const selectSql = platform.formatQuery('select name from probe where name = ?', [value]);
const row = db.prepare(selectSql).get() as { name: string } | undefined;
expect(row?.name).toBe(value);
});
/**
* Program rule 22's extension (Plan 3c Task 9 close-out, review A H1): a
* non-finite `number` used to render as an unquoted bareword (`NaN`/
* `Infinity`/`-Infinity`), which SQLite parses as a column reference and
* throws `no such column: …` — a 500 where the raw better-sqlite3 bind
* (`NaN` -> `NULL`, `±Infinity` -> the `REAL` value, verified empirically
* against the installed driver above the class docstring) never had the
* problem. These pin the rendered SQL literal AND the real round-trip.
*/
describe('non-finite numbers (rule 22 extension)', () => {
it('NaN renders as the literal `NULL`, not the bareword `NaN`', () => {
expect(platform.escape(NaN)).toBe('NULL');
});
it('+Infinity renders as the literal `9e999`, which SQLite parses back to the REAL value Infinity', () => {
expect(platform.escape(Infinity)).toBe('9e999');
const row = db.prepare('select typeof(9e999) as t, 9e999 as v').get() as { t: string; v: number };
expect(row).toEqual({ t: 'real', v: Infinity });
});
it('-Infinity renders as the literal `-9e999`, which SQLite parses back to the REAL value -Infinity', () => {
expect(platform.escape(-Infinity)).toBe('-9e999');
const row = db.prepare('select typeof(-9e999) as t, -9e999 as v').get() as { t: string; v: number };
expect(row).toEqual({ t: 'real', v: -Infinity });
});
it('a finite number is untouched (only the three non-finite values take the new branch)', () => {
expect(platform.escape(0)).toBe('0');
expect(platform.escape(-1)).toBe('-1');
expect(platform.escape(3.14)).toBe('3.14');
});
it("formatQuery renders `NULL` for a bound NaN, matching better-sqlite3's own binding of NaN as NULL", () => {
db.exec('CREATE TABLE nanprobe (n REAL)');
db.exec(platform.formatQuery('insert into nanprobe (n) values (?)', [NaN]));
const viaLiteral = db.prepare('select n from nanprobe').get() as { n: unknown };
const viaBind = db.prepare('select ? as n').get(NaN) as { n: unknown };
expect(viaLiteral.n).toBeNull();
expect(viaBind.n).toBeNull();
});
it("formatQuery renders `9e999`/`-9e999` for bound ±Infinity, matching better-sqlite3's own REAL binding", () => {
db.exec('CREATE TABLE infprobe (n REAL)');
db.exec(platform.formatQuery('insert into infprobe (n) values (?), (?)', [Infinity, -Infinity]));
const rows = db.prepare('select n from infprobe order by rowid').all() as { n: number }[];
expect(rows.map((r) => r.n)).toEqual([Infinity, -Infinity]);
});
});
/**
* The mechanism above through the REAL ORM call path (`findOne`,
* `nativeUpdate`, a QB `where`, and an `$in` list), against a real trip
* row — the shape `PlacesService.verifyTripAccess`/`RealtimeGateway
* .handleJoin` reach when a non-finite id slips past their own guard.
* Before this override, every one of these threw `SqliteError: no such
* column: NaN`; after, each answers a clean miss.
*/
describe('non-finite numbers through the real ORM call path', () => {
const orm = createSnapshotTestDb();
let t: TestOrm;
beforeAll(async () => {
t = await createTestOrm(orm);
});
beforeEach(() => {
resetTestDb(orm);
t.clear();
});
afterAll(async () => {
await t.close();
orm.close();
});
it('em.findOne(Trips, { id: NaN }) misses cleanly, never throws', async () => {
const { user } = createUser(orm);
createTrip(orm, user.id);
await expect(t.em.findOne(Trips, { id: NaN })).resolves.toBeNull();
});
it('em.nativeUpdate(Trips, { id: NaN }, …) updates 0 rows, never throws', async () => {
const { user } = createUser(orm);
const trip = createTrip(orm, user.id);
const affected = await t.em.nativeUpdate(Trips, { id: NaN }, { title: 'renamed' });
expect(affected).toBe(0);
const untouched = orm.prepare('SELECT title FROM trips WHERE id = ?').get(trip.id) as { title: string };
expect(untouched.title).not.toBe('renamed');
});
it('a QB `where` on a non-finite id misses cleanly, never throws (the exact `findAccessible` shape)', async () => {
const { user } = createUser(orm);
createTrip(orm, user.id);
const row = await t.em
.getRepository(Trips)
.qb('t')
.select(['t.id'])
.where('t.id = ?', [NaN])
.execute<{ id: number } | undefined>('get', false);
expect(row).toBeUndefined();
});
it('an `$in` list containing NaN/Infinity still matches the finite members, never throws', async () => {
const { user } = createUser(orm);
const trip = createTrip(orm, user.id);
const rows = await t.em.find(Trips, { id: { $in: [trip.id, NaN, Infinity, -Infinity] } });
expect(rows.map((r) => r.id)).toEqual([trip.id]);
});
});
});
@@ -0,0 +1,280 @@
import { buildLegacyStepMap, migrateToHead } from '../../../src/db/legacy-baseline';
import { Migration20200101040500_a_place_that_moves_takes_its_atlas as PlaceRegionsTrigger } from '../../../src/db/migrations/Migration20200101040500_a_place_that_moves_takes_its_atlas';
import { Migration20200101040700_the_2527_trigger_once_more_for_an as PlaceRegionsTriggerAgain } from '../../../src/db/migrations/Migration20200101040700_the_2527_trigger_once_more_for_an';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import {
createMigrationOrm,
migrateTo,
migratorOf,
rawExec,
rawQuery,
runMigrationDirect,
} from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import type Database from 'better-sqlite3';
import fs from 'node:fs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
// place_regions is Atlas's cache of the country and region a place resolved to.
// It is derived from the place's lat, lng and address, so a change to any of them
// has to take the row with it, whichever code path wrote the change (#2527).
// The trigger ships at legacy step 244, the same slot as on main (4.3.3). Web Push
// moved up to 245 to make room, and 246 creates the trigger again for an instance
// that ran Web Push at 244 before. Each step is its own MikroORM migration, mapped
// by its `Legacy migration step N` docstring; an install the legacy runner left at
// one of these steps is baselined by db/legacy-baseline.ts and runs the rest.
const PLACE_REGIONS_TRIGGER_VERSION = 244;
const WEB_PUSH_VERSION = 245;
const PLACE_REGIONS_TRIGGER_AGAIN_VERSION = 246;
describe('place_regions follows the place it was resolved from (#2527)', () => {
describe('the live trigger', () => {
let db: Database.Database;
let placeId: number;
let otherPlaceId: number;
const cached = (id: number) =>
db.prepare('SELECT country_code, region_code FROM place_regions WHERE place_id = ?').get(id) as
{ country_code: string; region_code: string } | undefined;
beforeEach(() => {
db = createSnapshotTestDb();
db.exec("INSERT INTO users (username, email, password_hash) VALUES ('traveller', 'traveller@example.test', 'x')");
const userId = (db.prepare('SELECT id FROM users').get() as { id: number }).id;
const tripId = db.prepare("INSERT INTO trips (user_id, title) VALUES (?, 'Trip')").run(userId)
.lastInsertRowid as number;
const insertPlace = db.prepare('INSERT INTO places (trip_id, name, lat, lng, address) VALUES (?, ?, ?, ?, ?)');
placeId = insertPlace.run(tripId, 'Hotel', 48.8566, 2.3522, 'Rue de Rivoli, Paris, France')
.lastInsertRowid as number;
otherPlaceId = insertPlace.run(tripId, 'Museum', 48.8606, 2.3376, 'Rue de Rivoli, Paris, France')
.lastInsertRowid as number;
const insertRegion = db.prepare(
"INSERT INTO place_regions (place_id, country_code, region_code, region_name) VALUES (?, 'FR', 'FR-IDF', 'Ile-de-France')",
);
insertRegion.run(placeId);
insertRegion.run(otherPlaceId);
});
afterEach(() => db?.close());
it('drops the cached region when the coordinates move', () => {
db.prepare('UPDATE places SET lat = ?, lng = ? WHERE id = ?').run(52.5163, 13.3777, placeId);
expect(cached(placeId)).toBeUndefined();
expect(cached(otherPlaceId)).toEqual({ country_code: 'FR', region_code: 'FR-IDF' });
});
it('drops it when only the latitude or only the longitude changes', () => {
db.prepare('UPDATE places SET lat = ? WHERE id = ?').run(48.9, placeId);
db.prepare('UPDATE places SET lng = ? WHERE id = ?').run(2.4, otherPlaceId);
expect(cached(placeId)).toBeUndefined();
expect(cached(otherPlaceId)).toBeUndefined();
});
it('drops it when the address changes, including one filled in where there was none', () => {
db.prepare('UPDATE places SET address = ? WHERE id = ?').run('Pariser Platz, Berlin, Germany', placeId);
db.prepare('UPDATE places SET address = NULL WHERE id = ?').run(otherPlaceId);
db.prepare(
"INSERT INTO place_regions (place_id, country_code, region_code, region_name) VALUES (?, 'FR', 'FR-IDF', 'Ile-de-France')",
).run(otherPlaceId);
// The import backfill only ever fills an empty address.
db.prepare('UPDATE places SET address = COALESCE(address, ?) WHERE id = ?').run('Paris, France', otherPlaceId);
expect(cached(placeId)).toBeUndefined();
expect(cached(otherPlaceId)).toBeUndefined();
});
it('drops it when the location is cleared', () => {
db.prepare('UPDATE places SET lat = NULL, lng = NULL WHERE id = ?').run(placeId);
expect(cached(placeId)).toBeUndefined();
});
it('keeps it when an edit writes the same location back', () => {
// The place editor and update_place write every column, location included.
db.prepare(
"UPDATE places SET name = 'Hotel du Louvre', notes = 'late check-in', lat = ?, lng = ?, address = ? WHERE id = ?",
).run(48.8566, 2.3522, 'Rue de Rivoli, Paris, France', placeId);
db.prepare("UPDATE places SET place_time = '09:00', updated_at = CURRENT_TIMESTAMP WHERE id = ?").run(
otherPlaceId,
);
expect(cached(placeId)).toEqual({ country_code: 'FR', region_code: 'FR-IDF' });
expect(cached(otherPlaceId)).toEqual({ country_code: 'FR', region_code: 'FR-IDF' });
});
});
it('ships at its own legacy step and replays without a second trigger', async () => {
// The live trigger behaves as above; the replay runs on a migration-only
// database, where each step can be applied on its own.
const orm = await createMigrationOrm();
try {
const triggers = () =>
rawQuery(
orm,
"SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = 'places' AND name = 'trg_place_regions_follow_place'",
);
await migratorOf(orm).up();
expect(await triggers()).toHaveLength(1);
await rawExec(orm, 'DROP TRIGGER trg_place_regions_follow_place');
expect(await triggers()).toHaveLength(0);
await runMigrationDirect(orm, PlaceRegionsTrigger);
await runMigrationDirect(orm, PlaceRegionsTrigger);
await runMigrationDirect(orm, PlaceRegionsTriggerAgain);
expect(await triggers()).toHaveLength(1);
await rawExec(orm, "INSERT INTO users (username, email, password_hash) VALUES ('t', 't@example.test', 'x')");
await rawExec(orm, "INSERT INTO trips (id, user_id, title) SELECT 1, id, 'Trip' FROM users");
await rawExec(orm, "INSERT INTO places (id, trip_id, name, lat, lng) VALUES (1, 1, 'Hotel', 48.8566, 2.3522)");
await rawExec(
orm,
"INSERT INTO place_regions (place_id, country_code, region_code, region_name) VALUES (1, 'FR', 'FR-IDF', 'Ile-de-France')",
);
await rawExec(orm, 'UPDATE places SET lat = ? WHERE id = 1', [52.5163]);
expect(await rawQuery(orm, 'SELECT 1 FROM place_regions WHERE place_id = 1')).toEqual([]);
} finally {
await orm.close(true);
}
}, 30000);
it('keeps the slot it has on main, with Web Push after it and the trigger once more after that', async () => {
const orm = await createMigrationOrm();
try {
const pending = await migratorOf(orm).getPending();
const map = buildLegacyStepMap(pending);
const sourceOf = (step: number): string => {
const migration = pending.find((m) => m.name === map.steps.get(step));
return fs.readFileSync(migration!.path!, 'utf8');
};
expect(map.steps.get(PLACE_REGIONS_TRIGGER_VERSION)).toBe(
'Migration20200101040500_a_place_that_moves_takes_its_atlas',
);
expect(sourceOf(PLACE_REGIONS_TRIGGER_VERSION)).toContain('await createPlaceRegionsFollowPlaceTrigger(this)');
expect(sourceOf(WEB_PUSH_VERSION)).toContain('CREATE TABLE IF NOT EXISTS push_subscriptions');
expect(sourceOf(WEB_PUSH_VERSION)).not.toMatch(
/trg_place_regions_follow_place|createPlaceRegionsFollowPlaceTrigger/,
);
expect(sourceOf(PLACE_REGIONS_TRIGGER_AGAIN_VERSION)).toContain(
'await createPlaceRegionsFollowPlaceTrigger(this)',
);
// Nothing after it creates the trigger a third time.
for (let step = PLACE_REGIONS_TRIGGER_AGAIN_VERSION + 1; step <= map.finalStep; step++) {
expect(sourceOf(step), `legacy step ${step}`).not.toMatch(
/trg_place_regions_follow_place|createPlaceRegionsFollowPlaceTrigger/,
);
}
} finally {
await orm.close(true);
}
}, 30000);
describe('an install the legacy runner left at step 244', () => {
let orm: MikroORM;
const triggers = () =>
rawQuery(
orm,
"SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = 'places' AND name = 'trg_place_regions_follow_place'",
);
const pushTable = () =>
rawQuery(
orm,
"SELECT name FROM sqlite_master WHERE tbl_name = 'push_subscriptions' AND type IN ('table', 'index') AND name NOT LIKE 'sqlite_%' ORDER BY name",
);
const recorded = async () =>
(await rawQuery<{ name: string }>(orm, 'SELECT name FROM mikro_orm_migrations')).map((r) => r.name);
/**
* What the positional runner left behind at step 244: the schema of every
* step up to it, a `schema_version` row and no MikroORM bookkeeping. The
* schema comes from the chain itself, then the bookkeeping is swapped for
* the legacy row, so the next boot sees exactly what an upgrade sees.
*/
async function legacyInstallAt244(): Promise<void> {
await migrateTo(orm, 'Migration20200101040500_a_place_that_moves_takes_its_atlas');
await rawExec(orm, 'DELETE FROM mikro_orm_migrations');
await rawExec(orm, 'DROP TABLE IF EXISTS schema_version');
await rawExec(orm, 'CREATE TABLE schema_version (version INTEGER NOT NULL)');
await rawExec(orm, 'INSERT INTO schema_version (version) VALUES (?)', [PLACE_REGIONS_TRIGGER_VERSION]);
}
const boot = () => migrateToHead(orm.em.getConnection(), migratorOf(orm));
beforeEach(async () => {
orm = await createMigrationOrm();
});
afterEach(async () => {
await orm.close(true);
});
it('gives a 4.3.3 install, already at 244 with the trigger, the Web Push table', async () => {
await legacyInstallAt244();
expect(await pushTable()).toEqual([]);
await boot();
expect(await pushTable()).toEqual([{ name: 'idx_push_subscriptions_user' }, { name: 'push_subscriptions' }]);
expect(await triggers()).toHaveLength(1);
expect(await recorded()).toContain('Migration20200101040700_the_2527_trigger_once_more_for_an');
}, 30000);
it('gives an instance that ran Web Push at 244 the trigger and keeps its subscriptions', async () => {
await legacyInstallAt244();
await rawExec(orm, 'DROP TRIGGER trg_place_regions_follow_place');
// Web Push at 244, as that instance ran it.
await rawExec(
orm,
`CREATE TABLE push_subscriptions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
endpoint TEXT NOT NULL UNIQUE,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
vapid_public_key TEXT NOT NULL,
user_agent TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_success_at TEXT,
failure_count INTEGER NOT NULL DEFAULT 0
)`,
);
await rawExec(orm, 'CREATE INDEX idx_push_subscriptions_user ON push_subscriptions(user_id)');
await rawExec(
orm,
"INSERT INTO users (username, email, password_hash) VALUES ('traveller', 'traveller@example.test', 'x')",
);
await rawExec(
orm,
"INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth, vapid_public_key) SELECT id, 'https://push.example.test/1', 'p', 'a', 'v' FROM users",
);
await rawExec(orm, "INSERT INTO trips (id, user_id, title) SELECT 1, id, 'Trip' FROM users");
await rawExec(
orm,
"INSERT INTO places (id, trip_id, name, lat, lng, address) VALUES (1, 1, 'Hotel', 48.8566, 2.3522, 'Rue de Rivoli, Paris, France'), (2, 1, 'Museum', 48.8606, 2.3376, 'Rue de Rivoli, Paris, France')",
);
await rawExec(
orm,
"INSERT INTO place_regions (place_id, country_code, region_code, region_name) VALUES (1, 'FR', 'FR-IDF', 'Ile-de-France'), (2, 'FR', 'FR-IDF', 'Ile-de-France')",
);
await boot();
expect(await triggers()).toHaveLength(1);
expect(await rawQuery(orm, 'SELECT endpoint FROM push_subscriptions')).toEqual([
{ endpoint: 'https://push.example.test/1' },
]);
expect(await recorded()).toContain('Migration20200101040700_the_2527_trigger_once_more_for_an');
await rawExec(orm, 'UPDATE places SET lat = ?, lng = ? WHERE id = 1', [52.5163, 13.3777]);
expect(await rawQuery(orm, 'SELECT country_code, region_code FROM place_regions WHERE place_id = 1')).toEqual([]);
expect(await rawQuery(orm, 'SELECT country_code, region_code FROM place_regions WHERE place_id = 2')).toEqual([
{ country_code: 'FR', region_code: 'FR-IDF' },
]);
}, 30000);
});
});
@@ -0,0 +1,207 @@
/**
* The copy of the database a boot takes before it migrates
* (`src/db/pre-migrate-snapshot.ts`), driven through `migrateToHead` against a
* temp FILE database, because an in-memory one has nothing to copy.
*
* The end-to-end case (a v4.3.3 install booting through `buildApp()`) is
* `tests/integration/legacy-upgrade-v244.test.ts`.
*/
import { readEnv, type AppEnv } from '../../../src/app-config';
import { knownMigrationNames } from '../../../src/db/known-migrations';
import { migrateToHead, migrationLabel } from '../../../src/db/legacy-baseline';
import { listSnapshots, preMigrateSnapshot, pruneSnapshots } from '../../../src/db/pre-migrate-snapshot';
import { Migrator } from '@mikro-orm/migrations';
import { MikroORM } from '@mikro-orm/sqlite';
import Database from 'better-sqlite3';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const MIGRATIONS = path.join(__dirname, '../../../src/db/migrations');
const MIDPOINT = 'Migration20200101040200_trek_photo_cache_meta_cache_key_not_null';
const NOW = new Date('2026-10-08T09:15:00.123Z');
const STAMP = '20261008T091500Z';
let dir: string;
let dbFile: string;
let orm: MikroORM;
function ormFor(dbName: string): Promise<MikroORM> {
return MikroORM.init({
entities: [],
discovery: { warnWhenNoEntities: false },
extensions: [Migrator],
migrations: { path: MIGRATIONS, pathTs: MIGRATIONS, snapshot: false, silent: true },
dbName,
});
}
const migrator = () => orm.config.getExtension('@mikro-orm/migrator') as Migrator;
/** The live env with the snapshot switches set as given. */
function envWith(db: Partial<AppEnv['db']>, isTest = false): () => AppEnv {
return () => {
const env = readEnv();
return { ...env, app: { ...env.app, isTest }, db: { ...env.db, ...db } };
};
}
function migrate(env: () => AppEnv): Promise<void> {
const connection = orm.em.getConnection();
return migrateToHead(
connection,
migrator(),
undefined,
undefined,
preMigrateSnapshot(connection, env, () => NOW),
);
}
async function recorded(): Promise<string[]> {
const rows: Array<{ name: string }> = await orm.em
.getConnection()
.execute('SELECT name FROM mikro_orm_migrations ORDER BY id');
return rows.map((row) => row.name);
}
const snapshotsIn = () =>
fs
.readdirSync(dir)
.filter((entry) => entry.startsWith('pre-migrate-'))
.sort();
beforeEach(async () => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-premigrate-'));
dbFile = path.join(dir, 'travel.db');
orm = await ormFor(dbFile);
vi.spyOn(console, 'log').mockImplementation(() => {});
});
afterEach(async () => {
vi.restoreAllMocks();
await orm.close(true);
fs.rmSync(dir, { recursive: true, force: true });
});
describe('the pre-migration snapshot', () => {
it('PREMIG-001: copies a database that is behind before migrating it, named after the schema it holds', async () => {
await migrator().up({ to: MIDPOINT });
await orm.em
.getConnection()
.execute(`INSERT INTO users (username, email, password_hash) VALUES ('kept', 'kept@example.test', 'x')`);
const before = await recorded();
await migrate(envWith({ preMigrateSnapshot: true }));
const name = `pre-migrate-${migrationLabel(MIDPOINT)}-${STAMP}.db`;
expect(snapshotsIn()).toEqual([name]);
expect(await recorded()).toHaveLength(knownMigrationNames().size);
const copy = new Database(path.join(dir, name), { readonly: true });
try {
// The copy holds the state from before the run: its rows and its migrations.
expect(copy.prepare('SELECT email FROM users').all()).toEqual([{ email: 'kept@example.test' }]);
expect(
(copy.prepare('SELECT name FROM mikro_orm_migrations ORDER BY id').all() as Array<{ name: string }>).map(
(r) => r.name,
),
).toEqual(before);
} finally {
copy.close();
}
});
it('PREMIG-002: a legacy install is labelled by its schema_version', async () => {
await orm.em.getConnection().execute('CREATE TABLE schema_version (version INTEGER NOT NULL)');
await orm.em.getConnection().execute('INSERT INTO schema_version (version) VALUES (10)');
await migrate(envWith({ preMigrateSnapshot: true }));
expect(snapshotsIn()).toEqual([`pre-migrate-legacy-10-${STAMP}.db`]);
});
it('PREMIG-003: a fresh install, a restart with nothing pending and the test default take none', async () => {
await migrate(envWith({ preMigrateSnapshot: true }));
expect(snapshotsIn()).toEqual([]);
await migrate(envWith({ preMigrateSnapshot: true }));
expect(snapshotsIn()).toEqual([]);
await orm.close(true);
fs.rmSync(dbFile);
orm = await ormFor(dbFile);
await migrator().up({ to: MIDPOINT });
await migrate(envWith({ preMigrateSnapshot: undefined }, true));
expect(snapshotsIn()).toEqual([]);
expect(await recorded()).toHaveLength(knownMigrationNames().size);
});
it('PREMIG-004: a copy that cannot be written refuses the boot and migrates nothing', async () => {
await migrator().up({ to: MIDPOINT });
const before = await recorded();
// A directory where the copy has to land makes the final rename fail.
fs.mkdirSync(path.join(dir, `pre-migrate-${migrationLabel(MIDPOINT)}-${STAMP}.db`));
await expect(migrate(envWith({ preMigrateSnapshot: true }))).rejects.toThrow(
/\[DB\] Refusing to boot: could not write a copy of the database to .* Nothing was migrated\..*TREK_DB_PRE_MIGRATE_SNAPSHOT=false/,
);
expect(await recorded()).toEqual(before);
expect(fs.readdirSync(dir).filter((entry) => entry.endsWith('.partial'))).toEqual([]);
});
it('PREMIG-005: TREK_DB_PRE_MIGRATE_SNAPSHOT=false migrates without a copy, and says so', async () => {
await migrator().up({ to: MIDPOINT });
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
await migrate(envWith({ preMigrateSnapshot: false }));
expect(snapshotsIn()).toEqual([]);
expect(await recorded()).toHaveLength(knownMigrationNames().size);
expect(String(warn.mock.calls[0]?.[0])).toContain('TREK_DB_PRE_MIGRATE_SNAPSHOT is off');
});
it('PREMIG-006: keeps only the newest copies', async () => {
for (const [i, name] of ['a', 'b', 'c', 'd'].entries()) {
const file = path.join(dir, `pre-migrate-${name}.db`);
fs.writeFileSync(file, '');
fs.utimesSync(file, 1_000 + i, 1_000 + i);
}
fs.writeFileSync(path.join(dir, 'pre-restore-1.db'), '');
fs.writeFileSync(path.join(dir, 'pre-migrate-e.db.partial'), '');
pruneSnapshots(dir, 2);
expect(listSnapshots(dir).map((file) => path.basename(file))).toEqual(['pre-migrate-d.db', 'pre-migrate-c.db']);
// Nothing else in the data dir is touched.
expect(fs.existsSync(path.join(dir, 'pre-restore-1.db'))).toBe(true);
expect(fs.existsSync(path.join(dir, 'pre-migrate-e.db.partial'))).toBe(true);
});
it('PREMIG-007: the boot prunes to TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP after a new copy', async () => {
for (const name of ['old-1', 'old-2']) {
const file = path.join(dir, `pre-migrate-${name}.db`);
fs.writeFileSync(file, '');
fs.utimesSync(file, 1_000, 1_000);
}
await migrator().up({ to: MIDPOINT });
await migrate(envWith({ preMigrateSnapshot: true, preMigrateSnapshotKeep: 1 }));
expect(snapshotsIn()).toEqual([`pre-migrate-${migrationLabel(MIDPOINT)}-${STAMP}.db`]);
});
it('PREMIG-008: refusing a database a newer TREK migrated names the copy taken from this release', async () => {
await migrate(envWith({ preMigrateSnapshot: true }));
const head = migrationLabel([...knownMigrationNames()].sort().at(-1) ?? '');
const match = path.join(dir, `pre-migrate-${head}-20261001T000000Z.db`);
fs.writeFileSync(match, '');
await orm.em
.getConnection()
.execute(
"INSERT INTO mikro_orm_migrations (name, executed_at) VALUES ('Migration20990101000000_from_a_newer_release', CURRENT_TIMESTAMP)",
);
const refusal = migrate(envWith({ preMigrateSnapshot: true }));
await expect(refusal).rejects.toThrow(/migrated by a newer TREK/);
await expect(refusal).rejects.toThrow(`The copy taken right before the newer TREK migrated it is ${match}`);
fs.rmSync(match);
fs.writeFileSync(path.join(dir, 'pre-migrate-legacy-200-20250101T000000Z.db'), '');
await expect(migrate(envWith({ preMigrateSnapshot: true }))).rejects.toThrow(/none of them from this release/);
});
});
@@ -0,0 +1,188 @@
import { Addons } from '../../../../src/db/entities/Addons.entity';
import type { AddonsRepository } from '../../../../src/db/repositories/Addons.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { deleteRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let addons: AddonsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
addons = t.repo(Addons);
});
beforeEach(async () => {
resetTestDb(testDb);
// resetTestDb deliberately keeps the seeded addons catalogue (test-db.ts's
// KEEP_TABLES) — these tests want a known, empty table so every case
// controls its own rows.
await deleteRows(t, Addons);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function rawRow(id: string): unknown {
// test-sql-allow: the stored integer is under test, which the entity reads back as a boolean.
return testDb.prepare('SELECT * FROM addons WHERE id = ?').get(id);
}
async function insertAddon(row: {
id: string;
name: string;
description?: string | null;
type?: string;
icon?: string | null;
enabled: 0 | 1;
sort_order?: number;
}): Promise<void> {
await insertRow(t, Addons, {
id: row.id,
name: row.name,
description: row.description ?? null,
type: row.type ?? 'global',
icon: row.icon ?? null,
enabled: row.enabled === 1,
sort_order: row.sort_order ?? 0,
});
}
describe('AddonsRepository', () => {
describe('isEnabled', () => {
it('ADDONSREPO-001: reads a stored 1 as true', async () => {
await insertAddon({ id: 'budget', name: 'Budget', enabled: 1 });
expect(await addons.isEnabled('budget')).toBe(true);
});
it('ADDONSREPO-002: reads a stored 0 as false', async () => {
await insertAddon({ id: 'budget', name: 'Budget', enabled: 0 });
expect(await addons.isEnabled('budget')).toBe(false);
});
it('ADDONSREPO-003: a missing row reads false', async () => {
expect(await addons.isEnabled('does-not-exist')).toBe(false);
});
// I1 (Task 0 review, carried forward): a primary-key findOne answers a
// repeat call from the identity map unless refresh: true is set —
// invisible to a write on the same id in the same request.
describe('sees a write on the same id in the same request (I1, identity-map regression)', () => {
it('ADDONSREPO-005: an UPDATE from another context on the same id then isEnabled reads the new value', async () => {
await insertAddon({ id: 'budget', name: 'Budget', enabled: 0 });
expect(await addons.isEnabled('budget')).toBe(false); // populate the identity map
await updateRows(t, Addons, { id: 'budget' }, { enabled: true });
expect(await addons.isEnabled('budget')).toBe(true);
});
});
});
describe('listEnabled', () => {
it('ADDONSREPO-006: returns only enabled addons, ordered by sort_order', async () => {
await insertAddon({ id: 'atlas', name: 'Atlas', type: 'page', icon: 'globe', enabled: 1, sort_order: 2 });
await insertAddon({ id: 'budget', name: 'Costs', type: 'trip', icon: 'wallet', enabled: 1, sort_order: 1 });
await insertAddon({ id: 'vacay', name: 'Vacay', type: 'page', icon: 'sun', enabled: 0, sort_order: 0 });
const rows = await addons.listEnabled();
expect(rows.map((r) => r.id)).toEqual(['budget', 'atlas']);
});
it('ADDONSREPO-007: the enabled column comes back as a JS boolean, not the stored int', async () => {
await insertAddon({ id: 'atlas', name: 'Atlas', enabled: 1 });
const [row] = await addons.listEnabled();
expect(row.enabled).toBe(true);
expect(rawRow('atlas')).toMatchObject({ enabled: 1 });
});
it('ADDONSREPO-008: an empty table returns an empty array', async () => {
expect(await addons.listEnabled()).toEqual([]);
});
it('ADDONSREPO-009: carries the full row shape (id, name, description, type, icon, enabled, config, sort_order)', async () => {
await insertAddon({
id: 'atlas',
name: 'Atlas',
description: 'Visited countries map',
type: 'page',
icon: 'globe',
enabled: 1,
sort_order: 3,
});
const [row] = await addons.listEnabled();
expect(row).toEqual({
id: 'atlas',
name: 'Atlas',
description: 'Visited countries map',
type: 'page',
icon: 'globe',
enabled: true,
config: {},
sort_order: 3,
});
});
});
// Plan 3i Task 4 fix wave (should-land 5): AD26 (listAllOrdered) and
// AD30/AD39 (findById) shipped in Task 1 with no repository-level test —
// full-key parity against the exact legacy SQL each method's own docstring
// names.
describe('listAllOrdered (AD26)', () => {
it('ADDONSREPO-010: matches SELECT * FROM addons ORDER BY sort_order, id — unfiltered, including a disabled addon', async () => {
await insertAddon({ id: 'vacay', name: 'Vacay', type: 'page', icon: 'sun', enabled: 0, sort_order: 1 });
await insertAddon({ id: 'budget', name: 'Costs', type: 'trip', icon: 'wallet', enabled: 1, sort_order: 0 });
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare('SELECT * FROM addons ORDER BY sort_order, id').all();
const rows = await addons.listAllOrdered();
expect(rows.map((r) => r.id)).toEqual(['budget', 'vacay']); // includes the disabled one, unlike listEnabled
expect(rows).toEqual(
(legacy as Array<{ enabled: number; config: string | null }>).map((r) => ({
...r,
enabled: !!r.enabled,
config: JSON.parse(r.config ?? '{}'),
})),
);
});
it('ADDONSREPO-011: an empty table returns an empty array', async () => {
expect(await addons.listAllOrdered()).toEqual([]);
});
});
describe('findById (AD30/AD39)', () => {
it('ADDONSREPO-012: matches SELECT * FROM addons WHERE id = ?, on both a pre-write read and a post-write re-select (byte-identical text at both call sites)', async () => {
await insertAddon({
id: 'budget',
name: 'Costs',
description: 'Track spend',
type: 'trip',
icon: 'wallet',
enabled: 0,
sort_order: 4,
});
const preWrite = await addons.findById('budget');
expect(preWrite).toEqual({
id: 'budget',
name: 'Costs',
description: 'Track spend',
type: 'trip',
icon: 'wallet',
enabled: false,
config: {},
sort_order: 4,
});
await updateRows(t, Addons, { id: 'budget' }, { enabled: true });
const postWrite = await addons.findById('budget');
expect(postWrite?.enabled).toBe(true);
});
it('ADDONSREPO-013: a missing id returns null', async () => {
expect(await addons.findById('does-not-exist')).toBeNull();
});
});
});
@@ -0,0 +1,100 @@
/**
* AiConnectionsRepository and the table under it: one connection per user and
* one for the instance, a save that replaces in place, the version check a
* token refresh writes under, and the checks that keep a custom server the
* admin's while a ChatGPT sign-in may be either side's.
*/
import { AiConnections } from '../../../../src/db/entities/AiConnections.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type { AiConnectionsRepository } from '../../../../src/db/repositories/AiConnections.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { countRows, deleteRows, findRow, insertRow } from '../../../helpers/factories/rows';
import { makeUser } from '../../../helpers/factories/users';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: AiConnectionsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(AiConnections);
});
beforeEach(async () => {
t.clear();
await deleteRows(t, AiConnections);
});
afterAll(async () => {
await t.close();
testDb.close();
});
const KEY = { kind: 'anthropic', model: 'claude', baseUrl: null, secrets: 'enc:v1:a', hint: '…aaaa', account: null };
describe('AiConnectionsRepository', () => {
it('AICREPO-001: a user and the instance each have one connection; a second save replaces it in place', async () => {
const { user } = await makeUser(t);
await repo.save(user.id, KEY);
await repo.save(null, { ...KEY, kind: 'custom', baseUrl: 'http://ollama:11434/v1', secrets: null, hint: null });
const first = await repo.findForUser(user.id);
expect(first).toMatchObject({
scope: 'user',
user_id: user.id,
kind: 'anthropic',
secrets_version: 0,
status: 'ok',
});
await repo.setStatus(first?.id ?? 0, 'error');
await repo.save(user.id, { ...KEY, kind: 'openai', model: 'gpt', secrets: 'enc:v1:b' });
const second = await repo.findForUser(user.id);
expect(second).toMatchObject({ id: first?.id, kind: 'openai', model: 'gpt', secrets_version: 1, status: 'ok' });
expect(await repo.findInstance()).toMatchObject({
scope: 'instance',
user_id: null,
base_url: 'http://ollama:11434/v1',
});
expect(await countRows(t, AiConnections)).toBe(2);
});
it('AICREPO-002: a refresh writes only over the version it read', async () => {
const { user } = await makeUser(t);
await repo.save(user.id, { ...KEY, kind: 'chatgpt' });
const row = await repo.findForUser(user.id);
const id = row?.id ?? 0;
expect(await repo.replaceSecretsIfUnchanged(id, 0, 'enc:v1:new', '{"sub":"s"}')).toBe(true);
expect(await repo.replaceSecretsIfUnchanged(id, 0, 'enc:v1:late', null)).toBe(false);
expect(await repo.findById(id)).toMatchObject({
secrets: 'enc:v1:new',
secrets_version: 1,
account: '{"sub":"s"}',
});
await repo.clearSecrets(id, 'signed_out');
expect(await repo.findById(id)).toMatchObject({ secrets: null, secrets_version: 2, status: 'signed_out' });
await repo.setModel(id, 'gpt-6');
expect((await repo.findById(id))?.model).toBe('gpt-6');
expect(await repo.deleteById(id)).toBe(1);
expect(await repo.findById(id)).toBeNull();
});
it('AICREPO-003: the table refuses a custom user connection and a stray base URL, takes a shared ChatGPT plan', async () => {
const { user } = await makeUser(t);
await expect(repo.save(user.id, { ...KEY, kind: 'custom', baseUrl: 'http://lan' })).rejects.toThrow(/CHECK/);
await expect(repo.save(null, { ...KEY, baseUrl: 'http://lan' })).rejects.toThrow(/CHECK/);
await expect(repo.save(null, { ...KEY, kind: 'custom' })).rejects.toThrow(/CHECK/);
await expect(insertRow(t, AiConnections, { scope: 'user', kind: 'openai', model: 'm' })).rejects.toThrow(/CHECK/);
// An admin may share their own ChatGPT plan with everyone.
await repo.save(null, { ...KEY, kind: 'chatgpt' });
expect(await repo.findInstance()).toMatchObject({ scope: 'instance', user_id: null, kind: 'chatgpt' });
});
it('AICREPO-004: a user deleted takes their connection along', async () => {
const { user } = await makeUser(t);
await repo.save(user.id, KEY);
await deleteRows(t, Users, { id: user.id });
expect(await findRow(t, AiConnections, { user: user.id })).toBeNull();
});
});
@@ -0,0 +1,224 @@
import { AppSettings } from '../../../../src/db/entities/AppSettings.entity';
import type { AppSettingsRepository } from '../../../../src/db/repositories/AppSettings.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { countRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let appSettings: AppSettingsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
appSettings = t.repo(AppSettings);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function rawRow(key: string): unknown {
// test-sql-allow: the row as SELECT * returns it is the oracle the repository writes are held to.
return testDb.prepare('SELECT * FROM app_settings WHERE key = ?').get(key);
}
async function insertRaw(key: string, value: string | null): Promise<void> {
await insertRow(t, AppSettings, { key, value });
}
/**
* Runs `fn` while counting queries MikroORM actually issues over the shared
* connection, so a regression test can assert "one query, with this value"
* rather than only the value — a regression in the `disableIdentityMap: true`
* ruling (Plan 3b Task 1 fix round, `task-1-review.md` B1) would return the
* *right* value from a stale identity-map hit with *zero* queries, which a
* value-only assertion would never catch.
*/
async function withQueryCount<T>(fn: () => Promise<T>): Promise<{ value: T; queries: number }> {
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
try {
const value = await fn();
return { value, queries: spy.mock.calls.length };
} finally {
spy.mockRestore();
}
}
describe('AppSettingsRepository', () => {
it('APPSETREPO-001: getValue reads the stored value', async () => {
await insertRaw('bag_tracking_enabled', 'true');
expect(await appSettings.getValue('bag_tracking_enabled')).toBe('true');
});
it('APPSETREPO-002: getValue returns null for an unset key', async () => {
expect(await appSettings.getValue('does_not_exist')).toBeNull();
});
it('APPSETREPO-003: getValues reads several keys into a Map, silently dropping keys with no row', async () => {
await insertRaw('collab_chat_enabled', 'false');
await insertRaw('collab_notes_enabled', 'true');
const values = await appSettings.getValues(['collab_chat_enabled', 'collab_notes_enabled', 'collab_links_enabled']);
expect(values).toEqual(
new Map([
['collab_chat_enabled', 'false'],
['collab_notes_enabled', 'true'],
]),
);
});
it('APPSETREPO-012 (M1): getValues also drops a key whose row exists but whose value is NULL, matching the "row present with a NULL value" case as absent, same as a missing row', async () => {
await insertRaw('collab_chat_enabled', 'false');
await insertRaw('collab_links_enabled', null); // present row, NULL value — legacy treated this as absent too
const values = await appSettings.getValues(['collab_chat_enabled', 'collab_links_enabled', 'collab_notes_enabled']);
expect(values).toEqual(new Map([['collab_chat_enabled', 'false']]));
expect(values.has('collab_links_enabled')).toBe(false);
});
// Plan 3b Task 1 fix round (task-1-review.md B1): getValue is a
// primary-key findOne, which MikroORM would answer from the identity map
// on a repeat call absent `disableIdentityMap: true` — invisible to a raw
// write or delete on the same key inside the same request. These pin the
// fix at one query each.
describe('getValue sees a raw write/delete on the same key in the same request (disableIdentityMap regression)', () => {
it('APPSETREPO-013: deleteValue then getValue reads null, not the deleted row, in one query', async () => {
await insertRaw('bag_tracking_enabled', 'v');
expect(await appSettings.getValue('bag_tracking_enabled')).toBe('v'); // populate the identity map
await appSettings.deleteValue('bag_tracking_enabled');
const { value, queries } = await withQueryCount(() => appSettings.getValue('bag_tracking_enabled'));
expect(value).toBeNull();
expect(queries).toBe(1);
});
it('APPSETREPO-014: an UPDATE from another context on the same key then getValue reads the new value, in one query', async () => {
await insertRaw('bag_tracking_enabled', 'old');
expect(await appSettings.getValue('bag_tracking_enabled')).toBe('old'); // populate the identity map
await updateRows(t, AppSettings, { key: 'bag_tracking_enabled' }, { value: 'new' });
const { value, queries } = await withQueryCount(() => appSettings.getValue('bag_tracking_enabled'));
expect(value).toBe('new');
expect(queries).toBe(1);
});
});
it('APPSETREPO-004: setValue inserts a new row exactly as INSERT OR REPLACE would', async () => {
await appSettings.setValue('bag_tracking_enabled', 'true');
expect(rawRow('bag_tracking_enabled')).toStrictEqual({ key: 'bag_tracking_enabled', value: 'true' });
});
it('APPSETREPO-005: setValue on an existing key replaces the value only — the row (key, value) is byte-identical to INSERT OR REPLACE/ON CONFLICT DO UPDATE, because app_settings has no third column for either to reset', async () => {
await insertRaw('bag_tracking_enabled', 'false');
await appSettings.setValue('bag_tracking_enabled', 'true');
expect(rawRow('bag_tracking_enabled')).toStrictEqual({ key: 'bag_tracking_enabled', value: 'true' });
// Only the one row exists for that key — no duplicate/ghost row from upsert.
expect(await countRows(t, AppSettings, { key: 'bag_tracking_enabled' })).toBe(1);
});
it('APPSETREPO-006: deleteValue removes the row and returns the legacy DELETE-affected-row count', async () => {
await insertRaw('whitespace_migration_collision', 'true');
expect(await appSettings.deleteValue('whitespace_migration_collision')).toBe(1);
expect(rawRow('whitespace_migration_collision')).toBeUndefined();
});
it('APPSETREPO-007: deleteValue on a missing key is a no-op that reports 0 rows', async () => {
expect(await appSettings.deleteValue('does_not_exist')).toBe(0);
});
it('APPSETREPO-008: findByKeyPrefix matches every key sharing the prefix, in whatever order the table returns them', async () => {
await insertRaw('perm_view_days', '1');
await insertRaw('perm_edit_budget', '2');
await insertRaw('unrelated_key', '3');
const rows = await appSettings.findByKeyPrefix('perm_');
expect(rows.map((r) => r.key).sort()).toEqual(['perm_edit_budget', 'perm_view_days']);
expect(rows).toEqual(
expect.arrayContaining([
{ key: 'perm_view_days', value: '1' },
{ key: 'perm_edit_budget', value: '2' },
]),
);
});
it('APPSETREPO-009: findByKeyPrefix with no matches returns an empty array', async () => {
await insertRaw('unrelated_key', 'x');
expect(await appSettings.findByKeyPrefix('perm_')).toEqual([]);
});
// Plan 3i (storage task) additions: countKeysPresent (SR1's
// `SELECT COUNT(*) ... WHERE key IN (?, ?)`) and upsertOrReplace (SS1's
// `INSERT OR REPLACE`), kept as distinct methods from setValue's
// `ON CONFLICT DO UPDATE` upsert per R4/R5's ruling even though their
// observable behavior on this table is identical (setValue's own
// docstring explains why).
it('APPSETREPO-015: countKeysPresent counts every matching ROW, including one whose value is NULL — unlike getValues, which drops it', async () => {
await insertRaw('storage.backends', '[]');
await insertRaw('storage.categories', null); // present row, NULL value
expect(await appSettings.countKeysPresent(['storage.backends', 'storage.categories'])).toBe(2);
expect(await appSettings.countKeysPresent(['storage.backends', 'storage.does_not_exist'])).toBe(1);
expect(await appSettings.countKeysPresent(['storage.nope_a', 'storage.nope_b'])).toBe(0);
});
it('APPSETREPO-016: upsertOrReplace inserts a new row exactly as INSERT OR REPLACE would', async () => {
await appSettings.upsertOrReplace('storage.usage', '{"computedAt":1}');
expect(rawRow('storage.usage')).toStrictEqual({ key: 'storage.usage', value: '{"computedAt":1}' });
});
it('APPSETREPO-017: upsertOrReplace on an existing key replaces the value only, with no duplicate/ghost row', async () => {
await insertRaw('storage.usage', '{"computedAt":1}');
await appSettings.upsertOrReplace('storage.usage', '{"computedAt":2}');
expect(rawRow('storage.usage')).toStrictEqual({ key: 'storage.usage', value: '{"computedAt":2}' });
expect(await countRows(t, AppSettings, { key: 'storage.usage' })).toBe(1);
});
// LIKE-escaping finding: neither the legacy `LIKE 'prefix%'` literal nor
// `$like`'s bound parameter here escapes `%`/`_` in the prefix — a bound
// LIKE parameter's wildcards are interpreted by SQLite exactly like a
// literal's are, so `findByKeyPrefix` reproduces the legacy statement's
// matches (and its same non-escaping quirk) for a prefix containing either
// character. These tests compare the repository's result against the
// legacy raw-SQL statement directly, not against a hand-picked expectation.
describe('LIKE escaping — % and _ in the prefix are wildcards, not escaped, exactly as the legacy statement behaved', () => {
function legacyPrefixMatch(prefix: string): { key: string; value: string }[] {
// test-sql-allow: the legacy LIKE statement is the oracle the repository read is held to.
return testDb.prepare('SELECT key, value FROM app_settings WHERE key LIKE ?').all(`${prefix}%`) as {
key: string;
value: string;
}[];
}
it('APPSETREPO-010: an underscore in the prefix matches any single character there, like a raw LIKE pattern would', async () => {
// 'ab_c%' as a LIKE pattern: '_' matches any one character, so both
// 'ab_cd' (literal underscore) and 'abXcd' (any other character) match.
await insertRaw('ab_cd', '1');
await insertRaw('abXcd', '2');
await insertRaw('abcd', '3'); // one character short at that position — no match
const rows = await appSettings.findByKeyPrefix('ab_c');
expect(rows.map((r) => r.key).sort()).toEqual(
legacyPrefixMatch('ab_c')
.map((r) => r.key)
.sort(),
);
expect(rows.map((r) => r.key).sort()).toEqual(['abXcd', 'ab_cd']);
});
it('APPSETREPO-011: a percent sign in the prefix matches zero or more characters there, like a raw LIKE pattern would', async () => {
// 'ab%c%' as a LIKE pattern: '%' matches zero-or-more, so both
// 'abc' (zero characters at the % position) and 'abZZc' match.
await insertRaw('abc', '1');
await insertRaw('abZZc', '2');
await insertRaw('abd', '3'); // no 'c' after the gap — no match
const rows = await appSettings.findByKeyPrefix('ab%c');
expect(rows.map((r) => r.key).sort()).toEqual(
legacyPrefixMatch('ab%c')
.map((r) => r.key)
.sort(),
);
expect(rows.map((r) => r.key).sort()).toEqual(['abZZc', 'abc']);
});
});
});
@@ -0,0 +1,351 @@
/**
* AssignmentParticipantsRepository.listForAssignments (Plan 3c Task 1, QH3):
* the batch participants-by-assignment loader behind
* `QueryHelpersService.loadParticipantsByAssignmentIds`, moved off
* `query-helpers.service.ts`. Deliberately no `COALESCE(display_name,
* username)` — unlike `AssignmentsService.getParticipants` (AS15) — see the
* repository's own docstring.
*/
import { AssignmentParticipants } from '../../../../src/db/entities/AssignmentParticipants.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type { AssignmentParticipantsRepository } from '../../../../src/db/repositories/AssignmentParticipants.repository';
import { withRequestContext } from '../../../../src/nest/database/request-context';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createDay, createDayAssignment, createPlace, createTrip, createUser } from '../../../helpers/factories';
import { findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let participants: AssignmentParticipantsRepository;
let uow: UnitOfWork;
beforeAll(async () => {
t = await createTestOrm(testDb);
participants = t.repo(AssignmentParticipants);
uow = new UnitOfWork(t.em);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function addParticipant(assignmentId: number, userId: number): Promise<void> {
await insertRow(t, AssignmentParticipants, { assignment: assignmentId, user: userId });
}
async function participantUserIds(assignmentId: number) {
return (await findRows(t, AssignmentParticipants, { assignment: assignmentId })).map((r) => ({ user_id: r.user_id }));
}
async function withQueryCount<T>(fn: () => Promise<T>): Promise<{ value: T; queries: number }> {
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
try {
const value = await fn();
return { value, queries: spy.mock.calls.length };
} finally {
spy.mockRestore();
}
}
describe('AssignmentParticipantsRepository.listForAssignments', () => {
it('ASSIGNPARTREPO-001: an empty assignmentIds array short-circuits to [] without querying', async () => {
const { value, queries } = await withQueryCount(() => participants.listForAssignments([]));
expect(value).toEqual([]);
expect(queries).toBe(0);
});
it("ASSIGNPARTREPO-002: joins the user's username/avatar, with NO COALESCE(display_name, username) — raw username only", async () => {
const { user: owner } = createUser(testDb);
const { user: participant } = createUser(testDb, { username: 'raw-username' });
await updateRows(t, Users, { id: participant.id }, { display_name: 'A Display Name' });
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
await addParticipant(assignment.id, participant.id);
const rows = await participants.listForAssignments([assignment.id]);
expect(rows).toEqual([
{ assignment_id: assignment.id, user_id: participant.id, username: 'raw-username', avatar: null },
]);
});
it('ASSIGNPARTREPO-003: batches across several assignments', async () => {
const { user: owner } = createUser(testDb);
const { user: p1 } = createUser(testDb);
const { user: p2 } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const placeA = createPlace(testDb, trip.id, { name: 'A' });
const placeB = createPlace(testDb, trip.id, { name: 'B' });
const a1 = createDayAssignment(testDb, day.id, placeA.id);
const a2 = createDayAssignment(testDb, day.id, placeB.id);
await addParticipant(a1.id, p1.id);
await addParticipant(a2.id, p2.id);
const rows = await participants.listForAssignments([a1.id, a2.id]);
expect(rows.map((r) => r.assignment_id).sort()).toEqual([a1.id, a2.id].sort());
});
it('ASSIGNPARTREPO-004: an assignment with no participants contributes no rows', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
expect(await participants.listForAssignments([assignment.id])).toEqual([]);
});
// Task 9 fix wave (B-M3): relabelled. `listForAssignments` is a
// `qb().execute('all', false)` projection, and `TrekRepository` applies
// `disableIdentityMap: true` to every read by construction anyway, so
// there is no live identity-map entry here to bypass — this proves a DB
// round-trip, not an identity-map bypass.
it('ASSIGNPARTREPO-005 (fresh after a raw UPDATE, not D-shape): a participant added after an unrelated identity-map read is visible in the FIRST wider projection', async () => {
const { user: owner } = createUser(testDb);
const { user: participant } = createUser(testDb, { username: 'fresh-participant' });
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
// Task 2 review (task-2-review.md, L1, program note): `{
// disableIdentityMap: false }` on the setup read, for consistency with
// every other D-shape test in this file — this particular read is
// genuinely empty (no participant row exists yet), so the flag changes
// nothing here, but the mechanical fix is applied uniformly rather than
// singled out.
await t.repo(AssignmentParticipants).find({}, { disableIdentityMap: false }); // populate the identity map with an unrelated (empty) read
await addParticipant(assignment.id, participant.id);
const rows = await participants.listForAssignments([assignment.id]);
expect(rows).toEqual([
{ assignment_id: assignment.id, user_id: participant.id, username: 'fresh-participant', avatar: null },
]);
});
});
// ---------------------------------------------------------------------------
// Plan 3c Task 3 (`AssignmentsService`) — appended after Task 1's own
// `listForAssignments` suite above, per this task's file-ownership rule.
// The whole file is committed under this task's message; see its report for
// the coordination note.
// ---------------------------------------------------------------------------
/** The AS2/AS15/AS31 statement, run raw — the parity oracle every assertion below is checked against. */
function legacyParticipantRows(assignmentId: number): unknown {
// test-sql-allow: the legacy statement is this parity test's oracle and has to run as written.
return testDb
.prepare(
`
SELECT ap.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM assignment_participants ap
JOIN users u ON ap.user_id = u.id
WHERE ap.assignment_id = ?
`,
)
.all(assignmentId);
}
describe('AssignmentParticipantsRepository.listWithDisplayName (AS2/AS15/AS31)', () => {
it('ASSIGNPARTREPO-006: no assignment_id key — a narrower row than listForAssignments (QH3)', async () => {
const { user: owner } = createUser(testDb);
const { user: participant } = createUser(testDb, { username: 'raw-username' });
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
await addParticipant(assignment.id, participant.id);
const rows = await participants.listWithDisplayName(assignment.id);
expect(rows).toStrictEqual(legacyParticipantRows(assignment.id));
expect(rows[0]).not.toHaveProperty('assignment_id');
});
it('ASSIGNPARTREPO-007: username COALESCEs display_name over username, when set', async () => {
const { user: owner } = createUser(testDb);
const { user: withDisplayName } = createUser(testDb, { username: 'raw-username' });
await updateRows(t, Users, { id: withDisplayName.id }, { display_name: 'Fancy Name' });
const { user: withoutDisplayName } = createUser(testDb, { username: 'plain-username' });
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
await addParticipant(assignment.id, withDisplayName.id);
await addParticipant(assignment.id, withoutDisplayName.id);
const rows = await participants.listWithDisplayName(assignment.id);
expect(rows).toEqual(
expect.arrayContaining([
{ user_id: withDisplayName.id, username: 'Fancy Name', avatar: null },
{ user_id: withoutDisplayName.id, username: 'plain-username', avatar: null },
]),
);
expect(rows).toStrictEqual(legacyParticipantRows(assignment.id));
});
it('ASSIGNPARTREPO-008: an assignment with no participants returns []', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
expect(await participants.listWithDisplayName(assignment.id)).toEqual([]);
});
// Task 9 fix wave (B-M3): relabelled — same reasoning as ASSIGNPARTREPO-005
// above: a `qb().execute('all', false)` projection never hydrates an
// entity into the identity map, and the base default leaves it disabled
// anyway, so this proves a DB round-trip, not an identity-map bypass.
it('ASSIGNPARTREPO-009 (fresh after a raw UPDATE, not D-shape): a participant added after an unrelated identity-map read is visible in the FIRST wider projection', async () => {
const { user: owner } = createUser(testDb);
const { user: participant } = createUser(testDb, { username: 'fresh-participant-2' });
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
await t.repo(AssignmentParticipants).find({}, { disableIdentityMap: false });
await addParticipant(assignment.id, participant.id);
const rows = await participants.listWithDisplayName(assignment.id);
expect(rows).toEqual([{ user_id: participant.id, username: 'fresh-participant-2', avatar: null }]);
});
});
describe('AssignmentParticipantsRepository.deleteForAssignment / insertIgnore (AS29/AS30)', () => {
it('ASSIGNPARTREPO-010: deleteForAssignment removes every row for the assignment, none other', async () => {
const { user: owner } = createUser(testDb);
const { user: p1 } = createUser(testDb);
const { user: p2 } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const a1 = createDayAssignment(testDb, day.id, place.id);
const a2 = createDayAssignment(testDb, day.id, place.id);
await addParticipant(a1.id, p1.id);
await addParticipant(a2.id, p2.id);
await withRequestContext(t.orm, async () => {
await participants.deleteForAssignment(a1.id);
});
expect(await participants.listWithDisplayName(a1.id)).toEqual([]);
expect(await participants.listWithDisplayName(a2.id)).toHaveLength(1);
});
it('ASSIGNPARTREPO-011: insertIgnore writes every id once; a duplicate id in the same call collapses to one row', async () => {
const { user: owner } = createUser(testDb);
const { user: p1 } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
await withRequestContext(t.orm, async () => {
await participants.insertIgnore(assignment.id, [p1.id, p1.id]);
});
const rows = await participantUserIds(assignment.id);
expect(rows).toEqual([{ user_id: p1.id }]);
});
it('ASSIGNPARTREPO-012: insertIgnore does not conflict with an existing row for a DIFFERENT assignment', async () => {
const { user: owner } = createUser(testDb);
const { user: shared } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const a1 = createDayAssignment(testDb, day.id, place.id);
const a2 = createDayAssignment(testDb, day.id, place.id);
await addParticipant(a1.id, shared.id);
await withRequestContext(t.orm, async () => {
await participants.insertIgnore(a2.id, [shared.id]);
});
expect(await participants.listWithDisplayName(a1.id)).toHaveLength(1);
expect(await participants.listWithDisplayName(a2.id)).toHaveLength(1);
});
it('ASSIGNPARTREPO-013: an empty user_ids array writes nothing (0 queries)', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
const { queries } = await withQueryCount(() =>
withRequestContext(t.orm, async () => {
await participants.insertIgnore(assignment.id, []);
}),
);
expect(queries).toBe(0);
});
it('ASSIGNPARTREPO-014: deleteForAssignment + insertIgnore inside a rolled-back transaction leave the row unchanged (joins the ambient transaction)', async () => {
const { user: owner } = createUser(testDb);
const { user: p1 } = createUser(testDb);
const { user: p2 } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
await addParticipant(assignment.id, p1.id);
let caught: unknown;
try {
await withRequestContext(t.orm, async () => {
await uow.transactional(async () => {
await participants.deleteForAssignment(assignment.id);
await participants.insertIgnore(assignment.id, [p2.id]);
throw new Error('force rollback');
});
});
} catch (e) {
caught = e;
}
expect((caught as Error).message).toBe('force rollback');
const rows = await participantUserIds(assignment.id);
expect(rows).toEqual([{ user_id: p1.id }]);
});
});
// ── Plan 3c Task 8 (`TripsService.copy`, TP53) — additive ───────────────────
describe('AssignmentParticipantsRepository.listForTrip (TP53)', () => {
it('ASSIGNPARTREPO-015: the two-hop join scopes participants to the trip, returning only assignment_id/user_id', async () => {
const { user: owner } = createUser(testDb);
const { user: p1 } = createUser(testDb);
const { user: p2 } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const other = createTrip(testDb, owner.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id);
const assignment = createDayAssignment(testDb, day.id, place.id);
await addParticipant(assignment.id, p1.id);
await addParticipant(assignment.id, p2.id);
const otherDay = createDay(testDb, other.id);
const otherPlace = createPlace(testDb, other.id);
const otherAssignment = createDayAssignment(testDb, otherDay.id, otherPlace.id);
await addParticipant(otherAssignment.id, p1.id);
const rows = await participants.listForTrip(trip.id);
expect(rows.map((r) => r.user_id).sort((a, b) => a - b)).toEqual([p1.id, p2.id].sort((a, b) => a - b));
expect(rows.every((r) => r.assignment_id === assignment.id)).toBe(true);
});
it('ASSIGNPARTREPO-016: a trip with no participants returns []', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(await participants.listForTrip(trip.id)).toEqual([]);
});
});
@@ -0,0 +1,141 @@
/**
* The files attached in a trip chat through their repository: an attachment
* is only reached in its own thread by the user who attached it, its text
* reaches the model only once it is shared, the first agreement's time stays,
* and the retention sweep finds, matches and drops rows by age and key.
*/
import { AssistantAttachments } from '../../../../src/db/entities/AssistantAttachments.entity';
import { AssistantThreads } from '../../../../src/db/entities/AssistantThreads.entity';
import type { AssistantAttachmentsRepository } from '../../../../src/db/repositories/AssistantAttachments.repository';
import type { AssistantThreadsRepository } from '../../../../src/db/repositories/AssistantThreads.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeTripFile } from '../../../helpers/factories/files';
import { makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let attachments: AssistantAttachmentsRepository;
let threads: AssistantThreadsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
attachments = t.repo(AssistantAttachments);
threads = t.repo(AssistantThreads);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const AT = '2026-10-20 10:00:00';
const LATER = '2026-10-21 10:00:00';
const ID_A = '0b6c1f7e-3d2a-4c5b-9e8f-1a2b3c4d5e6f';
const ID_B = '1c7d2a8f-4e3b-4d6c-8f9a-2b3c4d5e6f70';
async function threadOf() {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const threadId = await threads.createThread(user.id, trip.id, 'Porto', AT);
return { userId: user.id, tripId: trip.id, threadId };
}
function attach(
at: { userId: number; tripId: number; threadId: number },
id: string,
over: { text?: string | null; createdAt?: string; storageKey?: string } = {},
) {
return attachments.insertAttachment({
id,
threadId: at.threadId,
userId: at.userId,
tripId: at.tripId,
name: 'AirBnB Buchung.pdf',
mime: 'application/pdf',
size: 2048,
sha256: 'f'.repeat(64),
storageKey: over.storageKey ?? `assistant/${id}.pdf`,
text: over.text === undefined ? 'Check-in 14:00' : over.text,
textStatus: over.text === null ? 'empty' : 'ok',
createdAt: over.createdAt ?? AT,
});
}
describe('AssistantAttachmentsRepository', () => {
it('ASTATTREPO-001: an attachment is reached only in its own thread by the user who attached it', async () => {
const at = await threadOf();
const other = await threadOf();
await attach(at, ID_A);
const row = await attachments.findInThread(ID_A, at.threadId, at.userId);
expect(row).toMatchObject({ id: ID_A, name: 'AirBnB Buchung.pdf', text: 'Check-in 14:00', text_status: 'ok' });
expect(await attachments.findInThread(ID_A, other.threadId, at.userId)).toBeNull();
expect(await attachments.findInThread(ID_A, at.threadId, other.userId)).toBeNull();
expect(await attachments.findInThread(ID_B, at.threadId, at.userId)).toBeNull();
});
it('ASTATTREPO-002: a thread lists its attachments oldest first and without their text', async () => {
const at = await threadOf();
await attach(at, ID_B, { createdAt: LATER });
await attach(at, ID_A);
const listed = await attachments.listForThread(at.threadId, at.userId);
expect(listed.map((a) => a.id)).toEqual([ID_A, ID_B]);
expect(listed[0]).not.toHaveProperty('text');
expect(await attachments.listObjectsOfThread(at.threadId, at.userId)).toEqual(
expect.arrayContaining([
{ id: ID_A, storage_key: `assistant/${ID_A}.pdf` },
{ id: ID_B, storage_key: `assistant/${ID_B}.pdf` },
]),
);
});
it('ASTATTREPO-003: a text reaches the model only once shared, and the first agreement keeps its time', async () => {
const at = await threadOf();
await attach(at, ID_A);
await attach(at, ID_B, { text: null });
expect(await attachments.listSharedTexts(at.threadId, at.userId)).toEqual([]);
expect(await attachments.markShared(ID_A, at.threadId, at.userId, AT)).toBe(true);
expect(await attachments.markShared(ID_A, at.threadId, at.userId, LATER)).toBe(false);
expect(await attachments.markShared(ID_B, at.threadId, at.userId, AT)).toBe(true);
expect((await attachments.findInThread(ID_A, at.threadId, at.userId))?.shared_at).toBe(AT);
// A shared attachment without text has nothing to send.
expect(await attachments.listSharedTexts(at.threadId, at.userId)).toEqual([{ id: ID_A, text: 'Check-in 14:00' }]);
});
it('ASTATTREPO-004: a kept attachment names its trip file', async () => {
const at = await threadOf();
await attach(at, ID_A);
const file = await makeTripFile(t, at.tripId);
await attachments.setFile(ID_A, file.id);
expect((await attachments.findInThread(ID_A, at.threadId, at.userId))?.file_id).toBe(file.id);
});
it('ASTATTREPO-005: the sweep finds old rows by age, matches known keys and drops rows by id', async () => {
const at = await threadOf();
await attach(at, ID_A);
await attach(at, ID_B, { createdAt: LATER });
expect(await attachments.listCreatedBefore(LATER, 10)).toEqual([
{ id: ID_A, storage_key: `assistant/${ID_A}.pdf` },
]);
expect(await attachments.listCreatedBefore('2026-10-22 00:00:00', 1)).toHaveLength(1);
expect(await attachments.listKnownKeys([`assistant/${ID_B}.pdf`, 'assistant/gone.pdf'])).toEqual([
`assistant/${ID_B}.pdf`,
]);
expect(await attachments.listKnownKeys([])).toEqual([]);
expect(await attachments.deleteByIds([])).toBe(0);
expect(await attachments.deleteByIds([ID_A, 'not-there'])).toBe(1);
expect(await attachments.listForThread(at.threadId, at.userId)).toHaveLength(1);
});
});
@@ -0,0 +1,415 @@
/**
* The assistant's conversation tables through their repositories: threads
* reached only by their owner on their own trip or journey, messages in the
* order they were written, proposed changes decided and undone exactly once,
* the usage a daily limit counts, and everything going with its user, trip or
* journey (GDPR).
*/
import { AssistantMessages } from '../../../../src/db/entities/AssistantMessages.entity';
import { AssistantThreads } from '../../../../src/db/entities/AssistantThreads.entity';
import { AssistantToolCalls } from '../../../../src/db/entities/AssistantToolCalls.entity';
import { AssistantUsage } from '../../../../src/db/entities/AssistantUsage.entity';
import { JourneyContributors } from '../../../../src/db/entities/JourneyContributors.entity';
import { Journeys } from '../../../../src/db/entities/Journeys.entity';
import { TripJournalLinkMembers } from '../../../../src/db/entities/TripJournalLinkMembers.entity';
import { TripJournalLinks } from '../../../../src/db/entities/TripJournalLinks.entity';
import { Trips } from '../../../../src/db/entities/Trips.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type { AssistantMessagesRepository } from '../../../../src/db/repositories/AssistantMessages.repository';
import type { AssistantThreadsRepository } from '../../../../src/db/repositories/AssistantThreads.repository';
import type { AssistantToolCallsRepository } from '../../../../src/db/repositories/AssistantToolCalls.repository';
import type { AssistantUsageRepository } from '../../../../src/db/repositories/AssistantUsage.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { addJourneyContributor, makeJourney } from '../../../helpers/factories/journeys';
import { countRows, createRow, deleteRows, insertRow } from '../../../helpers/factories/rows';
import { addTripMember, makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let threads: AssistantThreadsRepository;
let messages: AssistantMessagesRepository;
let calls: AssistantToolCallsRepository;
let usage: AssistantUsageRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
threads = t.repo(AssistantThreads);
messages = t.repo(AssistantMessages);
calls = t.repo(AssistantToolCalls);
usage = t.repo(AssistantUsage);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const AT = '2026-10-20 10:00:00';
const LATER = '2026-10-20 11:00:00';
async function ownerWithTrip() {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
return { userId: user.id, tripId: trip.id };
}
async function ownerWithJourney() {
const { user } = await makeUser(t);
const journey = await makeJourney(t, user.id);
return { userId: user.id, journeyId: journey.id };
}
async function threadWithMessage() {
const { userId, tripId } = await ownerWithTrip();
const threadId = await threads.createThread(userId, tripId, 'Kyoto day', AT);
const messageId = await messages.append({
threadId,
role: 'assistant',
parts: '[]',
providerState: null,
status: 'awaiting_approval',
model: 'claude',
createdAt: AT,
});
return { userId, tripId, threadId, messageId };
}
function proposal(id: string, threadId: number, messageId: number, providerCallId = id) {
return {
id,
threadId,
messageId,
providerCallId,
toolName: 'create_place',
args: '{}',
preview: '{}',
createdAt: AT,
};
}
describe('threads', () => {
it('ASTREPO-001: a thread is found, listed and deleted only by its owner on its trip', async () => {
const { userId, tripId } = await ownerWithTrip();
const { user: other } = await makeUser(t);
const older = await threads.createThread(userId, tripId, 'First', AT);
const newer = await threads.createThread(userId, tripId, 'Second', AT);
await threads.touch(older, LATER);
expect((await threads.listRecent(userId, tripId, 20)).map((row) => row.id)).toEqual([older, newer]);
expect(await threads.listRecent(userId, tripId, 1)).toHaveLength(1);
expect(await threads.findOwned(older, other.id, tripId)).toBeNull();
expect(await threads.findOwned(older, userId, tripId + 1)).toBeNull();
expect(await threads.findOwned(older, userId, tripId)).toMatchObject({ title: 'First', last_message_at: LATER });
expect(await threads.deleteOwned(older, other.id, tripId)).toBe(false);
expect(await threads.deleteOwned(older, userId, tripId)).toBe(true);
});
it('ASTREPO-002: retention drops idle threads and the threads of users who left the trip', async () => {
const { userId, tripId } = await ownerWithTrip();
const { user: member } = await makeUser(t);
const { user: leaver } = await makeUser(t);
await addTripMember(t, tripId, member.id);
const idle = await threads.createThread(userId, tripId, 'Idle', '2026-01-01 00:00:00');
const kept = await threads.createThread(userId, tripId, 'Kept', AT);
const memberThread = await threads.createThread(member.id, tripId, 'Member', AT);
await threads.createThread(leaver.id, tripId, 'Leaver', AT);
expect(await threads.deleteIdleBefore('2026-06-01 00:00:00')).toBe(1);
expect(await threads.deleteWithoutAccess()).toBe(1);
expect((await threads.listRecent(userId, tripId, 20)).map((row) => row.id)).toEqual([kept]);
expect(await threads.findOwned(memberThread, member.id, tripId)).not.toBeNull();
expect(await threads.findOwned(idle, userId, tripId)).toBeNull();
});
});
describe('journey threads', () => {
it('ASTREPO-003: a journey thread is found, listed and deleted only by its owner on its journey, never on a trip', async () => {
const { userId, journeyId } = await ownerWithJourney();
const { user: other } = await makeUser(t);
const trip = await makeTrip(t, userId);
const older = await threads.createJourneyThread(userId, journeyId, 'Cover', AT);
const newer = await threads.createJourneyThread(userId, journeyId, 'Pages', AT);
const onTrip = await threads.createThread(userId, trip.id, 'Kyoto', AT);
await threads.touch(older, LATER);
expect((await threads.listRecentOnJourney(userId, journeyId, 20)).map((row) => row.id)).toEqual([older, newer]);
expect((await threads.listRecent(userId, trip.id, 20)).map((row) => row.id)).toEqual([onTrip]);
expect(await threads.findOwnedOnJourney(older, userId, journeyId)).toMatchObject({
title: 'Cover',
journey_id: journeyId,
trip_id: null,
});
expect(await threads.findOwnedOnJourney(older, other.id, journeyId)).toBeNull();
expect(await threads.findOwnedOnJourney(older, userId, journeyId + 1)).toBeNull();
expect(await threads.findOwnedOnJourney(onTrip, userId, journeyId)).toBeNull();
expect(await threads.findOwned(older, userId, trip.id)).toBeNull();
expect(await threads.findOwned(onTrip, userId, trip.id)).toMatchObject({ trip_id: trip.id, journey_id: null });
expect(await threads.deleteOwnedOnJourney(older, other.id, journeyId)).toBe(false);
expect(await threads.deleteOwned(older, userId, trip.id)).toBe(false);
expect(await threads.deleteOwnedOnJourney(older, userId, journeyId)).toBe(true);
});
it('ASTREPO-004: retention keeps the threads of the journey owner and its contributors, and drops those of people taken off it', async () => {
const { userId, journeyId } = await ownerWithJourney();
const { user: editor } = await makeUser(t);
const { user: leaver } = await makeUser(t);
await addJourneyContributor(t, journeyId, editor.id, 'editor');
await addJourneyContributor(t, journeyId, leaver.id, 'viewer');
const own = await threads.createJourneyThread(userId, journeyId, 'Own', AT);
const edited = await threads.createJourneyThread(editor.id, journeyId, 'Editor', AT);
const left = await threads.createJourneyThread(leaver.id, journeyId, 'Leaver', AT);
await deleteRows(t, JourneyContributors, { journey: journeyId, user: leaver.id });
expect(await threads.deleteWithoutAccess()).toBe(1);
expect(await threads.findOwnedOnJourney(own, userId, journeyId)).not.toBeNull();
expect(await threads.findOwnedOnJourney(edited, editor.id, journeyId)).not.toBeNull();
expect(await threads.findOwnedOnJourney(left, leaver.id, journeyId)).toBeNull();
});
it('ASTREPO-006: retention keeps the journey threads of someone a trip journal link lets in, until it drops them', async () => {
const { userId, journeyId } = await ownerWithJourney();
const trip = await makeTrip(t, userId);
const { user: member } = await makeUser(t);
const link = await createRow(t, TripJournalLinks, { trip: trip.id, journey: journeyId, created_at: Date.now() });
await insertRow(t, TripJournalLinkMembers, { link: link.id, user: member.id, added_at: Date.now() });
const linked = await threads.createJourneyThread(member.id, journeyId, 'Linked', AT);
expect(await threads.deleteWithoutAccess()).toBe(0);
expect(await threads.findOwnedOnJourney(linked, member.id, journeyId)).not.toBeNull();
await deleteRows(t, TripJournalLinkMembers, { link: link.id, user: member.id });
expect(await threads.deleteWithoutAccess()).toBe(1);
expect(await threads.findOwnedOnJourney(linked, member.id, journeyId)).toBeNull();
});
it('ASTREPO-005: a change of a journey thread is found only through its own user and journey', async () => {
const { userId, journeyId } = await ownerWithJourney();
const { user: other } = await makeUser(t);
const threadId = await threads.createJourneyThread(userId, journeyId, 'Book', AT);
const messageId = await messages.append({
threadId,
role: 'assistant',
parts: '[]',
providerState: null,
status: 'awaiting_approval',
model: 'claude',
createdAt: AT,
});
await calls.insertProposals([proposal('j1', threadId, messageId)]);
expect(await calls.findOwnedOnJourney('j1', userId, journeyId)).toMatchObject({ id: 'j1', thread_id: threadId });
expect(await calls.findOwnedOnJourney('j1', other.id, journeyId)).toBeNull();
expect(await calls.findOwnedOnJourney('j1', userId, journeyId + 1)).toBeNull();
expect(await calls.findOwned('j1', userId, journeyId)).toBeNull();
await deleteRows(t, Journeys, { id: journeyId });
expect(await countRows(t, AssistantThreads, { id: threadId })).toBe(0);
expect(await countRows(t, AssistantMessages, { id: messageId })).toBe(0);
expect(await countRows(t, AssistantToolCalls, { id: 'j1' })).toBe(0);
});
});
describe('home threads', () => {
it('ASTREPO-007: a home thread is found, listed and deleted only by its owner at home, never on a trip or a journey', async () => {
const { userId, tripId } = await ownerWithTrip();
const journey = await makeJourney(t, userId);
const { user: other } = await makeUser(t);
const older = await threads.createHomeThread(userId, 'Next trip', AT);
const newer = await threads.createHomeThread(userId, 'Atlas', AT);
const onTrip = await threads.createThread(userId, tripId, 'Kyoto', AT);
const onJourney = await threads.createJourneyThread(userId, journey.id, 'Book', AT);
await threads.createHomeThread(other.id, 'Theirs', AT);
await threads.touch(older, LATER);
expect((await threads.listRecentAtHome(userId, 20)).map((row) => row.id)).toEqual([older, newer]);
expect(await threads.listRecentAtHome(userId, 1)).toHaveLength(1);
expect((await threads.listRecent(userId, tripId, 20)).map((row) => row.id)).toEqual([onTrip]);
expect(await threads.findOwnedAtHome(older, userId)).toMatchObject({
title: 'Next trip',
trip_id: null,
journey_id: null,
last_message_at: LATER,
});
expect(await threads.findOwnedAtHome(older, other.id)).toBeNull();
expect(await threads.findOwnedAtHome(onTrip, userId)).toBeNull();
expect(await threads.findOwnedAtHome(onJourney, userId)).toBeNull();
expect(await threads.findOwned(older, userId, tripId)).toBeNull();
expect(await threads.findOwnedOnJourney(older, userId, journey.id)).toBeNull();
expect(await threads.deleteOwnedAtHome(older, other.id)).toBe(false);
expect(await threads.deleteOwnedAtHome(onTrip, userId)).toBe(false);
expect(await threads.deleteOwned(older, userId, tripId)).toBe(false);
expect(await threads.deleteOwnedAtHome(older, userId)).toBe(true);
expect(await threads.findOwnedAtHome(older, userId)).toBeNull();
});
it('ASTREPO-008: retention keeps a home thread while it is in use and its user stays', async () => {
const { user } = await makeUser(t);
const kept = await threads.createHomeThread(user.id, 'Kept', AT);
const idle = await threads.createHomeThread(user.id, 'Idle', '2026-01-01 00:00:00');
expect(await threads.deleteWithoutAccess()).toBe(0);
expect(await threads.deleteIdleBefore('2026-06-01 00:00:00')).toBe(1);
expect(await threads.findOwnedAtHome(kept, user.id)).not.toBeNull();
expect(await threads.findOwnedAtHome(idle, user.id)).toBeNull();
await deleteRows(t, Users, { id: user.id });
expect(await countRows(t, AssistantThreads, { id: kept })).toBe(0);
});
it('ASTREPO-009: a change of a home thread is found only through its own user, never on a trip or a journey', async () => {
const { userId, tripId } = await ownerWithTrip();
const { user: other } = await makeUser(t);
const threadId = await threads.createHomeThread(userId, 'Atlas', AT);
const messageId = await messages.append({
threadId,
role: 'assistant',
parts: '[]',
providerState: null,
status: 'awaiting_approval',
model: 'claude',
createdAt: AT,
});
await calls.insertProposals([proposal('h1', threadId, messageId)]);
expect(await calls.findOwnedAtHome('h1', userId)).toMatchObject({ id: 'h1', thread_id: threadId });
expect(await calls.findOwnedAtHome('h1', other.id)).toBeNull();
expect(await calls.findOwned('h1', userId, tripId)).toBeNull();
const { threadId: tripThread, messageId: tripMessage, userId: tripUser } = await threadWithMessage();
await calls.insertProposals([proposal('t1', tripThread, tripMessage)]);
expect(await calls.findOwnedAtHome('t1', tripUser)).toBeNull();
});
});
describe('messages', () => {
it('ASTREPO-010: the latest messages come oldest first, and a message changes its parts and status', async () => {
const { threadId, messageId } = await threadWithMessage();
const second = await messages.append({
threadId,
role: 'user',
parts: '[{"type":"text","text":"ok"}]',
providerState: null,
status: 'complete',
model: null,
createdAt: LATER,
});
expect((await messages.listLatest(threadId, 50)).map((row) => row.id)).toEqual([messageId, second]);
expect((await messages.listLatest(threadId, 1)).map((row) => row.id)).toEqual([second]);
await messages.update(messageId, {
status: 'complete',
providerState: '{"adapter":"openai-responses","items":[]}',
});
await messages.update(messageId, {});
expect(await messages.findInThread(messageId, threadId)).toMatchObject({
status: 'complete',
parts: '[]',
provider_state: '{"adapter":"openai-responses","items":[]}',
});
expect(await messages.findInThread(messageId, threadId + 1)).toBeNull();
});
});
describe('proposed changes', () => {
it('ASTREPO-020: a decision is taken once, only while waiting and in its own thread', async () => {
const { threadId, messageId } = await threadWithMessage();
await calls.insertProposals([proposal('c1', threadId, messageId), proposal('c2', threadId, messageId)]);
await calls.insertProposals([]);
expect((await calls.listOpen(threadId, AT)).map((row) => row.id)).toEqual(['c1', 'c2']);
// Proposed before `notBefore`, a change waits no more, though no sweep has marked it expired yet.
expect(await calls.listOpen(threadId, LATER)).toEqual([]);
expect(await calls.claimDecision('c1', threadId + 1, true, AT, LATER)).toBe(false);
expect(await calls.claimDecision('c1', threadId, true, '2026-10-21 00:00:00', LATER)).toBe(false);
expect(await calls.claimDecision('c1', threadId, true, AT, LATER)).toBe(true);
expect(await calls.claimDecision('c1', threadId, false, AT, LATER)).toBe(false);
expect(await calls.claimDecision('c2', threadId, false, AT, LATER)).toBe(true);
expect((await calls.listByMessage(messageId)).map((row) => [row.id, row.state])).toEqual([
['c1', 'approved'],
['c2', 'rejected'],
]);
});
it('ASTREPO-021: the provider call id is unique per thread, not across threads', async () => {
const a = await threadWithMessage();
const b = await threadWithMessage();
await calls.insertProposals([proposal('x1', a.threadId, a.messageId, 'toolu_1')]);
await calls.insertProposals([proposal('x2', b.threadId, b.messageId, 'toolu_1')]);
await expect(calls.insertProposals([proposal('x3', a.threadId, a.messageId, 'toolu_1')])).rejects.toThrow(/UNIQUE/);
});
it('ASTREPO-022: an executed change is undone once, by its owner, within its window', async () => {
const { userId, threadId, messageId } = await threadWithMessage();
const { user: other } = await makeUser(t);
await calls.insertProposals([proposal('u1', threadId, messageId)]);
await calls.claimDecision('u1', threadId, true, AT, AT);
await calls.recordOutcome('u1', 'executed', '{"place":{"id":5}}', '2026-10-20 10:15:00');
expect(await calls.findInThread('u1', threadId)).toMatchObject({ state: 'executed', result: '{"place":{"id":5}}' });
expect(await calls.claimUndo('u1', other.id, '2026-10-20 10:05:00')).toBe(false);
expect(await calls.claimUndo('u1', userId, '2026-10-20 10:20:00')).toBe(false);
expect(await calls.claimUndo('u1', userId, '2026-10-20 10:05:00')).toBe(true);
expect(await calls.claimUndo('u1', userId, '2026-10-20 10:05:00')).toBe(false);
});
it('ASTREPO-024: a call is found only through its own user and trip', async () => {
const { userId, tripId, threadId, messageId } = await threadWithMessage();
const { user: other } = await makeUser(t);
await calls.insertProposals([proposal('o1', threadId, messageId)]);
expect(await calls.findOwned('o1', userId, tripId)).toMatchObject({
id: 'o1',
thread_id: threadId,
state: 'approval_requested',
});
expect(await calls.findOwned('o1', other.id, tripId)).toBeNull();
expect(await calls.findOwned('o1', userId, tripId + 1)).toBeNull();
expect(await calls.findOwned('missing', userId, tripId)).toBeNull();
});
it('ASTREPO-023: proposals left waiting expire, and the answer names their messages', async () => {
const { threadId, messageId } = await threadWithMessage();
await calls.insertProposals([proposal('e1', threadId, messageId)]);
expect(await calls.expireBefore('2026-10-20 09:00:00')).toEqual([]);
expect(await calls.expireBefore('2026-10-21 10:00:00')).toEqual([{ id: 'e1', message_id: messageId }]);
expect((await calls.findInThread('e1', threadId))?.state).toBe('expired');
});
});
describe('usage', () => {
it('ASTREPO-030: turns and tokens add up per user, day and payer; old days are dropped', async () => {
const { user } = await makeUser(t);
await usage.add(user.id, '2026-10-20', 'instance', { turns: 1, inputTokens: 100, outputTokens: 10 });
await usage.add(user.id, '2026-10-20', 'instance', { turns: 1, inputTokens: 50, outputTokens: 5 });
await usage.add(user.id, '2026-10-20', 'user', { turns: 1, inputTokens: 0, outputTokens: 0 });
await usage.add(user.id, '2025-01-01', 'instance', { turns: 3, inputTokens: 0, outputTokens: 0 });
expect(await usage.turnsOn(user.id, '2026-10-20', 'instance')).toBe(2);
expect(await usage.turnsOn(user.id, '2026-10-21', 'instance')).toBe(0);
expect(await usage.deleteBefore('2026-01-01')).toBe(1);
expect(await countRows(t, AssistantUsage)).toBe(2);
});
});
describe('cascades', () => {
it('ASTREPO-040: a trip deleted takes its threads, messages and proposals; a user deleted takes their usage', async () => {
const { userId, tripId, threadId, messageId } = await threadWithMessage();
await calls.insertProposals([proposal('g1', threadId, messageId)]);
await usage.add(userId, '2026-10-20', 'user', { turns: 1, inputTokens: 0, outputTokens: 0 });
await deleteRows(t, Trips, { id: tripId });
expect(await countRows(t, AssistantThreads)).toBe(0);
expect(await countRows(t, AssistantMessages)).toBe(0);
expect(await countRows(t, AssistantToolCalls)).toBe(0);
await deleteRows(t, Users, { id: userId });
expect(await countRows(t, AssistantUsage)).toBe(0);
});
});
@@ -0,0 +1,172 @@
import { AppSettings } from '../../../../src/db/entities/AppSettings.entity';
import { AuditLog } from '../../../../src/db/entities/AuditLog.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type { AuditLogRepository } from '../../../../src/db/repositories/AuditLog.repository';
import { DB_TIMESTAMP_RE } from '../../../../src/db/types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser } from '../../../helpers/factories';
import { countRows, deleteRows, findRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let auditLog: AuditLogRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
auditLog = t.repo(AuditLog);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('AuditLogRepository', () => {
it('AUDITREPO-001: insert writes the legacy column set, matching the SELECT * row exactly', async () => {
const { user } = createUser(testDb);
await auditLog.insertEntry({
user_id: user.id,
action: 'trip.create',
resource: 'trip',
details: '{"title":"Rome"}',
ip: '1.2.3.4',
});
// test-sql-allow: the stored SELECT * row is the oracle for the legacy column set the insert must write.
const row = testDb.prepare('SELECT * FROM audit_log').get() as { id: number; created_at: string };
expect(row).toStrictEqual({
id: expect.any(Number),
created_at: expect.stringMatching(DB_TIMESTAMP_RE),
user_id: user.id,
action: 'trip.create',
resource: 'trip',
details: '{"title":"Rome"}',
ip: '1.2.3.4',
});
});
it('AUDITREPO-002: created_at is left to the column default, as text, in the YYYY-MM-DD HH:MM:SS shape', async () => {
const { user } = createUser(testDb);
await auditLog.insertEntry({ user_id: user.id, action: 'user.login', resource: null, details: null, ip: null });
// test-sql-allow: typeof() reports the storage class SQLite holds, which no entity maps.
const stored = testDb.prepare('SELECT created_at, typeof(created_at) AS kind FROM audit_log').get() as {
created_at: string;
kind: string;
};
expect(stored.kind).toBe('text');
expect(stored.created_at).toMatch(DB_TIMESTAMP_RE);
});
it('AUDITREPO-003: a null user writes a null user_id twin, not a foreign-key value', async () => {
await auditLog.insertEntry({ user_id: null, action: 'user.login', resource: null, details: null, ip: null });
const row = await findRow(t, AuditLog, {});
expect(row?.user_id).toBeNull();
});
it('AUDITREPO-004: null resource/details/ip are stored as NULL, not the string "null"', async () => {
const { user } = createUser(testDb);
await auditLog.insertEntry({ user_id: user.id, action: 'user.login', resource: null, details: null, ip: null });
const row = await findRow(t, AuditLog, {});
expect(row).toMatchObject({ resource: null, details: null, ip: null });
});
it('AUDITREPO-005: resolves without returning a value — no id or row is read back', async () => {
const { user } = createUser(testDb);
await expect(
auditLog.insertEntry({ user_id: user.id, action: 'user.login', resource: null, details: null, ip: null }),
).resolves.toBeUndefined();
});
it('AUDITREPO-006: a native insert, not a unit-of-work flush — another pending entity on the same EM stays unwritten', async () => {
const { user } = createUser(testDb);
// Left pending on purpose: `t.em.create` stages a change without flushing it.
t.em.create(AppSettings, { key: 'pending-during-audit-insert', value: 'should-not-be-written' });
await auditLog.insertEntry({ user_id: user.id, action: 'trip.create', resource: 'trip', details: null, ip: null });
const pendingCount = await countRows(t, AppSettings, { key: 'pending-during-audit-insert' });
expect(pendingCount).toBe(0);
const auditRow = await findRow(t, AuditLog, {});
expect(auditRow?.action).toBe('trip.create');
});
// ── Plan 3i Task 0 — listPage/count (AD22/AD23) ────────────────────────────
/** Byte-for-byte AD22 (`admin.service.ts#getAuditLog`). */
const LEGACY_PAGE_SQL = `
SELECT a.id, a.created_at, a.user_id, u.username, u.email as user_email, a.action, a.resource, a.details, a.ip
FROM audit_log a
LEFT JOIN users u ON u.id = a.user_id
ORDER BY a.id DESC
LIMIT ? OFFSET ?
`;
it('AUDITREPO-007: listPage matches the legacy joined SELECT exactly for a known user, a deleted (FK SET NULL) user, and a null user_id row', async () => {
const { user: alice } = createUser(testDb, { username: 'alice', email: 'alice@test.example.com' });
const { user: bob } = createUser(testDb, { username: 'bob', email: 'bob@test.example.com' });
await auditLog.insertEntry({
user_id: alice.id,
action: 'trip.create',
resource: 'trip',
details: '{"title":"Rome"}',
ip: '1.1.1.1',
});
await auditLog.insertEntry({
user_id: bob.id,
action: 'trip.update',
resource: 'trip',
details: null,
ip: '2.2.2.2',
});
await auditLog.insertEntry({ user_id: null, action: 'user.login', resource: null, details: null, ip: null });
// bob is deleted after the fact; `audit_log.user_id REFERENCES users(id)
// ON DELETE SET NULL` fires — this row's own user_id becomes NULL, the
// same shape a NULL-user_id row has, reached a different way.
await deleteRows(t, Users, { id: bob.id });
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb.prepare(LEGACY_PAGE_SQL).all(10, 0);
const result = await auditLog.listPage(10, 0);
expect(result).toEqual(legacy);
// The deleted user's row and the originally-null row both keep their
// place — a LEFT JOIN never drops the row.
expect(result).toHaveLength(3);
expect(result.filter((r) => r.username === null && r.user_email === null)).toHaveLength(2);
// The known user's row still carries its username/email.
const aliceRow = result.find((r) => r.user_id === alice.id);
expect(aliceRow?.username).toBe('alice');
expect(aliceRow?.user_email).toBe('alice@test.example.com');
});
it('AUDITREPO-008: listPage honors LIMIT/OFFSET and ORDER BY a.id DESC, matching the legacy statement', async () => {
const { user } = createUser(testDb);
for (let i = 0; i < 5; i++) {
await auditLog.insertEntry({ user_id: user.id, action: `action.${i}`, resource: null, details: null, ip: null });
}
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacyPage = testDb.prepare(LEGACY_PAGE_SQL).all(2, 1);
const result = await auditLog.listPage(2, 1);
expect(result).toEqual(legacyPage);
expect(result).toHaveLength(2);
});
it('AUDITREPO-009: count matches the legacy COUNT(*) over the whole table', async () => {
const { user } = createUser(testDb);
await auditLog.insertEntry({ user_id: user.id, action: 'a', resource: null, details: null, ip: null });
await auditLog.insertEntry({ user_id: null, action: 'b', resource: null, details: null, ip: null });
// test-sql-allow: the raw COUNT is the legacy oracle this parity test holds the repository to.
const legacyCount = (testDb.prepare('SELECT COUNT(*) as c FROM audit_log').get() as { c: number }).c;
const result = await auditLog.count();
expect(result).toBe(legacyCount);
expect(result).toBe(2);
});
});
@@ -0,0 +1,168 @@
import { BucketList } from '../../../../src/db/entities/BucketList.entity';
import type { BucketListRepository } from '../../../../src/db/repositories/BucketList.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser } from '../../../helpers/factories';
import { insertRow, insertRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let bucketList: BucketListRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
bucketList = t.repo(BucketList);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('BucketListRepository.listForPublicApi (Plan 4 Task 1, public-api.service.ts::listBucketList)', () => {
it('BUCKETREPO-001: name/lat/lng/country_code/notes/target_date only, ordered by created_at DESC then id DESC, scoped to the caller', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb, { username: 'other' });
await insertRows(t, BucketList, [
{
user: user.id,
name: 'Older',
lat: 1,
lng: 2,
country_code: 'JP',
notes: 'note',
target_date: null,
created_at: '2026-01-01T00:00:00.000Z',
},
{
user: user.id,
name: 'Newer',
lat: null,
lng: null,
country_code: null,
notes: null,
target_date: '2027-03-01',
created_at: '2026-02-01T00:00:00.000Z',
},
{
user: other.id,
name: 'Not mine',
lat: 9,
lng: 9,
country_code: null,
notes: null,
target_date: null,
created_at: '2026-03-01T00:00:00.000Z',
},
]);
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb
.prepare(
'SELECT name, lat, lng, country_code, notes, target_date FROM bucket_list WHERE user_id = ? ORDER BY created_at DESC, id DESC',
)
.all(user.id);
const rows = await bucketList.listForPublicApi(user.id);
expect(rows).toEqual(legacy);
expect(rows.map((r) => r.name)).toEqual(['Newer', 'Older']);
});
it('BUCKETREPO-002: same-instant rows tiebreak on id DESC (the second ORDER BY key)', async () => {
const { user } = createUser(testDb);
await insertRow(t, BucketList, { user: user.id, name: 'First inserted', created_at: '2026-01-01T00:00:00.000Z' });
await insertRow(t, BucketList, { user: user.id, name: 'Second inserted', created_at: '2026-01-01T00:00:00.000Z' });
const rows = await bucketList.listForPublicApi(user.id);
expect(rows.map((r) => r.name)).toEqual(['Second inserted', 'First inserted']);
});
it('BUCKETREPO-003: empty array for a user with nothing on their list', async () => {
const { user } = createUser(testDb);
expect(await bucketList.listForPublicApi(user.id)).toEqual([]);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Plan 4 Task 8b-2, item 3 (3f L6 carry): AT30/AT33/AT34 had no
// repository-level toEqual(<legacy raw>) parity test. `SELECT *` — every
// nullable column (target_date, visited_at, visited_source, notes, lat/lng,
// country_code) exercised both NULL and SET.
// ─────────────────────────────────────────────────────────────────────────────
describe('BucketListRepository.listForUser (AT30) — SELECT * ordered by created_at DESC', () => {
it('BUCKETREPO-004: matches the legacy row exactly, every nullable column both NULL and SET', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb, { username: 'other' });
const sparse = await insertRow(t, BucketList, {
user: user.id,
name: 'Sparse',
created_at: '2026-01-01T00:00:00.000Z',
});
const full = await insertRow(t, BucketList, {
user: user.id,
name: 'Full',
lat: 10.5,
lng: 20.5,
country_code: 'JP',
notes: 'note',
target_date: '2027-01-01',
visited_at: '2026-06-01',
visited_source: 'manual',
created_at: '2026-02-01T00:00:00.000Z',
});
await insertRow(t, BucketList, { user: other.id, name: 'Not mine' });
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare('SELECT * FROM bucket_list WHERE user_id = ? ORDER BY created_at DESC').all(user.id);
const rows = await bucketList.listForUser(user.id);
expect(rows).toEqual(legacy);
expect(rows.map((r) => r.id)).toEqual([full, sparse]);
});
it('BUCKETREPO-005: empty array for a user with nothing on their list', async () => {
const { user } = createUser(testDb);
expect(await bucketList.listForUser(user.id)).toEqual([]);
});
});
describe('BucketListRepository.findById (AT33) — SELECT * WHERE id = ?, NOT user-scoped', () => {
it('BUCKETREPO-006: matches the legacy row, regardless of owner', async () => {
const { user } = createUser(testDb);
const id = await insertRow(t, BucketList, { user: user.id, name: 'Item' });
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare('SELECT * FROM bucket_list WHERE id = ?').get(id);
expect(await bucketList.findById(id)).toEqual(legacy);
});
it('BUCKETREPO-007: undefined for a missing id', async () => {
expect(await bucketList.findById(999999)).toBeUndefined();
});
});
describe('BucketListRepository.findForUser (AT34/AT36/AT37) — SELECT * WHERE id = ? AND user_id = ?', () => {
it('BUCKETREPO-008: matches the legacy row for the owning user', async () => {
const { user } = createUser(testDb);
const id = await insertRow(t, BucketList, { user: user.id, name: 'Item' });
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare('SELECT * FROM bucket_list WHERE id = ? AND user_id = ?').get(id, user.id);
expect(await bucketList.findForUser(id, user.id)).toEqual(legacy);
});
it("BUCKETREPO-009: undefined for a foreign owner — the guard never leaks another user's item", async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb, { username: 'other' });
const id = await insertRow(t, BucketList, { user: user.id, name: 'Item' });
expect(await bucketList.findForUser(id, other.id)).toBeUndefined();
});
});
@@ -0,0 +1,121 @@
/**
* Plan 4 Task 8b-4a (3h L4) — full-key `toEqual(<legacy raw>)` parity for
* `BudgetItemsRepository.listPublicForShare` (`share.service.ts:391` SH14),
* flagged by the 3h ledger as having no repository-level parity test. The
* legacy statement (`BudgetItems.repository.ts`'s own docstring): `SELECT *
* FROM budget_items WHERE trip_id = ? ORDER BY category ASC` — unlike BG72's
* `listAllForTrip`, unfiltered by visibility (there is no per-item privacy
* model on budget items the way packing has) but WITH an `ORDER BY` that
* `listAllForTrip` lacks.
*/
import { BudgetItems } from '../../../../src/db/entities/BudgetItems.entity';
import type { BudgetItemsRepository } from '../../../../src/db/repositories/BudgetItems.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createBudgetItem, createPlace, createReservation, createTrip, createUser } from '../../../helpers/factories';
import { findRow, findRows, updateRows } from '../../../helpers/factories/rows';
import { createTestBudgetItemsRepo } from '../../../helpers/files-repos';
import { resetTestDb } from '../../../helpers/test-db';
import type { TestOrm } from '../../../helpers/test-orm';
import { sharedTestOrm } from '../../../helpers/test-uow';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let budgetItemsRepo: BudgetItemsRepository;
let orm: TestOrm;
beforeAll(async () => {
budgetItemsRepo = await createTestBudgetItemsRepo(testDb);
orm = await sharedTestOrm(testDb);
});
beforeEach(() => resetTestDb(testDb));
afterAll(() => testDb.close());
function legacyPublicForShare(tripId: number): unknown {
// test-sql-allow: the raw SELECT is the legacy oracle this parity test holds the repository to.
return testDb.prepare('SELECT * FROM budget_items WHERE trip_id = ? ORDER BY category ASC').all(tripId);
}
describe('BudgetItemsRepository — share.service.ts SH14 read', () => {
it('listPublicForShare — matches the legacy statement, ordered by category, every nullable column both null and set', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id);
const reservation = createReservation(testDb, trip.id);
// Every nullable column set — sorts second by category.
const withDetails = createBudgetItem(testDb, trip.id, { name: 'Hotel', category: 'Lodging', total_price: 250 });
await updateRows(
orm,
BudgetItems,
{ id: withDetails.id },
{
persons: 2,
days: 3,
note: 'non-refundable',
sort_order: 4,
paidByUser: user.id,
expense_date: '2026-09-02',
reservation: reservation.id,
currency: 'EUR',
exchange_rate: 0.92,
ticket_json: '{"seat":"12A"}',
place: place.id,
},
);
// Every nullable column left null — sorts first by category.
const bare = createBudgetItem(testDb, trip.id, { name: 'Snacks', category: 'Food', total_price: 12.5 });
await updateRows(
orm,
BudgetItems,
{ id: bare.id },
{
persons: null,
days: null,
note: null,
paidByUser: null,
expense_date: null,
reservation: null,
currency: null,
place: null,
},
);
// A budget item on a different trip must never leak in.
createBudgetItem(testDb, other.id, { category: 'Other' });
const legacy = legacyPublicForShare(trip.id);
const typed = await budgetItemsRepo.listPublicForShare(trip.id);
expect(typed).toEqual(legacy);
expect(typed.map((r) => r.id)).toEqual([bare.id, withDetails.id]);
});
it('listPublicForShare — [] for a trip with no budget items', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(await budgetItemsRepo.listPublicForShare(trip.id)).toEqual([]);
});
});
describe('BudgetItemsRepository — reservations.service.ts RS49 delete', () => {
it('deleteByIds — removes exactly the listed rows, as legacy `DELETE ... WHERE id IN (...)` does', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const first = createBudgetItem(testDb, trip.id, { name: 'Flight' });
const second = createBudgetItem(testDb, trip.id, { name: 'Seat' });
const kept = createBudgetItem(testDb, trip.id, { name: 'Hotel' });
await budgetItemsRepo.deleteByIds([first.id, second.id]);
expect((await findRows(orm, BudgetItems, { trip: trip.id })).map((r) => r.id)).toEqual([kept.id]);
});
it('deleteByIds — an empty list deletes nothing', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const kept = createBudgetItem(testDb, trip.id);
await budgetItemsRepo.deleteByIds([]);
expect(await findRow(orm, BudgetItems, { id: kept.id })).toMatchObject({ id: kept.id });
});
});
@@ -0,0 +1,266 @@
import { Categories } from '../../../../src/db/entities/Categories.entity';
import type { CategoriesRepository } from '../../../../src/db/repositories/Categories.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createCategory, createUser } from '../../../helpers/factories';
import { updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let categories: CategoriesRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
categories = t.repo(Categories);
});
// `categories` is a KEEP_TABLES table (tests/helpers/test-db.ts): resetTestDb
// never clears it and re-seeds the ten defaults by name, so rows created by
// one `it` persist into the next within this file — every case below reads
// back by the id/name it just created rather than assuming a fresh table.
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function rawCategory(id: number): unknown {
// test-sql-allow: the row as SELECT * returns it is the oracle the repository's output is held to.
return testDb.prepare('SELECT * FROM categories WHERE id = ?').get(id);
}
async function withQueryCount<T>(fn: () => Promise<T>): Promise<{ value: T; queries: number }> {
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
try {
const value = await fn();
return { value, queries: spy.mock.calls.length };
} finally {
spy.mockRestore();
}
}
describe('CategoriesRepository', () => {
describe('list', () => {
it('CATREPO-001: a row read through list is the SELECT * row, key for key', async () => {
const { user } = createUser(testDb);
const created = createCategory(testDb, { name: 'RepoListRow', user_id: user.id });
const rows = await categories.list();
const row = rows.find((r) => r.id === created.id);
expect(row).toStrictEqual(rawCategory(created.id));
});
it('CATREPO-002: ordered by name ascending', async () => {
createCategory(testDb, { name: 'RepoZZZ' });
createCategory(testDb, { name: 'RepoAAA' });
const names = (await categories.list()).map((r) => r.name);
expect(names.indexOf('RepoAAA')).toBeLessThan(names.indexOf('RepoZZZ'));
});
it('CATREPO-003: unfiltered — includes rows owned by any user and globally-shared (user_id NULL) rows alike', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
const before = (await categories.list()).length;
createCategory(testDb, { name: 'RepoOwnedA', user_id: a.id });
createCategory(testDb, { name: 'RepoOwnedB', user_id: b.id });
createCategory(testDb, { name: 'RepoGlobal', user_id: null });
expect(await categories.list()).toHaveLength(before + 3);
});
});
describe('findById', () => {
it('CATREPO-004: returns the row for a valid id', async () => {
const created = createCategory(testDb, { name: 'RepoFindMe' });
expect(await categories.findById(created.id)).toStrictEqual(rawCategory(created.id));
});
it('CATREPO-005: returns null for a non-existent id', async () => {
expect(await categories.findById(99999999)).toBeNull();
});
it('CATREPO-006: no owner filter — a row owned by one user is found looked up plainly (no ownerId parameter exists on this method)', async () => {
const { user } = createUser(testDb);
const created = createCategory(testDb, { name: 'RepoAnyonesFind', user_id: user.id });
expect((await categories.findById(created.id))?.id).toBe(created.id);
});
it('CATREPO-007: the scalar user_id twin hydrates without loading the user relation', async () => {
const { user } = createUser(testDb);
const created = createCategory(testDb, { name: 'RepoTwin', user_id: user.id });
const entity = await t.repo(Categories).findOne({ id: created.id });
expect(entity?.user_id).toBe(user.id);
expect(entity?.user?.isInitialized()).toBe(false);
});
// Plan 3b Task 1 fix round (task-1-review.md B1): findById carries
// `disableIdentityMap: true` — `{ id }` is exactly the primary key, so
// without it this would risk being served from the identity map with
// zero queries and the stale pre-UPDATE color. `queries === 1` proves
// the real re-query happens.
it('CATREPO-008: an UPDATE from another context on the same row then findById reads the new value, in one query', async () => {
const created = createCategory(testDb, { name: 'RepoStale', color: '#111111' });
expect((await categories.findById(created.id))?.color).toBe('#111111'); // populate the identity map
await updateRows(t, Categories, { id: created.id }, { color: '#222222' });
const { value, queries } = await withQueryCount(() => categories.findById(created.id));
expect(value?.color).toBe('#222222');
expect(queries).toBe(1);
});
});
describe('createCategory', () => {
it('CATREPO-009: inserts and returns exactly the row the legacy re-select returned', async () => {
const { user } = createUser(testDb);
const row = await categories.createCategory({
name: 'RepoCreated',
color: '#ff5500',
icon: '🍽️',
user_id: user.id,
});
expect(row).toStrictEqual(rawCategory(row.id));
expect(row.name).toBe('RepoCreated');
expect(row.color).toBe('#ff5500');
expect(row.icon).toBe('🍽️');
expect(row.user_id).toBe(user.id);
expect(typeof row.created_at).toBe('string');
});
it('CATREPO-010: writes exactly what it is given — no defaulting inside the repository', async () => {
const { user } = createUser(testDb);
const row = await categories.createCategory({
name: 'RepoNoDefault',
color: 'literal-color',
icon: 'literal-icon',
user_id: user.id,
});
expect(row.color).toBe('literal-color');
expect(row.icon).toBe('literal-icon');
});
it('CATREPO-010b: throws when the read-back after insert finds no row (coverage: the guard branch)', async () => {
const { user } = createUser(testDb);
const spy = vi.spyOn(categories, 'findById').mockResolvedValueOnce(null);
await expect(
categories.createCategory({ name: 'Ghost', color: '#000000', icon: '👻', user_id: user.id }),
).rejects.toThrow('createCategory: read-back after insert found no row');
spy.mockRestore();
});
});
describe('patch', () => {
it('CATREPO-011: updates name, color, and icon when all three are given', async () => {
const created = createCategory(testDb, { name: 'RepoOld', color: '#aaaaaa', icon: '❓' });
const updated = await categories.patch(created.id, { name: 'RepoNew', color: '#bbbbbb', icon: '✅' });
expect(updated).toStrictEqual(rawCategory(created.id));
expect(updated?.name).toBe('RepoNew');
expect(updated?.color).toBe('#bbbbbb');
expect(updated?.icon).toBe('✅');
});
it('CATREPO-012: an omitted key is left untouched — does not touch other columns', async () => {
const created = createCategory(testDb, { name: 'RepoKeepName', color: '#cccccc', icon: '⭐' });
const updated = await categories.patch(created.id, { color: '#dddddd' });
expect(updated?.name).toBe('RepoKeepName');
expect(updated?.color).toBe('#dddddd');
expect(updated?.icon).toBe('⭐');
});
it('CATREPO-013: an empty changes object leaves every column untouched', async () => {
const created = createCategory(testDb, { name: 'RepoUnchanged', color: '#eeeeee', icon: '🔥' });
const before = rawCategory(created.id);
const updated = await categories.patch(created.id, {});
expect(updated).toStrictEqual(before);
});
it('CATREPO-014: returns null for a non-existent id', async () => {
expect(await categories.patch(99999999, { name: 'Nope' })).toBeNull();
});
it('CATREPO-014b: an empty changes object against a non-existent id returns null via the existence-check branch (coverage)', async () => {
expect(await categories.patch(99999999, {})).toBeNull();
});
// Task 3 review, Important 1, consequence (a) — and Minor 1: the
// identity map is populated through `list()` here, not `findById`, so
// this doubles as the "list → raw UPDATE → patch" case the review
// asked for. Without `refresh: true` in `patch`'s lookup, `icon` would
// still read the pre-UPDATE 'OLD' (verified: fails without the fix).
it('CATREPO-018: an untouched column reflects an UPDATE from another context made after the identity map was populated by list()', async () => {
const created = createCategory(testDb, { name: 'RepoRaceIcon', color: '#aaaaaa', icon: 'OLD' });
await categories.list(); // populate the identity map with icon: 'OLD'
await updateRows(t, Categories, { id: created.id }, { icon: 'NEW' });
const updated = await categories.patch(created.id, { color: '#bbbbbb' });
expect(updated?.icon).toBe('NEW');
});
// Task 3 review, Important 1, consequence (b): without `refresh: true`,
// MikroORM diffs the patch against the stale in-memory snapshot; when
// the concurrent raw write and the patch happen to agree on the value,
// no changeset is produced and the UPDATE is silently dropped even
// though the method reports success. The raw-row assertion is what
// catches it — `updated?.color` alone would still read '#111111'
// either way (verified: fails without the fix).
it('CATREPO-019: a patch matching a concurrent write from another context is not silently dropped', async () => {
const created = createCategory(testDb, { name: 'RepoRaceColor', color: '#111111' });
await categories.findById(created.id); // populate the identity map with '#111111'
await updateRows(t, Categories, { id: created.id }, { color: '#333333' });
const updated = await categories.patch(created.id, { color: '#111111' });
expect(updated?.color).toBe('#111111');
expect(rawCategory(created.id)).toMatchObject({ color: '#111111' });
});
// Task 3 review, Important 1, consequence (c): `remove` uses
// `nativeDelete`, which does not clear the identity map, so a stale
// patch afterwards could fabricate a row for an id that no longer
// exists instead of returning `null` (verified: fails without the fix).
it('CATREPO-020: patch after remove in the same request returns null, not a fabricated row', async () => {
const created = createCategory(testDb, { name: 'RepoRaceDelete', color: '#444444' });
await categories.findById(created.id); // populate the identity map
await categories.remove(created.id);
expect(await categories.patch(created.id, { color: '#555555' })).toBeNull();
});
});
describe('remove', () => {
it('CATREPO-015: deletes the row and returns the affected count', async () => {
const created = createCategory(testDb, { name: 'RepoToDelete' });
expect(await categories.remove(created.id)).toBe(1);
expect(await categories.findById(created.id)).toBeNull();
});
it('CATREPO-016: removing a non-existent id returns 0 and does not throw', async () => {
await expect(categories.remove(99999999)).resolves.toBe(0);
});
it('CATREPO-017: removing one row does not affect others', async () => {
const keep = createCategory(testDb, { name: 'RepoKeep' });
const gone = createCategory(testDb, { name: 'RepoGone' });
await categories.remove(gone.id);
expect(await categories.findById(keep.id)).not.toBeNull();
expect(await categories.findById(gone.id)).toBeNull();
});
});
describe("listIdName (Plan 3c Task 5, PL33 — PlacesService.importKmlPlaces' folder → category lookup)", () => {
it('CATREPO-021: projects only id and name, no ORDER BY guaranteed, including a fresh row', async () => {
const created = createCategory(testDb, { name: 'RepoIdName' });
const rows = await categories.listIdName();
const match = rows.find((r) => r.id === created.id);
expect(match).toEqual({ id: created.id, name: 'RepoIdName' });
// Only the two columns — no color/icon/user_id/created_at leaking through.
expect(match ? Object.keys(match).sort() : []).toEqual(['id', 'name']);
});
it('CATREPO-022: includes every category row, seeded defaults and user-created alike', async () => {
const before = await categories.listIdName();
const created = createCategory(testDb, { name: 'RepoIdNameTwo' });
const after = await categories.listIdName();
expect(after.length).toBe(before.length + 1);
expect(after.map((r) => r.id)).toContain(created.id);
});
});
});
@@ -0,0 +1,105 @@
/**
* Plan 4 Task 8b-4a (3h L4) — full-key `toEqual(<legacy raw>)` parity for
* `CollabMessagesRepository.listPublicForShare` (`share.service.ts:400`
* SH16), flagged by the 3h ledger as having no repository-level parity
* test. The legacy statement (`CollabMessages.repository.ts`'s own
* docstring): `SELECT m.*, u.username, u.avatar FROM collab_messages m JOIN
* users u ON m.user_id = u.id WHERE m.trip_id = ? AND m.deleted = 0 ORDER BY
* m.created_at` — a public share viewer never resolves a reply thread
* through this read (no `reply_text`/`reply_username`, unlike
* `joinedQuery`), and a deleted message (`deleted = 1`) must never surface.
*/
import { Users } from '../../../../src/db/entities/Users.entity';
import type { CollabMessagesRepository } from '../../../../src/db/repositories/CollabMessages.repository';
import { createTestCollabMessagesRepo } from '../../../helpers/collab-repos';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createTrip, createUser } from '../../../helpers/factories';
import { makeCollabMessage } from '../../../helpers/factories/collab';
import { updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let collabMessagesRepo: CollabMessagesRepository;
let t: TestOrm;
beforeAll(async () => {
collabMessagesRepo = await createTestCollabMessagesRepo(testDb);
t = await createTestOrm(testDb);
});
beforeEach(() => resetTestDb(testDb));
afterAll(async () => {
await t.close();
testDb.close();
});
async function insertMessage(
tripId: number,
userId: number,
overrides: Partial<{ text: string; reply_to: number | null; deleted: number; created_at: string }> = {},
): Promise<number> {
const message = await makeCollabMessage(t, tripId, userId, {
text: overrides.text ?? 'hi',
replyToRef: overrides.reply_to ?? null,
deleted: overrides.deleted ?? 0,
created_at: overrides.created_at ?? '2026-09-01T00:00:00.000Z',
});
return message.id;
}
function legacyPublicForShare(tripId: number): unknown {
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
return testDb
.prepare(
'SELECT m.*, u.username, u.avatar FROM collab_messages m JOIN users u ON m.user_id = u.id WHERE m.trip_id = ? AND m.deleted = 0 ORDER BY m.created_at ASC',
)
.all(tripId);
}
describe('CollabMessagesRepository — share.service.ts SH16 read', () => {
it('listPublicForShare — matches the legacy statement, deleted excluded, every nullable column both null and set', async () => {
const { user: author } = createUser(testDb, { username: 'alice' });
await updateRows(t, Users, { id: author.id }, { avatar: 'alice.png' });
const { user: replier } = createUser(testDb, { username: 'bob' });
const trip = createTrip(testDb, author.id);
const other = createTrip(testDb, author.id);
const rootId = await insertMessage(trip.id, author.id, {
text: 'root',
reply_to: null,
created_at: '2026-09-01T10:00:00.000Z',
});
const replyId = await insertMessage(trip.id, replier.id, {
text: 'reply',
reply_to: rootId,
created_at: '2026-09-01T11:00:00.000Z',
});
await insertMessage(trip.id, author.id, { text: 'gone', deleted: 1, created_at: '2026-09-01T12:00:00.000Z' });
await insertMessage(other.id, author.id, { text: 'foreign' });
const legacy = legacyPublicForShare(trip.id);
const typed = await collabMessagesRepo.listPublicForShare(trip.id);
expect(typed).toEqual(legacy);
expect(typed.map((m) => m.id)).toEqual([rootId, replyId]);
expect(typed.map((m) => m.avatar)).toEqual(['alice.png', null]);
});
it('insertMessage — keeps where a message came from, and nothing for one typed in the chat', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const typed = await collabMessagesRepo.insertMessage(trip.id, user.id, 'typed', null);
const shared = await collabMessagesRepo.insertMessage(trip.id, user.id, 'shared', null, 'assistant');
expect((await collabMessagesRepo.findWithReply(typed))?.origin).toBeNull();
expect(await collabMessagesRepo.findWithReply(shared)).toMatchObject({ text: 'shared', origin: 'assistant' });
const listed = await collabMessagesRepo.listPublicForShare(trip.id);
expect(listed.find((m) => m.id === shared)?.origin).toBe('assistant');
});
it('listPublicForShare — [] for a trip with no messages', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(await collabMessagesRepo.listPublicForShare(trip.id)).toEqual([]);
});
});
@@ -0,0 +1,180 @@
/**
* `CollectionToursRepository` (LIB-03): the whole tours a collection keeps.
* A kept tour is written whole (CT3), listed newest first (CT1), read only
* within its collection (CT2) and removed only from it (CT4); the trips one
* could go into come with their owner (CT5).
*/
import { CollectionTours } from '../../../../src/db/entities/CollectionTours.entity';
import { Collections } from '../../../../src/db/entities/Collections.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type {
CollectionTourInsert,
CollectionToursRepository,
} from '../../../../src/db/repositories/CollectionTours.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeCollection } from '../../../helpers/factories/collections';
import { deleteRows, findRow, updateRows } from '../../../helpers/factories/rows';
import { makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: CollectionToursRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(CollectionTours);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const POINTS = [
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
{ lat: 47.01, lng: 11.01, role: 'via', sequence: 1, name: 'Hut', key: 'stop-hut-1' },
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 2 },
];
/** A kept hike with a line and three points, the middle one named, its points encoded as the service writes them. */
function snapshot(collectionId: number, savedBy: number | null, overrides: Partial<CollectionTourInsert> = {}) {
const row: CollectionTourInsert = {
collection_id: collectionId,
saved_by: savedBy,
name: 'Ridge',
description: 'Up high',
website: null,
route_geometry: '[[47,11,600],[47.01,11.01,650],[47.02,11.02,630]]',
waypoints: JSON.stringify(POINTS),
tour_type: 'hike',
distance: 4.2,
elevation_gain: 300,
elevation_loss: null,
duration: 90,
planned_duration_minutes: null,
break_additional_minutes: 20,
difficulty: null,
wanderer_ref: null,
match_confidence: 1,
max_hiking_difficulty: 3,
bike_profile: null,
run_profile: null,
run_pace_seconds_per_km: null,
ski_discipline: null,
ski_technique: null,
ski_options: null,
boat_type: null,
water_context: null,
paddle_speed_kmh: null,
portage_speed_kmh: null,
paddle_lake_style: null,
track_marks: null,
hiking_preferences: null,
origin: 'trek',
origin_file_name: null,
track_started_at: null,
track_ended_at: null,
source_trip_title: 'Alps',
source_tour_name: 'Ridge',
...overrides,
};
return row;
}
async function fixture() {
const { user } = await makeUser(t, { username: 'keeper' });
const mine = await makeCollection(t, user.id, { name: 'Hikes' });
const other = await makeCollection(t, user.id, { name: 'Other' });
return { user, mine, other };
}
describe('CollectionToursRepository', () => {
it('CT3/CT2: keeps a snapshot whole and reads it back with its points decoded and who saved it', async () => {
const { user, mine, other } = await fixture();
const id = await repo.insertSnapshot(snapshot(mine.id, user.id));
const row = await repo.findInCollection(mine.id, id);
expect(row).toMatchObject({
id,
collection_id: mine.id,
saved_by: user.id,
saved_by_name: 'keeper',
name: 'Ridge',
tour_type: 'hike',
distance: 4.2,
elevation_loss: null,
source_trip_title: 'Alps',
});
expect(row?.waypoints).toEqual(POINTS);
expect(typeof row?.created_at).toBe('string');
// Only within its own collection.
expect(await repo.findInCollection(other.id, id)).toBeUndefined();
});
it('CT1: lists a collection’s tours newest first, the id breaking ties, and nothing of another', async () => {
const { user, mine, other } = await fixture();
const first = await repo.insertSnapshot(snapshot(mine.id, user.id, { name: 'First' }));
const second = await repo.insertSnapshot(snapshot(mine.id, user.id, { name: 'Second' }));
const older = await repo.insertSnapshot(snapshot(mine.id, user.id, { name: 'Older' }));
await repo.insertSnapshot(snapshot(other.id, user.id, { name: 'Elsewhere' }));
await updateRows(t, CollectionTours, { id: older }, { created_at: '2020-01-01 00:00:00' });
await updateRows(t, CollectionTours, { id: { $in: [first, second] } }, { created_at: '2026-10-20 10:00:00' });
const rows = await repo.listForCollection(mine.id);
expect(rows.map((row) => row.name)).toEqual(['Second', 'First', 'Older']);
});
it('CT1/CT2: an account that is gone leaves the kept tour with nobody named', async () => {
const { mine } = await fixture();
const { user: gone } = await makeUser(t, { username: 'gone' });
const id = await repo.insertSnapshot(snapshot(mine.id, gone.id));
await deleteRows(t, Users, { id: gone.id });
expect(await repo.findInCollection(mine.id, id)).toMatchObject({ saved_by: null, saved_by_name: null });
});
it('CT2: a broken point list, or one of another shape, reads as no points, the line kept as it is', async () => {
const { user, mine } = await fixture();
const id = await repo.insertSnapshot(snapshot(mine.id, user.id));
await updateRows(t, CollectionTours, { id }, { waypoints: 'not json' });
const row = await repo.findInCollection(mine.id, id);
expect(row?.waypoints).toEqual([]);
expect(row?.route_geometry).toContain('47.01');
await updateRows(t, CollectionTours, { id }, { waypoints: JSON.stringify([{ lat: 147, lng: 11 }]) });
expect((await repo.listForCollection(mine.id))[0]?.waypoints).toEqual([]);
});
it('CT4: removes a kept tour only from its own collection', async () => {
const { user, mine, other } = await fixture();
const id = await repo.insertSnapshot(snapshot(mine.id, user.id));
expect(await repo.deleteInCollection(other.id, id)).toBe(false);
expect(await findRow(t, CollectionTours, { id })).not.toBeNull();
expect(await repo.deleteInCollection(mine.id, id)).toBe(true);
expect(await repo.findInCollection(mine.id, id)).toBeUndefined();
});
it('CT5: names the trips asked for with their owner and dates, and none for no ids', async () => {
const { user } = await fixture();
const alps = await makeTrip(t, user.id, { title: 'Alps', start_date: '2026-07-01', end_date: '2026-07-08' });
const coast = await makeTrip(t, user.id, { title: 'Coast', start_date: null, end_date: null });
await makeTrip(t, user.id, { title: 'Not asked' });
const rows = await repo.targetTrips([coast.id, alps.id]);
expect([...rows].sort((a, b) => a.id - b.id)).toEqual([
{ id: alps.id, user_id: user.id, title: 'Alps', start_date: '2026-07-01', end_date: '2026-07-08' },
{ id: coast.id, user_id: user.id, title: 'Coast', start_date: null, end_date: null },
]);
expect(await repo.targetTrips([])).toEqual([]);
});
it('goes with its collection', async () => {
const { user, mine } = await fixture();
const id = await repo.insertSnapshot(snapshot(mine.id, user.id));
await deleteRows(t, Collections, { id: mine.id });
expect(await findRow(t, CollectionTours, { id })).toBeNull();
});
});
@@ -0,0 +1,318 @@
import { DawarichConnections } from '../../../../src/db/entities/DawarichConnections.entity';
import { DawarichVisitSuggestions } from '../../../../src/db/entities/DawarichVisitSuggestions.entity';
import type { DawarichConnectionsRepository } from '../../../../src/db/repositories/DawarichConnections.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser } from '../../../helpers/factories';
import { countRows, deleteRows, findRow, insertRow, updateRows, upsertRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let connections: DawarichConnectionsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
connections = t.repo(DawarichConnections);
});
beforeEach(async () => {
resetTestDb(testDb);
t.clear();
await deleteRows(t, DawarichConnections);
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function seed(
userId: number,
over: Partial<{
url: string | null;
api_key: string | null;
allow_insecure_tls: number;
sync_enabled: number;
last_sync_at: string | null;
last_sync_state: string;
last_sync_error: string | null;
capabilities: string | null;
}> = {},
): Promise<void> {
await upsertRow(t, DawarichConnections, {
user: userId,
url: over.url === undefined ? 'https://dawarich.example' : over.url,
api_key: over.api_key === undefined ? 'enc:v1:cipher' : over.api_key,
allow_insecure_tls: over.allow_insecure_tls ?? 0,
sync_enabled: over.sync_enabled ?? 1,
last_sync_at: over.last_sync_at ?? null,
last_sync_state: over.last_sync_state ?? 'never',
last_sync_error: over.last_sync_error ?? null,
capabilities: over.capabilities ?? null,
});
}
function raw(userId: number) {
return findRow(t, DawarichConnections, { user: userId });
}
describe('DawarichConnectionsRepository', () => {
describe('findRow (DWC1)', () => {
it('CONNREPO-001: null when no connection exists', async () => {
const { user } = createUser(testDb);
expect(await connections.findRow(user.id)).toBeNull();
});
it('CONNREPO-002: a fully-seeded row comes back byte-identical to a legacy SELECT of the same 9 columns', async () => {
const { user } = createUser(testDb);
await seed(user.id, {
url: 'https://dawarich.example/api',
api_key: 'enc:v1:abcdef',
allow_insecure_tls: 1,
sync_enabled: 0,
last_sync_at: '2026-09-12T04:15:00.000Z',
last_sync_state: 'partial',
last_sync_error: 'rate_limited',
capabilities: '{"visits":true}',
});
const row = await connections.findRow(user.id);
// test-sql-allow: the legacy SELECT of the same 9 columns is the oracle this case holds findRow to.
const legacy = testDb.prepare('SELECT * FROM dawarich_connections WHERE user_id = ?').get(user.id) as Record<
string,
unknown
>;
expect(row).toEqual({
user_id: legacy.user_id,
url: legacy.url,
api_key: legacy.api_key,
allow_insecure_tls: legacy.allow_insecure_tls,
sync_enabled: legacy.sync_enabled,
last_sync_at: legacy.last_sync_at,
last_sync_state: legacy.last_sync_state,
last_sync_error: legacy.last_sync_error,
capabilities: legacy.capabilities,
});
});
});
describe('listSyncableUserIds (DWC2)', () => {
it('CONNREPO-010: only rows with sync on, a non-blank url and a key', async () => {
const syncable = createUser(testDb).user.id;
const pollOff = createUser(testDb).user.id;
const noUrl = createUser(testDb).user.id;
const blankUrl = createUser(testDb).user.id;
const noKey = createUser(testDb).user.id;
await seed(syncable);
await seed(pollOff, { sync_enabled: 0 });
await seed(noUrl, { url: null });
await seed(blankUrl, { url: '' });
await seed(noKey, { api_key: null });
expect(await connections.listSyncableUserIds()).toEqual([syncable]);
});
});
describe('getUrl (DWC3)', () => {
it('CONNREPO-020: the stored url, or null for no row / a null column', async () => {
const { user } = createUser(testDb);
expect(await connections.getUrl(user.id)).toBeNull();
await seed(user.id, { url: 'https://d.example' });
expect(await connections.getUrl(user.id)).toBe('https://d.example');
await seed(user.id, { url: null });
expect(await connections.getUrl(user.id)).toBeNull();
});
});
describe('upsertConnection (DWC4)', () => {
it('CONNREPO-030: inserts a new row with the other columns at their schema defaults', async () => {
const { user } = createUser(testDb);
await connections.upsertConnection(user.id, {
url: 'https://d.example',
allowInsecureTls: true,
syncEnabled: false,
});
const row = (await raw(user.id))!;
expect(row).toMatchObject({
url: 'https://d.example',
allow_insecure_tls: 1,
sync_enabled: 0,
api_key: null,
capabilities: null,
last_sync_state: 'never',
});
expect(row.updated_at).toBeTruthy();
});
it('CONNREPO-031: on conflict merges ONLY url/allow_insecure_tls/sync_enabled/updated_at — api_key and capabilities survive untouched', async () => {
const { user } = createUser(testDb);
await seed(user.id, {
url: 'https://old.example',
api_key: 'enc:v1:stored',
capabilities: '{"visits":true}',
last_sync_state: 'ok',
});
await connections.upsertConnection(user.id, {
url: 'https://new.example',
allowInsecureTls: true,
syncEnabled: true,
});
const row = (await raw(user.id))!;
expect(row.url).toBe('https://new.example');
expect(row.allow_insecure_tls).toBe(1);
expect(row.api_key).toBe('enc:v1:stored');
expect(row.capabilities).toBe('{"visits":true}');
expect(row.last_sync_state).toBe('ok');
});
it('CONNREPO-032: updated_at is bumped unconditionally, insert or merge alike', async () => {
const { user } = createUser(testDb);
await connections.upsertConnection(user.id, {
url: 'https://d.example',
allowInsecureTls: false,
syncEnabled: true,
});
await updateRows(t, DawarichConnections, {}, { updated_at: '2000-01-01 00:00:00' });
await connections.upsertConnection(user.id, {
url: 'https://d.example',
allowInsecureTls: false,
syncEnabled: false,
});
expect((await raw(user.id))!.updated_at).not.toBe('2000-01-01 00:00:00');
});
});
describe('setApiKey (DWC5/DWC7)', () => {
it('CONNREPO-040: writes the given ciphertext, and null scrubs it', async () => {
const { user } = createUser(testDb);
await seed(user.id, { api_key: 'enc:v1:old' });
await connections.setApiKey(user.id, 'enc:v1:new');
expect((await raw(user.id))!.api_key).toBe('enc:v1:new');
await connections.setApiKey(user.id, null);
expect((await raw(user.id))!.api_key).toBeNull();
});
});
describe('resetSyncState (DWC6)', () => {
it('CONNREPO-050: clears capabilities/last_sync_* without touching api_key', async () => {
const { user } = createUser(testDb);
await seed(user.id, {
api_key: 'enc:v1:kept',
capabilities: '{"a":1}',
last_sync_state: 'ok',
last_sync_error: 'x',
last_sync_at: '2026-01-01T00:00:00Z',
});
await connections.resetSyncState(user.id);
const row = (await raw(user.id))!;
expect(row).toMatchObject({
api_key: 'enc:v1:kept',
capabilities: null,
last_sync_state: 'never',
last_sync_error: null,
last_sync_at: null,
});
});
});
describe('clearForRemovedUrl (DWC8)', () => {
it('CONNREPO-060: clears api_key together with capabilities/last_sync_* in one statement', async () => {
const { user } = createUser(testDb);
await seed(user.id, {
api_key: 'enc:v1:gone',
capabilities: '{"a":1}',
last_sync_state: 'ok',
last_sync_error: 'x',
last_sync_at: '2026-01-01T00:00:00Z',
});
await connections.clearForRemovedUrl(user.id);
expect((await raw(user.id))!).toMatchObject({
api_key: null,
capabilities: null,
last_sync_state: 'never',
last_sync_error: null,
last_sync_at: null,
});
});
});
describe('disconnect (DWC9)', () => {
it("CONNREPO-070: removes only the named user's row, and does not cascade to suggestions (no FK relation exists for it to cascade through)", async () => {
const { user } = createUser(testDb);
const other = createUser(testDb).user.id;
await seed(user.id);
await seed(other);
await insertRow(t, DawarichVisitSuggestions, {
user: user.id,
source_visit_id: 'v1',
name: 'Cafe',
lat: 1,
lng: 1,
started_at: '2026-01-01T00:00:00Z',
ended_at: '2026-01-01T01:00:00Z',
local_date: '2026-01-01',
source_hash: 'hash',
});
await connections.disconnect(user.id);
expect(await raw(user.id)).toBeNull();
expect(await raw(other)).not.toBeNull();
expect(await countRows(t, DawarichVisitSuggestions, { user: user.id })).toBe(1);
});
});
describe('storeCapabilities (DWC10)', () => {
it('CONNREPO-080: writes the JSON blob and stamps updated_at', async () => {
const { user } = createUser(testDb);
await seed(user.id);
await connections.storeCapabilities(user.id, '{"visits":true,"tracks":false}');
expect((await raw(user.id))!.capabilities).toBe('{"visits":true,"tracks":false}');
});
});
describe('recordSyncResult (DWC11)', () => {
it('CONNREPO-090: writes all four columns for the named user only', async () => {
const { user } = createUser(testDb);
const other = createUser(testDb).user.id;
await seed(user.id);
await seed(other, { last_sync_state: 'ok' });
await connections.recordSyncResult(user.id, {
lastSyncAt: '2026-09-12T04:15:00.000Z',
state: 'failed',
error: 'unreachable',
});
expect((await raw(user.id))!).toMatchObject({
last_sync_at: '2026-09-12T04:15:00.000Z',
last_sync_state: 'failed',
last_sync_error: 'unreachable',
});
expect((await raw(other))!.last_sync_state).toBe('ok');
});
});
describe('getLastSyncState (DSY1)', () => {
it('CONNREPO-100: the stored state, or null with no row at all', async () => {
const { user } = createUser(testDb);
expect(await connections.getLastSyncState(user.id)).toBeNull();
await seed(user.id, { last_sync_state: 'partial' });
expect(await connections.getLastSyncState(user.id)).toBe('partial');
});
});
});
@@ -0,0 +1,454 @@
import { DawarichVisitSuggestions } from '../../../../src/db/entities/DawarichVisitSuggestions.entity';
import { JourneyEntries } from '../../../../src/db/entities/JourneyEntries.entity';
import { Journeys } from '../../../../src/db/entities/Journeys.entity';
import type { DawarichVisitSuggestionsRepository } from '../../../../src/db/repositories/DawarichVisitSuggestions.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser, createTrip } from '../../../helpers/factories';
import { makeBucketListItem } from '../../../helpers/factories/atlas';
import { makePlace } from '../../../helpers/factories/places';
import { deleteRows, findRow, findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let suggestions: DawarichVisitSuggestionsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
suggestions = t.repo(DawarichVisitSuggestions);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
testDb.exec('DELETE FROM dawarich_visit_suggestions');
});
afterAll(async () => {
await t.close();
testDb.close();
});
let _seq = 0;
async function seed(
userId: number,
over: Partial<{
source_visit_id: string;
trip_id: number | null;
name: string;
lat: number | null;
lng: number | null;
started_at: string;
ended_at: string;
duration_minutes: number;
local_date: string;
source_status: string;
confidence: number | null;
confidence_band: string | null;
country_code: string | null;
state: string;
target: string | null;
accepted_place_id: number | null;
accepted_journal_entry_id: number | null;
accepted_bucket_list_item_id: number | null;
matched_bucket_list_item_id: number | null;
source_hash: string;
accepted_hash: string | null;
source_missing_at: string | null;
}> = {},
): Promise<number> {
_seq++;
return insertRow(t, DawarichVisitSuggestions, {
user: userId,
source_visit_id: over.source_visit_id ?? `visit-${_seq}`,
trip: over.trip_id ?? null,
name: over.name ?? 'Cafe Central',
lat: over.lat === undefined ? 48.2092 : over.lat,
lng: over.lng === undefined ? 16.3658 : over.lng,
started_at: over.started_at ?? '2026-09-01T09:30:00Z',
ended_at: over.ended_at ?? '2026-09-01T11:45:00Z',
duration_minutes: over.duration_minutes ?? 135,
local_date: over.local_date ?? '2026-09-01',
source_status: over.source_status ?? 'suggested',
confidence: over.confidence ?? 0.7,
confidence_band: over.confidence_band ?? 'high',
country_code: over.country_code ?? 'AT',
state: over.state ?? 'new',
target: over.target ?? null,
acceptedPlace: over.accepted_place_id ?? null,
accepted_journal_entry_id: over.accepted_journal_entry_id ?? null,
acceptedBucketListItem: over.accepted_bucket_list_item_id ?? null,
matchedBucketListItem: over.matched_bucket_list_item_id ?? null,
source_hash: over.source_hash ?? `hash-${_seq}`,
accepted_hash: over.accepted_hash ?? null,
source_missing_at: over.source_missing_at ?? null,
});
}
function storedRow(id: number) {
return findRow(t, DawarichVisitSuggestions, { id });
}
/** The stored row; fails the case when it is gone. */
async function rawRow(id: number) {
const row = await storedRow(id);
if (!row) throw new Error(`no suggestion ${id}`);
return row;
}
async function seedPlace(tripId: number): Promise<number> {
return (await makePlace(t, tripId, { name: 'A place', lat: null, lng: null })).id;
}
async function seedJourneyEntry(userId: number): Promise<number> {
const journeyId = await insertRow(t, Journeys, {
user: userId,
title: 'Trip diary',
status: 'active',
created_at: 0,
updated_at: 0,
});
return insertRow(t, JourneyEntries, {
journey: journeyId,
author: userId,
type: 'entry',
title: 'Cafe',
entry_date: '2026-09-01',
created_at: 0,
updated_at: 0,
});
}
async function seedBucketItem(userId: number): Promise<number> {
return (await makeBucketListItem(t, userId, { name: 'Wish' })).id;
}
describe('DawarichVisitSuggestionsRepository', () => {
describe('list/getOne (DWS1/DWS3)', () => {
it('DVSREPO-001: a fully-seeded row (with a trip and a matched wish) joins trip_title/matched_bucket_name and every scalar column, matching a legacy raw join', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Vienna' });
const wish = await seedBucketItem(user.id);
const id = await seed(user.id, { trip_id: trip.id, matched_bucket_list_item_id: wish, name: 'Cafe Central' });
const rows = await suggestions.list(user.id, {});
const legacy = testDb
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
.prepare(
`SELECT s.*, t.title AS trip_title, b.name AS matched_bucket_name
FROM dawarich_visit_suggestions s
LEFT JOIN trips t ON t.id = s.trip_id
LEFT JOIN bucket_list b ON b.id = s.matched_bucket_list_item_id
WHERE s.user_id = ?`,
)
.get(user.id);
expect(rows).toHaveLength(1);
expect(rows[0]).toEqual(legacy);
expect(rows[0].id).toBe(id);
expect(rows[0].trip_title).toBe('Vienna');
expect(rows[0].matched_bucket_name).toBe('Wish');
});
it('DVSREPO-080: one day of one person, in the order the stays were lived (JRN-02)', async () => {
const { user } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const later = await seed(user.id, { local_date: '2026-09-01', started_at: '2026-09-01T15:00:00+02:00' });
const earlier = await seed(user.id, { local_date: '2026-09-01', started_at: '2026-09-01T09:00:00+02:00' });
await seed(user.id, { local_date: '2026-09-02' });
await seed(stranger.id, { local_date: '2026-09-01' });
const rows = await suggestions.listForDay(user.id, '2026-09-01');
expect(rows.map((row) => row.id)).toEqual([earlier, later]);
expect(rows[0]).toMatchObject({ trip_title: null, matched_bucket_name: null });
expect(await suggestions.listForDay(user.id, '2026-09-03')).toEqual([]);
});
it("DVSREPO-002: scoped by user_id — a stranger's row never appears", async () => {
const { user } = createUser(testDb);
const { user: stranger } = createUser(testDb);
await seed(stranger.id);
expect(await suggestions.list(user.id, {})).toEqual([]);
});
it('DVSREPO-003: filters by tripId and state, ordered started_at DESC, id DESC', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const older = await seed(user.id, { trip_id: trip.id, started_at: '2026-09-01T00:00:00Z' });
const newer = await seed(user.id, { trip_id: trip.id, started_at: '2026-09-02T00:00:00Z' });
await seed(user.id, { started_at: '2026-09-03T00:00:00Z' }); // no trip
const byTrip = await suggestions.list(user.id, { tripId: trip.id });
expect(byTrip.map((r) => r.id)).toEqual([newer, older]);
await seed(user.id, { trip_id: trip.id, state: 'dismissed' });
const byState = await suggestions.list(user.id, { state: 'dismissed' });
expect(byState).toHaveLength(1);
expect(byState[0].state).toBe('dismissed');
});
it('DVSREPO-004: getOne is the single-row variant, still user-scoped', async () => {
const { user } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const id = await seed(user.id);
expect(await suggestions.getOne(stranger.id, id)).toBeNull();
expect((await suggestions.getOne(user.id, id))?.id).toBe(id);
});
});
describe('reopenOrphaned (DWS2)', () => {
it('DVSREPO-010: place target with a NULL accepted_place_id is reopened', async () => {
const { user } = createUser(testDb);
const id = await seed(user.id, { state: 'accepted', target: 'place', accepted_place_id: null });
await suggestions.reopenOrphaned(user.id);
const row = await rawRow(id);
expect(row.state).toBe('new');
expect(row.target).toBeNull();
});
it('DVSREPO-011: bucket_list target with a NULL accepted_bucket_list_item_id is reopened', async () => {
const { user } = createUser(testDb);
const id = await seed(user.id, { state: 'accepted', target: 'bucket_list', accepted_bucket_list_item_id: null });
await suggestions.reopenOrphaned(user.id);
expect((await rawRow(id)).state).toBe('new');
});
it('DVSREPO-012: journal target whose entry no longer exists (cross-domain NOT EXISTS against journey_entries) is reopened', async () => {
const { user } = createUser(testDb);
const entryId = await seedJourneyEntry(user.id);
const id = await seed(user.id, { state: 'accepted', target: 'journal', accepted_journal_entry_id: entryId });
// Still exists: not reopened.
await suggestions.reopenOrphaned(user.id);
expect((await rawRow(id)).state).toBe('accepted');
await deleteRows(t, JourneyEntries, { id: entryId });
await suggestions.reopenOrphaned(user.id);
expect((await rawRow(id)).state).toBe('new');
expect((await rawRow(id)).accepted_journal_entry_id).toBeNull();
});
it('DVSREPO-013: journal target with a NULL accepted_journal_entry_id is reopened without needing a journey_entries lookup at all', async () => {
const { user } = createUser(testDb);
const id = await seed(user.id, { state: 'accepted', target: 'journal', accepted_journal_entry_id: null });
await suggestions.reopenOrphaned(user.id);
expect((await rawRow(id)).state).toBe('new');
});
it("DVSREPO-014: an intact acceptance (place still exists) is left alone; another user's orphan is untouched", async () => {
const { user } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const placeId = await seedPlace(trip.id);
const intact = await seed(user.id, { state: 'accepted', target: 'place', accepted_place_id: placeId });
const theirs = await seed(stranger.id, { state: 'accepted', target: 'place', accepted_place_id: null });
await suggestions.reopenOrphaned(user.id);
expect((await rawRow(intact)).state).toBe('accepted');
expect((await rawRow(theirs)).state).toBe('accepted');
});
});
describe('findForUser/findByUserAndVisit (DWS6/DSY3) — full-row parity, including persist(false) shadow FKs', () => {
it('DVSREPO-020: every scalar column round-trips, matching a legacy SELECT *', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const wish = await seedBucketItem(user.id);
const id = await seed(user.id, {
trip_id: trip.id,
matched_bucket_list_item_id: wish,
accepted_bucket_list_item_id: wish,
target: 'bucket_list',
state: 'accepted',
accepted_hash: 'hash-frozen',
});
const row = await suggestions.findForUser(id, user.id);
// test-sql-allow: the row as SELECT * returns it is the oracle the repository read is held to.
expect(row).toEqual(testDb.prepare('SELECT * FROM dawarich_visit_suggestions WHERE id = ?').get(id));
// The persist(false) shadow FKs specifically — the trap this Kysely
// full-row read exists to avoid.
expect(row!.trip_id).toBe(trip.id);
expect(row!.matched_bucket_list_item_id).toBe(wish);
expect(row!.accepted_bucket_list_item_id).toBe(wish);
});
it('DVSREPO-021: findForUser is scoped by id AND user_id; findByUserAndVisit by user_id AND source_visit_id', async () => {
const { user } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const id = await seed(stranger.id, { source_visit_id: 'abc' });
expect(await suggestions.findForUser(id, user.id)).toBeNull();
expect(await suggestions.findByUserAndVisit(user.id, 'abc')).toBeNull();
expect((await suggestions.findByUserAndVisit(stranger.id, 'abc'))?.id).toBe(id);
});
});
describe('insertVisit/updateNewVisit/refreshHash (DSY4/DSY5/DSY6)', () => {
it('DVSREPO-030: insertVisit writes state=new and every column handed to it', async () => {
const { user } = createUser(testDb);
const id = await suggestions.insertVisit({
user_id: user.id,
source_visit_id: 'v-1',
trip_id: null,
name: 'Stop',
lat: 1,
lng: 2,
started_at: '2026-01-01T00:00:00Z',
ended_at: '2026-01-01T01:00:00Z',
duration_minutes: 60,
local_date: '2026-01-01',
source_status: 'suggested',
confidence: null,
confidence_band: null,
country_code: 'DE',
source_hash: 'h1',
first_seen_at: '2026-01-01T00:00:00Z',
last_seen_at: '2026-01-01T00:00:00Z',
});
expect(await rawRow(id)).toMatchObject({ state: 'new', name: 'Stop', country_code: 'DE', source_hash: 'h1' });
});
it('DVSREPO-031: updateNewVisit overwrites the full row and clears source_missing_at', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const id = await seed(user.id, { source_missing_at: '2026-01-01T00:00:00Z', name: 'Old name' });
await suggestions.updateNewVisit(id, {
name: 'New name',
lat: 9,
lng: 9,
started_at: '2026-02-01T00:00:00Z',
ended_at: '2026-02-01T01:00:00Z',
duration_minutes: 30,
local_date: '2026-02-01',
source_status: 'confirmed',
confidence: 0.9,
confidence_band: 'high',
country_code: 'FR',
source_hash: 'h2',
trip_id: trip.id,
last_seen_at: '2026-02-01T00:00:00Z',
});
const row = await rawRow(id);
expect(row).toMatchObject({ name: 'New name', source_missing_at: null, trip_id: trip.id, source_hash: 'h2' });
});
it('DVSREPO-032: refreshHash touches only source_hash/source_missing_at/last_seen_at — the user-visible fields survive', async () => {
const { user } = createUser(testDb);
const id = await seed(user.id, {
name: 'Kept name',
state: 'accepted',
source_missing_at: '2026-01-01T00:00:00Z',
});
await suggestions.refreshHash(id, 'h3', '2026-03-01T00:00:00Z');
expect(await rawRow(id)).toMatchObject({
name: 'Kept name',
state: 'accepted',
source_hash: 'h3',
source_missing_at: null,
last_seen_at: '2026-03-01T00:00:00Z',
});
});
});
describe('listCandidatesForWindow/deleteById/stampMissingIfUnset (DSY7/DSY8/DSY9)', () => {
it('DVSREPO-040: candidates are scoped by user/trip and local_date bounds', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const inWindow = await seed(user.id, { trip_id: trip.id, local_date: '2026-05-05' });
await seed(user.id, { trip_id: trip.id, local_date: '2019-01-01' });
const candidates = await suggestions.listCandidatesForWindow(user.id, trip.id, '2026-05-01', '2026-05-10');
expect(candidates.map((c) => c.id)).toEqual([inWindow]);
});
it('DVSREPO-041: deleteById removes exactly the named row', async () => {
const { user } = createUser(testDb);
const id = await seed(user.id);
await suggestions.deleteById(id);
expect(await storedRow(id)).toBeNull();
});
it('DVSREPO-042: stampMissingIfUnset preserves the FIRST-missing timestamp (COALESCE, not overwrite)', async () => {
const { user } = createUser(testDb);
const id = await seed(user.id, { source_missing_at: '2026-01-01T00:00:00Z' });
await suggestions.stampMissingIfUnset(id, '2026-06-01T00:00:00Z');
expect((await rawRow(id)).source_missing_at).toBe('2026-01-01T00:00:00Z');
const id2 = await seed(user.id, { source_missing_at: null });
await suggestions.stampMissingIfUnset(id2, '2026-06-01T00:00:00Z');
expect((await rawRow(id2)).source_missing_at).toBe('2026-06-01T00:00:00Z');
});
});
describe('markAccepted (DWS11) — self-column-copy', () => {
it('DVSREPO-050: accepted_hash tracks CURRENT source_hash at UPDATE time, not a value bound earlier', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const placeId = await seedPlace(trip.id);
const id = await seed(user.id, { source_hash: 'hash-original' });
// A concurrent write lands between "the caller decided to accept" and
// the markAccepted call itself.
await updateRows(t, DawarichVisitSuggestions, { id }, { source_hash: 'hash-concurrent' });
await suggestions.markAccepted(id, { target: 'place', placeId, journalEntryId: null, bucketItemId: null });
const row = await rawRow(id);
expect(row.source_hash).toBe('hash-concurrent');
expect(row.accepted_hash).toBe('hash-concurrent');
expect(row.state).toBe('accepted');
expect(row.accepted_place_id).toBe(placeId);
});
});
describe('listHoldersOfWish/clearWishHolders/assignWishHolder (DSY11/12/13)', () => {
it("DVSREPO-060: listHoldersOfWish excludes the caller's own source_visit_id", async () => {
const { user } = createUser(testDb);
const wish = await seedBucketItem(user.id);
const holder = await seed(user.id, { source_visit_id: 'holder', matched_bucket_list_item_id: wish });
await seed(user.id, { source_visit_id: 'self', matched_bucket_list_item_id: wish });
const holders = await suggestions.listHoldersOfWish(user.id, wish, 'self');
expect(holders.map((h) => h.id)).toEqual([holder]);
});
it('DVSREPO-061: clear-then-assign leaves exactly one holder, scoped to the caller', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const wish = await seedBucketItem(user.id);
await seed(user.id, { source_visit_id: 'a', matched_bucket_list_item_id: wish });
await seed(user.id, { source_visit_id: 'b', matched_bucket_list_item_id: wish });
const winnerId = await seed(user.id, { source_visit_id: 'c', matched_bucket_list_item_id: null });
const otherHolder = await seed(other.id, { source_visit_id: 'a', matched_bucket_list_item_id: wish });
await suggestions.clearWishHolders(user.id, wish);
await suggestions.assignWishHolder(user.id, 'c', wish);
const all = await findRows(t, DawarichVisitSuggestions, { matchedBucketListItem: wish, user: user.id });
expect(all.map((r) => r.id)).toEqual([winnerId]);
// clearWishHolders is scoped by user_id — another user's row with the
// SAME wish id (a coincidence, wishes aren't globally unique ids across
// users here) is untouched.
expect((await rawRow(otherHolder)).matched_bucket_list_item_id).toBe(wish);
});
});
describe('matchedStayStart (DWS14)', () => {
it("DVSREPO-070: the most recent started_at among the user's stays matched to that wish", async () => {
const { user } = createUser(testDb);
const wish = await seedBucketItem(user.id);
await seed(user.id, { matched_bucket_list_item_id: wish, started_at: '2026-01-01T00:00:00Z' });
await seed(user.id, { matched_bucket_list_item_id: wish, started_at: '2026-06-01T00:00:00Z' });
expect(await suggestions.matchedStayStart(user.id, wish)).toBe('2026-06-01T00:00:00Z');
expect(await suggestions.matchedStayStart(user.id, 999999)).toBeNull();
});
});
});
@@ -0,0 +1,206 @@
/**
* DayAccommodationsRepository — parity tests (Plan 3d Task 7 whole-plan
* review, item 9/"missing parity tests": this repository had no standalone
* test file; its methods were only exercised indirectly through
* `accommodations.service.test.ts`/`reservations.service.test.ts`). ONE
* seeded world, one `toEqual(<legacy raw>)` test per read method.
*/
import { DayAccommodations } from '../../../../src/db/entities/DayAccommodations.entity';
import { Reservations } from '../../../../src/db/entities/Reservations.entity';
import type { DayAccommodationsRepository } from '../../../../src/db/repositories/DayAccommodations.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import {
createDayAccommodation,
createPlace,
createReservation,
createTrip,
createUser,
} from '../../../helpers/factories';
import { updateRows } from '../../../helpers/factories/rows';
import { readTripDays } from '../../../helpers/factories/trips';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: DayAccommodationsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(DayAccommodations);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('DayAccommodationsRepository — fully seeded world', () => {
// One seeded world for every test below: a trip with two stays —
// `named` (a place, a check-in/out, a linked live booking) and `bare`
// (no place, no booking) — plus a second trip's stay, to prove scoping.
const seed = async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { start_date: '2026-09-01', end_date: '2026-09-05' });
const otherTrip = createTrip(testDb, user.id, { start_date: '2026-09-01', end_date: '2026-09-02' });
const days = await readTripDays(t, trip.id);
const place = createPlace(testDb, trip.id, { name: 'The Plaza', description: 'Fancy' });
const named = createDayAccommodation(testDb, trip.id, place.id, days[0].id, days[1].id, {
check_in: '15:00',
check_out: '11:00',
confirmation: 'CONF-1',
});
const booking = createReservation(testDb, trip.id, { title: 'Plaza Stay', type: 'hotel' });
await updateRows(t, Reservations, { id: booking.id }, { accommodation_id: `${named.id}.0` });
const bare = createDayAccommodation(testDb, trip.id, place.id, days[2].id, days[3].id);
const otherDays = await readTripDays(t, otherTrip.id);
const otherPlace = createPlace(testDb, otherTrip.id, { name: 'Elsewhere' });
const otherStay = createDayAccommodation(testDb, otherTrip.id, otherPlace.id, otherDays[0].id, otherDays[1].id);
return { trip, otherTrip, days, place, named, booking, bare, otherStay };
};
it('AC2 findWithPlace — matches the legacy LEFT JOIN places statement, both with and without a place', async () => {
const { named, place } = await seed();
const legacySql = `
SELECT a.*, p.name as place_name, p.address as place_address, p.image_url as place_image, p.lat as place_lat, p.lng as place_lng
FROM day_accommodations a LEFT JOIN places p ON a.place_id = p.id WHERE a.id = ?`;
const typed = await repo.findWithPlace(named.id);
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb.prepare(legacySql).get(named.id);
expect(typed).toEqual(legacy);
expect(typed?.place_name).toBe(place.name);
});
it('AC3 listForTripWithPlaceAndBooking — matches the legacy LEFT JOIN places/reservations statement, fanning out one row per linked booking', async () => {
const { trip, named, bare, booking } = await seed();
const legacySql = `
SELECT a.*, p.name as place_name, p.address as place_address, p.image_url as place_image, p.lat as place_lat, p.lng as place_lng,
r.title as reservation_title
FROM day_accommodations a LEFT JOIN places p ON a.place_id = p.id LEFT JOIN reservations r ON r.accommodation_id = a.id
WHERE a.trip_id = ? ORDER BY a.created_at ASC`;
const typed = await repo.listForTripWithPlaceAndBooking(trip.id);
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb.prepare(legacySql).all(trip.id);
expect(typed).toEqual(legacy);
expect(typed.map((r) => r.id)).toEqual([named.id, bare.id]);
expect(typed.find((r) => r.id === named.id)?.reservation_title).toBe(booking.title);
expect(typed.find((r) => r.id === bare.id)?.reservation_title).toBeNull();
});
it('AC34 findInTrip — matches the legacy statement, scoped by trip (a foreign-trip id misses)', async () => {
const { trip, named, otherStay } = await seed();
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare('SELECT * FROM day_accommodations WHERE id = ? AND trip_id = ?')
.get(named.id, trip.id);
expect(await repo.findInTrip(named.id, trip.id)).toEqual(legacy);
expect(await repo.findInTrip(otherStay.id, trip.id)).toBeUndefined();
});
it('RS37/RS38/RS21 existsInTrip / getCheckIn / getTripId — match the legacy statements', async () => {
const { trip, named, otherStay } = await seed();
expect(await repo.existsInTrip(named.id, trip.id)).toBe(true);
expect(await repo.existsInTrip(otherStay.id, trip.id)).toBe(false);
expect(await repo.getCheckIn(named.id)).toBe('15:00');
expect(await repo.getTripId(named.id)).toBe(trip.id);
expect(await repo.getTripId(999999)).toBeUndefined();
});
it('DY19 listStartEndDayNumbers — matches the legacy joined day_number statement', async () => {
const { trip, named, bare } = await seed();
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare(
`
SELECT a.id, s.day_number as start_no, e.day_number as end_no FROM day_accommodations a
JOIN days s ON s.id = a.start_day_id JOIN days e ON e.id = a.end_day_id WHERE a.trip_id = ?`,
)
.all(trip.id);
const typed = await repo.listStartEndDayNumbers(trip.id);
expect(typed).toEqual(legacy);
expect(typed.map((r) => r.id).sort()).toEqual([named.id, bare.id].sort());
});
it('DY20 listForResync — matches the legacy statement, both persist(false) mirror columns present', async () => {
const { trip, named } = await seed();
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare('SELECT id, start_day_id, end_day_id, check_in FROM day_accommodations WHERE trip_id = ?')
.all(trip.id);
const typed = await repo.listForResync(trip.id);
expect(typed).toEqual(legacy);
expect(typed.find((r) => r.id === named.id)).toMatchObject({
start_day_id: named.start_day_id,
end_day_id: named.end_day_id,
check_in: '15:00',
});
});
it('DY41 listIdsCheckingInOrOutOn — matches the legacy statement: check-in day, check-out day, not a day only run across', async () => {
const { trip, days, named, bare } = await seed();
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = (dayId: number) =>
(
testDb
.prepare(
'SELECT id FROM day_accommodations WHERE trip_id = ? AND (start_day_id = ? OR end_day_id = ?) ORDER BY id',
)
.all(trip.id, dayId, dayId) as { id: number }[]
).map((r) => r.id);
for (const day of days) expect(await repo.listIdsCheckingInOrOutOn(trip.id, day.id)).toEqual(legacy(day.id));
expect(await repo.listIdsCheckingInOrOutOn(trip.id, days[0].id)).toEqual([named.id]);
expect(await repo.listIdsCheckingInOrOutOn(trip.id, days[1].id)).toEqual([named.id]);
expect(await repo.listIdsCheckingInOrOutOn(trip.id, days[3].id)).toEqual([bare.id]);
expect(await repo.listIdsCheckingInOrOutOn(trip.id, days[4].id)).toEqual([]);
});
it("DY41 listIdsCheckingInOrOutOn — scoped by trip (another trip's day matches nothing here)", async () => {
const { trip, otherStay } = await seed();
expect(await repo.listIdsCheckingInOrOutOn(trip.id, otherStay.start_day_id)).toEqual([]);
});
it('RPL3 listRoadtripStays — matches the legacy LEFT JOIN places + MIN(reservation) statement, id order', async () => {
const { trip, named, bare, booking } = await seed();
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare(
`
SELECT a.id, a.place_id, a.start_day_id, a.end_day_id, a.check_in, a.check_out,
p.name AS place_name, p.lat AS place_lat, p.lng AS place_lng,
(SELECT MIN(r.id) FROM reservations r WHERE r.accommodation_id = a.id) AS reservation_id
FROM day_accommodations a LEFT JOIN places p ON p.id = a.place_id WHERE a.trip_id = ? ORDER BY a.id`,
)
.all(trip.id);
const typed = await repo.listRoadtripStays(trip.id);
expect(typed).toEqual(legacy);
expect(typed.map((r) => r.id)).toEqual([named.id, bare.id]);
expect(typed.find((r) => r.id === named.id)?.reservation_id).toBe(booking.id);
expect(typed.find((r) => r.id === bare.id)?.reservation_id).toBeNull();
});
it('PL16 listForPlace — matches the legacy statement, scoped by trip AND place', async () => {
const { trip, place, named, bare } = await seed();
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare('SELECT id FROM day_accommodations WHERE trip_id = ? AND place_id = ?')
.all(trip.id, place.id);
const typed = await repo.listForPlace(trip.id, place.id);
expect(typed).toEqual(legacy);
expect(typed.map((r) => r.id).sort()).toEqual([named.id, bare.id].sort());
});
it('TP55 listAllForTrip — matches the legacy SELECT *, no ORDER BY, scoped by trip', async () => {
const { trip, otherTrip, named, bare, otherStay } = await seed();
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb.prepare('SELECT * FROM day_accommodations WHERE trip_id = ?').all(trip.id);
const typed = await repo.listAllForTrip(trip.id);
expect(typed).toEqual(legacy);
expect(typed.map((r) => r.id).sort()).toEqual([named.id, bare.id].sort());
expect(await repo.listAllForTrip(otherTrip.id)).toEqual([{ ...otherStay }]);
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,378 @@
import { DayNotes } from '../../../../src/db/entities/DayNotes.entity';
import type { DayNotesRepository } from '../../../../src/db/repositories/DayNotes.repository';
import { DB_TIMESTAMP_RE } from '../../../../src/db/types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createDay, createDayNote, createTrip, createUser } from '../../../helpers/factories';
import { findRow, insertRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let notes: DayNotesRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
notes = t.repo(DayNotes);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('DayNotesRepository timestamps', () => {
it('NOTEREPO-001: an ORM insert leaves created_at to the column default, as text', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const row = await notes.createNote({
day_id: day.id,
trip_id: trip.id,
text: 'Lunch',
time: null,
icon: '📝',
sort_order: 0,
color: null,
});
// test-sql-allow: typeof() reports the SQLite storage class of the stored value, which no entity maps.
const stored = testDb
.prepare('SELECT created_at, typeof(created_at) AS kind FROM day_notes WHERE id = ?')
.get(row.id) as { created_at: string; kind: string };
expect(stored.kind).toBe('text');
expect(stored.created_at).toMatch(DB_TIMESTAMP_RE);
expect(row.created_at).toBe(stored.created_at);
});
it('NOTEREPO-002: the returned row is the SELECT * row, with the values the caller passed written verbatim', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const row = await notes.createNote({
day_id: day.id,
trip_id: trip.id,
text: 'Lunch',
time: null,
icon: '📝',
sort_order: 0,
color: null,
});
// test-sql-allow: the raw full row is the parity oracle the repository's return value is compared against.
expect(row).toStrictEqual(testDb.prepare('SELECT * FROM day_notes WHERE id = ?').get(row.id));
expect(row.icon).toBe('📝');
expect(row.sort_order).toBe(0);
});
it('NOTEREPO-003: date() still works on a row the ORM wrote', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const row = await notes.createNote({
day_id: day.id,
trip_id: trip.id,
text: 'Lunch',
time: null,
icon: '📝',
sort_order: 0,
color: null,
});
// test-sql-allow: the point is that SQLite's own date() parses the stored value, so the read has to be SQL.
const d = testDb.prepare('SELECT date(created_at) AS d FROM day_notes WHERE id = ?').get(row.id) as { d: string };
expect(d.d).toMatch(/^\d{4}-\d{2}-\d{2}$/);
});
it('NOTEREPO-004: throws when the read-back after insert finds no row (coverage: the guard branch)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const spy = vi.spyOn(notes, 'findOne').mockResolvedValueOnce(null);
await expect(
notes.createNote({
day_id: day.id,
trip_id: trip.id,
text: 'Ghost',
time: null,
icon: null,
sort_order: 0,
color: null,
}),
).rejects.toThrow('createNote: read-back after insert found no row');
spy.mockRestore();
});
});
// ---------------------------------------------------------------------------
// Plan 3c Task 2 (DY4) — DaysService.list's day_notes batch load.
// ---------------------------------------------------------------------------
describe('DayNotesRepository.listByDayIds (DY4)', () => {
it('NOTEREPO-005: an empty day_ids array short-circuits to [] without querying', async () => {
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
expect(await notes.listByDayIds([])).toEqual([]);
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it('NOTEREPO-006: spans several days, ordered by sort_order ASC then created_at ASC', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const dayA = createDay(testDb, trip.id, { day_number: 1 });
const dayB = createDay(testDb, trip.id, { day_number: 2 });
createDayNote(testDb, dayA.id, trip.id, { text: 'Second', sort_order: 2 });
createDayNote(testDb, dayA.id, trip.id, { text: 'First', sort_order: 1 });
createDayNote(testDb, dayB.id, trip.id, { text: 'Only' });
const rows = await notes.listByDayIds([dayA.id, dayB.id]);
expect(rows.map((r) => r.text)).toEqual(['First', 'Second', 'Only']);
expect(rows.map((r) => r.day_id)).toEqual([dayA.id, dayA.id, dayB.id]);
});
it('NOTEREPO-007: a day with no notes contributes no rows', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
expect(await notes.listByDayIds([day.id])).toEqual([]);
});
// ---------------------------------------------------------------------------
// Task 9 fix wave (B-M3): relabelled. The Task 2 review comment this
// replaces claimed `listByDayIds` being `find`-based made the identity-map
// guard "a real, provable guarantee here, not 'proven regardless'" — that
// is not true: `TrekRepository.find` applies `disableIdentityMap: true` to
// EVERY read by default (rule 14), `listByDayIds` never opts in, and its
// filter (`day: { $in: day_ids }`) is not a primary-key lookup regardless.
// There is no live identity-map entry here to bypass. The setup read still
// passes `{ disableIdentityMap: false }` so it genuinely caches a managed
// entity first (a bare `find({})` would be a no-op under the base's own
// default, the same vacuousness `DAYREPO-018` had) — but what this proves
// is a DB round-trip (a text write after an unrelated wider read is
// visible), not an identity-map bypass.
// ---------------------------------------------------------------------------
it('NOTEREPO-008 (fresh after a raw UPDATE, not D-shape): a text write after an unrelated identity-map read is visible in the FIRST wider listByDayIds', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const note = createDayNote(testDb, day.id, trip.id, { text: 'Old text' });
await t.repo(DayNotes).find({}, { disableIdentityMap: false }); // populate the identity map with the managed note entity
// test-sql-allow: the out-of-band write this case is about has to bypass every EntityManager, the one under test included.
testDb.prepare('UPDATE day_notes SET text = ? WHERE id = ?').run('Fresh text', note.id);
const rows = await notes.listByDayIds([day.id]);
expect(rows).toEqual([expect.objectContaining({ id: note.id, text: 'Fresh text' })]);
});
});
// ── Plan 3c Task 8 (`TripsService.copy`, TP70/TP71) — additive ──────────────
describe('DayNotesRepository.listByTrip (TP70)', () => {
// Task 9 fix wave (B-M4, rule 19): widened from an ids-only assertion to
// full-row parity on a fully seeded fixture — every nullable column
// non-null in one row, null in the other, plus a unicode string and a
// '007'-style digit string — `toEqual(<the legacy SELECT * FROM day_notes
// WHERE trip_id = ? run raw>)`, so a renamed/dropped column or a changed
// row order would fail this, not just the id list.
it('NOTEREPO-009: every note of the trip, scoped by trip_id (not day_id) — toEqual(legacy) on a fully seeded fixture', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
// Row A: every nullable column non-null, a unicode string and a
// '007'-style digit string among the values.
const n1 = await insertRow(t, DayNotes, {
day: day.id,
trip: trip.id,
text: 'Keep — 日本 ☕️ 007',
time: '09:00',
icon: '🗒️',
sort_order: 1,
color: '#00ff00',
});
// Row B: every nullable column NULL.
const n2 = await insertRow(t, DayNotes, {
day: day.id,
trip: trip.id,
text: 'Bare note',
time: null,
icon: null,
sort_order: null,
color: null,
});
const otherDay = createDay(testDb, other.id);
createDayNote(testDb, otherDay.id, other.id, { text: 'Not this trip' });
const rows = await notes.listByTrip(trip.id);
// test-sql-allow: the legacy statement is the parity oracle the repository is compared against.
const legacy = testDb.prepare('SELECT * FROM day_notes WHERE trip_id = ?').all(trip.id);
expect(rows).toEqual(legacy);
expect(rows.map((r) => r.id)).toEqual([n1, n2]);
});
it('NOTEREPO-010: a trip with no notes returns []', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(await notes.listByTrip(trip.id)).toEqual([]);
});
});
describe('DayNotesRepository.insertNoteCopy (TP71)', () => {
it('NOTEREPO-011: writes the 6-column copy set (no color — left NULL, unlike createNote)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const newId = await notes.insertNoteCopy({
day_id: day.id,
trip_id: trip.id,
text: 'Copied note',
time: '09:00',
icon: '🎒',
sort_order: 5,
});
const { day_id, trip_id, text, time, icon, sort_order, color } = (await findRow(t, DayNotes, { id: newId }))!;
expect({ day_id, trip_id, text, time, icon, sort_order, color }).toEqual({
day_id: day.id,
trip_id: trip.id,
text: 'Copied note',
time: '09:00',
icon: '🎒',
sort_order: 5,
color: null,
});
});
});
describe('DayNotesRepository.listByDayAndTrip (Plan 4 Task 1, day-notes.service.ts::list)', () => {
it('NOTEREPO-012: scoped to BOTH day and trip, ordered by sort_order then created_at', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const otherDay = createDay(testDb, trip.id);
const second = createDayNote(testDb, day.id, trip.id, { sort_order: 5 });
const first = createDayNote(testDb, day.id, trip.id, { sort_order: 1 });
createDayNote(testDb, otherDay.id, trip.id);
// test-sql-allow: the legacy statement is the parity oracle the repository is compared against.
const legacy = testDb
.prepare('SELECT * FROM day_notes WHERE day_id = ? AND trip_id = ? ORDER BY sort_order ASC, created_at ASC')
.all(day.id, trip.id);
const rows = await notes.listByDayAndTrip(day.id, trip.id);
expect(rows).toEqual(legacy);
expect(rows.map((r) => r.id)).toEqual([first.id, second.id]);
});
it('NOTEREPO-013: a day with no notes returns []', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
expect(await notes.listByDayAndTrip(day.id, trip.id)).toEqual([]);
});
});
describe('DayNotesRepository.findByIdDayTrip (Plan 4 Task 1, day-notes.service.ts::getNote)', () => {
it('NOTEREPO-014: found only under its own id/day/trip triple', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const otherDay = createDay(testDb, trip.id);
const note = createDayNote(testDb, day.id, trip.id, { text: 'Lunch' });
expect(await notes.findByIdDayTrip(note.id, day.id, trip.id)).toEqual(note);
expect(await notes.findByIdDayTrip(note.id, otherDay.id, trip.id)).toBeUndefined();
expect(await notes.findByIdDayTrip(note.id, day.id, trip.id + 1)).toBeUndefined();
});
});
describe('DayNotesRepository.updateNote (Plan 4 Task 1, day-notes.service.ts::update)', () => {
it('NOTEREPO-015: updates every bound column and returns the re-selected row', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const note = createDayNote(testDb, day.id, trip.id, { text: 'Lunch', time: '12:00', icon: '🍜', sort_order: 2 });
const updated = await notes.updateNote(note.id, {
text: 'Dinner',
time: '19:00',
icon: '🍣',
sort_order: 3,
color: '#2563eb',
});
expect(updated).toMatchObject({
id: note.id,
text: 'Dinner',
time: '19:00',
icon: '🍣',
sort_order: 3,
color: '#2563eb',
});
const stored = (await findRow(t, DayNotes, { id: note.id }))!;
expect({
text: stored.text,
time: stored.time,
icon: stored.icon,
sort_order: stored.sort_order,
color: stored.color,
}).toEqual({ text: 'Dinner', time: '19:00', icon: '🍣', sort_order: 3, color: '#2563eb' });
});
it('NOTEREPO-016: undefined for an id that does not exist', async () => {
expect(
await notes.updateNote(999999, { text: 'x', time: null, icon: null, sort_order: null, color: null }),
).toBeUndefined();
});
});
describe('DayNotesRepository.deleteById (Plan 4 Task 1, day-notes.service.ts::remove)', () => {
it('NOTEREPO-017: deletes by bare id', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const note = createDayNote(testDb, day.id, trip.id);
await notes.deleteById(note.id);
expect(await findRow(t, DayNotes, { id: note.id })).toBeNull();
});
it('NOTEREPO-018: deleting an id that does not exist is a no-op, not an error', async () => {
await expect(notes.deleteById(999999)).resolves.toBeUndefined();
});
});
describe('DayNotesRepository.listForPublicApi (Plan 4 Task 1, public-api.service.ts::dayNotesByDay)', () => {
it('NOTEREPO-019: day_id/text/time only, ordered by day_id then sort_order, scoped to the trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const dayA = createDay(testDb, trip.id);
const dayB = createDay(testDb, trip.id);
createDayNote(testDb, dayB.id, trip.id, { text: 'B-second', sort_order: 5 });
createDayNote(testDb, dayA.id, trip.id, { text: 'A-first', sort_order: 1 });
createDayNote(testDb, dayB.id, trip.id, { text: 'B-first', sort_order: 1 });
createDayNote(testDb, createDay(testDb, other.id).id, other.id, { text: 'Not this trip' });
const rows = await notes.listForPublicApi(trip.id);
expect(rows).toEqual([
{ day_id: dayA.id, text: 'A-first', time: null },
{ day_id: dayB.id, text: 'B-first', time: null },
{ day_id: dayB.id, text: 'B-second', time: null },
]);
});
it('NOTEREPO-020: empty array for a trip with no notes', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(await notes.listForPublicApi(trip.id)).toEqual([]);
});
});
@@ -0,0 +1,440 @@
import { Days } from '../../../../src/db/entities/Days.entity';
import type { DaysRepository } from '../../../../src/db/repositories/Days.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import {
createDay,
createDayAccommodation,
createDayAssignment,
createDayNote,
createPlace,
createTrip,
createUser,
} from '../../../helpers/factories';
import { findRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let days: DaysRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
days = t.repo(Days);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
/** The SELECT * row as the database holds it: the oracle the repository's rows are compared with key for key. */
function rawDay(id: number): unknown {
// test-sql-allow: the raw row is the oracle the ORM's rows are held against, key for key.
return testDb.prepare('SELECT * FROM days WHERE id = ?').get(id);
}
describe('DaysRepository', () => {
it('DAYREPO-001: a row read through the ORM is the SELECT * row, key for key', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id, { date: '2026-07-01', title: 'Arrival' });
const [row] = await days.listByTrip(trip.id);
expect(row).toStrictEqual(rawDay(day.id));
});
it('DAYREPO-002: the scalar FK hydrates without loading the trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createDay(testDb, trip.id);
const entity = await t.repo(Days).findOne({ trip: trip.id });
expect(entity?.trip_id).toBe(trip.id);
expect(entity?.trip.isInitialized()).toBe(false);
});
it('DAYREPO-003: listByTrip orders by day_number', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createDay(testDb, trip.id, { day_number: 2 });
createDay(testDb, trip.id, { day_number: 1 });
const rows = await days.listByTrip(trip.id);
expect(rows.map((r) => r.day_number)).toEqual([1, 2]);
});
it('DAYREPO-004: findInTrip refuses a day from another trip', async () => {
const { user } = createUser(testDb);
const a = createTrip(testDb, user.id);
const b = createTrip(testDb, user.id);
const day = createDay(testDb, a.id);
expect(await days.findInTrip(day.id, b.id)).toBeUndefined();
expect((await days.findInTrip(day.id, a.id))?.id).toBe(day.id);
});
it('DAYREPO-005: maxDayNumber is 0 for an empty trip and the max otherwise', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(await days.maxDayNumber(trip.id)).toBe(0);
createDay(testDb, trip.id, { day_number: 1 });
createDay(testDb, trip.id, { day_number: 10 });
createDay(testDb, trip.id, { day_number: 2 });
// 10, not '2': the descending order has to be numeric, not lexicographic.
expect(await days.maxDayNumber(trip.id)).toBe(10);
});
it('DAYREPO-006: createDay writes the legacy column set and returns the re-read row', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const row = await days.createDay({ trip_id: trip.id, day_number: 1, date: '2026-07-01', notes: null });
expect(row).toStrictEqual(rawDay(row.id));
expect(row.notes).toBeNull();
expect(row.trip_id).toBe(trip.id);
});
it('DAYREPO-006b: throws when the read-back after insert finds no row (coverage: the guard branch)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const spy = vi.spyOn(days, 'findOne').mockResolvedValueOnce(null);
await expect(days.createDay({ trip_id: trip.id, day_number: 1, date: null, notes: null })).rejects.toThrow(
'createDay: read-back after insert found no row',
);
spy.mockRestore();
});
});
// ---------------------------------------------------------------------------
// Plan 3c Task 2 — the DaysService conversion's remaining methods (DY7/DY9/
// DY11/DY13/DY21/DY26–DY36).
// ---------------------------------------------------------------------------
describe('DaysRepository — Task 2 additions', () => {
it('DAYREPO-010: findById is the SELECT * row, undefined for a missing id', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id, { title: 'Arrival' });
expect(await days.findById(day.id)).toStrictEqual(rawDay(day.id));
expect(await days.findById(999999)).toBeUndefined();
});
it('DAYREPO-011: updateNotesAndTitle writes both columns verbatim (the presence-sentinel decision itself lives in the service)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await days.updateNotesAndTitle(day.id, 'Walking day', 'Arrival');
expect(await days.findById(day.id)).toMatchObject({ notes: 'Walking day', title: 'Arrival' });
await days.updateNotesAndTitle(day.id, null, null);
expect(await days.findById(day.id)).toMatchObject({ notes: null, title: null });
});
it('DAYREPO-012: setDefaultTransportMode sets and clears the column', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await days.setDefaultTransportMode(day.id, 'walk');
expect(await days.findById(day.id)).toMatchObject({ default_transport_mode: 'walk' });
await days.setDefaultTransportMode(day.id, null);
expect(await days.findById(day.id)).toMatchObject({ default_transport_mode: null });
});
it('DAYREPO-013: deleteById is unscoped by trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await days.deleteById(day.id);
expect(await days.findById(day.id)).toBeUndefined();
});
it('DAYREPO-014: listOrderedForReorder returns {id, day_number, date}, ordered by day_number', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const d2 = createDay(testDb, trip.id, { day_number: 2, date: '2026-01-02' });
const d1 = createDay(testDb, trip.id, { day_number: 1, date: '2026-01-01' });
const rows = await days.listOrderedForReorder(trip.id);
expect(rows).toEqual([
{ id: d1.id, day_number: 1, date: '2026-01-01' },
{ id: d2.id, day_number: 2, date: '2026-01-02' },
]);
});
it('DAYREPO-015: setDayNumber and setDayNumberAndDate write their columns; the two-phase (negative then positive) sequence a caller drives here never collides', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const a = createDay(testDb, trip.id, { day_number: 1 });
const b = createDay(testDb, trip.id, { day_number: 2 });
// Phase 1: negative, to dodge UNIQUE(trip_id, day_number) while swapping.
await days.setDayNumber(a.id, -2);
await days.setDayNumber(b.id, -1);
// Phase 2: positive (the swap).
await days.setDayNumberAndDate(a.id, 2, '2026-02-02');
await days.setDayNumberAndDate(b.id, 1, '2026-02-01');
expect(await days.findById(a.id)).toMatchObject({ day_number: 2, date: '2026-02-02' });
expect(await days.findById(b.id)).toMatchObject({ day_number: 1, date: '2026-02-01' });
});
it('DAYREPO-016: insertDay writes trip_id/day_number/date only (no notes column named) and returns the inserted id', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const id = await days.insertDay({ trip_id: trip.id, day_number: 1, date: '2026-03-01' });
expect(typeof id).toBe('number');
const row = rawDay(id) as { notes: string | null; date: string | null; day_number: number; trip_id: number };
expect(row).toMatchObject({ trip_id: trip.id, day_number: 1, date: '2026-03-01', notes: null });
});
it('DAYREPO-017: findByTripAndDate finds the day at that date, undefined otherwise, scoped to the trip', async () => {
const { user } = createUser(testDb);
const tripA = createTrip(testDb, user.id);
const tripB = createTrip(testDb, user.id);
const day = createDay(testDb, tripA.id, { date: '2026-04-01' });
createDay(testDb, tripB.id, { date: '2026-04-01' });
expect(await days.findByTripAndDate(tripA.id, '2026-04-01')).toEqual({ id: day.id, day_number: day.day_number });
expect(await days.findByTripAndDate(tripA.id, '2026-04-02')).toBeUndefined();
});
// D-shape: `findById` (findOne-based, `disableIdentityMap: true` by the base
// class default) must see a column written after an unrelated identity-map
// read populated the same entity type — written column (`notes`) is outside
// the narrower read's own projection scope, so a stale write-back would
// revert it if the base class's guarantee ever regressed.
//
// Task 2 review (task-2-review.md, L1): the original setup read
// (`find({})` with no options) went through `TrekRepository`'s OWN
// `disableIdentityMap: true` default too, so it never actually populated
// the identity map with the managed `day` entity — the test passed
// trivially, with nothing stale for `findById` to ever return. `{
// disableIdentityMap: false }` on THIS read is what makes the setup real:
// the managed entity (pre-write `notes`) is cached first, and `findById`'s
// own default must still bypass it. Mutation-proved (Task 3 session): with
// `TrekRepository.findOne`'s `disableIdentityMap` default temporarily
// flipped to `false`, this test fails (`findById` returns the stale
// pre-write `notes`); reverted immediately after.
it('DAYREPO-018 (D-shape): a notes write after an unrelated identity-map read is visible in findById', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await t.repo(Days).find({}, { disableIdentityMap: false }); // populate the identity map with the managed `day` entity
await days.updateNotesAndTitle(day.id, 'Fresh notes', null);
expect(await days.findById(day.id)).toMatchObject({ notes: 'Fresh notes' });
});
// ---------------------------------------------------------------------------
// Plan 3c Task 3 (`AssignmentsService.dayExists`, AS4) — appended per the
// task's own file-ownership rule.
// ---------------------------------------------------------------------------
describe('existsInTrip (AS4)', () => {
it('DAYREPO-019: true only for the matching day AND trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const { user: other } = createUser(testDb);
const otherTrip = createTrip(testDb, other.id);
const day = createDay(testDb, trip.id);
expect(await days.existsInTrip(day.id, trip.id)).toBe(true);
expect(await days.existsInTrip(day.id, otherTrip.id)).toBe(false);
expect(await days.existsInTrip(999999, trip.id)).toBe(false);
});
it('DAYREPO-020: raw-bind — a string id/trip_id binds unconverted, same as a real number', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
expect(await days.existsInTrip(String(day.id), String(trip.id))).toBe(true);
expect(await days.existsInTrip('not-a-number', trip.id)).toBe(false);
});
});
});
// ── Plan 3c Task 8 (`TripsService.copy`, TP39) — additive ───────────────────
describe('DaysRepository.insertDayCopy (TP39)', () => {
it('DAYREPO-025: writes the 5-column copy set (trip_id, day_number, date, notes, title) verbatim, no read-back', async () => {
const { user } = createUser(testDb);
const src = createTrip(testDb, user.id);
const dst = createTrip(testDb, user.id);
const srcDay = createDay(testDb, src.id, { date: '2026-03-01', title: 'Arrival' });
await updateRows(t, Days, { id: srcDay.id }, { notes: 'Bring passport' });
const newId = await days.insertDayCopy({
trip_id: dst.id,
day_number: srcDay.day_number,
date: srcDay.date,
notes: 'Bring passport',
title: srcDay.title,
});
const row = await findRow(t, Days, { id: newId });
expect(row).toMatchObject({
trip_id: dst.id,
day_number: srcDay.day_number,
date: '2026-03-01',
notes: 'Bring passport',
title: 'Arrival',
});
});
it('DAYREPO-026: null date/notes/title are written as NULL, not coerced', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const newId = await days.insertDayCopy({ trip_id: trip.id, day_number: 1, date: null, notes: null, title: null });
const row = await findRow(t, Days, { id: newId });
expect(row).toMatchObject({ date: null, notes: null, title: null });
});
});
describe('DaysRepository.listForPublicApi (Plan 4 Task 1, public-api.service.ts::buildDays)', () => {
it('DAYREPO-027: id/day_number/date/title/notes only, ordered by day_number, scoped to the trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const day2 = createDay(testDb, trip.id, { day_number: 2, date: '2026-06-02' });
const day1 = createDay(testDb, trip.id, { day_number: 1, date: '2026-06-01' });
createDay(testDb, other.id, { day_number: 1 });
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare('SELECT id, day_number, date, title, notes FROM days WHERE trip_id = ? ORDER BY day_number ASC')
.all(trip.id);
const rows = await days.listForPublicApi(trip.id);
expect(rows).toEqual(legacy);
expect(rows.map((r) => r.id)).toEqual([day1.id, day2.id]);
});
it('DAYREPO-028: empty array for a trip with no days', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(await days.listForPublicApi(trip.id)).toEqual([]);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Plan 4 Task 8b-2, item 1 (3d Task 7 review's "Days.listPlanDays" carry):
// RPL1 (`roadtrip-plan.service.ts::context`) had no repository-level
// toEqual(<legacy raw>) test.
// ─────────────────────────────────────────────────────────────────────────────
describe('DaysRepository.listPlanDays (RPL1, roadtrip-plan.service.ts::context)', () => {
it('DAYREPO-029: id/day_number/date/title/default_transport_mode, ordered by day_number, default_transport_mode both NULL and set', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const day2 = createDay(testDb, trip.id, { day_number: 2, date: '2026-06-02', title: 'Day 2' });
const day1 = createDay(testDb, trip.id, { day_number: 1, date: '2026-06-01', title: null });
await updateRows(t, Days, { id: day2.id }, { default_transport_mode: 'walking' });
createDay(testDb, other.id, { day_number: 1 });
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare(
'SELECT id, day_number, date, title, default_transport_mode FROM days WHERE trip_id = ? ORDER BY day_number ASC',
)
.all(trip.id);
const rows = await days.listPlanDays(trip.id);
expect(rows).toEqual(legacy);
expect(rows.map((r) => r.id)).toEqual([day1.id, day2.id]);
expect(rows[0].default_transport_mode).toBeNull();
expect(rows[1].default_transport_mode).toBe('walking');
});
it('DAYREPO-030: empty array for a trip with no days', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(await days.listPlanDays(trip.id)).toEqual([]);
});
});
// ── Plan 3c Task 7 (`TripsService.generateDays` on the shared planDayGrid: TP77, TP78) ──
describe('DaysRepository.listForDayGrid (TP77, trips.service.ts::generateDays)', () => {
it('DAYREPO-031: id/day_number/date plus has_plan_items as 0/1, set by an assignment or a note and never by a stay, ordered by day_number, scoped to the trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const withNote = createDay(testDb, trip.id, { day_number: 3 });
const bare = createDay(testDb, trip.id, { day_number: 1, date: '2026-06-01' });
const withAssignment = createDay(testDb, trip.id, { day_number: 2, date: '2026-06-02' });
// A stay is not a plan item: the plan reads stays separately (TP78) and
// this flag must stay 0 for a day that only checks a stay in or out.
const withStay = createDay(testDb, trip.id, { day_number: 4 });
createDay(testDb, other.id, { day_number: 1 });
const place = createPlace(testDb, trip.id);
createDayAssignment(testDb, withAssignment.id, place.id);
createDayNote(testDb, withNote.id, trip.id);
createDayAccommodation(testDb, trip.id, place.id, withStay.id, withStay.id);
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare(
`
SELECT d.id, d.day_number, d.date,
EXISTS (SELECT 1 FROM day_assignments da WHERE da.day_id = d.id)
OR EXISTS (SELECT 1 FROM day_notes dn WHERE dn.day_id = d.id) AS has_plan_items
FROM days d WHERE d.trip_id = ? ORDER BY d.day_number ASC
`,
)
.all(trip.id);
const rows = await days.listForDayGrid(trip.id);
expect(rows).toEqual(legacy);
expect(rows.map((r) => [r.id, r.has_plan_items])).toEqual([
[bare.id, 0],
[withAssignment.id, 1],
[withNote.id, 1],
[withStay.id, 0],
]);
expect(rows.map((r) => r.date)).toEqual(['2026-06-01', '2026-06-02', null, null]);
});
it('DAYREPO-032: empty array for a trip with no days', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(await days.listForDayGrid(trip.id)).toEqual([]);
});
});
describe('DaysRepository.listDayGridStays (TP78, trips.service.ts::generateDays)', () => {
it("DAYREPO-033: start_day_id/end_day_id of every stay checking in OR out on one of the trip's days, a stay on another trip's days left out", async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const d1 = createDay(testDb, trip.id, { day_number: 1 });
const d2 = createDay(testDb, trip.id, { day_number: 2 });
const foreign = createDay(testDb, other.id, { day_number: 1 });
const place = createPlace(testDb, trip.id);
const otherPlace = createPlace(testDb, other.id);
createDayAccommodation(testDb, trip.id, place.id, d1.id, d2.id);
createDayAccommodation(testDb, trip.id, place.id, d2.id, d2.id);
createDayAccommodation(testDb, other.id, otherPlace.id, foreign.id, foreign.id);
// Only the check-out day is one of this trip's: reached through the
// `end_day_id IN` half alone, so that half cannot be dropped unnoticed.
createDayAccommodation(testDb, other.id, otherPlace.id, foreign.id, d1.id);
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare(
`
SELECT dac.start_day_id, dac.end_day_id FROM day_accommodations dac
WHERE dac.start_day_id IN (SELECT id FROM days WHERE trip_id = ?)
OR dac.end_day_id IN (SELECT id FROM days WHERE trip_id = ?)
`,
)
.all(trip.id, trip.id);
const rows = await days.listDayGridStays(trip.id);
expect(rows).toEqual(legacy);
const byDay = (a: { start_day_id: number; end_day_id: number }, b: { start_day_id: number; end_day_id: number }) =>
a.start_day_id - b.start_day_id || a.end_day_id - b.end_day_id;
expect([...rows].sort(byDay)).toEqual([
{ start_day_id: d1.id, end_day_id: d2.id },
{ start_day_id: d2.id, end_day_id: d2.id },
{ start_day_id: foreign.id, end_day_id: d1.id },
]);
});
it('DAYREPO-034: empty array when no stay touches the trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createDay(testDb, trip.id);
expect(await days.listDayGridStays(trip.id)).toEqual([]);
});
});
@@ -0,0 +1,318 @@
import { AppSettings } from '../../../../src/db/entities/AppSettings.entity';
import { BudgetItems } from '../../../../src/db/entities/BudgetItems.entity';
import { DayAssignments } from '../../../../src/db/entities/DayAssignments.entity';
import { DayNotes } from '../../../../src/db/entities/DayNotes.entity';
import { Days } from '../../../../src/db/entities/Days.entity';
import { PackingItems } from '../../../../src/db/entities/PackingItems.entity';
import { Places } from '../../../../src/db/entities/Places.entity';
import { Reservations } from '../../../../src/db/entities/Reservations.entity';
import { TripMembers } from '../../../../src/db/entities/TripMembers.entity';
import { Trips } from '../../../../src/db/entities/Trips.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import { DemoRepository, type NewDemoPlaceRow } from '../../../../src/db/repositories/DemoRepository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser, createAdmin } from '../../../helpers/factories';
import { findRow, findRows, insertRows, updateRows } from '../../../helpers/factories/rows';
import { readAppSetting } from '../../../helpers/factories/settings';
import { readUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
/** The given columns of a row, the shape a narrow SELECT returned. */
function pick<T extends object, K extends keyof T>(row: T | null, keys: K[]): Pick<T, K> | null {
if (!row) return null;
const out = {} as Pick<T, K>;
for (const key of keys) out[key] = row[key];
return out;
}
const testDb = createSnapshotTestDb();
let t: TestOrm;
let demo: DemoRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
demo = new DemoRepository(t.em);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('DemoRepository', () => {
it('DEMOREPO-001: findUserByEmail — DMS1, case-sensitive, no guest filter', async () => {
const { user } = createUser(testDb, { email: 'admin@trek.app' });
await expect(demo.findUserByEmail('admin@trek.app')).resolves.toEqual({ id: user.id });
await expect(demo.findUserByEmail('nope@trek.app')).resolves.toBeNull();
});
it('DEMOREPO-002: createUser — DMS2, leaves first_seen_version/login_count/oidc/avatar to the entity default', async () => {
const id = await demo.createUser({ username: 'demo', email: 'demo@trek.app', password_hash: 'x', role: 'user' });
const row = pick(await readUser(t, id), ['username', 'email', 'role', 'first_seen_version', 'login_count']);
expect(row).toEqual({
username: 'demo',
email: 'demo@trek.app',
role: 'user',
first_seen_version: '0.0.0',
login_count: 0,
});
});
it('DEMOREPO-003: setAllowRegistrationFalse — DMS3', async () => {
await demo.setAllowRegistrationFalse();
expect(await readAppSetting(t, 'allow_registration')).toBe('false');
// Idempotent — a second call still lands 'false' (INSERT OR REPLACE dialect).
await demo.setAllowRegistrationFalse();
expect(await readAppSetting(t, 'allow_registration')).toBe('false');
});
it('DEMOREPO-004: countTripsByUser / listTripIdsByUser — DMS4/DMS5', async () => {
const { user } = createAdmin(testDb);
expect(await demo.countTripsByUser(user.id)).toBe(0);
const t1 = await demo.insertTrip(user.id, 'A', 'desc', '2026-01-01', '2026-01-02', 'EUR');
const t2 = await demo.insertTrip(user.id, 'B', 'desc', '2026-02-01', '2026-02-02', 'EUR');
expect(await demo.countTripsByUser(user.id)).toBe(2);
expect((await demo.listTripIdsByUser(user.id)).sort()).toEqual([t1, t2].sort());
});
it('DEMOREPO-005: addTripMember — DMS6, INSERT OR IGNORE (a repeat call does not throw)', async () => {
const { user: owner } = createAdmin(testDb);
const { user: member } = createUser(testDb);
const tripId = await demo.insertTrip(owner.id, 'A', 'desc', '2026-01-01', '2026-01-02', 'EUR');
await demo.addTripMember(tripId, member.id, owner.id);
await demo.addTripMember(tripId, member.id, owner.id); // no UNIQUE-constraint throw
const rows = (await findRows(t, TripMembers, { trip: tripId })).map((r) =>
pick(r, ['trip_id', 'user_id', 'invited_by']),
);
expect(rows).toEqual([{ trip_id: tripId, user_id: member.id, invited_by: owner.id }]);
});
it('DEMOREPO-006: insertDay/insertPlace/insertDayAssignment/insertPackingItem/insertBudgetItem/insertReservation/insertDayNote — DMS7-14', async () => {
const { user } = createAdmin(testDb);
const tripId = await demo.insertTrip(user.id, 'Test Trip', 'd', '2026-04-15', '2026-04-16', 'JPY');
const dayId = await demo.insertDay(tripId, 1, '2026-04-15');
expect(pick(await findRow(t, Days, { id: dayId }), ['trip_id', 'day_number', 'date'])).toEqual({
trip_id: tripId,
day_number: 1,
date: '2026-04-15',
});
const place: NewDemoPlaceRow = [
tripId,
'Hotel X',
35.1,
139.1,
'Addr',
1,
'15:00',
60,
'notes',
null,
'gpid',
null,
null,
];
const placeId = await demo.insertPlace(place);
const placeRow = pick(await findRow(t, Places, { id: placeId }), ['trip_id', 'name', 'category_id']);
expect(placeRow).toEqual({ trip_id: tripId, name: 'Hotel X', category_id: 1 });
await demo.insertDayAssignment(dayId, placeId, 0);
expect(pick(await findRow(t, DayAssignments, { day: dayId }), ['day_id', 'place_id', 'order_index'])).toEqual({
day_id: dayId,
place_id: placeId,
order_index: 0,
});
await demo.insertPackingItem(tripId, 'Passport', 1, 'Documents', 0);
const packing = pick(await findRow(t, PackingItems, { trip: tripId }), [
'trip_id',
'name',
'checked',
'category',
'sort_order',
]);
expect(packing).toEqual({ trip_id: tripId, name: 'Passport', checked: 1, category: 'Documents', sort_order: 0 });
await demo.insertBudgetItem(tripId, 'Food', 'Lunch', 1000, 2, null);
const budget = pick(await findRow(t, BudgetItems, { trip: tripId }), [
'trip_id',
'category',
'name',
'total_price',
'persons',
'note',
]);
expect(budget).toEqual({
trip_id: tripId,
category: 'Food',
name: 'Lunch',
total_price: 1000,
persons: 2,
note: null,
});
await demo.insertReservation(
tripId,
dayId,
'Check-in',
'2026-04-15T15:00',
'CONF-1',
'confirmed',
'hotel',
'Tokyo',
);
const reservation = pick(await findRow(t, Reservations, { trip: tripId }), [
'trip_id',
'day_id',
'title',
'reservation_time',
'confirmation_number',
'status',
'type',
'location',
]);
expect(reservation).toEqual({
trip_id: tripId,
day_id: dayId,
title: 'Check-in',
reservation_time: '2026-04-15T15:00',
confirmation_number: 'CONF-1',
status: 'confirmed',
type: 'hotel',
location: 'Tokyo',
});
await demo.insertDayNote(dayId, tripId, 'Note text', '13:00', 'Info', 0.5);
const note = pick(await findRow(t, DayNotes, { day: dayId }), [
'day_id',
'trip_id',
'text',
'time',
'icon',
'sort_order',
]);
expect(note).toEqual({
day_id: dayId,
trip_id: tripId,
text: 'Note text',
time: '13:00',
icon: 'Info',
sort_order: 0.5,
});
});
it('DEMOREPO-007: the inserts read the new id back with RETURNING, and a packing item gets its updated_at stamp', async () => {
const { user } = createAdmin(testDb);
const tripId = await demo.insertTrip(user.id, 'Ids', 'd', '2026-05-01', '2026-05-02', 'EUR');
expect(typeof tripId).toBe('number');
const [latest] = await findRows(t, Trips, {}, { id: 'desc' });
expect(tripId).toBe(latest.id);
const dayId = await demo.insertDay(tripId, 1, '2026-05-01');
const secondDayId = await demo.insertDay(tripId, 2, '2026-05-02');
expect(secondDayId).toBeGreaterThan(dayId);
await demo.insertPackingItem(tripId, 'Charger', 0, 'Tech', 1);
const packing = await findRow(t, PackingItems, { trip: tripId });
expect(packing?.updated_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
});
it('DEMOREPO-CRED-001 (DMR1/DMR5 round trip): getAdminCredentials reads exactly what restoreAdminCredentials wrote', async () => {
const { user } = createAdmin(testDb, { email: 'admin@nomad.app' });
await updateRows(
t,
Users,
{ id: user.id },
{
maps_api_key: 'maps-key',
openweather_api_key: 'ow-key',
unsplash_api_key: 'un-key',
avatar: 'avatar.png',
},
);
const before = await demo.getAdminCredentials('admin@nomad.app');
expect(before).toEqual({
password_hash: expect.any(String),
maps_api_key: 'maps-key',
openweather_api_key: 'ow-key',
unsplash_api_key: 'un-key',
avatar: 'avatar.png',
});
// Simulate a baseline restore clobbering the row, then restore the preserved values.
await updateRows(
t,
Users,
{ id: user.id },
{
password_hash: 'stale-hash-from-baseline',
maps_api_key: null,
openweather_api_key: null,
unsplash_api_key: null,
avatar: null,
},
);
await demo.restoreAdminCredentials('admin@nomad.app', before!);
const after = pick(await readUser(t, user.id), [
'password_hash',
'maps_api_key',
'openweather_api_key',
'unsplash_api_key',
'avatar',
]);
expect(after).toEqual(before);
});
it('DEMOREPO-CRED-002 (DMR5): writes exactly the 5 named columns, no updated_at bump', async () => {
const { user } = createAdmin(testDb, { email: 'admin@nomad.app' });
const before = await readUser(t, user.id);
await demo.restoreAdminCredentials('admin@nomad.app', {
password_hash: 'h',
maps_api_key: 'm',
openweather_api_key: 'o',
unsplash_api_key: 'u',
avatar: 'a',
});
const after = await readUser(t, user.id);
expect(after.updated_at).toBe(before.updated_at);
});
it('DEMOREPO-KEYS-001 (DMR2/DMR6 round trip): getInstanceApiKeys preserves a NULL value, restoreInstanceApiKeys writes it back as NULL', async () => {
await insertRows(t, AppSettings, [
{ key: 'maps_api_key', value: 'a-maps-key' },
{ key: 'unsplash_api_key', value: null },
]);
const rows = await demo.getInstanceApiKeys();
expect(rows.sort((a, b) => a.key.localeCompare(b.key))).toEqual([
{ key: 'maps_api_key', value: 'a-maps-key' },
{ key: 'unsplash_api_key', value: null },
]);
// Clobber, then restore from what was read.
await updateRows(t, AppSettings, { key: 'maps_api_key' }, { value: 'clobbered' });
await demo.restoreInstanceApiKeys(rows);
const after = (
await findRows(t, AppSettings, { key: { $in: ['maps_api_key', 'unsplash_api_key'] } }, { key: 'asc' })
).map((r) => pick(r, ['key', 'value']));
expect(after).toEqual([
{ key: 'maps_api_key', value: 'a-maps-key' },
{ key: 'unsplash_api_key', value: null },
]);
});
it('DEMOREPO-KEYS-002: restoreInstanceApiKeys upserts a row that did not previously exist', async () => {
await demo.restoreInstanceApiKeys([{ key: 'maps_api_key', value: 'brand-new' }]);
expect(await readAppSetting(t, 'maps_api_key')).toBe('brand-new');
});
});
@@ -0,0 +1,109 @@
import { DocumentProviders } from '../../../../src/db/entities/DocumentProviders.entity';
import type { DocumentProvidersRepository } from '../../../../src/db/repositories/DocumentProviders.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { insertRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let documentProviders: DocumentProvidersRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
documentProviders = t.repo(DocumentProviders);
});
beforeEach(() => {
resetTestDb(testDb);
// document_provider_fields FK-references document_providers, so clear the
// child first — resetTestDb keeps both tables (test-db.ts's KEEP_TABLES).
testDb.exec('DELETE FROM document_provider_fields');
testDb.exec('DELETE FROM document_providers');
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function insertProvider(row: {
id: string;
name: string;
description?: string | null;
icon?: string | null;
enabled: 0 | 1;
sort_order?: number;
}): Promise<void> {
await insertRow(t, DocumentProviders, {
id: row.id,
name: row.name,
description: row.description ?? null,
icon: row.icon ?? null,
enabled: row.enabled,
sort_order: row.sort_order ?? 0,
});
}
// Plan 3i Task 4 fix wave (should-land 5): AD29 (listAllOrdered) and AD32
// (findById) shipped in Task 1 with no repository-level test at all — this
// shared table (owned by 3h's doc-sync task; these two methods are 3i's
// additive admin-reuse per R6) had zero coverage of its own. One seeded
// world, full-key parity against the exact legacy SQL each method's own
// docstring names.
describe('DocumentProvidersRepository — admin (AD29/AD32) read methods, full-key parity', () => {
it('DOCPROVREPO-001 (AD29): listAllOrdered matches SELECT * FROM document_providers ORDER BY sort_order, id — unfiltered, including a disabled provider', async () => {
await insertProvider({
id: 'paperless',
name: 'Paperless',
description: 'Self-hosted document management',
icon: 'FileText',
enabled: 0,
sort_order: 1,
});
await insertProvider({ id: 'papra', name: 'Papra', enabled: 1, sort_order: 0 });
// test-sql-allow: the legacy AD29 statement is the parity oracle the repository is compared against.
const legacy = testDb.prepare('SELECT * FROM document_providers ORDER BY sort_order, id').all();
const rows = await documentProviders.listAllOrdered();
expect(rows.map((r) => r.id)).toEqual(['papra', 'paperless']); // includes the disabled one, unlike listEnabledCatalog
// `enabled` stays the raw stored integer on this entity (no boolean
// coercion, unlike Addons.enabled), so the row shape is identical to the
// legacy `SELECT *` — no per-column remap needed.
expect(rows).toEqual(legacy);
});
it('DOCPROVREPO-002: listAllOrdered on an empty table returns an empty array', async () => {
expect(await documentProviders.listAllOrdered()).toEqual([]);
});
it('DOCPROVREPO-003 (AD32): findById matches SELECT * FROM document_providers WHERE id = ?, on both a pre-write read and a post-write re-select', async () => {
await insertProvider({
id: 'paperless',
name: 'Paperless',
description: 'Self-hosted document management',
icon: 'FileText',
enabled: 0,
sort_order: 3,
});
const preWrite = await documentProviders.findById('paperless');
expect(preWrite).toEqual({
id: 'paperless',
name: 'Paperless',
description: 'Self-hosted document management',
icon: 'FileText',
enabled: 0,
sort_order: 3,
});
// test-sql-allow: the out-of-band write this case is about has to bypass every EntityManager, the one under test included.
testDb.prepare('UPDATE document_providers SET enabled = 1 WHERE id = ?').run('paperless');
const postWrite = await documentProviders.findById('paperless');
expect(postWrite?.enabled).toBe(1);
});
it('DOCPROVREPO-004: findById on a missing id returns null', async () => {
expect(await documentProviders.findById('does-not-exist')).toBeNull();
});
});
@@ -0,0 +1,385 @@
/**
* `DocumentSyncItemsRepository` (Plan 3h Task 5, R3's own two named
* requirements): DS24's partial-unique-index upsert
* (`insertOrUpsertOnConflict`, `ON CONFLICT(link_id, remote_id) WHERE
* remote_id IS NOT NULL DO UPDATE`) and DS23's plain conditional update
* (`recordAttempt`, ten `COALESCE` columns + the backoff second-count).
*/
import { currentTimestampKysely } from '../../../../src/db/dialect/kysely-functions';
import { DocumentConnections } from '../../../../src/db/entities/DocumentConnections.entity';
import { DocumentSyncItems } from '../../../../src/db/entities/DocumentSyncItems.entity';
import { TripDocumentLinks } from '../../../../src/db/entities/TripDocumentLinks.entity';
import { TripFiles } from '../../../../src/db/entities/TripFiles.entity';
import type { DocumentSyncItemsRepository } from '../../../../src/db/repositories/DocumentSyncItems.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createTrip, createUser } from '../../../helpers/factories';
import { findRow, findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: DocumentSyncItemsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(DocumentSyncItems);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function fixture() {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const connectionId = await insertRow(t, DocumentConnections, {
trip: trip.id,
provider: 'paperless',
ownerUser: user.id,
base_url: 'https://paperless.example.com',
secrets: null,
settings: '{}',
});
const linkId = await insertRow(t, TripDocumentLinks, {
trip: trip.id,
connection: connectionId,
provider_id: 'paperless',
remote_scope_key: 'tag:1',
remote_label: 'Japan',
direction: 'both',
delete_policy: 'unlink',
conflict_policy: 'manual',
sync_enabled: 1,
createdByRef: user.id,
});
return { user, trip, linkId };
}
/** The sync item as it is now; fails the test when it is gone. */
async function itemRow(id: number) {
return (await findRow(t, DocumentSyncItems, { id }))!;
}
function insertData(
linkId: number,
tripId: number,
over: Partial<Parameters<DocumentSyncItemsRepository['insertOrUpsertOnConflict']>[0]> = {},
) {
return {
link_id: linkId,
trip_id: tripId,
file_id: null,
trek_doc_uid: `uid-${Math.random()}`,
remote_id: null,
remote_name: null,
remote_version: null,
remote_size: null,
remote_modified_at: null,
content_sha256: null,
pushed_sha256: null,
state: 'synced',
error_code: null,
attempts: 0,
next_attempt_after_seconds: null,
synced_now: true,
...over,
};
}
describe('DocumentSyncItemsRepository', () => {
describe('insertOrUpsertOnConflict (DS24, R3 — the partial-unique-index upsert)', () => {
it('DS24REPO-001: pinned rendered SQL for the ON CONFLICT DO UPDATE target and SET clause', () => {
const platform = t.em.getPlatform();
const compiled = t.em
.getKysely<{ document_sync_items: Record<string, unknown> }>()
.insertInto('document_sync_items')
.values({
link_id: 1,
trip_id: 1,
file_id: null,
trek_doc_uid: 'x',
remote_id: 'r1',
remote_name: null,
remote_version: null,
remote_size: null,
remote_modified_at: null,
content_sha256: null,
pushed_sha256: null,
state: 'synced',
error_code: null,
attempts: 0,
next_attempt_at: null,
synced_at: null,
last_seen_at: 'CURRENT_TIMESTAMP',
})
.onConflict((oc) =>
oc
.columns(['link_id', 'remote_id'])
.where('remote_id', 'is not', null)
.doUpdateSet({
state: (eb) => eb.ref('excluded.state'),
error_code: (eb) => eb.ref('excluded.error_code'),
file_id: (eb) => eb.fn.coalesce(eb.ref('excluded.file_id'), eb.ref('document_sync_items.file_id')),
remote_version: (eb) =>
eb.fn.coalesce(eb.ref('excluded.remote_version'), eb.ref('document_sync_items.remote_version')),
content_sha256: (eb) =>
eb.fn.coalesce(eb.ref('excluded.content_sha256'), eb.ref('document_sync_items.content_sha256')),
pushed_sha256: (eb) =>
eb.fn.coalesce(eb.ref('excluded.pushed_sha256'), eb.ref('document_sync_items.pushed_sha256')),
last_seen_at: () => currentTimestampKysely(platform),
}),
)
.compile();
// Pinned for the task report — the exact ON CONFLICT clause Kysely
// renders for this table, proving the partial-index predicate is
// restated verbatim (SQLite's own requirement, DS24's own doc
// comment) and the DO UPDATE SET matches the legacy statement's own
// five re-written columns plus the two verbatim-from-excluded ones.
expect(compiled.sql).toContain(
'on conflict ("link_id", "remote_id") where "remote_id" is not null do update set',
);
expect(compiled.sql).toContain('"state" = "excluded"."state"');
expect(compiled.sql).toContain('"error_code" = "excluded"."error_code"');
expect(compiled.sql).toContain('"file_id" = coalesce("excluded"."file_id", "document_sync_items"."file_id")');
expect(compiled.sql).toContain(
'"remote_version" = coalesce("excluded"."remote_version", "document_sync_items"."remote_version")',
);
expect(compiled.sql).toContain(
'"content_sha256" = coalesce("excluded"."content_sha256", "document_sync_items"."content_sha256")',
);
expect(compiled.sql).toContain(
'"pushed_sha256" = coalesce("excluded"."pushed_sha256", "document_sync_items"."pushed_sha256")',
);
expect(compiled.sql).toContain('"last_seen_at" = CURRENT_TIMESTAMP');
// Pinned in full, for the task report:
expect(compiled.sql).toBe(
'insert into "document_sync_items" ("link_id", "trip_id", "file_id", "trek_doc_uid", "remote_id", "remote_name", "remote_version", "remote_size", "remote_modified_at", "content_sha256", "pushed_sha256", "state", "error_code", "attempts", "next_attempt_at", "synced_at", "last_seen_at") values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) on conflict ("link_id", "remote_id") where "remote_id" is not null do update set "state" = "excluded"."state", "error_code" = "excluded"."error_code", "file_id" = coalesce("excluded"."file_id", "document_sync_items"."file_id"), "remote_version" = coalesce("excluded"."remote_version", "document_sync_items"."remote_version"), "content_sha256" = coalesce("excluded"."content_sha256", "document_sync_items"."content_sha256"), "pushed_sha256" = coalesce("excluded"."pushed_sha256", "document_sync_items"."pushed_sha256"), "last_seen_at" = CURRENT_TIMESTAMP',
);
});
/**
* R3's own required mutation test: insert two rows differing only in
* `remote_id` under the same `link_id` (both succeed — the partial
* index only constrains non-NULL `remote_id`s against each other), then
* a THIRD insert colliding on `(link_id, remote_id)` with one of them —
* proving the partial index still enforces "at most one non-NULL
* remote_id per link" post-conversion by upserting (not duplicating).
*/
it('DS24REPO-002 (R3 mutation proof): a colliding (link_id, remote_id) pair upserts in place rather than duplicating', async () => {
const { linkId, trip } = await fixture();
await repo.insertOrUpsertOnConflict(
insertData(linkId, trip.id, { remote_id: 'r1', trek_doc_uid: 'uid-a', state: 'synced', remote_version: 'v1' }),
);
await repo.insertOrUpsertOnConflict(
insertData(linkId, trip.id, { remote_id: 'r2', trek_doc_uid: 'uid-b', state: 'synced', remote_version: 'v1' }),
);
const afterTwo = await findRows(t, DocumentSyncItems, { link: linkId }, { id: 'asc' });
expect(afterTwo).toHaveLength(2);
const r1Id = afterTwo.find((r) => r.remote_id === 'r1')!.id;
// The colliding insert: same link_id + remote_id='r1' as the first row.
await repo.insertOrUpsertOnConflict(
insertData(linkId, trip.id, {
remote_id: 'r1',
trek_doc_uid: 'uid-c',
state: 'conflict',
remote_version: 'v2',
}),
);
const afterThree = await findRows(t, DocumentSyncItems, { link: linkId }, { id: 'asc' });
// Still exactly two rows — the third insert upserted onto the first, not a third row.
expect(afterThree).toHaveLength(2);
const upserted = afterThree.find((r) => r.id === r1Id)!;
expect(upserted.remote_id).toBe('r1');
expect(upserted.state).toBe('conflict');
expect(upserted.remote_version).toBe('v2');
});
it('DS24REPO-003: two rows with NULL remote_id under the same link never collide (the partial index only constrains non-NULL)', async () => {
const { linkId, trip } = await fixture();
await repo.insertOrUpsertOnConflict(insertData(linkId, trip.id, { remote_id: null, trek_doc_uid: 'uid-x' }));
await repo.insertOrUpsertOnConflict(insertData(linkId, trip.id, { remote_id: null, trek_doc_uid: 'uid-y' }));
const rows = await findRows(t, DocumentSyncItems, { link: linkId });
expect(rows).toHaveLength(2);
});
});
describe('recordAttempt (DS23, R3 — the plain conditional update, itemId≠null)', () => {
async function seedRow(linkId: number, tripId: number) {
const id = await repo
.insertOrUpsertOnConflict(
insertData(linkId, tripId, {
remote_id: 'r1',
file_id: null,
remote_name: 'a.pdf',
remote_version: 'v1',
remote_size: 512,
remote_modified_at: '2026-09-01T08:00:00Z',
content_sha256: 'old-hash',
pushed_sha256: 'old-pushed',
}),
)
.then(async () => (await findRow(t, DocumentSyncItems, { link: linkId, remote_id: 'r1' }))!.id);
return id;
}
/**
* R3's full-key parity test: all ten `COALESCE` columns win with a
* non-null new value (branch 1) — matching the legacy `COALESCE(?,
* col)` — and each falls back to the EXISTING column when the new
* value is null (branch 2), the same statement's other half. Both
* branches proved on the SAME row, sequentially, so branch 2 is
* genuinely proving "kept", not merely "never changed".
*/
it('DS23REPO-001 (R3 parity): a non-null new value overwrites every COALESCE column; a null one keeps the existing value', async () => {
const { linkId, trip } = await fixture();
const itemId = await seedRow(linkId, trip.id);
const newFileId = await insertRow(t, TripFiles, {
trip: trip.id,
filename: 'stored.pdf',
original_name: 'b.pdf',
});
// Branch 1: every COALESCE column gets a genuinely new, non-null value.
await repo.recordAttempt(itemId, {
state: 'synced',
error_code: null,
file_id: newFileId,
remote_id: 'r1-new',
remote_version: 'v2',
remote_name: 'b.pdf',
remote_size: 2048,
remote_modified_at: '2026-09-18T10:00:00Z',
content_sha256: 'new-hash',
pushed_sha256: 'new-pushed',
attempts: 0,
next_attempt_after_seconds: null,
});
let row = await itemRow(itemId);
expect(row).toMatchObject({
file_id: newFileId,
remote_id: 'r1-new',
remote_version: 'v2',
remote_name: 'b.pdf',
remote_size: 2048,
remote_modified_at: '2026-09-18T10:00:00Z',
content_sha256: 'new-hash',
pushed_sha256: 'new-pushed',
});
// Branch 2: every COALESCE column arrives null — the existing (branch-1) value survives untouched.
await repo.recordAttempt(itemId, {
state: 'synced',
error_code: null,
file_id: null,
remote_id: null,
remote_version: null,
remote_name: null,
remote_size: null,
remote_modified_at: null,
content_sha256: null,
pushed_sha256: null,
attempts: 0,
next_attempt_after_seconds: null,
});
row = await itemRow(itemId);
expect(row).toMatchObject({
file_id: newFileId,
remote_id: 'r1-new',
remote_version: 'v2',
remote_name: 'b.pdf',
remote_size: 2048,
remote_modified_at: '2026-09-18T10:00:00Z',
content_sha256: 'new-hash',
pushed_sha256: 'new-pushed',
});
});
it('DS23REPO-002: next_attempt_after_seconds shifts the DB clock forward by the given second count; null leaves it NULL', async () => {
const { linkId, trip } = await fixture();
const itemId = await seedRow(linkId, trip.id);
await repo.recordAttempt(itemId, {
state: 'error',
error_code: 'timeout',
file_id: null,
remote_id: null,
remote_version: null,
remote_name: null,
remote_size: null,
remote_modified_at: null,
content_sha256: null,
pushed_sha256: null,
attempts: 1,
next_attempt_after_seconds: 300,
});
const nextAttemptAt = (await itemRow(itemId)).next_attempt_at;
const expected = Date.now() + 300_000;
expect(nextAttemptAt).not.toBeNull();
expect(Math.abs(new Date(`${nextAttemptAt!.replace(' ', 'T')}Z`).getTime() - expected)).toBeLessThan(5000);
await repo.recordAttempt(itemId, {
state: 'synced',
error_code: null,
file_id: null,
remote_id: null,
remote_version: null,
remote_name: null,
remote_size: null,
remote_modified_at: null,
content_sha256: null,
pushed_sha256: null,
attempts: 0,
next_attempt_after_seconds: null,
});
const cleared = await itemRow(itemId);
expect(cleared.next_attempt_at).toBeNull();
});
it('DS23REPO-003: synced_at is stamped only when state is synced, and left alone otherwise', async () => {
const { linkId, trip } = await fixture();
const itemId = await seedRow(linkId, trip.id);
await updateRows(t, DocumentSyncItems, { id: itemId }, { synced_at: '2020-01-01 00:00:00' });
await repo.recordAttempt(itemId, {
state: 'error',
error_code: 'timeout',
file_id: null,
remote_id: null,
remote_version: null,
remote_name: null,
remote_size: null,
remote_modified_at: null,
content_sha256: null,
pushed_sha256: null,
attempts: 1,
next_attempt_after_seconds: null,
});
expect((await itemRow(itemId)).synced_at).toBe('2020-01-01 00:00:00');
await repo.recordAttempt(itemId, {
state: 'synced',
error_code: null,
file_id: null,
remote_id: null,
remote_version: null,
remote_name: null,
remote_size: null,
remote_modified_at: null,
content_sha256: null,
pushed_sha256: null,
attempts: 0,
next_attempt_after_seconds: null,
});
expect((await itemRow(itemId)).synced_at).not.toBe('2020-01-01 00:00:00');
});
});
});
@@ -0,0 +1,98 @@
/**
* FerrataTilesRepository: the cells of the via ferrata grid that
* FerratasService keeps between restarts, read by key and written as a batch.
*/
import { FerrataTiles } from '../../../../src/db/entities/FerrataTiles.entity';
import type { FerrataTilesRepository } from '../../../../src/db/repositories/FerrataTiles.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { findRow, findRows, insertRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let tiles: FerrataTilesRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
tiles = t.repo(FerrataTiles);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const empty = '{"ferratas":[],"truncated":false}';
describe('FerrataTilesRepository.findByKeys', () => {
it('FERTILEREPO-001: answers the stored cells among the keys and leaves the others out', async () => {
await insertRows(t, FerrataTiles, [
{ tile_key: '942,224', payload: empty, fetched_at: 100 },
{ tile_key: '942,225', payload: '{"ferratas":[],"truncated":true}', fetched_at: 200 },
{ tile_key: '950,230', payload: empty, fetched_at: 300 },
]);
const rows = await tiles.findByKeys(['942,224', '942,225', '943,224']);
expect(rows.sort((a, b) => a.tile_key.localeCompare(b.tile_key))).toEqual([
{ tile_key: '942,224', payload: empty, fetched_at: 100 },
{ tile_key: '942,225', payload: '{"ferratas":[],"truncated":true}', fetched_at: 200 },
]);
});
it('FERTILEREPO-002: no keys asks for nothing', async () => {
await insertRows(t, FerrataTiles, [{ tile_key: '942,224', payload: empty, fetched_at: 100 }]);
expect(await tiles.findByKeys([])).toEqual([]);
});
it('FERTILEREPO-003: a cell on the other side of the globe keeps its negative key', async () => {
await insertRows(t, FerrataTiles, [{ tile_key: '-1800,-3600', payload: empty, fetched_at: 5 }]);
expect(await tiles.findByKeys(['-1800,-3600'])).toEqual([
{ tile_key: '-1800,-3600', payload: empty, fetched_at: 5 },
]);
});
});
describe('FerrataTilesRepository.upsertTiles', () => {
it('FERTILEREPO-004: writes a row per new cell', async () => {
await tiles.upsertTiles([
{ tile_key: '942,224', payload: empty, fetched_at: 100 },
{ tile_key: '942,225', payload: empty, fetched_at: 100 },
]);
const rows = await findRows(t, FerrataTiles, {}, { tile_key: 'asc' });
expect(rows).toEqual([
{ tile_key: '942,224', payload: empty, fetched_at: 100 },
{ tile_key: '942,225', payload: empty, fetched_at: 100 },
]);
});
it('FERTILEREPO-005: a cell stored before gets the new payload and fetch time, still as one row', async () => {
await insertRows(t, FerrataTiles, [{ tile_key: '942,224', payload: empty, fetched_at: 100 }]);
const refreshed = '{"ferratas":[],"truncated":true}';
await tiles.upsertTiles([
{ tile_key: '942,224', payload: refreshed, fetched_at: 900 },
{ tile_key: '942,225', payload: empty, fetched_at: 900 },
]);
expect(await findRows(t, FerrataTiles, { tile_key: '942,224' })).toHaveLength(1);
expect(await findRow(t, FerrataTiles, { tile_key: '942,224' })).toEqual({
tile_key: '942,224',
payload: refreshed,
fetched_at: 900,
});
expect(await findRow(t, FerrataTiles, { tile_key: '942,225' })).toMatchObject({ fetched_at: 900 });
});
it('FERTILEREPO-006: an empty batch writes nothing', async () => {
await tiles.upsertTiles([]);
expect(await findRows(t, FerrataTiles)).toEqual([]);
});
});
@@ -0,0 +1,166 @@
/**
* GooglePlacePhotoMetaRepository (Plan 3c Task 1, PP1–PP5/PP7/PP8): every
* statement `PlacePhotoCacheService` used to issue raw, on real rows.
* `place_id` is a TEXT key — pseudo-ids like `coords:lat:lng` are legal
* values, exercised below alongside real Google place ids.
*/
import { GooglePlacePhotoMeta } from '../../../../src/db/entities/GooglePlacePhotoMeta.entity';
import type { GooglePlacePhotoMetaRepository } from '../../../../src/db/repositories/GooglePlacePhotoMeta.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { countRows, findRow, insertRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let meta: GooglePlacePhotoMetaRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
meta = t.repo(GooglePlacePhotoMeta);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function storedRow(placeId: string) {
return findRow(t, GooglePlacePhotoMeta, { place_id: placeId });
}
function seedMeta(placeId: string, attribution: string | null, fetchedAt: number, errorAt: number | null) {
return insertRow(t, GooglePlacePhotoMeta, {
place_id: placeId,
attribution,
fetched_at: fetchedAt,
error_at: errorAt,
});
}
describe('GooglePlacePhotoMetaRepository.findLive / findErrored', () => {
it('GPPMREPO-001: findLive returns the attribution only when error_at is NULL', async () => {
await seedMeta('p1', 'Some Author', 1000, null);
expect(await meta.findLive('p1')).toEqual({ attribution: 'Some Author' });
});
it('GPPMREPO-002: findLive returns null when error_at is set, even with an attribution present', async () => {
await seedMeta('p1', null, 1000, 2000);
expect(await meta.findLive('p1')).toBeNull();
});
it('GPPMREPO-003: findLive returns null for a missing row', async () => {
expect(await meta.findLive('missing')).toBeNull();
});
it('GPPMREPO-004: works with coords:lat:lng pseudo-ids (TEXT key, colons and dots included)', async () => {
const pseudoId = 'coords:48.8566:2.3522';
await seedMeta(pseudoId, null, 1000, null);
expect(await meta.findLive(pseudoId)).toEqual({ attribution: null });
});
it('GPPMREPO-005: findErrored returns {error_at} only when error_at IS NOT NULL', async () => {
await seedMeta('p1', null, 1000, 5000);
expect(await meta.findErrored('p1')).toEqual({ error_at: 5000 });
});
it('GPPMREPO-006: findErrored returns null when error_at is NULL', async () => {
await seedMeta('p1', 'A', 1000, null);
expect(await meta.findErrored('p1')).toBeNull();
});
});
describe('GooglePlacePhotoMetaRepository.deleteByPlaceId', () => {
it('GPPMREPO-007: deletes the row for the given place_id', async () => {
await seedMeta('p1', null, 1000, null);
await meta.deleteByPlaceId('p1');
expect(await storedRow('p1')).toBeNull();
});
it('GPPMREPO-008: deleting a missing place_id does not throw', async () => {
await expect(meta.deleteByPlaceId('never-existed')).resolves.toBeUndefined();
});
});
describe('GooglePlacePhotoMetaRepository.upsertError / upsertPhoto — INSERT OR REPLACE parity', () => {
it('GPPMREPO-009: upsertError writes NULL attribution and matching fetched_at/error_at on a fresh row', async () => {
await meta.upsertError('p1', 12345);
expect(await storedRow('p1')).toMatchObject({
place_id: 'p1',
attribution: null,
fetched_at: 12345,
error_at: 12345,
});
});
it('GPPMREPO-010: upsertPhoto writes the attribution with a NULL error_at on a fresh row', async () => {
await meta.upsertPhoto('p1', 'Some Author · CC BY 2.0', 999);
expect(await storedRow('p1')).toMatchObject({
place_id: 'p1',
attribution: 'Some Author · CC BY 2.0',
fetched_at: 999,
error_at: null,
});
});
// PP4 forces attribution NULL; PP5 forces error_at NULL — same PK, mirror
// images. Writes PE3-style twice then a third time, asserting the exact
// row after each (Task 1 brief's explicit test requirement).
it('GPPMREPO-011: put then markError then put again — each call overwrites the row exactly (INSERT OR REPLACE semantics via em.upsert merge)', async () => {
await meta.upsertPhoto('p1', 'Author A', 100);
expect(await storedRow('p1')).toMatchObject({ attribution: 'Author A', fetched_at: 100, error_at: null });
await meta.upsertError('p1', 200);
expect(await storedRow('p1')).toMatchObject({ attribution: null, fetched_at: 200, error_at: 200 });
await meta.upsertPhoto('p1', 'Author B', 300);
expect(await storedRow('p1')).toMatchObject({ attribution: 'Author B', fetched_at: 300, error_at: null });
// Only one row exists for this PK throughout — no duplicate insert.
expect(await countRows(t, GooglePlacePhotoMeta, { place_id: 'p1' })).toBe(1);
});
});
describe('GooglePlacePhotoMetaRepository.listPlaceIds', () => {
it('GPPMREPO-012: lists every place_id, full table scan', async () => {
await insertRow(t, GooglePlacePhotoMeta, { place_id: 'p1', fetched_at: 1 });
await insertRow(t, GooglePlacePhotoMeta, { place_id: 'p2', fetched_at: 2 });
expect((await meta.listPlaceIds()).sort()).toEqual(['p1', 'p2']);
});
it('GPPMREPO-013: an empty table yields an empty array', async () => {
expect(await meta.listPlaceIds()).toEqual([]);
});
});
// Task 9 fix wave (B-M3): relabelled. `findLive`/`findErrored` are
// `findOne`-based, but their filter is `{ place_id, error_at: null }` /
// `{ place_id, error_at: { $ne: null } }` — the PK plus a second condition,
// not a PK-only lookup, so rule 20's D-shape guarantee does not apply (a
// non-PK-only `findOne` always re-runs its WHERE against the live table).
describe('GooglePlacePhotoMetaRepository — fresh after a raw UPDATE', () => {
it('GPPMREPO-014 (fresh after a raw UPDATE, not D-shape): a raw write after an unrelated identity-map read is visible in the next findLive call, in one query (disableIdentityMap regression)', async () => {
await seedMeta('p1', 'Old', 1000, null);
// The FIRST, wider setup read passes `disableIdentityMap: false`
// explicitly and carries the column the later write targets
// (`attribution`) — a PK-only `findOne` on `place_id` alone (not
// `findLive`'s own `error_at IS NULL`-narrowed filter under test).
await t.repo(GooglePlacePhotoMeta).findOne({ place_id: 'p1' }, { disableIdentityMap: false });
// test-sql-allow: the out-of-band write this case is about has to bypass every EntityManager, the one under test included.
testDb.prepare('UPDATE google_place_photo_meta SET attribution = ? WHERE place_id = ?').run('New', 'p1');
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
try {
expect(await meta.findLive('p1')).toEqual({ attribution: 'New' });
expect(spy.mock.calls.length).toBe(1);
} finally {
spy.mockRestore();
}
});
});
@@ -0,0 +1,53 @@
/**
* `HiddenRegionsRepository.listForUser` — Plan 4 Task 8b-2 item 3 (3f L6
* carry): AT22 (`getHiddenRegions`) had no repository-level
* `toEqual(<legacy raw>)` parity test.
*/
import { HiddenRegions } from '../../../../src/db/entities/HiddenRegions.entity';
import type { HiddenRegionsRepository } from '../../../../src/db/repositories/HiddenRegions.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser } from '../../../helpers/factories';
import { insertRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: HiddenRegionsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(HiddenRegions);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('HiddenRegionsRepository.listForUser (AT22)', () => {
it('HIDDENREGREPO-001: matches SELECT region_code FROM hidden_regions WHERE user_id = ? run raw, scoped to the user', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb, { username: 'other' });
await insertRow(t, HiddenRegions, { user: user.id, region_code: 'DE-BY', country_code: 'DE' });
await insertRow(t, HiddenRegions, { user: user.id, region_code: 'DE-BE', country_code: 'DE' });
await insertRow(t, HiddenRegions, { user: other.id, region_code: 'FR-IDF', country_code: 'FR' });
// test-sql-allow: the legacy AT22 statement is the parity oracle the repository is compared against.
const legacy = testDb.prepare('SELECT region_code FROM hidden_regions WHERE user_id = ?').all(user.id);
const codes = await repo.listForUser(user.id);
expect(codes).toEqual(legacy.map((r) => (r as { region_code: string }).region_code));
expect(codes.sort()).toEqual(['DE-BE', 'DE-BY']);
});
it('HIDDENREGREPO-002: empty array for a user with nothing hidden', async () => {
const { user } = createUser(testDb);
expect(await repo.listForUser(user.id)).toEqual([]);
});
});
@@ -0,0 +1,177 @@
import { IdempotencyKeys } from '../../../../src/db/entities/IdempotencyKeys.entity';
import type { IdempotencyKeysRepository } from '../../../../src/db/repositories/IdempotencyKeys.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser } from '../../../helpers/factories';
import { countRows, findRow, findRows, insertRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
function seedKey(
key: string,
userId: number,
method: string,
path: string,
statusCode: number,
responseBody: string,
createdAt?: number,
) {
return insertRow(t, IdempotencyKeys, {
key,
user: userId,
method,
path,
status_code: statusCode,
response_body: responseBody,
...(createdAt !== undefined ? { created_at: createdAt } : {}),
});
}
const testDb = createSnapshotTestDb();
let t: TestOrm;
let idempotencyKeys: IdempotencyKeysRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
idempotencyKeys = t.repo(IdempotencyKeys);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('IdempotencyKeysRepository.findResponse (Plan 4 Task 1)', () => {
it('IDEMPREPO-001: returns status_code/response_body only, scoped by the full (key, user, method, path) composite key', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb, { username: 'other' });
await seedKey('k', user.id, 'POST', '/api/categories', 201, '{"id":1}');
expect(await idempotencyKeys.findResponse('k', user.id, 'POST', '/api/categories')).toEqual({
status_code: 201,
response_body: '{"id":1}',
});
// Same key, different user — a different row entirely, not this one.
expect(await idempotencyKeys.findResponse('k', other.id, 'POST', '/api/categories')).toBeNull();
// Same key/user, different method or path — must not cross-match.
expect(await idempotencyKeys.findResponse('k', user.id, 'PUT', '/api/categories')).toBeNull();
expect(await idempotencyKeys.findResponse('k', user.id, 'POST', '/api/tags')).toBeNull();
});
it('IDEMPREPO-002: null when no row matches at all', async () => {
const { user } = createUser(testDb);
expect(await idempotencyKeys.findResponse('missing', user.id, 'POST', '/x')).toBeNull();
});
});
describe('IdempotencyKeysRepository.insertIfAbsent (Plan 4 Task 1)', () => {
it('IDEMPREPO-003: inserts every bound column, including the caller-supplied created_at', async () => {
const { user } = createUser(testDb);
await idempotencyKeys.insertIfAbsent({
key: 'k',
user_id: user.id,
method: 'POST',
path: '/api/places',
status_code: 201,
response_body: '{"ok":true}',
created_at: 1_700_000_000,
});
const stored = (await findRow(t, IdempotencyKeys, { key: 'k' }))!;
const row = {
key: stored.key,
user_id: stored.user_id,
method: stored.method,
path: stored.path,
status_code: stored.status_code,
response_body: stored.response_body,
created_at: stored.created_at,
};
expect(row).toEqual({
key: 'k',
user_id: user.id,
method: 'POST',
path: '/api/places',
status_code: 201,
response_body: '{"ok":true}',
created_at: 1_700_000_000,
});
});
it('IDEMPREPO-004: a second insert on the SAME (key, user, method, path) is ignored — the first write wins (INSERT OR IGNORE parity)', async () => {
const { user } = createUser(testDb);
await idempotencyKeys.insertIfAbsent({
key: 'k',
user_id: user.id,
method: 'POST',
path: '/api/places',
status_code: 201,
response_body: '{"first":true}',
created_at: 1_700_000_000,
});
await idempotencyKeys.insertIfAbsent({
key: 'k',
user_id: user.id,
method: 'POST',
path: '/api/places',
status_code: 500,
response_body: '{"second":true}',
created_at: 1_800_000_000,
});
expect(await idempotencyKeys.findResponse('k', user.id, 'POST', '/api/places')).toEqual({
status_code: 201,
response_body: '{"first":true}',
});
expect(await countRows(t, IdempotencyKeys)).toBe(1);
});
it('IDEMPREPO-005: the SAME key for a DIFFERENT user is a separate row, not a conflict', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb, { username: 'b' });
await idempotencyKeys.insertIfAbsent({
key: 'k',
user_id: a.id,
method: 'POST',
path: '/x',
status_code: 200,
response_body: '{}',
created_at: 1,
});
await idempotencyKeys.insertIfAbsent({
key: 'k',
user_id: b.id,
method: 'POST',
path: '/x',
status_code: 200,
response_body: '{}',
created_at: 2,
});
expect(await countRows(t, IdempotencyKeys)).toBe(2);
});
});
describe('IdempotencyKeysRepository.deleteExpired (Plan 4 Task 1)', () => {
it('IDEMPREPO-006: deletes rows strictly older than the cutoff, returns the row count, leaves the rest', async () => {
const { user } = createUser(testDb);
await seedKey('old', user.id, 'POST', '/x', 200, '{}', 100);
await seedKey('boundary', user.id, 'POST', '/y', 200, '{}', 200);
await seedKey('fresh', user.id, 'POST', '/z', 200, '{}', 300);
const removed = await idempotencyKeys.deleteExpired(200);
expect(removed).toBe(1);
const keys = (await findRows(t, IdempotencyKeys, {}, { key: 'asc' })).map((r) => r.key);
expect(keys).toEqual(['boundary', 'fresh']);
});
it('IDEMPREPO-007: zero rows removed when nothing is old enough', async () => {
const { user } = createUser(testDb);
await seedKey('fresh', user.id, 'POST', '/z', 200, '{}', 1000);
expect(await idempotencyKeys.deleteExpired(500)).toBe(0);
});
});
@@ -0,0 +1,252 @@
import { InviteTokens } from '../../../../src/db/entities/InviteTokens.entity';
import type { InviteTokensRepository } from '../../../../src/db/repositories/InviteTokens.repository';
import { withRequestContext } from '../../../../src/nest/database/request-context';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createInviteToken, createTrip, createUser } from '../../../helpers/factories';
import { updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let invites: InviteTokensRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
invites = t.repo(InviteTokens);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function rawInvite(id: number): unknown {
// test-sql-allow: the raw full row is the parity oracle the repository's reads are compared against.
return testDb.prepare('SELECT * FROM invite_tokens WHERE id = ?').get(id);
}
/**
* Spies on the ORM connection to capture the raw generated SQL of the one
* query `fn` runs, the same idiom `Categories.repository.test.ts`'s
* `withQueryCount` uses for a call-count assertion — here for the query
* text itself, since `listWithCreatorAndTrip`/`findWithCreatorAndTrip` run
* with `mapResults: false` and return driver rows, not a QueryBuilder a
* test could inspect directly (Plan 3b Task 3 review, F4).
*/
async function captureSql<T>(fn: () => Promise<T>): Promise<{ value: T; sql: string }> {
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
try {
const value = await fn();
const call = spy.mock.calls.find((c) => typeof c[0] === 'string' && c[0].includes('invite_tokens'));
return { value, sql: (call?.[0] as string | undefined) ?? '' };
} finally {
spy.mockRestore();
}
}
describe('InviteTokensRepository', () => {
describe('findByToken', () => {
it('INVREPO-001: a row read through findByToken is the SELECT * row, key for key', async () => {
const created = createInviteToken(testDb, { token: 'find-me' });
const row = await invites.findByToken('find-me');
expect(row).toStrictEqual(rawInvite(created.id));
});
it('INVREPO-002: an unknown token is null', async () => {
expect(await invites.findByToken('does-not-exist')).toBeNull();
});
});
describe('insertInvite', () => {
it('INVREPO-003: inserts and returns exactly the row the legacy re-select would return', async () => {
const { user } = createUser(testDb);
const row = await invites.insertInvite({
token: 'insert-me',
max_uses: 3,
expires_at: null,
created_by: user.id,
});
expect(row).toStrictEqual(rawInvite(row.id));
expect(row.token).toBe('insert-me');
expect(row.max_uses).toBe(3);
expect(row.used_count).toBe(0);
expect(row.created_by).toBe(user.id);
expect(row.trip_id).toBeNull();
expect(typeof row.created_at).toBe('string');
});
it('INVREPO-004: trip_id is written when given (per-trip invite)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const row = await invites.insertInvite({
token: 'trip-bound',
max_uses: 1,
expires_at: null,
created_by: user.id,
trip_id: trip.id,
});
expect(row.trip_id).toBe(trip.id);
});
});
describe('incrementUsedCount', () => {
it('INVREPO-005: under capacity — increments and returns the updated row', async () => {
const created = createInviteToken(testDb, { token: 'under-cap', max_uses: 3 });
const row = await invites.incrementUsedCount('under-cap');
expect(row).not.toBeNull();
expect(row?.used_count).toBe(1);
expect(row).toStrictEqual(rawInvite(created.id));
});
it('INVREPO-006: at capacity — no row matches, returns null, used_count unchanged', async () => {
const created = createInviteToken(testDb, { token: 'at-cap', max_uses: 1 });
await updateRows(t, InviteTokens, { id: created.id }, { used_count: 1 });
const row = await invites.incrementUsedCount('at-cap');
expect(row).toBeNull();
expect((rawInvite(created.id) as { used_count: number }).used_count).toBe(1);
});
it('INVREPO-007: max_uses = 0 means unlimited — always increments', async () => {
createInviteToken(testDb, { token: 'unlimited', max_uses: 0 });
await updateRows(t, InviteTokens, { token: 'unlimited' }, { used_count: 500 });
const row = await invites.incrementUsedCount('unlimited');
expect(row?.used_count).toBe(501);
});
it('INVREPO-008: an unknown token returns null', async () => {
expect(await invites.incrementUsedCount('nonexistent-token')).toBeNull();
});
it('INVREPO-009: two concurrent increments on a one-use invite — exactly one wins (D6 single-connection race safety)', async () => {
const created = createInviteToken(testDb, { token: 'race-me', max_uses: 1 });
const [a, b] = await Promise.all([invites.incrementUsedCount('race-me'), invites.incrementUsedCount('race-me')]);
const results = [a, b];
const winners = results.filter((r) => r !== null);
const losers = results.filter((r) => r === null);
expect(winners).toHaveLength(1);
expect(losers).toHaveLength(1);
expect(winners[0]?.used_count).toBe(1);
expect((rawInvite(created.id) as { used_count: number }).used_count).toBe(1);
});
});
// RI1/RI5 — the admin invite list's joined projection.
describe('listWithCreatorAndTrip / findWithCreatorAndTrip', () => {
it("INVREPO-010: projects the creator's username and a bound trip's title, newest first", async () => {
const { user: admin } = createUser(testDb, { username: 'inviter-1' });
const trip = createTrip(testDb, admin.id, { title: 'Bound Trip' });
const older = createInviteToken(testDb, { token: 'older', created_by: admin.id });
await updateRows(t, InviteTokens, { id: older.id }, { created_at: '2026-01-01 00:00:00' });
const newer = createInviteToken(testDb, { token: 'newer', created_by: admin.id });
await updateRows(t, InviteTokens, { id: newer.id }, { created_at: '2026-02-01 00:00:00', trip: trip.id });
const rows = await invites.listWithCreatorAndTrip();
expect(rows.map((r) => r.token)).toEqual(['newer', 'older']); // ORDER BY created_at DESC
expect(rows[0]).toMatchObject({
token: 'newer',
created_by_name: 'inviter-1',
trip_title: 'Bound Trip',
trip_id: trip.id,
});
expect(rows[1]).toMatchObject({ token: 'older', created_by_name: 'inviter-1', trip_title: null, trip_id: null });
});
it('INVREPO-011: findWithCreatorAndTrip filters the same projection to one id', async () => {
const { user: admin } = createUser(testDb, { username: 'inviter-2' });
const invite = createInviteToken(testDb, { token: 'single', created_by: admin.id });
const row = await invites.findWithCreatorAndTrip(invite.id);
expect(row).toMatchObject({ id: invite.id, token: 'single', created_by_name: 'inviter-2', trip_title: null });
});
it('INVREPO-012: findWithCreatorAndTrip is null for an unknown id', async () => {
expect(await invites.findWithCreatorAndTrip(999_999)).toBeNull();
});
it("INVREPO-015: the generated SQL joins users with an INNER JOIN and trips with a LEFT JOIN — pins RI1's join TYPE (Plan 3b Task 3 review, F4; a `leftJoin` rewrite of the users join must fail this)", async () => {
const { user: admin } = createUser(testDb, { username: 'join-type-check' });
createInviteToken(testDb, { token: 'join-type-check', created_by: admin.id });
const { sql } = await captureSql(() => invites.listWithCreatorAndTrip());
expect(sql).toMatch(/inner join `?users`?/i);
expect(sql).toMatch(/left join `?trips`?/i);
expect(sql).not.toMatch(/left join `?users`?/i);
});
it("INVREPO-016: findWithCreatorAndTrip's generated SQL joins users with an INNER JOIN and trips with a LEFT JOIN — pins RI5's join TYPE (task-3-rereview.md R2; a `leftJoin` rewrite of the users join must fail this)", async () => {
const { user: admin } = createUser(testDb, { username: 'join-type-check-single' });
const invite = createInviteToken(testDb, { token: 'join-type-check-single', created_by: admin.id });
const { sql } = await captureSql(() => invites.findWithCreatorAndTrip(invite.id));
expect(sql).toMatch(/inner join `?users`?/i);
expect(sql).toMatch(/left join `?trips`?/i);
expect(sql).not.toMatch(/left join `?users`?/i);
});
});
// RI6/RI7 — deleteInvite's 404 check and the delete itself.
describe('findIdById / deleteById', () => {
it('INVREPO-013: findIdById returns the id for a known row, null otherwise', async () => {
const invite = createInviteToken(testDb, { token: 'exists' });
expect(await invites.findIdById(invite.id)).toBe(invite.id);
expect(await invites.findIdById(999_999)).toBeNull();
});
it('INVREPO-014: deleteById removes exactly that row', async () => {
const keep = createInviteToken(testDb, { token: 'keep' });
const gone = createInviteToken(testDb, { token: 'gone' });
await invites.deleteById(gone.id);
expect(rawInvite(gone.id)).toBeUndefined();
expect(rawInvite(keep.id)).toBeDefined();
});
});
// Task 7 review, M2: InviteTokensRepository had no D-shape identity-map
// test at all, although `findByToken`/`insertInvite`'s own docstrings
// both cite the disableIdentityMap-not-refresh ruling. The shape: wide
// findByToken (carries used_count) first, narrow findIdById (`fields:
// ['id']`, no used_count) second, then a nativeUpdate-equivalent write
// (incrementUsedCount, via the QueryBuilder) inside uow.transactional —
// this repository is a Plan-3b-created one on a public, unauthenticated
// route (GET /api/auth/invite/:token) that also runs inside
// registerUser's transaction.
describe('identity-map isolation (D-shape, program RULING)', () => {
it('INVREPO-017: incrementUsedCount inside uow.transactional is not discarded by a stale entity read earlier under a different projection', async () => {
const { user: admin } = createUser(testDb, { username: 'invrepo-017-admin' });
const invite = createInviteToken(testDb, { token: 'invrepo-017', max_uses: 5, created_by: admin.id });
const uow = new UnitOfWork(t.em);
await withRequestContext(t.orm, async () => {
// Projection A — wide, full row, carries used_count.
const before = await invites.findByToken('invrepo-017');
expect(before!.used_count).toBe(0);
// Projection B — narrow, `fields: ['id']`, no used_count.
await invites.findIdById(invite.id);
await uow.transactional(async () => {
await invites.incrementUsedCount('invrepo-017');
});
});
// A column only the wide read carried (`max_uses`) must be unchanged,
// and the write itself must have stuck.
const after = await invites.findByToken('invrepo-017');
expect(after!.used_count).toBe(1);
expect(after!.max_uses).toBe(5);
expect((rawInvite(invite.id) as { used_count: number }).used_count).toBe(1);
});
});
});
@@ -0,0 +1,78 @@
/**
* `JourneyBookRevisionsRepository` (JBREV-*): a revision is the book as it
* stood at a version, read back only for its own journey; pruning keeps a
* journey's newest revisions and leaves another journey's alone; a revision
* goes with its journey.
*/
import { JourneyBookRevisions } from '../../../../src/db/entities/JourneyBookRevisions.entity';
import { Journeys } from '../../../../src/db/entities/Journeys.entity';
import type { JourneyBookRevisionsRepository } from '../../../../src/db/repositories/JourneyBookRevisions.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeJourney } from '../../../helpers/factories/journeys';
import { countRows, deleteRows } from '../../../helpers/factories/rows';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let revisions: JourneyBookRevisionsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
revisions = t.repo(JourneyBookRevisions);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('JourneyBookRevisionsRepository', () => {
it('JBREV-001: a revision reads back as kept, for its own journey only', async () => {
const { user } = await makeUser(t);
const journey = await makeJourney(t, user.id);
const other = await makeJourney(t, user.id);
const id = await revisions.insertRevision(journey.id, 4, '{"title":"Lisbon"}');
const kept = await revisions.findForJourney(id, journey.id);
expect(kept).toMatchObject({ id, journey_id: journey.id, version: 4, document: '{"title":"Lisbon"}' });
expect(kept?.created_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
expect(await revisions.findForJourney(id, other.id)).toBeUndefined();
expect(await revisions.findForJourney(id + 100, journey.id)).toBeUndefined();
});
it("JBREV-002: pruning keeps the journey's newest revisions and leaves another journey's alone", async () => {
const { user } = await makeUser(t);
const journey = await makeJourney(t, user.id);
const other = await makeJourney(t, user.id);
// One after another, so the ids follow the versions.
const ids = await [1, 2, 3, 4, 5, 6, 7].reduce<Promise<number[]>>(
async (kept, version) => [...(await kept), await revisions.insertRevision(journey.id, version, '{}')],
Promise.resolve([]),
);
const elsewhere = await revisions.insertRevision(other.id, 1, '{}');
expect(await revisions.pruneRevisions(journey.id, 5)).toBe(2);
expect(await revisions.findForJourney(ids[0] ?? 0, journey.id)).toBeUndefined();
expect(await revisions.findForJourney(ids[1] ?? 0, journey.id)).toBeUndefined();
expect((await revisions.findForJourney(ids[2] ?? 0, journey.id))?.version).toBe(3);
expect(await revisions.findForJourney(elsewhere, other.id)).toBeDefined();
expect(await revisions.pruneRevisions(journey.id, 5)).toBe(0);
});
it('JBREV-003: a revision goes with its journey', async () => {
const { user } = await makeUser(t);
const journey = await makeJourney(t, user.id);
await revisions.insertRevision(journey.id, 1, '{}');
await deleteRows(t, Journeys, { id: journey.id });
expect(await countRows(t, JourneyBookRevisions)).toBe(0);
});
});
@@ -0,0 +1,175 @@
/**
* `JourneyEntryStaysRepository` (JRN-02): the stays an entry was taken over
* from, written together, read back as the ledger of one person's stays in
* one journey with the entry holding each, unique per journey, source, person
* and visit, gone with their entry and kept past the account they came from.
*/
import { JourneyEntries } from '../../../../src/db/entities/JourneyEntries.entity';
import { JourneyEntryStays } from '../../../../src/db/entities/JourneyEntryStays.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type {
JourneyEntryStaysRepository,
JourneyEntryStayWrite,
} from '../../../../src/db/repositories/JourneyEntryStays.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeJourney } from '../../../helpers/factories/journeys';
import { countRows, deleteRows, findRows, insertRow } from '../../../helpers/factories/rows';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let stays: JourneyEntryStaysRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
stays = t.repo(JourneyEntryStays);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function journeyWithEntry(title = 'Venice') {
const { user } = await makeUser(t, { username: 'marta' });
const journey = await makeJourney(t, user.id);
const entryId = await entry(journey.id, user.id, title);
return { user, journey, entryId };
}
function entry(journeyId: number, authorId: number, title: string) {
return insertRow(t, JourneyEntries, {
journey: journeyId,
author: authorId,
type: 'entry',
title,
entry_date: '2026-05-14',
created_at: 0,
updated_at: 0,
});
}
function stay(
journeyId: number,
entryId: number,
userId: number,
overrides: Partial<JourneyEntryStayWrite> = {},
): JourneyEntryStayWrite {
return {
journey_id: journeyId,
entry_id: entryId,
source: 'dawarich',
source_visit_id: '101',
name: 'Piazza San Marco',
lat: 45.434,
lng: 12.3388,
started_at: '2026-05-14T09:10:00+02:00',
ended_at: '2026-05-14T10:05:00+02:00',
duration_minutes: 55,
sort_order: 0,
user_id: userId,
...overrides,
};
}
describe('JourneyEntryStaysRepository', () => {
it('JESTAYS-001: writes the stays of an entry together and reads which of them the journey holds', async () => {
const { user, journey, entryId } = await journeyWithEntry('Morning in San Marco');
await stays.insertStays([
stay(journey.id, entryId, user.id),
stay(journey.id, entryId, user.id, { source_visit_id: '102', name: 'Rialto', sort_order: 1 }),
]);
const held = await stays.listHeld(journey.id, user.id, 'dawarich', ['101', '102', '103']);
expect(held).toHaveLength(2);
expect(held).toEqual(
expect.arrayContaining([
{ source_visit_id: '101', entry_id: entryId, entry_title: 'Morning in San Marco' },
{ source_visit_id: '102', entry_id: entryId, entry_title: 'Morning in San Marco' },
]),
);
expect(await findRows(t, JourneyEntryStays, { entry: entryId })).toHaveLength(2);
});
it('JESTAYS-002: the ledger is per person, journey and source, and an empty ask reads nothing', async () => {
const { user, journey, entryId } = await journeyWithEntry();
const { user: editor } = await makeUser(t);
const other = await makeJourney(t, user.id);
await stays.insertStays([stay(journey.id, entryId, user.id)]);
expect(await stays.listHeld(journey.id, editor.id, 'dawarich', ['101'])).toEqual([]);
expect(await stays.listHeld(other.id, user.id, 'dawarich', ['101'])).toEqual([]);
expect(await stays.listHeld(journey.id, user.id, 'other', ['101'])).toEqual([]);
expect(await stays.listHeld(journey.id, user.id, 'dawarich', [])).toEqual([]);
await stays.insertStays([]);
expect(await countRows(t, JourneyEntryStays, {})).toBe(1);
});
it('JESTAYS-003: the same stay of the same person lands in a journey once; another person may hold the same visit id', async () => {
const { user, journey, entryId } = await journeyWithEntry();
const { user: editor } = await makeUser(t);
await stays.insertStays([stay(journey.id, entryId, user.id)]);
await expect(stays.insertStays([stay(journey.id, entryId, user.id)])).rejects.toThrow();
await stays.insertStays([stay(journey.id, entryId, editor.id)]);
expect(await countRows(t, JourneyEntryStays, {})).toBe(2);
});
it('JESTAYS-004: the stays go with their entry and outlive the account they came from', async () => {
const { user, journey, entryId } = await journeyWithEntry();
const { user: editor } = await makeUser(t);
const second = await entry(journey.id, user.id, 'Afternoon');
await stays.insertStays([
stay(journey.id, entryId, editor.id),
stay(journey.id, second, user.id, { source_visit_id: '200' }),
]);
await deleteRows(t, Users, { id: editor.id });
expect(await countRows(t, JourneyEntryStays, { entry: entryId, user: null })).toBe(1);
await deleteRows(t, JourneyEntries, { id: second });
expect(await countRows(t, JourneyEntryStays, {})).toBe(1);
});
it('JESTAYS-005: the map reads the located stays of a journey by entry, in the order they were lived', async () => {
const { user, journey, entryId } = await journeyWithEntry();
const second = await entry(journey.id, user.id, 'Afternoon');
const other = await makeJourney(t, user.id);
await stays.insertStays([
stay(journey.id, second, user.id, { source_visit_id: '300', name: 'Giudecca' }),
stay(journey.id, entryId, user.id, { source_visit_id: '102', name: 'Rialto', sort_order: 1 }),
stay(journey.id, entryId, user.id, { source_visit_id: '101', name: 'San Marco', sort_order: 0 }),
stay(journey.id, entryId, user.id, {
source_visit_id: '103',
name: 'Nowhere',
lat: null,
lng: null,
sort_order: 2,
}),
]);
await stays.insertStays([stay(other.id, entryId, user.id, { source_visit_id: '400' })]);
const located = await stays.listLocatedForJourney(journey.id);
expect(located.map((s) => [s.entry_id, s.name])).toEqual([
[entryId, 'San Marco'],
[entryId, 'Rialto'],
[second, 'Giudecca'],
]);
expect(located[0]).toEqual({
id: expect.any(Number),
entry_id: entryId,
name: 'San Marco',
lat: 45.434,
lng: 12.3388,
started_at: '2026-05-14T09:10:00+02:00',
ended_at: '2026-05-14T10:05:00+02:00',
});
});
});
@@ -0,0 +1,168 @@
/**
* `JourneyRecordedDaysRepository` (JRN-01): a day a journey keeps written
* whole, read back with the name of whose recording it is, one version per
* journey, day and source with a second write replacing the first in place,
* removed on its own, gone with its journey and kept past its importer.
*/
import { JourneyRecordedDays } from '../../../../src/db/entities/JourneyRecordedDays.entity';
import { Journeys } from '../../../../src/db/entities/Journeys.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type {
JourneyRecordedDaysRepository,
JourneyRecordedDayWrite,
} from '../../../../src/db/repositories/JourneyRecordedDays.repository';
import { dbNow } from '../../../../src/db/types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeJourney } from '../../../helpers/factories/journeys';
import { countRows, deleteRows, updateRows } from '../../../helpers/factories/rows';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let days: JourneyRecordedDaysRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
days = t.repo(JourneyRecordedDays);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function journey() {
const { user } = await makeUser(t, { username: 'marta' });
const j = await makeJourney(t, user.id);
return { user, journey: j };
}
function day(journeyId: number, importedBy: number | null, overrides: Partial<JourneyRecordedDayWrite> = {}) {
return {
journey_id: journeyId,
local_date: '2026-05-14',
source: 'dawarich',
source_kind: 'tracks',
utc_offset_minutes: 120,
window_from: '2026-05-13T22:00:00.000Z',
window_to: '2026-05-14T22:00:00.000Z',
segments: '[{"points":[[45.43,12.33],[45.44,12.34]],"mode":"walking"}]',
point_count: 2,
distance_m: 1300,
content_hash: 'a'.repeat(64),
truncated: 0,
fetched_at: '2026-05-15T08:00:00.000Z',
imported_by: importedBy,
...overrides,
} satisfies JourneyRecordedDayWrite;
}
describe('JourneyRecordedDaysRepository', () => {
it('JRDAYS-001: keeps a day whole and reads it back with the name of whose recording it is', async () => {
const { user, journey: j } = await journey();
const id = await days.upsertDay(day(j.id, user.id));
const row = await days.findDay(j.id, '2026-05-14', 'dawarich');
expect(row).toMatchObject({
id,
journey_id: j.id,
local_date: '2026-05-14',
source_kind: 'tracks',
utc_offset_minutes: 120,
window_from: '2026-05-13T22:00:00.000Z',
point_count: 2,
distance_m: 1300,
truncated: 0,
imported_by: user.id,
imported_by_username: 'marta',
});
expect(row?.created_at).toEqual(expect.any(String));
expect(await days.findDay(j.id, '2026-05-15', 'dawarich')).toBeUndefined();
});
it('JRDAYS-002: a second write of the same day replaces the first in place, keeping its id', async () => {
const { user, journey: j } = await journey();
const first = await days.upsertDay(day(j.id, user.id));
const second = await days.upsertDay(
day(j.id, user.id, { content_hash: 'b'.repeat(64), point_count: 40, source_kind: 'points', distance_m: null }),
);
expect(second).toBe(first);
expect(await countRows(t, JourneyRecordedDays, {})).toBe(1);
expect(await days.findDay(j.id, '2026-05-14', 'dawarich')).toMatchObject({
content_hash: 'b'.repeat(64),
point_count: 40,
source_kind: 'points',
distance_m: null,
});
});
it('JRDAYS-007: a write that keeps only while none is kept leaves the version there first and says so', async () => {
const { user, journey: j } = await journey();
const first = await days.insertDayIfAbsent(day(j.id, user.id));
expect(first).toEqual(expect.any(Number));
expect(await days.insertDayIfAbsent(day(j.id, user.id, { content_hash: 'b'.repeat(64) }))).toBeUndefined();
expect(await countRows(t, JourneyRecordedDays, {})).toBe(1);
expect(await days.findDay(j.id, '2026-05-14', 'dawarich')).toMatchObject({
id: first,
content_hash: 'a'.repeat(64),
});
});
it('JRDAYS-003: lists the days of one journey earliest first, and only its own', async () => {
const { user, journey: j } = await journey();
const other = await makeJourney(t, user.id);
await days.upsertDay(day(j.id, user.id, { local_date: '2026-05-16' }));
await days.upsertDay(day(j.id, user.id, { local_date: '2026-05-14' }));
await days.upsertDay(day(other.id, user.id, { local_date: '2026-05-15' }));
expect((await days.listForJourney(j.id)).map((row) => row.local_date)).toEqual(['2026-05-14', '2026-05-16']);
expect(await days.listForJourney(9999)).toEqual([]);
});
it('JRDAYS-004: removes one day and says whether there was one', async () => {
const { user, journey: j } = await journey();
await days.upsertDay(day(j.id, user.id));
await days.upsertDay(day(j.id, user.id, { local_date: '2026-05-15' }));
expect(await days.deleteDay(j.id, '2026-05-14', 'dawarich')).toBe(true);
expect(await days.deleteDay(j.id, '2026-05-14', 'dawarich')).toBe(false);
expect((await days.listForJourney(j.id)).map((row) => row.local_date)).toEqual(['2026-05-15']);
});
it('JRDAYS-005: a day goes with its journey and outlives the account that took it over', async () => {
const { journey: j } = await journey();
const { user: editor } = await makeUser(t);
await days.upsertDay(day(j.id, editor.id));
await deleteRows(t, Users, { id: editor.id });
expect(await days.findDay(j.id, '2026-05-14', 'dawarich')).toMatchObject({
imported_by: null,
imported_by_username: null,
});
await deleteRows(t, Journeys, { id: j.id });
expect(await countRows(t, JourneyRecordedDays, {})).toBe(0);
});
it('JRDAYS-006: a replacing write stamps the time it was kept again', async () => {
const { user, journey: j } = await journey();
await days.upsertDay(day(j.id, user.id));
const longAgo = dbNow(new Date('2020-01-01T00:00:00Z'));
await updateRows(t, JourneyRecordedDays, { journey: j.id }, { created_at: longAgo, updated_at: longAgo });
await days.upsertDay(day(j.id, user.id, { content_hash: 'c'.repeat(64) }));
const row = await days.findDay(j.id, '2026-05-14', 'dawarich');
expect(row?.created_at).toBe(longAgo);
expect(row?.updated_at).not.toBe(longAgo);
});
});
@@ -0,0 +1,129 @@
/**
* `JourneyRecordingPrepRepository` (JRN-03): the linked trips of the journeys
* a person prepares, only while the journey asks for it and the person may
* edit it, within the sync's reach; and the status row of one journey and
* person, where a success clears an earlier failure and a failure keeps the
* last success.
*/
import { JourneyRecordingPrep } from '../../../../src/db/entities/JourneyRecordingPrep.entity';
import { Journeys } from '../../../../src/db/entities/Journeys.entity';
import type { JourneyRecordingPrepRepository } from '../../../../src/db/repositories/JourneyRecordingPrep.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { addJourneyContributor, linkTripToJourney, makeJourney } from '../../../helpers/factories/journeys';
import { countRows, deleteRows, updateRows } from '../../../helpers/factories/rows';
import { makeTrip, type TripOverrides } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let prep: JourneyRecordingPrepRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
prep = t.repo(JourneyRecordingPrep);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const REACH = { endedAfter: '2025-09-01', startedBy: '2026-10-22' };
async function preparedJourney() {
const { user: owner } = await makeUser(t);
const journey = await makeJourney(t, owner.id, { auto_prepare_recordings: 1 });
const trip = await makeTrip(t, owner.id, { start_date: '2026-05-12', end_date: '2026-05-18' });
await linkTripToJourney(t, journey.id, trip.id);
return { owner, journey, trip };
}
describe('JourneyRecordingPrepRepository.listPreparedTrips', () => {
it('JRNPREP-REPO-001: lists the linked trips of a prepared journey for its owner and its editors, not its readers', async () => {
const { owner, journey, trip } = await preparedJourney();
const { user: editor } = await makeUser(t);
const { user: viewer } = await makeUser(t);
await addJourneyContributor(t, journey.id, editor.id, 'editor');
await addJourneyContributor(t, journey.id, viewer.id, 'viewer');
const row = { journey_id: journey.id, trip_id: trip.id, start_date: '2026-05-12', end_date: '2026-05-18' };
expect(await prep.listPreparedTrips(owner.id, REACH)).toEqual([row]);
expect(await prep.listPreparedTrips(editor.id, REACH)).toEqual([row]);
expect(await prep.listPreparedTrips(viewer.id, REACH)).toEqual([]);
});
it('JRNPREP-REPO-002: a journey with the switch off, and an undated, archived or out-of-reach trip, give nothing', async () => {
const { owner, journey } = await preparedJourney();
const link = async (overrides: TripOverrides) =>
linkTripToJourney(t, journey.id, (await makeTrip(t, owner.id, overrides)).id);
await link({ start_date: null, end_date: null });
await link({ start_date: '2026-06-01', end_date: '2026-06-05', is_archived: 1 });
await link({ start_date: '2024-05-01', end_date: '2024-05-10' });
await link({ start_date: '2026-12-01', end_date: '2026-12-10' });
await link({ start_date: '2026-10-01', end_date: null });
expect((await prep.listPreparedTrips(owner.id, REACH)).map((row) => row.start_date)).toEqual([
'2026-05-12',
'2026-10-01',
]);
await updateRows(t, Journeys, { id: journey.id }, { auto_prepare_recordings: 0 });
expect(await prep.listPreparedTrips(owner.id, REACH)).toEqual([]);
});
});
describe('JourneyRecordingPrepRepository status', () => {
it('JRNPREP-REPO-003: reads nothing before the first run, then one row per journey and person', async () => {
const { owner, journey } = await preparedJourney();
expect(await prep.findStatus(journey.id, owner.id)).toBeUndefined();
await prep.recordAttempt(journey.id, owner.id, '2026-05-14T08:00:00.000Z', null);
await prep.recordAttempt(journey.id, owner.id, '2026-05-14T09:00:00.000Z', null);
expect(await prep.findStatus(journey.id, owner.id)).toEqual({
last_attempt_at: '2026-05-14T09:00:00.000Z',
last_success_at: '2026-05-14T09:00:00.000Z',
last_error: null,
});
expect(await countRows(t, JourneyRecordingPrep, {})).toBe(1);
});
it('JRNPREP-REPO-004: a failure keeps the last success, the next success clears the failure', async () => {
const { owner, journey } = await preparedJourney();
await prep.recordAttempt(journey.id, owner.id, '2026-05-14T08:00:00.000Z', null);
await prep.recordAttempt(journey.id, owner.id, '2026-05-14T09:00:00.000Z', 'unreachable');
expect(await prep.findStatus(journey.id, owner.id)).toEqual({
last_attempt_at: '2026-05-14T09:00:00.000Z',
last_success_at: '2026-05-14T08:00:00.000Z',
last_error: 'unreachable',
});
await prep.recordAttempt(journey.id, owner.id, '2026-05-14T10:00:00.000Z', null);
expect(await prep.findStatus(journey.id, owner.id)).toMatchObject({
last_success_at: '2026-05-14T10:00:00.000Z',
last_error: null,
});
});
it('JRNPREP-REPO-005: a first run that fails has no success yet, and the row goes with its journey', async () => {
const { owner, journey } = await preparedJourney();
await prep.recordAttempt(journey.id, owner.id, '2026-05-14T08:00:00.000Z', 'unauthorized');
expect(await prep.findStatus(journey.id, owner.id)).toEqual({
last_attempt_at: '2026-05-14T08:00:00.000Z',
last_success_at: null,
last_error: 'unauthorized',
});
await deleteRows(t, Journeys, { id: journey.id });
expect(await countRows(t, JourneyRecordingPrep, {})).toBe(0);
});
});
@@ -0,0 +1,105 @@
/**
* `JourneyTripsRepository`'s journey map reads (JRN-04): the located places
* the linked trips plan on a day, one row per day, and the places of those
* trips that carry a route, both through `journey_trips` so a trip nobody
* has written about counts too.
*/
import { JourneyTrips } from '../../../../src/db/entities/JourneyTrips.entity';
import type { JourneyTripsRepository } from '../../../../src/db/repositories/JourneyTrips.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeDayAssignment } from '../../../helpers/factories/itinerary';
import { linkTripToJourney, makeJourney } from '../../../helpers/factories/journeys';
import { makeCategory, makePlace } from '../../../helpers/factories/places';
import { makeTrip, readTripDays } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: JourneyTripsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(JourneyTrips);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function linkedTrip() {
const { user } = await makeUser(t);
const journey = await makeJourney(t, user.id);
const trip = await makeTrip(t, user.id, { title: 'Venice', start_date: '2026-05-14', end_date: '2026-05-15' });
await linkTripToJourney(t, journey.id, trip.id);
const [first, second] = await readTripDays(t, trip.id);
if (!first || !second) throw new Error('the trip has no two days');
return { user, journey, trip, first, second };
}
describe('JourneyTripsRepository map reads', () => {
it('JTRIPMAP-001: one row per planned day of a located place, the assignment time before the place time', async () => {
const { user, journey, trip, first, second } = await linkedTrip();
const category = await makeCategory(t, { color: '#e11d48', icon: 'landmark' });
const square = await makePlace(t, trip.id, { name: 'San Marco', lat: 45.434, lng: 12.3388, category: category.id });
const bridge = await makePlace(t, trip.id, {
name: 'Rialto',
lat: 45.438,
lng: 12.336,
place_time: '16:00',
category: null,
});
const nowhere = await makePlace(t, trip.id, { name: 'Nowhere', lat: null, lng: null });
await makePlace(t, trip.id, { name: 'Wishlist', lat: 45.43, lng: 12.33 });
await makeDayAssignment(t, first.id, square.id, { assignment_time: '10:00' });
await makeDayAssignment(t, second.id, bridge.id);
await makeDayAssignment(t, second.id, square.id);
await makeDayAssignment(t, first.id, nowhere.id);
const unlinked = await makeTrip(t, user.id, { start_date: '2026-05-14', end_date: '2026-05-14' });
const [unlinkedDay] = await readTripDays(t, unlinked.id);
if (!unlinkedDay) throw new Error('the trip has no day');
await makeDayAssignment(t, unlinkedDay.id, (await makePlace(t, unlinked.id, { name: 'Elsewhere' })).id);
const rows = await repo.listMapPlacesForJourney(journey.id);
expect(rows).toEqual([
{
place_id: square.id,
trip_id: trip.id,
trip_title: 'Venice',
name: 'San Marco',
lat: 45.434,
lng: 12.3388,
day_date: '2026-05-14',
time: '10:00',
category_color: '#e11d48',
category_icon: 'landmark',
},
expect.objectContaining({ place_id: bridge.id, day_date: '2026-05-15', time: '16:00', category_color: null }),
expect.objectContaining({ place_id: square.id, day_date: '2026-05-15', time: null }),
]);
});
it('JTRIPMAP-002: the routes of the linked trips, with or without an entry, and nothing of other trips', async () => {
const { user, journey, trip } = await linkedTrip();
const route = JSON.stringify([
[45.43, 12.33],
[45.44, 12.34],
]);
const ridge = await makePlace(t, trip.id, { name: 'Ridge', route_geometry: route, route_color: '#aa0000' });
await makePlace(t, trip.id, { name: 'No route' });
const other = await makeTrip(t, user.id);
await makePlace(t, other.id, { name: 'Other', route_geometry: route });
expect(await repo.listRouteSourcesForJourney(journey.id)).toEqual([
{ place_id: ridge.id, trip_id: trip.id, name: 'Ridge', route_color: '#aa0000', route_geometry: route },
]);
});
});
@@ -0,0 +1,95 @@
import { MaintenanceRepository } from '../../../../src/db/repositories/MaintenanceRepository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import Database from 'better-sqlite3';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let maintenance: MaintenanceRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
maintenance = new MaintenanceRepository(t.em);
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('MaintenanceRepository', () => {
it('MAINTREPO-001: walCheckpoint renders PRAGMA wal_checkpoint(TRUNCATE) — pinned text, equivalent to the legacy raw call', async () => {
// Rendered-SQL-equivalence: the exact text a direct statement on the
// handle executes without throwing, string-for-string what the legacy
// `db.exec('PRAGMA wal_checkpoint(TRUNCATE)')` issued.
const RENDERED = 'PRAGMA wal_checkpoint(TRUNCATE)';
// test-sql-allow: the pragma text itself is under test, run as the raw statement it renders to.
expect(() => testDb.prepare(RENDERED).run()).not.toThrow();
await expect(maintenance.walCheckpoint()).resolves.toBeUndefined();
});
describe('vacuumInto', () => {
let scratchPath: string;
afterEach(() => {
if (scratchPath && fs.existsSync(scratchPath)) fs.rmSync(scratchPath, { force: true });
});
it("MAINTREPO-002: vacuumInto renders `VACUUM INTO '<path>'` — pinned text, produces a readable snapshot at the given path", async () => {
scratchPath = path.join(os.tmpdir(), `maintrepo-vacuum-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
await maintenance.vacuumInto(scratchPath);
expect(fs.existsSync(scratchPath)).toBe(true);
const snap = new Database(scratchPath, { readonly: true });
try {
// test-sql-allow: a snapshot file no ORM is bound to, read through sqlite_master.
const row = snap.prepare('SELECT name FROM sqlite_master WHERE type = ? AND name = ?').get('table', 'users');
expect(row).toBeTruthy();
} finally {
snap.close();
}
});
it('MAINTREPO-003: single quotes in the path are escaped by doubling, matching the legacy `dbSnap.replaceAll("\'", "\'\'")` shape', async () => {
const dirWithQuote = path.join(os.tmpdir(), `maintrepo-o'brien-${Date.now()}`);
fs.mkdirSync(dirWithQuote, { recursive: true });
scratchPath = path.join(dirWithQuote, 'snap.db');
try {
await maintenance.vacuumInto(scratchPath);
expect(fs.existsSync(scratchPath)).toBe(true);
// Rendered-SQL-equivalence: the SAME escaped text, run directly
// against another target path, succeeds identically.
const directPath = path.join(dirWithQuote, 'snap-direct.db');
const escaped = directPath.replaceAll("'", "''");
// test-sql-allow: the VACUUM INTO text itself is under test, run as the raw statement it renders to.
expect(() => testDb.prepare(`VACUUM INTO '${escaped}'`).run()).not.toThrow();
expect(fs.existsSync(directPath)).toBe(true);
fs.rmSync(directPath, { force: true });
} finally {
fs.rmSync(dirWithQuote, { recursive: true, force: true });
}
});
});
it('MAINTREPO-004: both methods throw outside a request context (fail-closed, matching TrekRepository)', async () => {
const { MikroORM } = await import('@mikro-orm/core');
const fresh = await MikroORM.init({
entities: [],
driver: (await import('../../../../src/db/orm-driver')).createBoundSqliteDriver(() => testDb),
dbName: ':memory:',
allowGlobalContext: false,
discovery: { warnWhenNoEntities: false },
});
try {
const unwrapped = new MaintenanceRepository(fresh.em);
await expect(unwrapped.walCheckpoint()).rejects.toThrow();
} finally {
await fresh.close(false);
}
});
});
@@ -0,0 +1,535 @@
import { McpTokens } from '../../../../src/db/entities/McpTokens.entity';
import type { McpTokensRepository } from '../../../../src/db/repositories/McpTokens.repository';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createMcpToken, createUser } from '../../../helpers/factories';
import { countRows, findRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { createHash } from 'crypto';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let tokens: McpTokensRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
tokens = t.repo(McpTokens);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
/** The stored row, read past the shared identity map; undefined when it is gone. */
async function storedToken(id: number) {
return (await findRow(t, McpTokens, { id })) ?? undefined;
}
describe('McpTokensRepository', () => {
describe('listByUserAndKind', () => {
it('MCPTOKREPO-001: scoped to user + kind, ordered by created_at DESC, exact column set', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const older = createMcpToken(testDb, user.id, { name: 'older', kind: 'mcp' });
await updateRows(t, McpTokens, { id: older.id }, { created_at: '2020-01-01 00:00:00' });
const newer = createMcpToken(testDb, user.id, { name: 'newer', kind: 'mcp' });
await updateRows(t, McpTokens, { id: newer.id }, { created_at: '2020-01-02 00:00:00' });
createMcpToken(testDb, user.id, { name: 'an api key', kind: 'api' });
createMcpToken(testDb, other.id, { name: 'not mine', kind: 'mcp' });
const rows = await tokens.listByUserAndKind(user.id, 'mcp');
expect(rows.map((r) => r.name)).toEqual(['newer', 'older']);
expect(Object.keys(rows[0]).sort()).toEqual(
['api_scopes', 'created_at', 'id', 'last_used_at', 'name', 'scope_mode', 'token_prefix'].sort(),
);
});
it('MCPTOKREPO-002: no tokens for the kind returns an empty array', async () => {
const { user } = createUser(testDb);
expect(await tokens.listByUserAndKind(user.id, 'api')).toEqual([]);
});
it('MCPTOKREPO-002b: created_at NULL comes back null, not undefined (coverage: rule 16)', async () => {
const { user } = createUser(testDb);
const token = createMcpToken(testDb, user.id, { name: 'null-created', kind: 'mcp' });
await updateRows(t, McpTokens, { id: token.id }, { created_at: null });
const [row] = await tokens.listByUserAndKind(user.id, 'mcp');
expect(row.created_at).toBeNull();
});
});
describe('countByUserAndKind', () => {
it('MCPTOKREPO-003: counts only the matching user + kind', async () => {
const { user } = createUser(testDb);
createMcpToken(testDb, user.id, { kind: 'mcp' });
createMcpToken(testDb, user.id, { kind: 'mcp' });
createMcpToken(testDb, user.id, { kind: 'api' });
expect(await tokens.countByUserAndKind(user.id, 'mcp')).toBe(2);
expect(await tokens.countByUserAndKind(user.id, 'api')).toBe(1);
});
});
describe('insertToken', () => {
it('MCPTOKREPO-004: inserts the row a legacy re-select would return, and returns only the generated id (Plan 3b Task 2 review, F4)', async () => {
const { user } = createUser(testDb);
const inserted = await tokens.insertToken({
user_id: user.id,
name: 'My Token',
token_hash: 'hash-value',
token_prefix: 'trek_abc123',
kind: 'mcp',
scope_mode: 'all',
api_scopes: null,
});
// Only `{ id }` comes back — no full-row re-select is folded into
// insertToken itself, so it cannot leak `token_hash` (or anything
// else) to a caller that only asked to mint a row. `findBasic` (TK4)
// stays the one place a caller reads the row back.
expect(Object.keys(inserted)).toEqual(['id']);
const row = (await storedToken(inserted.id)) as Record<string, unknown>;
expect(row.user_id).toBe(user.id);
expect(row.name).toBe('My Token');
expect(row.token_hash).toBe('hash-value');
expect(row.kind).toBe('mcp');
expect(row.scope_mode).toBe('all');
expect(row.api_scopes).toBeNull();
expect(row.last_used_at).toBeNull();
expect(typeof row.created_at).toBe('string');
});
it('MCPTOKREPO-005: api_scopes is written when narrowed', async () => {
const { user } = createUser(testDb);
const inserted = await tokens.insertToken({
user_id: user.id,
name: 'Narrowed',
token_hash: 'hash-2',
token_prefix: 'trek_def456',
kind: 'api',
scope_mode: 'limited',
api_scopes: '["stats","trips"]',
});
const row = (await storedToken(inserted.id)) as { scope_mode: string; api_scopes: string };
expect(row.scope_mode).toBe('limited');
expect(row.api_scopes).toBe('["stats","trips"]');
});
it('MCPTOKREPO-024: the mint path (insertToken + findBasic) issues exactly two statements and never selects token_hash (Plan 3b Task 2 review, F4)', async () => {
const { user } = createUser(testDb);
const statements: string[] = [];
const original = testDb.prepare.bind(testDb);
const spy = vi.spyOn(testDb, 'prepare').mockImplementation((sql: string) => {
statements.push(sql);
return original(sql);
});
let insertedId: number;
try {
const inserted = await tokens.insertToken({
user_id: user.id,
name: 'Statement Count',
token_hash: 'hash-count',
token_prefix: 'trek_countpr',
kind: 'mcp',
scope_mode: 'all',
api_scopes: null,
});
insertedId = inserted.id;
await tokens.findBasic(insertedId);
} finally {
spy.mockRestore();
}
expect(statements).toHaveLength(2);
expect(statements[0].toLowerCase()).toContain('insert into');
expect(statements[1].toLowerCase()).toContain('select');
// The INSERT necessarily names `token_hash` as a column to write; the
// point is that no SELECT on the mint path reads it back into memory —
// the discarded middle re-select an earlier version issued did.
const selects = statements.filter((sql) => sql.trim().toLowerCase().startsWith('select'));
for (const sql of selects) expect(sql.toLowerCase()).not.toContain('token_hash');
});
});
describe('findBasic', () => {
it('MCPTOKREPO-006: returns the TK4/TK9 union column set by id', async () => {
const { user } = createUser(testDb);
const created = createMcpToken(testDb, user.id, { name: 'lookup-me' });
const row = await tokens.findBasic(created.id);
expect(row).toEqual({
id: created.id,
user_id: user.id,
name: 'lookup-me',
token_prefix: expect.any(String),
created_at: expect.any(String),
last_used_at: null,
});
});
it('MCPTOKREPO-007: an unknown id is null', async () => {
expect(await tokens.findBasic(999999)).toBeNull();
});
it('MCPTOKREPO-007c: created_at NULL comes back null, not undefined (coverage: rule 16)', async () => {
const { user } = createUser(testDb);
const created = createMcpToken(testDb, user.id, { name: 'null-created-basic' });
await updateRows(t, McpTokens, { id: created.id }, { created_at: null });
const row = await tokens.findBasic(created.id);
expect(row?.created_at).toBeNull();
});
it('MCPTOKREPO-007b: identity-map regression — sees a raw UPDATE on the same id in the same request', async () => {
const { user } = createUser(testDb);
const created = createMcpToken(testDb, user.id, { name: 'before' });
await tokens.findBasic(created.id); // populate identity map
await updateRows(t, McpTokens, { id: created.id }, { name: 'after' });
const row = await tokens.findBasic(created.id);
expect(row?.name).toBe('after');
});
});
describe('findOwnedByKind', () => {
it('MCPTOKREPO-008: matches on id + user + kind', async () => {
const { user } = createUser(testDb);
const created = createMcpToken(testDb, user.id, { kind: 'mcp' });
expect(await tokens.findOwnedByKind(created.id, user.id, 'mcp')).toEqual({ id: created.id });
});
it('MCPTOKREPO-009: a different owner is null (ownership scoping)', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const created = createMcpToken(testDb, user.id, { kind: 'mcp' });
expect(await tokens.findOwnedByKind(created.id, other.id, 'mcp')).toBeNull();
});
it('MCPTOKREPO-010: the wrong kind is null (kind scoping)', async () => {
const { user } = createUser(testDb);
const created = createMcpToken(testDb, user.id, { kind: 'mcp' });
expect(await tokens.findOwnedByKind(created.id, user.id, 'api')).toBeNull();
});
});
describe('deleteById', () => {
it('MCPTOKREPO-011: deletes the row', async () => {
const { user } = createUser(testDb);
const created = createMcpToken(testDb, user.id);
await tokens.deleteById(created.id);
expect(await storedToken(created.id)).toBeUndefined();
});
});
describe('listAllWithUsername', () => {
it('MCPTOKREPO-012: spans users, carries the owner username, ordered by created_at DESC', async () => {
const { user: ada } = createUser(testDb, { username: 'ada' });
const { user: bob } = createUser(testDb, { username: 'bob' });
const first = createMcpToken(testDb, ada.id, { name: 'first' });
await updateRows(t, McpTokens, { id: first.id }, { created_at: '2020-01-01 00:00:00' });
const second = createMcpToken(testDb, bob.id, { name: 'second' });
await updateRows(t, McpTokens, { id: second.id }, { created_at: '2020-06-01 00:00:00' });
const rows = await tokens.listAllWithUsername();
expect(rows.map((r) => r.name)).toEqual(['second', 'first']);
expect(rows.find((r) => r.name === 'first')).toEqual({
id: first.id,
name: 'first',
token_prefix: expect.any(String),
created_at: '2020-01-01 00:00:00',
last_used_at: null,
user_id: ada.id,
username: 'ada',
});
expect(rows.find((r) => r.name === 'second')?.username).toBe('bob');
});
it('MCPTOKREPO-012b: no token_hash leaks through the projection', async () => {
const { user } = createUser(testDb);
createMcpToken(testDb, user.id);
const rows = await tokens.listAllWithUsername();
expect(rows.every((r) => !('token_hash' in r))).toBe(true);
});
it('MCPTOKREPO-012c: created_at NULL comes back null, not undefined (coverage: rule 16)', async () => {
const { user } = createUser(testDb, { username: 'null-created-user' });
const created = createMcpToken(testDb, user.id, { name: 'null-created-list' });
await updateRows(t, McpTokens, { id: created.id }, { created_at: null });
const rows = await tokens.listAllWithUsername();
expect(rows.find((r) => r.id === created.id)?.created_at).toBeNull();
});
});
describe('findGrantByHash', () => {
it('MCPTOKREPO-013: an API-kind token resolves the user + grant columns', async () => {
const { user } = createUser(testDb, { username: 'grant-user' });
createMcpToken(testDb, user.id, {
kind: 'api',
rawToken: 'trek_grant_raw',
scope_mode: 'limited',
api_scopes: '["stats"]',
});
const hash = createHash('sha256').update('trek_grant_raw').digest('hex');
const row = await tokens.findGrantByHash(hash);
expect(row).toEqual({
id: user.id,
username: 'grant-user',
email: user.email,
role: user.role,
scope_mode: 'limited',
api_scopes: '["stats"]',
});
});
it('MCPTOKREPO-014: the same hash under kind=mcp does not resolve — kind is in the WHERE', async () => {
const { user } = createUser(testDb);
createMcpToken(testDb, user.id, { kind: 'mcp', rawToken: 'trek_mcp_raw' });
const hash = createHash('sha256').update('trek_mcp_raw').digest('hex');
expect(await tokens.findGrantByHash(hash)).toBeNull();
});
it('MCPTOKREPO-015: an unknown hash is null', async () => {
expect(await tokens.findGrantByHash('does-not-exist')).toBeNull();
});
});
describe('findUserByHashAndKind', () => {
it('MCPTOKREPO-016: a matching hash + kind resolves the user identity columns', async () => {
const { user } = createUser(testDb, { username: 'verify-user' });
createMcpToken(testDb, user.id, { kind: 'mcp', rawToken: 'trek_verify_raw' });
const hash = createHash('sha256').update('trek_verify_raw').digest('hex');
const row = await tokens.findUserByHashAndKind(hash, 'mcp');
expect(row).toEqual({ id: user.id, username: 'verify-user', email: user.email, role: user.role });
});
it('MCPTOKREPO-017: a real token of the wrong kind is indistinguishable from a missing one', async () => {
const { user } = createUser(testDb);
createMcpToken(testDb, user.id, { kind: 'api', rawToken: 'trek_wrong_kind' });
const hash = createHash('sha256').update('trek_wrong_kind').digest('hex');
expect(await tokens.findUserByHashAndKind(hash, 'mcp')).toBeNull();
expect(await tokens.findUserByHashAndKind('completely-unknown-hash', 'mcp')).toBeNull();
});
it('MCPTOKREPO-018: an unknown hash is null', async () => {
expect(await tokens.findUserByHashAndKind('nope', 'api')).toBeNull();
});
it('MCPTOKREPO-025: kind is genuinely inside the generated WHERE clause, not a post-filter on the result (Plan 3b Task 2 review, F6)', async () => {
const { user } = createUser(testDb);
createMcpToken(testDb, user.id, { kind: 'mcp', rawToken: 'trek_sql_shape' });
const hash = createHash('sha256').update('trek_sql_shape').digest('hex');
const statements: string[] = [];
const original = testDb.prepare.bind(testDb);
const spy = vi.spyOn(testDb, 'prepare').mockImplementation((sql: string) => {
statements.push(sql);
return original(sql);
});
try {
await tokens.findUserByHashAndKind(hash, 'mcp');
} finally {
spy.mockRestore();
}
expect(statements).toHaveLength(1);
const select = statements[0].toLowerCase();
const whereIndex = select.indexOf('where');
expect(whereIndex).toBeGreaterThan(-1);
// `kind` must appear on the SQL side of the WHERE keyword — a
// post-filter shape (select every column, compare `kind` in JS) would
// still pass every behavioural test in this describe block (M1 in the
// review's mutation table: 56/56 green with kind moved to a JS
// check), so the SQL text itself is the only thing that can catch it.
expect(select.slice(whereIndex)).toContain('kind');
});
});
describe('touchLastUsedByHash', () => {
it('MCPTOKREPO-019: stamps last_used_at only on the matching row, no other column changes', async () => {
const { user } = createUser(testDb);
const target = createMcpToken(testDb, user.id, { rawToken: 'trek_touch_me' });
const other = createMcpToken(testDb, user.id, { rawToken: 'trek_leave_me' });
const before = (await storedToken(target.id)) as { name: string; token_hash: string };
await tokens.touchLastUsedByHash(target.tokenHash);
const after = (await storedToken(target.id)) as Record<string, unknown>;
expect(after.last_used_at).not.toBeNull();
expect(after.name).toBe(before.name);
expect(after.token_hash).toBe(before.token_hash);
expect(((await storedToken(other.id)) as { last_used_at: string | null }).last_used_at).toBeNull();
});
it('MCPTOKREPO-019b: an unknown hash touches nothing (no error, no row)', async () => {
await expect(tokens.touchLastUsedByHash('nonexistent')).resolves.toBeUndefined();
});
});
describe('deleteAllForUser', () => {
it('MCPTOKREPO-020: deletes every mcp_tokens row for the user, both kinds, leaves other users alone', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
createMcpToken(testDb, user.id, { kind: 'mcp' });
createMcpToken(testDb, user.id, { kind: 'api' });
const untouched = createMcpToken(testDb, other.id, { kind: 'mcp' });
await tokens.deleteAllForUser(user.id);
expect(await countRows(t, McpTokens, { user: user.id })).toBe(0);
expect(await storedToken(untouched.id)).toBeDefined();
});
});
// ---------------------------------------------------------------------
// Controller ruling on Task 1's review (BLOCKER): a `findOne`/`find` with
// `fields` + `refresh: true` used to re-snapshot only the selected fields
// into the SHARED identity map; loading the same row again elsewhere in
// the request with a different projection merged the two, and a later
// `nativeUpdate` (which bypasses the identity map) left that merged entity
// stale — the closing `flush()` of a `uow.transactional` block could then
// write the stale unselected values back over the `nativeUpdate`. Every
// entity-hydrating read in this repository now takes
// `disableIdentityMap: true` instead (never merged anywhere a flush could
// find it), and `insertToken` writes through `em.insert` rather than
// `create()` + `persist()` + `flush()`. This is the regression proof.
// ---------------------------------------------------------------------
describe('identity-map isolation (disableIdentityMap regression)', () => {
/**
* `disableIdentityMap: true` means the returned entity is never merged
* into `EntityManager.getUnitOfWork()`'s tracked set at all — checked
* directly via `getById`, which is the same lookup MikroORM's own
* `flush()` consults to decide what to write.
*
* CORRECTION (Plan 3b Task 2 review, F2): an earlier version of this
* docstring claimed the stale write-back this ruling guards against
* could not be reproduced as an observable black-box failure on this
* repository's own call shapes, and settled for this structural
* `getById` assertion alone. That claim was wrong — it IS reproducible.
* `MCPTOKREPO-023` below is the request-shaped reproduction: read
* projection A (`listByUserAndKind`, which selects `scope_mode`), read
* projection B (`findBasic`, which does not), then a `nativeUpdate` on
* `scope_mode` inside `uow.transactional`. On the fixed code (every read
* `disableIdentityMap: true`) the `nativeUpdate` survives the block's
* closing flush. Reverting `listByUserAndKind` to a bare `find` (no
* `disableIdentityMap`) and `findBasic` to `refresh: true` instead
* reproduces the exact hazard the ruling describes: both reads merge
* into the same managed entity, the `nativeUpdate` bypasses it, and the
* closing `flush()` writes the merged entity's stale `scope_mode: 'all'`
* back over the intended `'limited'` — `update mcp_tokens set
* scope_mode='all', api_scopes=null where id=?` observed immediately
* after `update mcp_tokens set scope_mode='limited' where id=?` in the
* query log, reverting the very write the test just made. `getById`
* (this test, `MCPTOKREPO-021`) stays as the structural companion: it is
* the assertion that fails first and pinpoints which method regressed,
* while `MCPTOKREPO-023` pins the actual end-to-end behaviour the
* ruling exists to protect.
*/
it('MCPTOKREPO-021: every entity-hydrating read leaves nothing behind in the shared identity map', async () => {
const { user } = createUser(testDb);
const created = createMcpToken(testDb, user.id, { name: 'stays-original' });
await tokens.findBasic(created.id);
expect(t.em.getUnitOfWork().getById(McpTokens, created.id)).toBeUndefined();
await tokens.findOwnedByKind(created.id, user.id, 'mcp');
expect(t.em.getUnitOfWork().getById(McpTokens, created.id)).toBeUndefined();
const [listed] = await tokens.listByUserAndKind(user.id, 'mcp');
expect(t.em.getUnitOfWork().getById(McpTokens, listed.id)).toBeUndefined();
});
it('MCPTOKREPO-021b: a nativeUpdate made after an isolated read is never discarded by an unrelated flush', async () => {
// Belt-and-suspenders behavioural pin alongside MCPTOKREPO-021's
// structural proof above: even though hand mutation-testing could not
// turn the un-isolated shape into an observable failure here (see that
// test's docstring), the fixed code's actual end-to-end behaviour —
// read, nativeUpdate, flush, still correct — is still worth pinning.
const { user } = createUser(testDb);
const created = createMcpToken(testDb, user.id, { name: 'stays-original' });
const uow = new UnitOfWork(t.em);
await uow.transactional(async () => {
const basic = await tokens.findBasic(created.id);
expect(basic?.last_used_at).toBeNull();
await tokens.findOwnedByKind(created.id, user.id, 'mcp');
await tokens.touchLastUsedByHash(created.tokenHash);
});
const row = (await storedToken(created.id)) as { last_used_at: string | null; name: string };
expect(row.last_used_at).not.toBeNull();
expect(row.name).toBe('stays-original');
});
it('MCPTOKREPO-022: insertToken never flushes an unrelated dirty entity sitting in the shared identity map', async () => {
// A create()+persist()+flush() shape would flush the WHOLE unit of
// work of the shared context-resolving EntityManager, not just the
// row being inserted — including any other managed entity's unflushed
// in-memory change (D4/AuditLogRepository's own precedent for this
// exact hazard). `em.insert()` fires one native INSERT with no such
// side effect. Proof: load a DIFFERENT row through the plain (merging)
// EntityManager API, mutate it in memory only, call `insertToken`, and
// confirm the mutation was never written — nothing here ever called
// `flush()` on that dirty entity's context.
const { user } = createUser(testDb);
const untouched = createMcpToken(testDb, user.id, { name: 'do-not-flush-me' });
const dirty = await t.em.findOneOrFail(McpTokens, { id: untouched.id });
dirty.name = 'mutated-in-memory-only';
await tokens.insertToken({
user_id: user.id,
name: 'the actual insert',
token_hash: 'insert-no-side-effect-hash',
token_prefix: 'trek_txprefi',
kind: 'mcp',
scope_mode: 'all',
api_scopes: null,
});
expect(((await storedToken(untouched.id)) as { name: string }).name).toBe('do-not-flush-me');
expect(await findRow(t, McpTokens, { token_hash: 'insert-no-side-effect-hash' })).not.toBeNull();
});
/**
* The request-shaped reproduction (Plan 3b Task 2 review, F2, shape D):
* projection A (`listByUserAndKind`, which selects `scope_mode`),
* projection B (`findBasic`, which does not), then a `nativeUpdate` on
* `scope_mode` — the column only projection A touched — inside
* `uow.transactional`. On the fixed code (every read
* `disableIdentityMap: true`) neither read is ever merged into the
* shared identity map, so the transaction's closing `flush()` has
* nothing stale to write and the `nativeUpdate` survives untouched.
*
* Mutation-proven by hand (not committed as a variant, per the brief —
* see the fix report for the transcript): reverting
* `listByUserAndKind`'s `find` to drop `disableIdentityMap` and
* `findBasic`'s `findOne` from `disableIdentityMap: true` to
* `refresh: true` makes this test fail — the row comes back
* `scope_mode: 'all'`, and the captured query log shows `update
* mcp_tokens set scope_mode='all', api_scopes=null where id=?` executed
* immediately AFTER `update mcp_tokens set scope_mode='limited' where
* id=?`, i.e. the transaction's closing flush silently reverting the
* intended write.
*/
it('MCPTOKREPO-023: projection A then projection B then a nativeUpdate on an A-only column, inside uow.transactional — the nativeUpdate survives the closing flush', async () => {
const { user } = createUser(testDb);
const created = createMcpToken(testDb, user.id, { name: 'stays-original', scope_mode: 'all' });
const uow = new UnitOfWork(t.em);
await uow.transactional(async () => {
// Projection A: selects `scope_mode` among its columns.
await tokens.listByUserAndKind(user.id, 'mcp');
// Projection B: a disjoint column set that does NOT select `scope_mode`.
await tokens.findBasic(created.id);
// A native write on the column only projection A touched.
await t.em.nativeUpdate(McpTokens, { id: created.id }, { scope_mode: 'limited' });
});
const row = (await storedToken(created.id)) as { scope_mode: string; name: string };
expect(row.scope_mode).toBe('limited');
expect(row.name).toBe('stays-original');
});
});
});
@@ -0,0 +1,162 @@
import { NotificationChannelPreferences } from '../../../../src/db/entities/NotificationChannelPreferences.entity';
import type { NotificationChannelPreferencesRepository } from '../../../../src/db/repositories/NotificationChannelPreferences.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser, type TestUser } from '../../../helpers/factories';
import { countRows, findRow, insertRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: NotificationChannelPreferencesRepository;
let user: TestUser;
let otherUser: TestUser;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(NotificationChannelPreferences);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
user = createUser(testDb).user;
otherUser = createUser(testDb).user;
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function insertRaw(userId: number, eventType: string, channel: string, enabled: number): Promise<void> {
await insertRow(t, NotificationChannelPreferences, { user: userId, event_type: eventType, channel, enabled });
}
/** The stored preference row, or null. */
function storedPref(userId: number, eventType: string, channel: string) {
return findRow(t, NotificationChannelPreferences, { user: userId, event_type: eventType, channel });
}
describe('notification_channel_preferences — the (user_id, event_type, channel) composite PK the ON CONFLICT target relies on (R5/§14)', () => {
it("NCPREPO-SCHEMA-001: PRAGMA table_info('notification_channel_preferences') reports a 3-column PRIMARY KEY over exactly (user_id, event_type, channel), matching the migration DDL", () => {
// test-sql-allow: schema introspection, which no entity or repository maps.
const cols = testDb.prepare("PRAGMA table_info('notification_channel_preferences')").all() as {
name: string;
pk: number;
}[];
const pkCols = cols
.filter((c) => c.pk > 0)
.sort((a, b) => a.pk - b.pk)
.map((c) => c.name);
expect(pkCols).toEqual(['user_id', 'event_type', 'channel']);
});
it('NCPREPO-SCHEMA-002: the entity metadata declares the same 3-property composite PK, naming the RELATION property, not its persist(false) twin', () => {
const meta = t.orm.getMetadata(NotificationChannelPreferences);
expect(
meta
.getPrimaryProps()
.map((p) => p.name)
.sort(),
).toEqual(['channel', 'event_type', 'user'].sort());
});
});
describe('NotificationChannelPreferencesRepository — reads (NP2/NP3 parity)', () => {
it('NCPREPO-001 — findEnabled matches `SELECT enabled FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?`, and is null for an absent row (default-enabled)', async () => {
await insertRaw(user.id, 'trip_invite', 'email', 0);
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = 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 };
const converted = await repo.findEnabled(user.id, 'trip_invite', 'email');
// A plain-object equality against the MikroORM-returned entity would also
// compare its (identical, but differently-shaped) relation/metadata
// fields — the field values are the parity contract here, not the
// wrapper shape (the `AppSettingsRepository.getValue` precedent).
expect(converted?.enabled).toBe(legacy.enabled);
expect(await repo.findEnabled(user.id, 'trip_invite', 'webhook')).toBeNull();
});
it('NCPREPO-002 — listForUser matches `SELECT event_type, channel, enabled FROM notification_channel_preferences WHERE user_id = ?`, fully seeded across every event×channel combination, and never leaks another user', async () => {
const combos: Array<[string, string, number]> = [
['trip_invite', 'email', 0],
['trip_invite', 'webhook', 1],
['trip_invite', 'inapp', 0],
['booking_change', 'email', 1],
['booking_change', 'ntfy', 0],
['vacay_invite', 'inapp', 0],
];
for (const [event_type, channel, enabled] of combos) await insertRaw(user.id, event_type, channel, enabled);
await insertRaw(otherUser.id, 'trip_invite', 'email', 0); // a different user's row — must not leak in
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = (
testDb
.prepare('SELECT event_type, channel, enabled FROM notification_channel_preferences WHERE user_id = ?')
.all(user.id) as { event_type: string; channel: string; enabled: number }[]
)
.map((r) => ({ event_type: r.event_type, channel: r.channel, enabled: r.enabled }))
.sort((a, b) => a.event_type.localeCompare(b.event_type) || a.channel.localeCompare(b.channel));
const converted = (await repo.listForUser(user.id))
.map((r) => ({ event_type: r.event_type, channel: r.channel, enabled: r.enabled }))
.sort((a, b) => a.event_type.localeCompare(b.event_type) || a.channel.localeCompare(b.channel));
expect(converted.length).toBe(combos.length);
expect(converted).toEqual(legacy);
});
});
describe('NotificationChannelPreferencesRepository — writes (NP5/NP6, R5)', () => {
it('NCPREPO-UPSERT-SQL: em.upsert renders `insert into "notification_channel_preferences" ... on conflict (`user_id`, `event_type`, `channel`) do update set ...` — the composite-PK conflict target Task 0\'s R5 worked example pinned, checked directly against the rendered SQL, not assumed from onConflictFields alone', async () => {
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
try {
// Insert branch: no existing row.
await repo.upsertPreference(user.id, 'trip_invite', 'email', 0);
expect((await storedPref(user.id, 'trip_invite', 'email'))?.enabled).toBe(0);
const insertSql = spy.mock.calls
.map(([sql]) => sql)
.find((sql): sql is string => typeof sql === 'string' && /insert into/i.test(sql));
expect(insertSql).toContain('on conflict (`user_id`, `event_type`, `channel`)');
spy.mockClear();
// Merge branch: an existing row, same call shape — the SAME conflict
// target both creates and merges, matching `OR REPLACE`'s semantics
// (there is no other non-key column REPLACE would reset that merge
// does not also set).
await repo.upsertPreference(user.id, 'trip_invite', 'email', 1);
expect((await storedPref(user.id, 'trip_invite', 'email'))?.enabled).toBe(1);
expect(
await countRows(t, NotificationChannelPreferences, {
user: user.id,
event_type: 'trip_invite',
channel: 'email',
}),
).toBe(1);
const mergeSql = spy.mock.calls
.map(([sql]) => sql)
.find((sql): sql is string => typeof sql === 'string' && /insert into/i.test(sql));
expect(mergeSql).toContain('on conflict (`user_id`, `event_type`, `channel`)');
} finally {
spy.mockRestore();
}
});
it('NCPREPO-003 — deletePreference matches `DELETE FROM notification_channel_preferences WHERE user_id = ? AND event_type = ? AND channel = ?`, scoped to exactly that triple', async () => {
await insertRaw(user.id, 'trip_invite', 'email', 0);
await insertRaw(user.id, 'trip_invite', 'webhook', 0); // a different channel — must survive
await insertRaw(otherUser.id, 'trip_invite', 'email', 0); // a different user — must survive
expect(await repo.deletePreference(user.id, 'trip_invite', 'email')).toBe(1);
expect(await storedPref(user.id, 'trip_invite', 'email')).toBeNull();
expect(await storedPref(user.id, 'trip_invite', 'webhook')).not.toBeNull();
expect(await storedPref(otherUser.id, 'trip_invite', 'email')).not.toBeNull();
expect(await repo.deletePreference(user.id, 'trip_invite', 'email')).toBe(0); // already gone — no-op
});
});
@@ -0,0 +1,344 @@
import { Notifications } from '../../../../src/db/entities/Notifications.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type { NotificationsRepository } from '../../../../src/db/repositories/Notifications.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser, createTrip, addTripMember, type TestUser, type TestTrip } from '../../../helpers/factories';
import { findRow, findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: NotificationsRepository;
let owner: TestUser;
let trip: TestTrip;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(Notifications);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
owner = createUser(testDb).user;
trip = createTrip(testDb, owner.id);
});
afterAll(async () => {
await t.close();
testDb.close();
});
/** Inserts one of each NT-inventory notification type, with every optional field set, for `recipientId`. Returns the three ids in insertion order (simple, boolean, navigate). */
async function seedThreeTypes(
recipientId: number,
senderId: number | null,
): Promise<{ simpleId: number; booleanId: number; navigateId: number }> {
const simpleId = await insertRow(t, Notifications, {
type: 'simple',
scope: 'trip',
target: trip.id,
sender: senderId,
recipient: recipientId,
title_key: 'notif.trip_invite.title',
title_params: '{"trip":"Rome"}',
text_key: 'notif.trip_invite.text',
text_params: '{"actor":"Alice"}',
});
const booleanId = await insertRow(t, Notifications, {
type: 'boolean',
scope: 'trip',
target: trip.id,
sender: senderId,
recipient: recipientId,
title_key: 'notif.vacay_invite.title',
title_params: '{"trip":"Rome"}',
text_key: 'notif.vacay_invite.text',
text_params: '{"actor":"Bob"}',
positive_text_key: 'notif.action.accept',
negative_text_key: 'notif.action.decline',
positive_callback: '{"action":"noop","payload":{"x":1}}',
negative_callback: '{"action":"noop","payload":{"x":2}}',
});
const navigateId = await insertRow(t, Notifications, {
type: 'navigate',
scope: 'trip',
target: trip.id,
sender: senderId,
recipient: recipientId,
title_key: 'notif.booking_change.title',
title_params: '{"trip":"Rome"}',
text_key: 'notif.booking_change.text',
text_params: '{"actor":"Carl"}',
navigate_text_key: 'notif.action.view_trip',
navigate_target: '/trips/1',
});
return { simpleId, booleanId, navigateId };
}
/** The legacy `SELECT * FROM notifications WHERE id = ?`, run raw, for a full-key parity comparison. */
function legacyFindById(id: number): unknown {
// test-sql-allow: the legacy full-row SELECT is the parity oracle the repository is compared against.
return testDb.prepare('SELECT * FROM notifications WHERE id = ?').get(id);
}
/** The notification row as it is now; fails the test when it is gone. */
async function notificationRow(id: number) {
return (await findRow(t, Notifications, { id }))!;
}
describe('NotificationsRepository — findById/findByIdForRecipient parity (fully seeded: simple/boolean/navigate, every optional field set)', () => {
it('NOTREPO-001 — findById matches the legacy full-row SELECT, byte for byte, for all three notification types', async () => {
const { user: recipient } = createUser(testDb);
const { user: sender } = createUser(testDb);
const { simpleId, booleanId, navigateId } = await seedThreeTypes(recipient.id, sender.id);
for (const id of [simpleId, booleanId, navigateId]) {
const legacy = legacyFindById(id);
const converted = await repo.findById(id);
expect(converted).toEqual(legacy);
}
});
it('NOTREPO-002 — findByIdForRecipient matches the legacy recipient-scoped SELECT, and returns undefined for the wrong recipient', async () => {
const { user: recipient } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const { booleanId } = await seedThreeTypes(recipient.id, null);
// test-sql-allow: the legacy recipient-scoped SELECT is the parity oracle the repository is compared against.
const legacy = testDb
.prepare('SELECT * FROM notifications WHERE id = ? AND recipient_id = ?')
.get(booleanId, recipient.id);
expect(await repo.findByIdForRecipient(booleanId, recipient.id)).toEqual(legacy);
expect(await repo.findByIdForRecipient(booleanId, stranger.id)).toBeUndefined();
});
it('NOTREPO-003 — findWithSenderById matches the legacy LEFT JOIN users projection (sender_username/sender_avatar), including a NULL sender', async () => {
const { user: recipient } = createUser(testDb);
const { user: sender } = createUser(testDb, { username: 'Alice', email: 'alice@test.example.com' });
const { simpleId } = await seedThreeTypes(recipient.id, sender.id);
// test-sql-allow: the legacy LEFT JOIN projection is the parity oracle the repository is compared against.
const legacy = testDb
.prepare(
`
SELECT n.*, u.username AS sender_username, u.avatar AS sender_avatar
FROM notifications n LEFT JOIN users u ON n.sender_id = u.id
WHERE n.id = ?
`,
)
.get(simpleId);
expect(await repo.findWithSenderById(simpleId)).toEqual(legacy);
// A system notification (no sender) — the LEFT JOIN's NULL side.
const systemId = await insertRow(t, Notifications, {
type: 'simple',
scope: 'admin',
target: 0,
sender: null,
recipient: recipient.id,
title_key: 'notif.version_available.title',
title_params: '{}',
text_key: 'notif.version_available.text',
text_params: '{}',
});
// test-sql-allow: the legacy LEFT JOIN projection is the parity oracle the repository is compared against.
const legacySystem = testDb
.prepare(
`
SELECT n.*, u.username AS sender_username, u.avatar AS sender_avatar
FROM notifications n LEFT JOIN users u ON n.sender_id = u.id
WHERE n.id = ?
`,
)
.get(systemId);
expect(await repo.findWithSenderById(systemId)).toEqual(legacySystem);
});
it('NOTREPO-004 — listForRecipient matches the legacy joined page read, for both unreadOnly variants', async () => {
const { user: recipient } = createUser(testDb);
const { user: sender } = createUser(testDb);
await seedThreeTypes(recipient.id, sender.id);
// The recipient's first notification is read, the other two are not.
const [first] = await findRows(t, Notifications, { recipient: recipient.id }, { id: 'asc' });
await updateRows(t, Notifications, { id: first.id }, { is_read: 1 });
for (const unreadOnly of [false, true]) {
const whereAliased = unreadOnly ? 'WHERE n.recipient_id = ? AND n.is_read = 0' : 'WHERE n.recipient_id = ?';
// test-sql-allow: the legacy joined page read is the parity oracle the repository is compared against.
const legacy = testDb
.prepare(
`
SELECT n.*, u.username AS sender_username, u.avatar AS sender_avatar
FROM notifications n LEFT JOIN users u ON n.sender_id = u.id
${whereAliased}
ORDER BY n.created_at DESC
LIMIT ? OFFSET ?
`,
)
.all(recipient.id, 20, 0);
const converted = await repo.listForRecipient(recipient.id, 20, 0, unreadOnly);
expect(converted).toEqual(legacy);
}
});
});
describe('NotificationsRepository — recipient resolution (NT1-NT4)', () => {
it('NOTREPO-005 — getTripOwnerId matches `SELECT user_id FROM trips WHERE id = ?`', async () => {
// test-sql-allow: the legacy statement named in the case title is the parity oracle.
const legacy = (testDb.prepare('SELECT user_id FROM trips WHERE id = ?').get(trip.id) as { user_id: number })
.user_id;
expect(await repo.getTripOwnerId(trip.id)).toBe(legacy);
expect(await repo.getTripOwnerId(999999)).toBeNull();
});
it('NOTREPO-006 — listNonGuestTripMemberIds (NT2, the guest-exclusion chokepoint, #1362): a guest member never appears, a real member always does', async () => {
const { user: member } = createUser(testDb);
addTripMember(testDb, trip.id, member.id);
const guestId = await insertRow(t, Users, {
username: 'Guest',
email: 'guest-repo@guests.invalid',
password_hash: '',
role: 'user',
is_guest: 1,
});
addTripMember(testDb, trip.id, guestId);
// test-sql-allow: the legacy statement named in the case title is the parity oracle.
const legacy = (
testDb
.prepare(
'SELECT m.user_id FROM trip_members m JOIN users u ON u.id = m.user_id WHERE m.trip_id = ? AND COALESCE(u.is_guest, 0) = 0',
)
.all(trip.id) as { user_id: number }[]
).map((r) => r.user_id);
const converted = await repo.listNonGuestTripMemberIds(trip.id);
expect(converted.sort()).toEqual(legacy.sort());
expect(converted).toContain(member.id);
expect(converted).not.toContain(guestId);
});
it('NOTREPO-007 — findGuestFlag matches `SELECT is_guest FROM users WHERE id = ?`, and is undefined for a nonexistent user', async () => {
const { user } = createUser(testDb);
expect(await repo.findGuestFlag(user.id)).toEqual({ is_guest: 0 });
expect(await repo.findGuestFlag(999999)).toBeUndefined();
});
it('NOTREPO-008 — listNonGuestUserIdsByRole matches `SELECT id FROM users WHERE role = ? AND COALESCE(is_guest, 0) = 0`', async () => {
const { user: admin1 } = createUser(testDb, { role: 'admin' });
const { user: admin2 } = createUser(testDb, { role: 'admin' });
createUser(testDb); // a regular user — must not appear
const guestAdminId = await insertRow(t, Users, {
username: 'GuestAdmin',
email: 'guest-admin@guests.invalid',
password_hash: '',
role: 'admin',
is_guest: 1,
});
// test-sql-allow: the legacy statement named in the case title is the parity oracle.
const legacy = (
testDb.prepare('SELECT id FROM users WHERE role = ? AND COALESCE(is_guest, 0) = 0').all('admin') as {
id: number;
}[]
).map((r) => r.id);
const converted = await repo.listNonGuestUserIdsByRole('admin');
expect(converted.sort()).toEqual(legacy.sort());
expect(converted).toContain(admin1.id);
expect(converted).toContain(admin2.id);
expect(converted).not.toContain(guestAdminId);
});
it('NOTREPO-009 — findUserBasic matches `SELECT username, avatar FROM users WHERE id = ?`', async () => {
const { user } = createUser(testDb);
await updateRows(t, Users, { id: user.id }, { avatar: 'avatar.png' });
// test-sql-allow: the legacy statement named in the case title is the parity oracle.
const legacy = testDb.prepare('SELECT username, avatar FROM users WHERE id = ?').get(user.id);
expect(await repo.findUserBasic(user.id)).toEqual(legacy);
expect(await repo.findUserBasic(999999)).toBeUndefined();
});
});
describe('NotificationsRepository — writes', () => {
it('NOTREPO-010 — insertNotification writes all 15 columns and returns the new id', async () => {
const { user: recipient } = createUser(testDb);
const { user: sender } = createUser(testDb);
const id = await repo.insertNotification({
type: 'boolean',
scope: 'trip',
target: trip.id,
sender_id: sender.id,
recipient_id: recipient.id,
title_key: 'notif.trip_invite.title',
title_params: '{"trip":"Rome"}',
text_key: 'notif.trip_invite.text',
text_params: '{"actor":"A"}',
positive_text_key: 'notif.action.accept',
negative_text_key: 'notif.action.decline',
positive_callback: '{"action":"noop","payload":{}}',
negative_callback: '{"action":"noop","payload":{}}',
navigate_text_key: null,
navigate_target: null,
});
const row = await notificationRow(id);
expect(row.type).toBe('boolean');
expect(row.scope).toBe('trip');
expect(row.target).toBe(trip.id);
expect(row.sender_id).toBe(sender.id);
expect(row.recipient_id).toBe(recipient.id);
expect(row.positive_callback).toBe('{"action":"noop","payload":{}}');
expect(row.is_read).toBe(0);
expect(row.response).toBeNull();
});
it('NOTREPO-011 — setRead/markAllRead/deleteForRecipient/deleteAllForRecipient are recipient-scoped and return the affected-row count', async () => {
const { user: recipient } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const { simpleId, booleanId } = await seedThreeTypes(recipient.id, null);
expect(await repo.setRead(simpleId, stranger.id, 1)).toBe(0); // wrong recipient — no-op
expect(await repo.setRead(simpleId, recipient.id, 1)).toBe(1);
expect((await notificationRow(simpleId)).is_read).toBe(1);
expect(await repo.setRead(simpleId, recipient.id, 0)).toBe(1);
expect(await repo.markAllRead(recipient.id)).toBe(3); // simple + boolean + navigate, all currently unread
expect(await repo.countUnreadForRecipient(recipient.id)).toBe(0);
expect(await repo.deleteForRecipient(booleanId, stranger.id)).toBe(0);
expect(await repo.deleteForRecipient(booleanId, recipient.id)).toBe(1);
expect(await repo.deleteAllForRecipient(recipient.id)).toBe(2); // simple + navigate remain
expect(await repo.countForRecipient(recipient.id, false)).toBe(0);
});
it('NOTREPO-012 — claimResponse (NT20) only succeeds once: the atomic double-submit claim', async () => {
const { user: recipient } = createUser(testDb);
const { booleanId } = await seedThreeTypes(recipient.id, null);
expect(await repo.claimResponse(booleanId, recipient.id, 'positive')).toBe(1);
// A second claim on the same, now-claimed notification affects 0 rows —
// the `response IS NULL` guard is the load-bearing part of this statement.
expect(await repo.claimResponse(booleanId, recipient.id, 'negative')).toBe(0);
expect((await notificationRow(booleanId)).response).toBe('positive');
});
it('NOTREPO-013 — releaseResponse (NT21) restores the claim so a retry can succeed', async () => {
const { user: recipient } = createUser(testDb);
const { booleanId } = await seedThreeTypes(recipient.id, null);
await repo.claimResponse(booleanId, recipient.id, 'positive');
await repo.releaseResponse(booleanId, recipient.id, 0);
const row = await notificationRow(booleanId);
expect(row.response).toBeNull();
expect(row.is_read).toBe(0);
expect(await repo.claimResponse(booleanId, recipient.id, 'negative')).toBe(1);
});
});
@@ -0,0 +1,380 @@
import { OauthClients } from '../../../../src/db/entities/OauthClients.entity';
import { OauthTokens } from '../../../../src/db/entities/OauthTokens.entity';
import type { OauthClientsRepository } from '../../../../src/db/repositories/OauthClients.repository';
import { dbNow } from '../../../../src/db/types';
import { withRequestContext } from '../../../../src/nest/database/request-context';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser } from '../../../helpers/factories';
import { deleteRows, findRow, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let clients: OauthClientsRepository;
let uow: UnitOfWork;
beforeAll(async () => {
t = await createTestOrm(testDb);
clients = t.repo(OauthClients);
uow = new UnitOfWork(t.em);
});
beforeEach(async () => {
resetTestDb(testDb);
t.clear();
await deleteRows(t, OauthTokens);
await deleteRows(t, OauthClients);
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function seedClient(
overrides: Partial<{
id: string;
userId: number | null;
name: string;
clientId: string;
secretHash: string;
redirectUris: string;
allowedScopes: string;
isPublic: number;
createdVia: string;
allowsClientCredentials: number;
}> = {},
): Promise<{ id: string; userId: number | null; clientId: string }> {
const id = overrides.id ?? `row-${Math.random().toString(36).slice(2)}`;
const clientId = overrides.clientId ?? `proto-${Math.random().toString(36).slice(2)}`;
await insertRow(t, OauthClients, {
id,
user: overrides.userId ?? null,
name: overrides.name ?? 'Test Client',
client_id: clientId,
client_secret_hash: overrides.secretHash ?? 'hash-value',
redirect_uris: overrides.redirectUris ?? '["https://example.com/cb"]',
allowed_scopes: overrides.allowedScopes ?? '["trips:read"]',
is_public: overrides.isPublic ?? 0,
created_via: overrides.createdVia ?? 'settings_ui',
allows_client_credentials: overrides.allowsClientCredentials ?? 0,
});
return { id, userId: overrides.userId ?? null, clientId };
}
/** The stored row, client_secret_hash included, which no repository read returns. */
function storedClient(id: string) {
return findRow(t, OauthClients, { id });
}
describe('OauthClientsRepository', () => {
describe('listByUser (OA1)', () => {
it("OAUTHCLIENTREPO-001: returns the caller's clients only, newest first, without the secret hash", async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await seedClient({ userId: user.id, name: 'first', createdVia: 'settings_ui' });
testDb.exec("UPDATE oauth_clients SET created_at = '2020-01-01 00:00:00' WHERE name = 'first'");
await seedClient({ userId: user.id, name: 'second' });
testDb.exec("UPDATE oauth_clients SET created_at = '2021-01-01 00:00:00' WHERE name = 'second'");
await seedClient({ userId: other.id, name: 'not-mine' });
const rows = await clients.listByUser(user.id);
expect(rows.map((r) => r.name)).toEqual(['second', 'first']);
expect(rows[0]).not.toHaveProperty('client_secret_hash');
expect(rows[0].user_id).toBe(user.id);
});
it('OAUTHCLIENTREPO-002: empty for a user with no clients', async () => {
const { user } = createUser(testDb);
expect(await clients.listByUser(user.id)).toEqual([]);
});
it('OAUTHCLIENTREPO-002b: created_at NULL comes back null, not undefined (coverage: rule 16)', async () => {
const { user } = createUser(testDb);
const { id } = await seedClient({ userId: user.id, name: 'null-created' });
await updateRows(t, OauthClients, { id }, { created_at: null });
const rows = await clients.listByUser(user.id);
expect(rows[0].created_at).toBeNull();
});
});
describe('countByUser / countAnonymous (OA2/OA3)', () => {
it("OAUTHCLIENTREPO-003: countByUser only counts the given user's rows", async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await seedClient({ userId: user.id });
await seedClient({ userId: user.id });
await seedClient({ userId: other.id });
expect(await clients.countByUser(user.id)).toBe(2);
expect(await clients.countByUser(other.id)).toBe(1);
});
it('OAUTHCLIENTREPO-004: countAnonymous counts only NULL-user rows', async () => {
const { user } = createUser(testDb);
await seedClient({ userId: user.id });
await seedClient({ userId: null });
await seedClient({ userId: null });
expect(await clients.countAnonymous()).toBe(2);
});
});
describe('insertClient / findPublicById (OA4/OA5)', () => {
it('OAUTHCLIENTREPO-005: writes exactly the given columns and the re-select matches', async () => {
const { user } = createUser(testDb);
const row = await clients.insertClient({
id: 'client-row-1',
user_id: user.id,
name: 'My Client',
client_id: 'proto-abc',
client_secret_hash: 'secrethash',
redirect_uris: '["https://a.example.com/cb"]',
allowed_scopes: '["trips:read","trips:write"]',
is_public: 0,
created_via: 'settings_ui',
allows_client_credentials: 0,
});
expect(row).toMatchObject({
id: 'client-row-1',
user_id: user.id,
name: 'My Client',
client_id: 'proto-abc',
redirect_uris: '["https://a.example.com/cb"]',
allowed_scopes: '["trips:read","trips:write"]',
is_public: 0,
created_via: 'settings_ui',
allows_client_credentials: 0,
});
const raw = await storedClient('client-row-1');
expect(raw?.client_secret_hash).toBe('secrethash');
});
it('OAUTHCLIENTREPO-005b: findPublicById is null for an unknown id', async () => {
expect(await clients.findPublicById('nope')).toBeNull();
});
it('OAUTHCLIENTREPO-005c: findPublicById — created_at NULL comes back null, not undefined (coverage: rule 16)', async () => {
const { id } = await seedClient({ name: 'null-created-public' });
await updateRows(t, OauthClients, { id }, { created_at: null });
const row = await clients.findPublicById(id);
expect(row?.created_at).toBeNull();
});
it('OAUTHCLIENTREPO-006: insertClient writes a NULL user_id for anonymous DCR clients', async () => {
const row = await clients.insertClient({
id: 'client-row-2',
user_id: null,
name: 'DCR Client',
client_id: 'proto-dcr',
client_secret_hash: 'x',
redirect_uris: '[]',
allowed_scopes: '[]',
is_public: 1,
created_via: 'dcr',
allows_client_credentials: 0,
});
expect(row.user_id).toBeNull();
});
it('OAUTHCLIENTREPO-006b: throws when the read-back after insert finds no row (coverage: the guard branch)', async () => {
const spy = vi.spyOn(clients, 'findPublicById').mockResolvedValueOnce(null);
await expect(
clients.insertClient({
id: 'client-row-ghost',
user_id: null,
name: 'Ghost Client',
client_id: 'proto-ghost',
client_secret_hash: 'x',
redirect_uris: '[]',
allowed_scopes: '[]',
is_public: 1,
created_via: 'dcr',
allows_client_credentials: 0,
}),
).rejects.toThrow('OauthClientsRepository.insertClient: row client-row-ghost not found immediately after insert');
spy.mockRestore();
});
});
describe('findOwned (OA6/OA9)', () => {
it('OAUTHCLIENTREPO-007: matches id+user, returns the superset projection', async () => {
const { user } = createUser(testDb);
const { id, clientId } = await seedClient({ userId: user.id, isPublic: 1 });
const row = await clients.findOwned(id, user.id);
expect(row).toEqual({ id, client_id: clientId, is_public: 1 });
});
it("OAUTHCLIENTREPO-008: 404-shape null for another user's client (never 403)", async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const { id } = await seedClient({ userId: other.id });
expect(await clients.findOwned(id, user.id)).toBeNull();
});
});
describe('updateSecretHash (OA7)', () => {
it('OAUTHCLIENTREPO-009: writes the new hash, nothing else', async () => {
const { id } = await seedClient({ secretHash: 'old' });
await clients.updateSecretHash(id, 'new-hash');
const row = await storedClient(id);
expect(row?.client_secret_hash).toBe('new-hash');
});
});
describe('remove (OA10)', () => {
it('OAUTHCLIENTREPO-010: deletes the row', async () => {
const { id } = await seedClient();
await clients.remove(id);
expect(await storedClient(id)).toBeNull();
});
});
describe('findSdkProjection (OA15)', () => {
it('OAUTHCLIENTREPO-011: never carries client_secret_hash', async () => {
const { clientId } = await seedClient({ secretHash: 'super-secret', name: 'SDK Client' });
const row = await clients.findSdkProjection(clientId);
expect(row).toEqual({
client_id: clientId,
name: 'SDK Client',
redirect_uris: '["https://example.com/cb"]',
allowed_scopes: '["trips:read"]',
is_public: 0,
created_via: 'settings_ui',
});
expect(row).not.toHaveProperty('client_secret_hash');
});
it('OAUTHCLIENTREPO-012: null for unknown client_id', async () => {
expect(await clients.findSdkProjection('nonexistent')).toBeNull();
});
});
describe('findAuthRow (OA21)', () => {
it('OAUTHCLIENTREPO-013: exactly the three auth columns, a distinct projection from OA15', async () => {
const { clientId } = await seedClient({ secretHash: 'auth-secret', isPublic: 0 });
const row = await clients.findAuthRow(clientId);
expect(row).toEqual({ client_id: clientId, client_secret_hash: 'auth-secret', is_public: 0 });
});
it('OAUTHCLIENTREPO-013b: null for unknown client_id', async () => {
expect(await clients.findAuthRow('nope')).toBeNull();
});
});
describe('findByClientIdFull (OA29/OA30)', () => {
it('OAUTHCLIENTREPO-014: the full row, including the secret hash', async () => {
const { user } = createUser(testDb);
const { clientId } = await seedClient({ userId: user.id, secretHash: 'full-row-secret' });
const row = await clients.findByClientIdFull(clientId);
expect(row?.client_secret_hash).toBe('full-row-secret');
expect(row?.user_id).toBe(user.id);
});
it('OAUTHCLIENTREPO-015: null for unknown client_id', async () => {
expect(await clients.findByClientIdFull('nope')).toBeNull();
});
});
describe('identity-map write-back regression (program RULING, D-shape)', () => {
// task-4-review.md F1: the D-shape needs the `nativeUpdate`'s target
// column in the FIRST, WIDER projection and absent from the SECOND,
// narrower one — a stale write-back only reverts a column the second
// read's snapshot doesn't already carry fresh. The original ordering
// here (`listByUser`, narrow, then `findAuthRow`, wide) had it backwards:
// `findAuthRow`'s own re-snapshot of `client_secret_hash` left that
// column clean, so the mutation this test exists to catch (reverting
// `disableIdentityMap: true` back to `refresh: true`) passed anyway.
// `findAuthRow` (wide, carries `client_secret_hash`) now goes FIRST and
// `findOwned` (narrow, no `client_secret_hash`) second — mutation-proven
// load-bearing in the task report.
it('OAUTHCLIENTREPO-016: findAuthRow then findOwned then updateSecretHash inside uow.transactional — the write survives', async () => {
const { user } = createUser(testDb);
const { id, clientId } = await seedClient({ userId: user.id, secretHash: 'original', name: 'kept-name' });
await withRequestContext(t.orm, async () => {
// Projection A — wide, carries client_secret_hash.
await clients.findAuthRow(clientId);
// Projection B — narrow, a different (smaller) field set on the same row.
await clients.findOwned(id, user.id);
// The intended write, inside the request's own transaction.
await uow.transactional(async () => {
await clients.updateSecretHash(id, 'rotated');
});
});
const row = await storedClient(id);
expect(row?.client_secret_hash).toBe('rotated'); // the nativeUpdate must stick
expect(row?.name).toBe('kept-name'); // untouched by either read
});
});
describe('upsertCimdClient', () => {
const cimd = (name: string, scopes = '["trips:read"]') => ({
id: 'cimd-row',
name,
client_id: 'https://claude.ai/oauth/mcp-client.json',
client_secret_hash: '',
redirect_uris: '["https://claude.ai/api/mcp/auth_callback"]',
allowed_scopes: scopes,
});
it('OAUTHCLIENTREPO-017: registers a public cimd client, then refreshes it from its document', async () => {
await clients.upsertCimdClient(cimd('Claude'));
expect(await storedClient('cimd-row')).toMatchObject({
name: 'Claude',
is_public: 1,
created_via: 'cimd',
user_id: null,
allows_client_credentials: 0,
});
await clients.upsertCimdClient({ ...cimd('Claude (new)', '["trips:read","places:write"]'), id: 'ignored' });
expect(await findRow(t, OauthClients, { id: 'ignored' })).toBeNull();
expect(await storedClient('cimd-row')).toMatchObject({
name: 'Claude (new)',
allowed_scopes: '["trips:read","places:write"]',
});
});
it('OAUTHCLIENTREPO-018: leaves a client another path registered under that client_id alone', async () => {
const { id } = await seedClient({ clientId: 'https://claude.ai/oauth/mcp-client.json', name: 'Registered' });
await clients.upsertCimdClient(cimd('Claude'));
expect(await storedClient(id)).toMatchObject({ name: 'Registered', created_via: 'settings_ui' });
});
});
describe('deleteUnusedCimdBefore', () => {
const CUTOFF = dbNow(new Date('2026-10-01T00:00:00Z'));
const OLD = '2026-09-01 00:00:00';
async function holdToken(clientId: string): Promise<void> {
const { user } = createUser(testDb);
await insertRow(t, OauthTokens, {
client: clientId,
user: user.id,
access_token_hash: `acc-${clientId}`,
refresh_token_hash: `ref-${clientId}`,
access_token_expires_at: new Date(Date.now() + 3600_000).toISOString(),
refresh_token_expires_at: new Date(Date.now() + 86_400_000).toISOString(),
});
}
it('OAUTHCLIENTREPO-019: drops old cimd clients nobody holds a token for, and counts them', async () => {
const unused = await seedClient({ createdVia: 'cimd' });
const held = await seedClient({ createdVia: 'cimd' });
const recent = await seedClient({ createdVia: 'cimd' });
const registered = await seedClient({ createdVia: 'settings_ui' });
await Promise.all(
[unused, held, registered].map((client) => updateRows(t, OauthClients, { id: client.id }, { created_at: OLD })),
);
await updateRows(t, OauthClients, { id: recent.id }, { created_at: '2026-10-15 00:00:00' });
await holdToken(held.clientId);
expect(await clients.deleteUnusedCimdBefore(CUTOFF)).toBe(1);
expect(await storedClient(unused.id)).toBeNull();
const kept = await Promise.all([held, recent, registered].map((client) => storedClient(client.id)));
for (const row of kept) expect(row).not.toBeNull();
expect(await clients.deleteUnusedCimdBefore(CUTOFF)).toBe(0);
});
});
});
@@ -0,0 +1,152 @@
import { OauthClients } from '../../../../src/db/entities/OauthClients.entity';
import { OauthConsents } from '../../../../src/db/entities/OauthConsents.entity';
import type { OauthConsentsRepository } from '../../../../src/db/repositories/OauthConsents.repository';
import { withRequestContext } from '../../../../src/nest/database/request-context';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser } from '../../../helpers/factories';
import { findRow, findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let consents: OauthConsentsRepository;
let uow: UnitOfWork;
beforeAll(async () => {
t = await createTestOrm(testDb);
consents = t.repo(OauthConsents);
uow = new UnitOfWork(t.em);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
testDb.exec('DELETE FROM oauth_consents');
testDb.exec('DELETE FROM oauth_clients');
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function seedClient(userId: number, clientId: string): Promise<void> {
await insertRow(t, OauthClients, {
id: `row-${clientId}`,
user: userId,
name: 'C',
client_id: clientId,
client_secret_hash: 'hash',
redirect_uris: '[]',
allowed_scopes: '[]',
});
}
/** The stored consent of `userId` for `clientId`, or null. */
function storedConsent(clientId: string, userId: number) {
return findRow(t, OauthConsents, { client: clientId, user: userId });
}
describe('OauthConsentsRepository', () => {
describe('findScopes (OA11)', () => {
it('OAUTHCONSENTREPO-001: null when no consent has been granted', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-1');
expect(await consents.findScopes('proto-1', user.id)).toBeNull();
});
it('OAUTHCONSENTREPO-002: returns the stored scopes JSON text', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-2');
await insertRow(t, OauthConsents, { client: 'proto-2', user: user.id, scopes: '["trips:read"]' });
expect(await consents.findScopes('proto-2', user.id)).toEqual({ scopes: '["trips:read"]' });
});
});
describe('upsertGrant (OA12)', () => {
it('OAUTHCONSENTREPO-003: inserts a new row exactly as the legacy INSERT would', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-3');
await consents.upsertGrant('proto-3', user.id, '["a"]');
const row = await storedConsent('proto-3', user.id);
expect({ client_id: row?.client_id, user_id: row?.user_id, scopes: row?.scopes }).toEqual({
client_id: 'proto-3',
user_id: user.id,
scopes: '["a"]',
});
});
it('OAUTHCONSENTREPO-004: on an existing (client, user) it replaces the row in place — no duplicate, matching ON CONFLICT(client_id, user_id) DO UPDATE', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-4');
await consents.upsertGrant('proto-4', user.id, '["a"]');
await consents.upsertGrant('proto-4', user.id, '["a","b"]');
const rows = await findRows(t, OauthConsents, { client: 'proto-4', user: user.id });
expect(rows).toHaveLength(1);
expect(rows[0].scopes).toBe('["a","b"]');
});
it('OAUTHCONSENTREPO-005: updated_at is bumped on every call, insert or merge alike (unconditional, matching INSERT OR REPLACE)', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-5');
await consents.upsertGrant('proto-5', user.id, '["a"]');
const first = await storedConsent('proto-5', user.id);
await updateRows(t, OauthConsents, { client: 'proto-5' }, { updated_at: '2000-01-01 00:00:00' });
await consents.upsertGrant('proto-5', user.id, '["a","b"]');
const second = await storedConsent('proto-5', user.id);
expect(second?.updated_at).not.toBe('2000-01-01 00:00:00');
expect(first?.updated_at).toBeTruthy();
});
it('OAUTHCONSENTREPO-006: the same client scoped by different users stores two separate rows, not a collision', async () => {
const { user: a } = createUser(testDb);
const { user: b } = createUser(testDb);
await seedClient(a.id, 'proto-6');
await consents.upsertGrant('proto-6', a.id, '["a"]');
await consents.upsertGrant('proto-6', b.id, '["b"]');
expect(await consents.findScopes('proto-6', a.id)).toEqual({ scopes: '["a"]' });
expect(await consents.findScopes('proto-6', b.id)).toEqual({ scopes: '["b"]' });
});
});
// task-4-review.md F2: this is NOT a B1/D-shape regression test — that
// shape needs TWO managed reads with different field sets on the same
// row (task-1-rereview.md M-A/M-B), and `OauthConsentsRepository` has
// exactly one read method, so the D-shape is not constructible here at
// all. Mutating `findScopes`'s `disableIdentityMap: true` to `refresh:
// true` leaves this case green either way — it was never testing the
// mechanism its old name/comment claimed. What it DOES pin, genuinely:
// a single `findScopes` read leaves nothing dirty (the entity's snapshot
// and current data are identical, so the change-set computer finds no
// diff), and a raw write to the same row on the transaction's own
// connection, made afterward, is never fought by the closing flush.
describe('findScopes does not dirty the entity it reads', () => {
it("OAUTHCONSENTREPO-007: findScopes then a raw write on the same transaction connection — the raw write survives the transaction's closing flush", async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-7');
await insertRow(t, OauthConsents, { client: 'proto-7', user: user.id, scopes: '["a"]' });
await withRequestContext(t.orm, async () => {
await uow.transactional(async () => {
// The only read shape this repository has — a single projection,
// so no second, differently-projected read of the same row can
// ever be lingering in the identity map for this one to collide
// with.
await consents.findScopes('proto-7', user.id);
// A write bypassing the ORM entirely, on the SAME single SQLite
// connection the open transaction holds (D3/D6) — the shape any
// nativeUpdate write from elsewhere in the same request takes.
// test-sql-allow: the write has to run on the connection the open transaction holds, past the ORM.
testDb
.prepare('UPDATE oauth_consents SET scopes = ? WHERE client_id = ? AND user_id = ?')
.run('["a","b"]', 'proto-7', user.id);
});
});
const row = await storedConsent('proto-7', user.id);
expect(row?.scopes).toBe('["a","b"]');
});
});
});
@@ -0,0 +1,680 @@
import { OauthClients } from '../../../../src/db/entities/OauthClients.entity';
import { OauthConsents } from '../../../../src/db/entities/OauthConsents.entity';
import { OauthTokens } from '../../../../src/db/entities/OauthTokens.entity';
import type { OauthTokensRepository } from '../../../../src/db/repositories/OauthTokens.repository';
import { dbNow } from '../../../../src/db/types';
import { withRequestContext } from '../../../../src/nest/database/request-context';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser } from '../../../helpers/factories';
import { deleteRows, findRow, findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let tokens: OauthTokensRepository;
let uow: UnitOfWork;
beforeAll(async () => {
t = await createTestOrm(testDb);
tokens = t.repo(OauthTokens);
uow = new UnitOfWork(t.em);
});
beforeEach(async () => {
resetTestDb(testDb);
t.clear();
await deleteRows(t, OauthTokens);
await deleteRows(t, OauthConsents);
await deleteRows(t, OauthClients);
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function seedClient(userId: number, clientId: string, name = 'Client'): Promise<void> {
await insertRow(t, OauthClients, {
id: `row-${clientId}`,
user: userId,
name,
client_id: clientId,
client_secret_hash: 'hash',
redirect_uris: '[]',
allowed_scopes: '[]',
});
}
/** The stored token row; fails the case when it is gone. */
async function tokenRow(id: number) {
const row = await findRow(t, OauthTokens, { id });
if (!row) throw new Error(`no token ${id}`);
return row;
}
async function revokedAtOf(id: number) {
return (await tokenRow(id)).revoked_at;
}
async function seedToken(
overrides: Partial<{
id: number;
clientId: string;
userId: number;
accessHash: string;
refreshHash: string;
scopes: string;
audience: string | null;
accessExpiresAt: string;
refreshExpiresAt: string;
revokedAt: string | null;
parentId: number | null;
}> = {},
): Promise<number> {
const id = await insertRow(t, OauthTokens, {
client: overrides.clientId as string,
user: overrides.userId as number,
access_token_hash: overrides.accessHash ?? `acc-${Math.random().toString(36).slice(2)}`,
refresh_token_hash: overrides.refreshHash ?? `ref-${Math.random().toString(36).slice(2)}`,
scopes: overrides.scopes ?? '["trips:read"]',
audience: overrides.audience ?? null,
access_token_expires_at: overrides.accessExpiresAt ?? new Date(Date.now() + 3600_000).toISOString(),
refresh_token_expires_at: overrides.refreshExpiresAt ?? new Date(Date.now() + 30 * 24 * 3600_000).toISOString(),
revoked_at: overrides.revokedAt ?? null,
parentToken: overrides.parentId ?? null,
});
if (overrides.id !== undefined) {
await updateRows(t, OauthTokens, { id }, { id: overrides.id });
return overrides.id;
}
return id;
}
describe('OauthTokensRepository', () => {
describe('insertToken (OA13/OA14)', () => {
it('OAUTHTOKREPO-001: writes exactly the given columns', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-1');
const accessExpiry = dbNow(new Date(Date.now() + 3600_000));
const refreshExpiry = dbNow(new Date(Date.now() + 30 * 24 * 3600_000));
await tokens.insertToken({
client_id: 'proto-1',
user_id: user.id,
access_token_hash: 'acchash',
refresh_token_hash: 'refhash',
scopes: '["trips:read"]',
audience: 'https://mcp.example.com',
access_token_expires_at: accessExpiry,
refresh_token_expires_at: refreshExpiry,
parent_token_id: null,
});
const row = await findRow(t, OauthTokens, { access_token_hash: 'acchash' });
expect(row).toMatchObject({
client_id: 'proto-1',
user_id: user.id,
access_token_hash: 'acchash',
refresh_token_hash: 'refhash',
scopes: '["trips:read"]',
audience: 'https://mcp.example.com',
revoked_at: null,
parent_token_id: null,
});
});
it('OAUTHTOKREPO-002: parent_token_id is written when given (rotation)', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-2');
const parentId = await seedToken({ clientId: 'proto-2', userId: user.id });
await tokens.insertToken({
client_id: 'proto-2',
user_id: user.id,
access_token_hash: 'a2',
refresh_token_hash: 'r2',
scopes: '[]',
audience: null,
access_token_expires_at: dbNow(),
refresh_token_expires_at: dbNow(),
parent_token_id: parentId,
});
const row = await findRow(t, OauthTokens, { access_token_hash: 'a2' });
expect(row?.parent_token_id).toBe(parentId);
});
});
describe('revokeAllForClient (OA8) — the two spellings of "now"', () => {
it("OAUTHTOKREPO-003: revokeAllForClient (legacy datetime('now')) and revokeById (legacy CURRENT_TIMESTAMP) store byte-identical text", async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-3');
const idA = await seedToken({ clientId: 'proto-3', userId: user.id });
const idB = await seedToken({ clientId: 'proto-3', userId: user.id });
await tokens.revokeAllForClient('proto-3'); // legacy: datetime('now')
await tokens.revokeById(idB); // legacy: CURRENT_TIMESTAMP
// test-sql-allow: the stored text of revoked_at is under test, which DbTimestampType would normalise on read.
const rowA = testDb.prepare('SELECT revoked_at FROM oauth_tokens WHERE id = ?').get(idA) as {
revoked_at: unknown;
};
// test-sql-allow: the stored text of revoked_at is under test, which DbTimestampType would normalise on read.
const rowB = testDb.prepare('SELECT revoked_at FROM oauth_tokens WHERE id = ?').get(idB) as {
revoked_at: unknown;
};
expect(typeof rowA.revoked_at).toBe('string');
expect(typeof rowB.revoked_at).toBe('string');
expect(rowA.revoked_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
expect(rowB.revoked_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
});
it('OAUTHTOKREPO-004: revokeAllForClient only touches un-revoked rows of that client', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-4');
await seedClient(user.id, 'proto-4b');
const idOther = await seedToken({ clientId: 'proto-4b', userId: user.id });
const idAlready = await seedToken({ clientId: 'proto-4', userId: user.id, revokedAt: '2020-01-01 00:00:00' });
const idLive = await seedToken({ clientId: 'proto-4', userId: user.id });
await tokens.revokeAllForClient('proto-4');
expect(await revokedAtOf(idOther)).toBeNull();
expect(await revokedAtOf(idAlready)).toBe('2020-01-01 00:00:00');
expect(await revokedAtOf(idLive)).not.toBeNull();
});
});
describe('findByAccessTokenHashWithUser (OA16)', () => {
it("OAUTHTOKREPO-005: joins the token owner's username/email/role", async () => {
const { user } = createUser(testDb, { username: 'bearer-user', email: 'bearer@example.test' });
await seedClient(user.id, 'proto-5');
await seedToken({
clientId: 'proto-5',
userId: user.id,
accessHash: 'bearer-hash',
scopes: '["trips:read"]',
audience: 'aud',
});
const row = await tokens.findByAccessTokenHashWithUser('bearer-hash');
expect(row).toMatchObject({
scopes: '["trips:read"]',
audience: 'aud',
revoked_at: null,
user_id: user.id,
client_id: 'proto-5',
username: 'bearer-user',
email: 'bearer@example.test',
role: 'user',
});
});
it('OAUTHTOKREPO-006: null for an unknown hash', async () => {
expect(await tokens.findByAccessTokenHashWithUser('nope')).toBeNull();
});
});
describe('findParent (OA17)', () => {
it('OAUTHTOKREPO-007: returns id + parent_token_id', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-7');
const rootId = await seedToken({ clientId: 'proto-7', userId: user.id });
const childId = await seedToken({ clientId: 'proto-7', userId: user.id, parentId: rootId });
expect(await tokens.findParent(childId)).toEqual({ id: childId, parent_token_id: rootId });
expect(await tokens.findParent(rootId)).toEqual({ id: rootId, parent_token_id: null });
});
it('OAUTHTOKREPO-007b: an unknown id is null', async () => {
expect(await tokens.findParent(999999)).toBeNull();
});
});
describe('collectChainIds (OA18) — recursive CTE, proven against the legacy raw statement', () => {
it('OAUTHTOKREPO-008: a 4-level chain is fully collected, a sibling branch is excluded — matches the legacy WITH RECURSIVE statement exactly', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-8');
const id1 = await seedToken({ clientId: 'proto-8', userId: user.id });
const id2 = await seedToken({ clientId: 'proto-8', userId: user.id, parentId: id1 });
const id3 = await seedToken({ clientId: 'proto-8', userId: user.id, parentId: id2 });
const id4 = await seedToken({ clientId: 'proto-8', userId: user.id, parentId: id3 });
// A sibling branch off a DIFFERENT root — must not be collected.
const sibRoot = await seedToken({ clientId: 'proto-8', userId: user.id });
const sibChild = await seedToken({ clientId: 'proto-8', userId: user.id, parentId: sibRoot });
// test-sql-allow: the legacy recursive statement is the oracle the repository read is held to.
const legacyRows = testDb
.prepare(
`
WITH RECURSIVE chain(id) AS (
SELECT id FROM oauth_tokens WHERE id = ?
UNION ALL
SELECT t.id FROM oauth_tokens t JOIN chain c ON t.parent_token_id = c.id
)
SELECT id FROM chain
`,
)
.all(id1) as Array<{ id: number }>;
const legacyIds = legacyRows.map((r) => r.id).sort((a, b) => a - b);
const ids = (await tokens.collectChainIds(id1)).sort((a, b) => a - b);
expect(ids).toEqual(legacyIds);
expect(ids).toEqual([id1, id2, id3, id4].sort((a, b) => a - b));
expect(ids).not.toContain(sibRoot);
expect(ids).not.toContain(sibChild);
});
it('OAUTHTOKREPO-009: a token with no children collects only itself', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-9');
const id = await seedToken({ clientId: 'proto-9', userId: user.id });
expect(await tokens.collectChainIds(id)).toEqual([id]);
});
});
describe('revokeByIds (OA19) — the $in revoke', () => {
it('OAUTHTOKREPO-010: revokes exactly the given ids, only if still live', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-10');
const idLive1 = await seedToken({ clientId: 'proto-10', userId: user.id });
const idLive2 = await seedToken({ clientId: 'proto-10', userId: user.id });
const idAlready = await seedToken({ clientId: 'proto-10', userId: user.id, revokedAt: '2020-01-01 00:00:00' });
const idUntouched = await seedToken({ clientId: 'proto-10', userId: user.id });
await tokens.revokeByIds([idLive1, idLive2, idAlready]);
expect(await revokedAtOf(idLive1)).not.toBeNull();
expect(await revokedAtOf(idLive2)).not.toBeNull();
expect(await revokedAtOf(idAlready)).toBe('2020-01-01 00:00:00'); // untouched, not re-stamped
expect(await revokedAtOf(idUntouched)).toBeNull();
});
it('OAUTHTOKREPO-011: an empty array is a no-op (matches the legacy `if (ids.length > 0)` guard)', async () => {
await expect(tokens.revokeByIds([])).resolves.toBeUndefined();
});
});
describe('collectChainIds + revokeByIds inside a transaction — proves it joins the OPEN transaction', () => {
it('OAUTHTOKREPO-012: revoking a chain inside a uow.transactional that then ROLLS BACK revokes nothing', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-12');
const rootId = await seedToken({ clientId: 'proto-12', userId: user.id });
const childId = await seedToken({ clientId: 'proto-12', userId: user.id, parentId: rootId });
let caught: unknown;
try {
await withRequestContext(t.orm, async () => {
await uow.transactional(async () => {
const ids = await tokens.collectChainIds(rootId);
expect(ids.sort((a, b) => a - b)).toEqual([rootId, childId].sort((a, b) => a - b));
await tokens.revokeByIds(ids);
throw new Error('force rollback');
});
});
} catch (e) {
caught = e;
}
expect((caught as Error).message).toBe('force rollback');
const rows = await findRows(t, OauthTokens, { id: { $in: [rootId, childId] } });
expect(rows.every((r) => r.revoked_at === null)).toBe(true);
});
it('OAUTHTOKREPO-013: the same sequence, committed, actually revokes the chain', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-13');
const rootId = await seedToken({ clientId: 'proto-13', userId: user.id });
const childId = await seedToken({ clientId: 'proto-13', userId: user.id, parentId: rootId });
await withRequestContext(t.orm, async () => {
await uow.transactional(async () => {
const ids = await tokens.collectChainIds(rootId);
await tokens.revokeByIds(ids);
});
});
const rows = await findRows(t, OauthTokens, { id: { $in: [rootId, childId] } });
expect(rows.every((r) => r.revoked_at !== null)).toBe(true);
});
});
describe('findSuccessorAlive (OA20)', () => {
it('OAUTHTOKREPO-014: a revoked parent with a live child returns the child', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-14');
const parentId = await seedToken({ clientId: 'proto-14', userId: user.id, revokedAt: '2020-01-01 00:00:00' });
const childId = await seedToken({ clientId: 'proto-14', userId: user.id, parentId });
expect(await tokens.findSuccessorAlive(parentId)).toEqual({ id: childId });
});
it('OAUTHTOKREPO-015: no live child returns null', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-15');
const parentId = await seedToken({ clientId: 'proto-15', userId: user.id, revokedAt: '2020-01-01 00:00:00' });
await seedToken({ clientId: 'proto-15', userId: user.id, parentId, revokedAt: '2020-01-01 00:00:01' });
expect(await tokens.findSuccessorAlive(parentId)).toBeNull();
});
});
describe('findByRefreshTokenHash (OA22)', () => {
it('OAUTHTOKREPO-016: returns every column the legacy statement selects, FK scalars read from the raw column value', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-16');
const parentId = await seedToken({ clientId: 'proto-16', userId: user.id });
const id = await seedToken({
clientId: 'proto-16',
userId: user.id,
refreshHash: 'refresh-16',
parentId,
audience: 'aud-16',
});
const row = await tokens.findByRefreshTokenHash('refresh-16');
expect(row).toEqual({
id,
client_id: 'proto-16',
user_id: user.id,
scopes: '["trips:read"]',
audience: 'aud-16',
refresh_token_expires_at: expect.any(String),
revoked_at: null,
parent_token_id: parentId,
});
});
it('OAUTHTOKREPO-017: null for an unknown hash', async () => {
expect(await tokens.findByRefreshTokenHash('nope')).toBeNull();
});
});
describe('revokeById (OA23/OA28/OA33)', () => {
it('OAUTHTOKREPO-018: revokes the given id only', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-18');
const idA = await seedToken({ clientId: 'proto-18', userId: user.id });
const idB = await seedToken({ clientId: 'proto-18', userId: user.id });
await tokens.revokeById(idA);
expect(await revokedAtOf(idA)).not.toBeNull();
expect(await revokedAtOf(idB)).toBeNull();
});
});
describe('findByAccessOrRefreshHashAndClient / revokeByAccessOrRefreshHashAndClient (OA24/OA25)', () => {
it('OAUTHTOKREPO-019: finds by access hash OR refresh hash, scoped to the client', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-19');
await seedToken({ clientId: 'proto-19', userId: user.id, accessHash: 'acc-19', refreshHash: 'ref-19' });
expect(await tokens.findByAccessOrRefreshHashAndClient('acc-19', 'proto-19')).toEqual({ user_id: user.id });
expect(await tokens.findByAccessOrRefreshHashAndClient('ref-19', 'proto-19')).toEqual({ user_id: user.id });
});
it('OAUTHTOKREPO-020: does not match a token belonging to a different client', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-20a');
await seedClient(user.id, 'proto-20b');
await seedToken({ clientId: 'proto-20a', userId: user.id, accessHash: 'acc-20' });
expect(await tokens.findByAccessOrRefreshHashAndClient('acc-20', 'proto-20b')).toBeNull();
});
it('OAUTHTOKREPO-021: revokeByAccessOrRefreshHashAndClient revokes by either hash, scoped to the client', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-21');
const id = await seedToken({
clientId: 'proto-21',
userId: user.id,
accessHash: 'acc-21',
refreshHash: 'ref-21',
});
await tokens.revokeByAccessOrRefreshHashAndClient('acc-21', 'proto-21');
expect(await revokedAtOf(id)).not.toBeNull();
});
});
describe('listActiveByUser (OA26) — QueryBuilder join on the real oauth_clients.client_id column', () => {
it("OAUTHTOKREPO-022: lists only this user's non-revoked, non-expired-refresh sessions, newest first, with the client name joined in", async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await seedClient(user.id, 'proto-22a', 'Client A');
await seedClient(user.id, 'proto-22b', 'Client B');
await seedToken({ clientId: 'proto-22a', userId: user.id, scopes: '["trips:read"]' });
testDb.exec("UPDATE oauth_tokens SET created_at = '2020-01-01 00:00:00' WHERE client_id = 'proto-22a'");
await seedToken({ clientId: 'proto-22b', userId: user.id });
testDb.exec("UPDATE oauth_tokens SET created_at = '2021-01-01 00:00:00' WHERE client_id = 'proto-22b'");
// revoked — excluded
await seedToken({ clientId: 'proto-22a', userId: user.id, revokedAt: '2020-01-01 00:00:00' });
// expired refresh — excluded
await seedToken({ clientId: 'proto-22a', userId: user.id, refreshExpiresAt: '2000-01-01 00:00:00' });
// another user's session — excluded
await seedClient(other.id, 'proto-22c');
await seedToken({ clientId: 'proto-22c', userId: other.id });
const rows = await tokens.listActiveByUser(user.id);
expect(rows.map((r) => r.client_name)).toEqual(['Client B', 'Client A']);
expect(rows[0].scopes).toBeDefined();
});
it('OAUTHTOKREPO-022c: created_at NULL comes back null, not undefined (coverage: rule 16)', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-22null');
const id = await seedToken({ clientId: 'proto-22null', userId: user.id });
await updateRows(t, OauthTokens, { id }, { created_at: null });
const rows = await tokens.listActiveByUser(user.id);
expect(rows[0].created_at).toBeNull();
});
});
describe('findOwnedById (OA27)', () => {
it('OAUTHTOKREPO-023: matches id+user', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-23');
const id = await seedToken({ clientId: 'proto-23', userId: user.id });
expect(await tokens.findOwnedById(id, user.id)).toEqual({ id, client_id: 'proto-23' });
});
it("OAUTHTOKREPO-024: 404-shape null for another user's session", async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await seedClient(other.id, 'proto-24');
const id = await seedToken({ clientId: 'proto-24', userId: other.id });
expect(await tokens.findOwnedById(id, user.id)).toBeNull();
});
});
describe('listAllActiveWithClientAndUser (OA31) — the admin panel', () => {
it('OAUTHTOKREPO-025: lists every active session across all users, with client name and username joined in', async () => {
const { user: a } = createUser(testDb, { username: 'admin-panel-a' });
const { user: b } = createUser(testDb, { username: 'admin-panel-b' });
await seedClient(a.id, 'proto-25a', 'Client A');
await seedClient(b.id, 'proto-25b', 'Client B');
await seedToken({ clientId: 'proto-25a', userId: a.id });
await seedToken({ clientId: 'proto-25b', userId: b.id, revokedAt: '2020-01-01 00:00:00' }); // excluded
const rows = await tokens.listAllActiveWithClientAndUser();
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({ client_name: 'Client A', username: 'admin-panel-a', user_id: a.id });
});
it('OAUTHTOKREPO-025b: created_at NULL comes back null, not undefined (coverage: rule 16)', async () => {
const { user } = createUser(testDb, { username: 'admin-panel-null' });
await seedClient(user.id, 'proto-25null', 'Client Null');
const id = await seedToken({ clientId: 'proto-25null', userId: user.id });
await updateRows(t, OauthTokens, { id }, { created_at: null });
const rows = await tokens.listAllActiveWithClientAndUser();
expect(rows.find((r) => r.id === id)?.created_at).toBeNull();
});
});
describe('findById (OA32)', () => {
it('OAUTHTOKREPO-026: unscoped by owner — for the admin 404 check', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-26');
const id = await seedToken({ clientId: 'proto-26', userId: user.id });
expect(await tokens.findById(id)).toEqual({ id, user_id: user.id, client_id: 'proto-26' });
});
it('OAUTHTOKREPO-027: null for an unknown id', async () => {
expect(await tokens.findById(999999)).toBeNull();
});
});
describe('revokeAllForUser (AU18/AU46 — built now for Task 5)', () => {
it('OAUTHTOKREPO-028: revokes every live session for the user, across every client, leaves other users untouched', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await seedClient(user.id, 'proto-28a');
await seedClient(user.id, 'proto-28b');
await seedClient(other.id, 'proto-28c');
const idA = await seedToken({ clientId: 'proto-28a', userId: user.id });
const idB = await seedToken({ clientId: 'proto-28b', userId: user.id });
const idAlready = await seedToken({ clientId: 'proto-28a', userId: user.id, revokedAt: '2020-01-01 00:00:00' });
const idOther = await seedToken({ clientId: 'proto-28c', userId: other.id });
await tokens.revokeAllForUser(user.id);
expect(await revokedAtOf(idA)).not.toBeNull();
expect(await revokedAtOf(idB)).not.toBeNull();
expect(await revokedAtOf(idAlready)).toBe('2020-01-01 00:00:00');
expect(await revokedAtOf(idOther)).toBeNull();
});
});
describe('client relation join (Plan 3b interlude A — RULE11_referencedColumns)', () => {
it('OAUTHTOKREPO-030: a QueryBuilder join on the client relation resolves the right client, even though oauth_clients.id !== client_id', async () => {
const { user } = createUser(testDb);
// seedClient's own `id` ("row-<clientId>") is already never equal to
// `client_id` — this test additionally asserts the two literally
// differ, so a future fixture change can't silently make the
// distinction disappear and hide a regression.
await seedClient(user.id, 'proto-30', 'Client Thirty');
const clientRow = await findRow(t, OauthClients, { client_id: 'proto-30' });
expect(clientRow?.id).not.toBe(clientRow?.client_id);
const id = await seedToken({ clientId: 'proto-30', userId: user.id });
const em = t.orm.em.fork();
const qb = em
.getRepository(OauthTokens)
.qb('ot')
.innerJoin('ot.client', 'oc')
.select(['ot.id', 'oc.name as client_name'])
.where({ 'ot.id': id });
expect(qb.getFormattedQuery()).toContain(
'inner join `oauth_clients` as `oc` on `ot`.`client_id` = `oc`.`client_id`',
);
const row = await qb.execute<{ id: number; client_name: string }>('get', false);
expect(row).toEqual({ id, client_name: 'Client Thirty' });
});
it('OAUTHTOKREPO-031: a DECOY client whose row id equals the real client_id — regression-proofs the join against silently falling back to oauth_clients.id (task-4-review.md, "For Task 5 / interlude A")', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-31-real', 'Real Client');
const realClientRow = await findRow(t, OauthClients, { client_id: 'proto-31-real' });
if (!realClientRow) throw new Error('the real client should be seeded');
// The decoy's own PRIMARY KEY (`id`) is deliberately set to the REAL
// client's `client_id` — a wrong join (`oc.id = ot.client_id`, the pre-
// Rule-11 defect) would match THIS row instead of the real one, and
// return the decoy's name, not silently return nothing. A regression
// to the wrong column is caught by a WRONG answer, not just an absent
// one — the strongest form of this proof.
await insertRow(t, OauthClients, {
id: realClientRow.client_id,
user: user.id,
name: 'Decoy Client',
client_id: 'proto-31-decoy',
client_secret_hash: 'hash',
redirect_uris: '[]',
allowed_scopes: '[]',
});
const id = await seedToken({ clientId: 'proto-31-real', userId: user.id });
const em = t.orm.em.fork();
const qb = em
.getRepository(OauthTokens)
.qb('ot')
.innerJoin('ot.client', 'oc')
.select(['ot.id', 'oc.name as client_name'])
.where({ 'ot.id': id });
const row = await qb.execute<{ id: number; client_name: string }>('get', false);
expect(row).toEqual({ id, client_name: 'Real Client' });
// Same proof through the actual repository methods (OA26/OA31), not
// just a hand-rolled QueryBuilder query.
const active = await tokens.listActiveByUser(user.id);
expect(active.map((r) => r.client_name)).toEqual(['Real Client']);
const allActive = await tokens.listAllActiveWithClientAndUser();
expect(allActive.map((r) => r.client_name)).toEqual(['Real Client']);
});
});
describe('identity-map write-back regression (program RULING, D-shape)', () => {
it('OAUTHTOKREPO-029: findByRefreshTokenHash (projection A) then findParent (projection B) then revokeById inside uow.transactional — the write survives', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'proto-29');
const id = await seedToken({
clientId: 'proto-29',
userId: user.id,
refreshHash: 'refresh-29',
scopes: '["kept-scope"]',
});
await withRequestContext(t.orm, async () => {
// Projection A — a wide fields set (id, client, user, scopes, audience, refresh_token_expires_at, revoked_at, parentToken).
await tokens.findByRefreshTokenHash('refresh-29');
// Projection B — a narrow, DIFFERENT field set on the same row.
await tokens.findParent(id);
// The intended write, inside the request's own transaction.
await uow.transactional(async () => {
await tokens.revokeById(id);
});
});
const row = await tokenRow(id);
expect(row.revoked_at).not.toBeNull(); // the nativeUpdate must stick
expect(row.scopes).toBe('["kept-scope"]'); // untouched by either read
});
});
describe('deleteExpiredBefore (retention)', () => {
const longAgo = '2026-01-01 00:00:00';
const cutoff = dbNow(new Date('2026-06-01T00:00:00.000Z'));
const ids = async () => (await findRows(t, OauthTokens, {}, { id: 'asc' })).map((r) => r.id);
it('OAUTHTOKREPO-040: deletes a whole expired chain, parents after their children', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'ret-1');
const root = await seedToken({
clientId: 'ret-1',
userId: user.id,
refreshExpiresAt: longAgo,
revokedAt: longAgo,
});
const mid = await seedToken({
clientId: 'ret-1',
userId: user.id,
refreshExpiresAt: longAgo,
revokedAt: longAgo,
parentId: root,
});
await seedToken({ clientId: 'ret-1', userId: user.id, refreshExpiresAt: longAgo, parentId: mid });
expect(await withRequestContext(t.orm, () => tokens.deleteExpiredBefore(cutoff))).toBe(3);
expect(await ids()).toEqual([]);
});
it('OAUTHTOKREPO-041: keeps an expired parent while a live token still names it', async () => {
const { user } = createUser(testDb);
await seedClient(user.id, 'ret-2');
const root = await seedToken({
clientId: 'ret-2',
userId: user.id,
refreshExpiresAt: longAgo,
revokedAt: longAgo,
});
const live = await seedToken({ clientId: 'ret-2', userId: user.id, parentId: root });
const unrelated = await seedToken({ clientId: 'ret-2', userId: user.id, refreshExpiresAt: longAgo });
expect(await withRequestContext(t.orm, () => tokens.deleteExpiredBefore(cutoff))).toBe(1);
expect(await ids()).toEqual([root, live].sort((a, b) => a - b));
expect(await ids()).not.toContain(unrelated);
});
});
});
@@ -0,0 +1,114 @@
/**
* Plan 4 Task 8b-4a (3h L4) — full-key `toEqual(<legacy raw>)` parity for
* `PackingItemsRepository.listPublicForShare` (`share.service.ts:386` SH13),
* flagged by the 3h ledger as having no repository-level parity test. The
* legacy statement (PackingItems.repository.ts's own docstring): `SELECT *
* FROM packing_items WHERE trip_id = ? AND is_private = 0 ORDER BY
* sort_order ASC` — a public share viewer is neither owner nor recipient,
* so a Personal or Shared-with-people item (`is_private = 1`) must never
* surface, regardless of `owner_id`/recipient rows (the `_shared/packing-
* visibility.ts` three-tier model this method deliberately does NOT route
* through — it only ever sees the Common tier).
*/
import { PackingItems } from '../../../../src/db/entities/PackingItems.entity';
import type { PackingItemsRepository } from '../../../../src/db/repositories/PackingItems.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createPackingItem, createTrip, createUser } from '../../../helpers/factories';
import { addPackingItemRecipients } from '../../../helpers/factories/packing';
import { updateRows } from '../../../helpers/factories/rows';
import { createTestPackingItemsRepo } from '../../../helpers/packing-repos';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let packingItemsRepo: PackingItemsRepository;
let t: TestOrm;
beforeAll(async () => {
packingItemsRepo = await createTestPackingItemsRepo(testDb);
t = await createTestOrm(testDb);
});
beforeEach(() => resetTestDb(testDb));
afterAll(async () => {
await t.close();
testDb.close();
});
function legacyPublicForShare(tripId: number): unknown {
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
return testDb
.prepare('SELECT * FROM packing_items WHERE trip_id = ? AND is_private = 0 ORDER BY sort_order ASC')
.all(tripId);
}
describe('PackingItemsRepository — share.service.ts SH13 read', () => {
it('listPublicForShare — matches the legacy statement, Common items only, every nullable column both null and set', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const other = createTrip(testDb, owner.id);
// Common, every nullable column set.
const commonFull = createPackingItem(testDb, trip.id, { name: 'Tent', category: 'Gear' });
await updateRows(
t,
PackingItems,
{ id: commonFull.id },
{
checked: 1,
sort_order: 5,
weight_grams: 1200,
bag: null,
quantity: 2,
updated_at: '2026-09-01T00:00:00.000Z',
is_private: 0,
owner: owner.id,
},
);
// Common, every nullable column left null.
const commonBare = createPackingItem(testDb, trip.id, { name: 'Rope' });
await updateRows(
t,
PackingItems,
{ id: commonBare.id },
{
category: null,
sort_order: null,
weight_grams: null,
bag: null,
updated_at: null,
is_private: 0,
owner: null,
},
);
// Personal (is_private = 1, owned) — must be excluded even though it has an owner.
const personal = createPackingItem(testDb, trip.id, { name: 'Passport' });
await updateRows(t, PackingItems, { id: personal.id }, { is_private: 1, owner: owner.id });
// Shared-with-people (is_private = 1, has a recipient) — must be excluded too.
const shared = createPackingItem(testDb, trip.id, { name: 'First aid kit' });
await updateRows(t, PackingItems, { id: shared.id }, { is_private: 1, owner: owner.id });
await addPackingItemRecipients(t, shared.id, [owner.id]);
// A Common item on a different trip must never leak in.
const foreign = createPackingItem(testDb, other.id, { name: 'Foreign item' });
await updateRows(t, PackingItems, { id: foreign.id }, { is_private: 0 });
const legacy = legacyPublicForShare(trip.id);
const typed = await packingItemsRepo.listPublicForShare(trip.id);
expect(typed).toEqual(legacy);
// ORDER BY sort_order ASC: commonBare (default sort_order 0) before commonFull (sort_order 5).
expect(typed.map((r) => r.id)).toEqual([commonBare.id, commonFull.id]);
});
it('listPublicForShare — [] for a trip with no Common items', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const personalOnly = createPackingItem(testDb, trip.id);
await updateRows(t, PackingItems, { id: personalOnly.id }, { is_private: 1 });
expect(await packingItemsRepo.listPublicForShare(trip.id)).toEqual([]);
});
});
@@ -0,0 +1,211 @@
/**
* The two repositories of PAD-05A: `paddle_regions` (the regions an admin
* chose, their queue and their state) and `paddle_features` (a region's
* objects, found by box and replaced whole).
*/
import { PaddleFeatures } from '../../../../src/db/entities/PaddleFeatures.entity';
import { PaddleRegions } from '../../../../src/db/entities/PaddleRegions.entity';
import type {
PaddleFeatureRow,
PaddleFeaturesRepository,
} from '../../../../src/db/repositories/PaddleFeatures.repository';
import type { PaddleRegionsRepository } from '../../../../src/db/repositories/PaddleRegions.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { countRows, findRow, findRows, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let regions: PaddleRegionsRepository;
let features: PaddleFeaturesRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
regions = t.repo(PaddleRegions);
features = t.repo(PaddleFeatures);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const box = { min_lat: 49, min_lng: 12, max_lat: 50, max_lng: 13 };
const add = (id: string, name = id) => regions.insertRegion({ id, name, boundary: null, ...box });
const feature = (ref: string, lat: number, lng: number): PaddleFeatureRow => ({
region_id: 'ignored',
osm_ref: ref,
kind: 'weir',
group_key: null,
name: null,
geometry: JSON.stringify({ type: 'Point', coordinates: [lng, lat] }),
tags: '{}',
tag_hash: ref,
min_lat: lat,
min_lng: lng,
max_lat: lat,
max_lng: lng,
});
describe('PaddleRegionsRepository', () => {
it('PADREGREPO-001: a region is added queued and empty; adding it again changes nothing', async () => {
await add('oberpfalz', 'Oberpfalz');
await regions.updateRegion('oberpfalz', { status: 'ready', feature_count: 3 });
await add('oberpfalz', 'Renamed');
expect(await regions.findById('oberpfalz')).toMatchObject({
id: 'oberpfalz',
name: 'Oberpfalz',
status: 'ready',
feature_count: 3,
...box,
});
expect(await regions.findById('nowhere')).toBeUndefined();
});
it('PADREGREPO-002: lists by name; the queue answers the oldest waiting region first', async () => {
await add('b', 'Bayern');
await add('a', 'Allgäu');
await updateRows(t, PaddleRegions, { id: 'b' }, { created_at: '2026-01-01 00:00:00' });
await updateRows(t, PaddleRegions, { id: 'a' }, { created_at: '2026-02-01 00:00:00' });
expect((await regions.list()).map((row) => row.name)).toEqual(['Allgäu', 'Bayern']);
expect((await regions.nextQueued())?.id).toBe('b');
await regions.updateRegion('b', { status: 'importing' });
expect((await regions.nextQueued())?.id).toBe('a');
await regions.updateRegion('a', { status: 'ready' });
expect(await regions.nextQueued()).toBeUndefined();
});
it('PADREGREPO-003: only regions holding data whose box reaches in count for a box', async () => {
await add('read');
await add('waiting');
await add('elsewhere');
await regions.updateRegion('read', { status: 'importing', imported_at: '2026-10-02 04:20:00' });
await regions.updateRegion('elsewhere', {
imported_at: '2026-10-02 04:20:00',
min_lat: 53,
max_lat: 54,
min_lng: 12,
max_lng: 13,
});
const inBox = await regions.withDataInBox({ south: 49.5, west: 12.5, north: 49.6, east: 12.6 });
expect(inBox.map((row) => row.id)).toEqual(['read']);
});
it('PADREGREPO-004: the monthly refresh queues ready and failed regions and clears their error', async () => {
await add('ready');
await add('failed');
await add('queued');
await regions.updateRegion('ready', { status: 'ready' });
await regions.updateRegion('failed', { status: 'failed', error: 'Geofabrik download 500' });
expect(await regions.queueReady()).toBe(2);
expect(await findRows(t, PaddleRegions, {}, { id: 'asc' })).toMatchObject([
{ id: 'failed', status: 'queued', error: null },
{ id: 'queued', status: 'queued' },
{ id: 'ready', status: 'queued' },
]);
});
it('PADREGREPO-005: a cut read goes back to the queue; removing a region takes its objects', async () => {
await add('oberpfalz');
await regions.updateRegion('oberpfalz', { status: 'importing' });
await regions.requeueInterrupted();
expect((await regions.findById('oberpfalz'))?.status).toBe('queued');
await features.replaceRegion('oberpfalz', [feature('node/1', 49.5, 12.5)]);
expect(await regions.deleteRegion('oberpfalz')).toBe(true);
expect(await regions.deleteRegion('oberpfalz')).toBe(false);
expect(await countRows(t, PaddleFeatures)).toBe(0);
});
});
describe('PaddleFeaturesRepository', () => {
it('PADFEATREPO-001: replaces a region whole, chunk by chunk, and leaves other regions alone', async () => {
await add('oberpfalz');
await add('bayern');
await features.replaceRegion('bayern', [feature('node/9', 49.5, 12.5)]);
const many = Array.from({ length: 450 }, (_, i) => feature(`node/${i + 1}`, 49 + i / 1000, 12.5));
await features.replaceRegion('oberpfalz', many);
expect(await countRows(t, PaddleFeatures, { region: 'oberpfalz' })).toBe(450);
await features.replaceRegion('oberpfalz', [feature('node/1', 49.5, 12.5), feature('node/1', 49.5, 12.5)]);
expect(await countRows(t, PaddleFeatures, { region: 'oberpfalz' })).toBe(1);
expect(await countRows(t, PaddleFeatures, { region: 'bayern' })).toBe(1);
expect(await findRow(t, PaddleFeatures, { region: 'oberpfalz' })).toMatchObject({ osm_ref: 'node/1' });
await features.replaceRegion('oberpfalz', []);
expect(await countRows(t, PaddleFeatures, { region: 'oberpfalz' })).toBe(0);
});
it('PADFEATREPO-002: finds the objects whose box reaches into the box, in a stable order, at most the limit', async () => {
await add('oberpfalz');
await features.replaceRegion('oberpfalz', [
feature('node/1', 49.5, 12.5),
feature('node/2', 49.55, 12.55),
feature('node/3', 49.9, 12.9),
{
...feature('way/4', 49.4, 12.4),
geometry: JSON.stringify({
type: 'LineString',
coordinates: [
[12.4, 49.4],
[12.6, 49.6],
],
}),
max_lat: 49.6,
max_lng: 12.6,
},
]);
const inside = await features.findInBox({ south: 49.45, west: 12.45, north: 49.6, east: 12.6 }, 10);
expect(inside.map((row) => row.osm_ref)).toEqual(['node/1', 'node/2', 'way/4']);
expect(inside[0]).toMatchObject({ region_id: 'oberpfalz', kind: 'weir', tag_hash: 'node/1' });
const capped = await features.findInBox({ south: 49, west: 12, north: 50, east: 13 }, 2);
expect(capped.map((row) => row.osm_ref)).toEqual(['node/1', 'node/2']);
});
it('PADFEATREPO-003: counts the objects and names the newest row, nothing for an empty table', async () => {
expect(await features.stats()).toEqual({ count: 0, max_id: null });
await add('oberpfalz');
await features.replaceRegion('oberpfalz', [feature('node/1', 49.5, 12.5), feature('node/2', 49.6, 12.6)]);
const stats = await features.stats();
expect(stats.count).toBe(2);
expect(stats.max_id).toEqual(expect.any(Number));
});
it('PADFEATREPO-004: reads only the parts of the given locks inside a box', async () => {
await add('oberpfalz');
await features.replaceRegion('oberpfalz', [
{ ...feature('node/1', 49.5, 12.5), group_key: 'lock:node/1' },
{ ...feature('node/2', 49.51, 12.5), group_key: 'lock:node/1' },
{ ...feature('node/3', 49.52, 12.5), group_key: 'lock:node/3' },
{ ...feature('node/4', 49.9, 12.5), group_key: 'lock:node/1' },
]);
const parts = await features.findGroupParts(
['lock:node/1'],
{ south: 49.4, west: 12.4, north: 49.6, east: 12.6 },
10,
);
expect(parts.map((row) => row.osm_ref)).toEqual(['node/1', 'node/2']);
});
it('PADREGREPO-010: names when each region was last read, without its boundary', async () => {
await add('oberpfalz');
await add('bayern');
await regions.updateRegion('oberpfalz', { status: 'ready', imported_at: '2026-10-02 04:20:00' });
expect(await regions.readTimes()).toEqual([
{ id: 'bayern', imported_at: null },
{ id: 'oberpfalz', imported_at: '2026-10-02 04:20:00' },
]);
});
});
@@ -0,0 +1,88 @@
/**
* `PaddleWaterGraphsRepository` (PAD-11): the water network each paddle
* region built for routing, recorded, found by the point it covers, and
* forgotten when its file is gone.
*/
import { PaddleRegions } from '../../../../src/db/entities/PaddleRegions.entity';
import { PaddleWaterGraphs } from '../../../../src/db/entities/PaddleWaterGraphs.entity';
import type { PaddleRegionsRepository } from '../../../../src/db/repositories/PaddleRegions.repository';
import type { PaddleWaterGraphsRepository } from '../../../../src/db/repositories/PaddleWaterGraphs.repository';
import { dbNow } from '../../../../src/db/types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let graphs: PaddleWaterGraphsRepository;
let regions: PaddleRegionsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
graphs = t.repo(PaddleWaterGraphs);
regions = t.repo(PaddleRegions);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const box = (min: number, max: number) => ({ min_lat: min, min_lng: min, max_lat: max, max_lng: max });
async function region(id: string, min: number, max: number, file = `${id}.bin`) {
await regions.insertRegion({ id, name: id, boundary: null, ...box(min, max) });
await graphs.saveGraph({
region_id: id,
file,
rev: 'r1',
bytes: 10,
built_at: dbNow(),
stats: '{}',
...box(min, max),
});
}
describe('PaddleWaterGraphsRepository (PAD-11)', () => {
it('PWG-001: records a network, replaces it when built again, and lists them by region', async () => {
await region('b', 10, 20);
await region('a', 0, 5);
await graphs.saveGraph({
region_id: 'a',
file: 'a2.bin',
rev: 'r2',
bytes: 20,
built_at: dbNow(),
stats: '{"n":1}',
...box(0, 6),
});
expect((await graphs.list()).map((row) => [row.region_id, row.file, row.rev])).toEqual([
['a', 'a2.bin', 'r2'],
['b', 'b.bin', 'r1'],
]);
expect(await graphs.findByRegion('a')).toMatchObject({ file: 'a2.bin', max_lat: 6 });
expect(await graphs.findByRegion('none')).toBeUndefined();
});
it('PWG-002: finds the networks whose box holds a point, the smallest box first', async () => {
await region('wide', 0, 20);
await region('local', 4, 6);
await region('far', 30, 40);
expect((await graphs.coveringPoint(5, 5)).map((row) => row.region_id)).toEqual(['local', 'wide']);
expect(await graphs.coveringPoint(25, 25)).toEqual([]);
});
it('PWG-003: forgets a network whose file is gone, but not one built again under another name', async () => {
await region('lake', 0, 5, 'lake-1.bin');
expect(await graphs.forgetMissing('lake', 'lake-0.bin')).toBe(false);
expect(await graphs.findByRegion('lake')).toBeDefined();
expect(await graphs.forgetMissing('lake', 'lake-1.bin')).toBe(true);
expect(await graphs.findByRegion('lake')).toBeUndefined();
expect(await graphs.forgetMissing('lake', 'lake-1.bin')).toBe(false);
});
});
@@ -0,0 +1,259 @@
import { PasswordResetTokens } from '../../../../src/db/entities/PasswordResetTokens.entity';
import type { PasswordResetTokensRepository } from '../../../../src/db/repositories/PasswordResetTokens.repository';
import { dbNow } from '../../../../src/db/types';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createUser } from '../../../helpers/factories';
import { findRow, insertRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { createHash } from 'crypto';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let tokens: PasswordResetTokensRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
tokens = t.repo(PasswordResetTokens);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function hash(raw: string): string {
return createHash('sha256').update(raw).digest('hex');
}
async function rawRow(id: number) {
const row = await findRow(t, PasswordResetTokens, { id });
if (!row) throw new Error(`no password reset token ${id}`);
return row;
}
async function seedToken(
userId: number,
tokenHash: string,
opts: { expires_at?: string; consumed_at?: string | null; created_ip?: string | null } = {},
): Promise<number> {
const expiresAt = opts.expires_at ?? new Date(Date.now() + 60 * 60 * 1000).toISOString();
return insertRow(t, PasswordResetTokens, {
user: userId,
token_hash: tokenHash,
expires_at: expiresAt,
consumed_at: opts.consumed_at ?? null,
created_ip: opts.created_ip ?? null,
});
}
describe('PasswordResetTokensRepository', () => {
describe('insertToken', () => {
it('PWDRESETREPO-001: writes the exact column set, hash-only (the raw token never appears)', async () => {
const { user } = createUser(testDb);
const tokenHash = hash('raw-token-value');
const expiresAt = dbNow(new Date(Date.now() + 60 * 60 * 1000));
await tokens.insertToken({
user_id: user.id,
token_hash: tokenHash,
expires_at: expiresAt,
created_ip: '1.2.3.4',
});
const row = await findRow(t, PasswordResetTokens, { token_hash: tokenHash });
expect(row).toMatchObject({
user_id: user.id,
token_hash: tokenHash,
expires_at: expiresAt,
consumed_at: null,
created_ip: '1.2.3.4',
});
});
it('PWDRESETREPO-002: writes a NULL created_ip', async () => {
const { user } = createUser(testDb);
const tokenHash = hash('no-ip-token');
await tokens.insertToken({ user_id: user.id, token_hash: tokenHash, expires_at: dbNow(), created_ip: null });
const row = await findRow(t, PasswordResetTokens, { token_hash: tokenHash });
expect(row?.created_ip).toBeNull();
});
});
describe('findByTokenHash', () => {
it('PWDRESETREPO-003: finds a live token by its hash', async () => {
const { user } = createUser(testDb);
const tokenHash = hash('lookup-me');
const id = await seedToken(user.id, tokenHash);
const found = await tokens.findByTokenHash(tokenHash);
expect(found).toEqual({ id, user_id: user.id, expires_at: expect.any(String), consumed_at: null });
});
it('PWDRESETREPO-004: a consumed token is still found (consumed_at is checked by the caller, not filtered here)', async () => {
const { user } = createUser(testDb);
const tokenHash = hash('already-used');
await seedToken(user.id, tokenHash, { consumed_at: '2026-01-01T00:00:00.000Z' });
const found = await tokens.findByTokenHash(tokenHash);
expect(found?.consumed_at).toBe('2026-01-01T00:00:00.000Z');
});
it('PWDRESETREPO-005: an unknown hash is null', async () => {
expect(await tokens.findByTokenHash(hash('never-issued'))).toBeNull();
});
});
describe('markConsumed', () => {
it('PWDRESETREPO-006: stamps consumed_at on the target row only', async () => {
const { user } = createUser(testDb);
const target = await seedToken(user.id, hash('mark-me'));
const other = await seedToken(user.id, hash('leave-me'));
await tokens.markConsumed(target);
expect((await rawRow(target)).consumed_at).not.toBeNull();
expect((await rawRow(other)).consumed_at).toBeNull();
});
});
describe('consumeAllLiveForUser', () => {
it('PWDRESETREPO-007: without an exclusion, burns every live token for the user', async () => {
const { user } = createUser(testDb);
const a = await seedToken(user.id, hash('a'));
const b = await seedToken(user.id, hash('b'));
await tokens.consumeAllLiveForUser(user.id);
expect((await rawRow(a)).consumed_at).not.toBeNull();
expect((await rawRow(b)).consumed_at).not.toBeNull();
});
it('PWDRESETREPO-008: with an exclusion, burns every OTHER live token but leaves the excluded id alone', async () => {
const { user } = createUser(testDb);
const keep = await seedToken(user.id, hash('keep-me'));
const burn1 = await seedToken(user.id, hash('burn-1'));
const burn2 = await seedToken(user.id, hash('burn-2'));
await tokens.consumeAllLiveForUser(user.id, keep);
expect((await rawRow(keep)).consumed_at).toBeNull();
expect((await rawRow(burn1)).consumed_at).not.toBeNull();
expect((await rawRow(burn2)).consumed_at).not.toBeNull();
});
it("PWDRESETREPO-009: never touches another user's tokens or an already-consumed row", async () => {
const { user: victim } = createUser(testDb);
const { user: bystander } = createUser(testDb);
const already = await seedToken(victim.id, hash('already-consumed'), { consumed_at: '2026-01-01T00:00:00.000Z' });
const bystanderToken = await seedToken(bystander.id, hash('bystander'));
await tokens.consumeAllLiveForUser(victim.id);
// The already-consumed row's consumed_at is untouched (still the original
// stamp, not overwritten by this call — the WHERE only matches consumed_at
// IS NULL rows).
expect((await rawRow(already)).consumed_at).toBe('2026-01-01T00:00:00.000Z');
expect((await rawRow(bystanderToken)).consumed_at).toBeNull();
});
});
// ---------------------------------------------------------------------
// Identity-map isolation (Plan 3b Task 5 ruling — every row-out read
// passes `disableIdentityMap: true`, applied by `TrekRepository`'s
// default). This repository has only ONE entity-hydrating read method
// (`findByTokenHash`) — unlike `McpTokensRepository`/`Users.repository.ts`,
// which each have two differently-projected NAMED read methods to
// combine. PWDRESETREPO-010 is the structural proof (no managed entity
// left behind); PWDRESETREPO-011 pins the REAL call shape (`findByTokenHash`
// then `markConsumed` inside the same `uow.transactional`) as safe under
// the shipped default, but — by construction — it CANNOT fail: a single
// managed read re-snapshots every field it names, so nothing is dirty at
// the closing flush regardless of whether the mechanism exists on this
// table. It is not, on its own, proof the B1 stale-write-back mechanism
// (`task-1-review.md` B1) is absent here.
//
// Task 5's original report tried a THIRD test — two raw `find`/`findOne`
// calls with disjoint field sets, `disableIdentityMap: false` — and did
// not reproduce it. `task-5-review-template.md` T2 found that attempt used
// the ordering `task-4-review.md` F1 already showed is non-load-bearing
// (narrower projection first). The mechanism DOES reproduce on this table
// once the WIDER projection — the one carrying the written column,
// `consumed_at` — runs FIRST: PWDRESETREPO-012 pairs this repository's own
// read (projection A, wide) with a narrower **managed** `em.findOne`
// (projection B) and is mutation-proved (green here, red once
// `findByTokenHash` is forced to `disableIdentityMap: false, refresh:
// true` — see the fix report). PWDRESETREPO-013 repeats the shape for
// `consumeAllLiveForUser`, the repository's other write method.
// ---------------------------------------------------------------------
describe('identity-map isolation', () => {
it('PWDRESETREPO-010: findByTokenHash never leaves a managed entity behind', async () => {
const { user } = createUser(testDb);
const id = await seedToken(user.id, hash('isolated'));
await tokens.findByTokenHash(hash('isolated'));
expect(t.em.getUnitOfWork().getById(PasswordResetTokens, id)).toBeUndefined();
});
it('PWDRESETREPO-011: findByTokenHash then markConsumed inside uow.transactional survives the closing flush (cannot fail by construction — see PWDRESETREPO-012 for the mutation-proved guard)', async () => {
const { user } = createUser(testDb);
const id = await seedToken(user.id, hash('survives'));
const uow = new UnitOfWork(t.em);
await uow.transactional(async () => {
const found = await tokens.findByTokenHash(hash('survives'));
expect(found?.consumed_at).toBeNull();
await tokens.markConsumed(id);
});
expect((await rawRow(id)).consumed_at).not.toBeNull();
});
it('PWDRESETREPO-012: findByTokenHash is the FIRST, wider read (it carries consumed_at); a narrower managed read follows; markConsumed still lands', async () => {
const { user } = createUser(testDb);
const id = await seedToken(user.id, hash('dshape'));
const uow = new UnitOfWork(t.em);
await uow.transactional(async () => {
await tokens.findByTokenHash(hash('dshape')); // projection A — WIDE (carries consumed_at)
await t.em.findOne(
PasswordResetTokens,
{ id },
{ fields: ['id', 'token_hash'], refresh: true, disableIdentityMap: false },
); // projection B — NARROW, managed
await tokens.markConsumed(id);
});
expect((await rawRow(id)).consumed_at).not.toBeNull();
});
it('PWDRESETREPO-013: same D-shape guard for consumeAllLiveForUser', async () => {
const { user } = createUser(testDb);
const id = await seedToken(user.id, hash('dshape-consume-all'));
const uow = new UnitOfWork(t.em);
await uow.transactional(async () => {
await tokens.findByTokenHash(hash('dshape-consume-all')); // projection A — WIDE (carries consumed_at)
await t.em.findOne(
PasswordResetTokens,
{ id },
{ fields: ['id', 'token_hash'], refresh: true, disableIdentityMap: false },
); // projection B — NARROW, managed
await tokens.consumeAllLiveForUser(user.id);
});
expect((await rawRow(id)).consumed_at).not.toBeNull();
});
});
});
@@ -0,0 +1,209 @@
import { PhotoProviderFields } from '../../../../src/db/entities/PhotoProviderFields.entity';
import { PhotoProviders } from '../../../../src/db/entities/PhotoProviders.entity';
import type { PhotoProviderFieldsRepository } from '../../../../src/db/repositories/PhotoProviderFields.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { deleteRows, insertRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let fields: PhotoProviderFieldsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
fields = t.repo(PhotoProviderFields);
});
beforeEach(async () => {
resetTestDb(testDb);
await deleteRows(t, PhotoProviderFields);
await deleteRows(t, PhotoProviders);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function insertProvider(id: string): Promise<void> {
await insertRow(t, PhotoProviders, { id, name: id, icon: 'Image', enabled: 1, sort_order: 0 });
}
async function insertField(row: {
provider_id: string;
field_key: string;
label: string;
input_type?: string;
placeholder?: string | null;
hint?: string | null;
required?: 0 | 1;
secret?: 0 | 1;
settings_key?: string | null;
payload_key?: string | null;
sort_order?: number;
}): Promise<void> {
await insertRow(t, PhotoProviderFields, {
provider: row.provider_id,
field_key: row.field_key,
label: row.label,
input_type: row.input_type ?? 'text',
placeholder: row.placeholder ?? null,
hint: row.hint ?? null,
required: row.required ?? 0,
secret: row.secret ?? 0,
settings_key: row.settings_key ?? null,
payload_key: row.payload_key ?? null,
sort_order: row.sort_order ?? 0,
});
}
describe('PhotoProviderFieldsRepository.listAllOrdered', () => {
it('ADDONSPPFREPO-001: returns every field, ordered by sort_order then id, across all providers', async () => {
await insertProvider('immich');
await insertProvider('synology');
await insertField({ provider_id: 'synology', field_key: 'url', label: 'URL', sort_order: 1 });
await insertField({ provider_id: 'immich', field_key: 'url', label: 'URL', sort_order: 0 });
await insertField({ provider_id: 'immich', field_key: 'token', label: 'Token', sort_order: 0 });
const rows = await fields.listAllOrdered();
// Two rows share sort_order 0 — insertion order (ascending id) breaks the tie.
expect(rows.map((r) => [r.provider_id, r.field_key])).toEqual([
['immich', 'url'],
['immich', 'token'],
['synology', 'url'],
]);
});
it('ADDONSPPFREPO-002: the provider_id twin reads back from find(), same as trip_id on Days', async () => {
await insertProvider('immich');
await insertField({ provider_id: 'immich', field_key: 'url', label: 'URL' });
const [row] = await fields.listAllOrdered();
expect(row.provider_id).toBe('immich');
});
it('ADDONSPPFREPO-003: required/secret come back as the raw stored integer, matching the entity type (not a coerced boolean)', async () => {
await insertProvider('immich');
await insertField({ provider_id: 'immich', field_key: 'token', label: 'Token', required: 1, secret: 1 });
const [row] = await fields.listAllOrdered();
expect(row.required).toBe(1);
expect(row.secret).toBe(1);
expect(typeof row.required).toBe('number');
});
it('ADDONSPPFREPO-004: nullable columns (placeholder, hint, settings_key, payload_key) come back null when unset', async () => {
await insertProvider('immich');
await insertField({ provider_id: 'immich', field_key: 'k', label: 'L' });
const [row] = await fields.listAllOrdered();
expect(row.placeholder).toBeNull();
expect(row.hint).toBeNull();
expect(row.settings_key).toBeNull();
expect(row.payload_key).toBeNull();
});
it('ADDONSPPFREPO-005: an empty table returns an empty array', async () => {
expect(await fields.listAllOrdered()).toEqual([]);
});
});
describe('PhotoProviderFieldsRepository.listAllOrderedForAdminShelf', () => {
// Plan 3i Task 4 fix wave: `listAllOrderedForAdminShelf` used to project a
// bare `'provider_id'` — the `persist(false)` shadow of the `provider`
// relation — which MikroORM's `fields` selector never hydrates (same trap
// `RoadtripDayBoundariesRepository` and `TripPhotosRepository` document).
// Every row came back with `provider_id: undefined`, so `listAddons`
// grouped every photo provider's fields under `undefined` and every
// provider answered `fields: []`. Full-key parity against AD28's legacy
// `SELECT provider_id, field_key, label, input_type, placeholder,
// required, secret, settings_key, payload_key, sort_order FROM
// photo_provider_fields ORDER BY sort_order, id` pins every column, not
// just `provider_id`, so a future narrowed-projection regression on any
// other column fails here too.
it('AD28: returns the full legacy row shape, ordered by sort_order then id, across all providers', async () => {
await insertProvider('immich');
await insertProvider('synology');
await insertField({
provider_id: 'synology',
field_key: 'url',
label: 'Server URL',
input_type: 'text',
placeholder: 'https://photos.example.com',
hint: 'ignored: not in the AD28 shape',
required: 1,
secret: 0,
settings_key: 'synology_url',
payload_key: 'url',
sort_order: 1,
});
await insertField({
provider_id: 'immich',
field_key: 'url',
label: 'Server URL',
input_type: 'text',
placeholder: 'https://immich.example.com',
required: 1,
secret: 0,
settings_key: 'immich_url',
payload_key: 'url',
sort_order: 0,
});
await insertField({
provider_id: 'immich',
field_key: 'api_key',
label: 'API Key',
input_type: 'password',
required: 1,
secret: 1,
settings_key: 'immich_api_key',
payload_key: 'apiKey',
sort_order: 1,
});
const rows = await fields.listAllOrderedForAdminShelf();
// sort_order 0 first; the sort_order-1 tie breaks by id (insertion order:
// synology's url row was inserted before immich's api_key row).
expect(rows).toEqual([
{
provider_id: 'immich',
field_key: 'url',
label: 'Server URL',
input_type: 'text',
placeholder: 'https://immich.example.com',
required: 1,
secret: 0,
settings_key: 'immich_url',
payload_key: 'url',
sort_order: 0,
},
{
provider_id: 'synology',
field_key: 'url',
label: 'Server URL',
input_type: 'text',
placeholder: 'https://photos.example.com',
required: 1,
secret: 0,
settings_key: 'synology_url',
payload_key: 'url',
sort_order: 1,
},
{
provider_id: 'immich',
field_key: 'api_key',
label: 'API Key',
input_type: 'password',
placeholder: null,
required: 1,
secret: 1,
settings_key: 'immich_api_key',
payload_key: 'apiKey',
sort_order: 1,
},
]);
});
it('AD28: an empty table returns an empty array', async () => {
expect(await fields.listAllOrderedForAdminShelf()).toEqual([]);
});
});
@@ -0,0 +1,164 @@
import { PhotoProviders } from '../../../../src/db/entities/PhotoProviders.entity';
import type { PhotoProvidersRepository } from '../../../../src/db/repositories/PhotoProviders.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { findRow, insertRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let photoProviders: PhotoProvidersRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
photoProviders = t.repo(PhotoProviders);
});
beforeEach(() => {
resetTestDb(testDb);
// photo_provider_fields FK-references photo_providers, so clear the child
// first — resetTestDb keeps both tables (test-db.ts's KEEP_TABLES).
testDb.exec('DELETE FROM photo_provider_fields');
testDb.exec('DELETE FROM photo_providers');
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function storedRow(id: string) {
return findRow(t, PhotoProviders, { id });
}
async function insertProvider(row: {
id: string;
name: string;
description?: string | null;
icon?: string | null;
enabled: 0 | 1;
sort_order?: number;
}): Promise<void> {
await insertRow(t, PhotoProviders, {
id: row.id,
name: row.name,
description: row.description ?? null,
icon: row.icon ?? null,
enabled: row.enabled,
sort_order: row.sort_order ?? 0,
});
}
describe('PhotoProvidersRepository.listEnabled', () => {
it('ADDONSPPREPO-001: returns only enabled providers, ordered by sort_order then id', async () => {
await insertProvider({ id: 'synology', name: 'Synology', enabled: 1, sort_order: 0 });
await insertProvider({ id: 'immich', name: 'Immich', enabled: 1, sort_order: 0 });
await insertProvider({ id: 'off', name: 'Off', enabled: 0, sort_order: -1 });
const rows = await photoProviders.listEnabled();
// Same sort_order (0) for both enabled rows — id breaks the tie.
expect(rows.map((r) => r.id)).toEqual(['immich', 'synology']);
});
it('ADDONSPPREPO-002: the enabled column comes back as the raw stored integer, not a coerced boolean', async () => {
await insertProvider({ id: 'immich', name: 'Immich', enabled: 1 });
const [row] = await photoProviders.listEnabled();
expect(row.enabled).toBe(1);
expect(typeof row.enabled).toBe('number');
});
it('ADDONSPPREPO-003: an empty table returns an empty array', async () => {
expect(await photoProviders.listEnabled()).toEqual([]);
});
it('ADDONSPPREPO-004: carries the full row shape (id, name, description, icon, enabled, sort_order)', async () => {
await insertProvider({
id: 'immich',
name: 'Immich',
description: 'Self-hosted photos',
icon: 'image',
enabled: 1,
sort_order: 4,
});
const [row] = await photoProviders.listEnabled();
expect(row).toEqual({
id: 'immich',
name: 'Immich',
description: 'Self-hosted photos',
icon: 'image',
enabled: 1,
sort_order: 4,
});
expect(await storedRow('immich')).toMatchObject({ enabled: 1 });
});
});
describe('PhotoProvidersRepository.listAll / findEnabled', () => {
it('M1: listAll (the admin listing) returns every row regardless of enabled, unordered by that flag', async () => {
await insertProvider({ id: 'immich', name: 'Immich', enabled: 1 });
await insertProvider({ id: 'off', name: 'Off', enabled: 0 });
const rows = await photoProviders.listAll();
expect(rows.map((r) => r.id).sort()).toEqual(['immich', 'off']);
expect(rows.find((r) => r.id === 'off')?.enabled).toBe(0);
});
it('M1: findEnabled reads the enabled flag for a known provider and null for an unknown one', async () => {
await insertProvider({ id: 'synology', name: 'Synology', enabled: 1 });
expect(await photoProviders.findEnabled('synology')).toEqual({ enabled: 1 });
expect(await photoProviders.findEnabled('does-not-exist')).toBeNull();
});
});
// Plan 3i Task 4 fix wave (should-land 5): AD27 (listAllOrdered) and
// AD31/AD40 (findById) shipped in Task 1 with no repository-level test —
// full-key parity against the exact legacy SQL each method's own docstring
// names.
describe('PhotoProvidersRepository.listAllOrdered (AD27) / findById (AD31/AD40)', () => {
it('ADDONSPPREPO-005: listAllOrdered matches SELECT id, name, description, icon, enabled, sort_order FROM photo_providers ORDER BY sort_order, id — unfiltered, including a disabled provider', async () => {
await insertProvider({ id: 'off', name: 'Off', enabled: 0, sort_order: 1 });
await insertProvider({ id: 'immich', name: 'Immich', enabled: 1, sort_order: 0 });
// test-sql-allow: the legacy statement is the parity oracle the repository is compared against.
const legacy = testDb
.prepare('SELECT id, name, description, icon, enabled, sort_order FROM photo_providers ORDER BY sort_order, id')
.all();
const rows = await photoProviders.listAllOrdered();
expect(rows.map((r) => r.id)).toEqual(['immich', 'off']); // includes the disabled one, unlike listEnabled
expect(rows).toEqual(legacy);
});
it('ADDONSPPREPO-006: listAllOrdered on an empty table returns an empty array', async () => {
expect(await photoProviders.listAllOrdered()).toEqual([]);
});
it('ADDONSPPREPO-007: findById matches SELECT * FROM photo_providers WHERE id = ?, on both a pre-write read and a post-write re-select (byte-identical text at both call sites)', async () => {
await insertProvider({
id: 'immich',
name: 'Immich',
description: 'Self-hosted photos',
icon: 'image',
enabled: 0,
sort_order: 2,
});
const preWrite = await photoProviders.findById('immich');
expect(preWrite).toEqual({
id: 'immich',
name: 'Immich',
description: 'Self-hosted photos',
icon: 'image',
enabled: 0,
sort_order: 2,
});
// test-sql-allow: the out-of-band write this case is about has to bypass every EntityManager, the one under test included.
testDb.prepare('UPDATE photo_providers SET enabled = 1 WHERE id = ?').run('immich');
const postWrite = await photoProviders.findById('immich');
expect(postWrite?.enabled).toBe(1);
});
it('ADDONSPPREPO-008: findById on a missing id returns null', async () => {
expect(await photoProviders.findById('does-not-exist')).toBeNull();
});
});
@@ -0,0 +1,148 @@
/**
* PlaceDetailsCacheRepository (Plan 3c Task 1, PE2/PE3): the two statements
* `PlaceEnrichmentService` used to issue raw, on real rows. The table's real
* PRIMARY KEY is the composite `(place_id, lang, expanded)` — the parity
* proof below writes the same triple twice and asserts exactly one row.
*/
import { PlaceDetailsCache } from '../../../../src/db/entities/PlaceDetailsCache.entity';
import type { PlaceDetailsCacheRepository } from '../../../../src/db/repositories/PlaceDetailsCache.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { findRow, findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let cache: PlaceDetailsCacheRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
cache = t.repo(PlaceDetailsCache);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function rawRow(placeId: string, lang: string, expanded: number) {
return findRow(t, PlaceDetailsCache, { place_id: placeId, lang, expanded });
}
function seedEntry(placeId: string, lang: string, expanded: number, payloadJson: string, fetchedAt: number) {
return insertRow(t, PlaceDetailsCache, {
place_id: placeId,
lang,
expanded,
payload_json: payloadJson,
fetched_at: fetchedAt,
});
}
describe('PlaceDetailsCacheRepository.findEntry', () => {
it('PDCREPO-001: finds the entry for the exact (place_id, lang, expanded) triple', async () => {
await seedEntry('p1', 'en', 0, '{"a":1}', 1000);
expect(await cache.findEntry('p1', 'en', 0)).toEqual({ payload_json: '{"a":1}', fetched_at: 1000 });
});
it('PDCREPO-002: a different lang or expanded value is a miss, not a fuzzy match', async () => {
await seedEntry('p1', 'en', 0, '{"a":1}', 1000);
expect(await cache.findEntry('p1', 'fr', 0)).toBeNull();
expect(await cache.findEntry('p1', 'en', 2)).toBeNull();
});
it('PDCREPO-003: an empty-string lang (the "no lang requested" default) is its own distinct row', async () => {
await seedEntry('p1', '', 2, '{"b":2}', 2000);
expect(await cache.findEntry('p1', '', 2)).toEqual({ payload_json: '{"b":2}', fetched_at: 2000 });
expect(await cache.findEntry('p1', 'en', 2)).toBeNull();
});
it('PDCREPO-004: a missing entry resolves to null', async () => {
expect(await cache.findEntry('missing', '', 0)).toBeNull();
});
});
describe('PlaceDetailsCacheRepository.upsertEntry — composite-key INSERT OR REPLACE parity', () => {
it('PDCREPO-005: writes a fresh row for a new (place_id, lang, expanded) triple', async () => {
await cache.upsertEntry({ place_id: 'p1', lang: '', expanded: 2, payload_json: '{"v":1}', fetched_at: 100 });
expect(await rawRow('p1', '', 2)).toMatchObject({ payload_json: '{"v":1}', fetched_at: 100 });
});
// The composite-key proof the Task 1 brief requires: writes the SAME
// triple twice and asserts exactly ONE row survives (proving
// `onConflictFields: ['place_id', 'lang', 'expanded']` is the real
// conflict target, not an inferred single-column PK that would silently
// insert a duplicate).
it('PDCREPO-006: writing the same (place_id, lang, expanded) triple twice leaves exactly one row, with the second payload', async () => {
await cache.upsertEntry({ place_id: 'p1', lang: 'en', expanded: 2, payload_json: '{"v":1}', fetched_at: 100 });
await cache.upsertEntry({ place_id: 'p1', lang: 'en', expanded: 2, payload_json: '{"v":2}', fetched_at: 200 });
const rows = await findRows(t, PlaceDetailsCache, { place_id: 'p1', lang: 'en', expanded: 2 });
expect(rows).toHaveLength(1);
expect(await rawRow('p1', 'en', 2)).toMatchObject({ payload_json: '{"v":2}', fetched_at: 200 });
});
it('PDCREPO-007: a different lang or expanded value for the same place_id is a SEPARATE row, not overwritten', async () => {
await cache.upsertEntry({
place_id: 'p1',
lang: 'en',
expanded: 0,
payload_json: '{"kind":"details"}',
fetched_at: 100,
});
await cache.upsertEntry({
place_id: 'p1',
lang: 'en',
expanded: 2,
payload_json: '{"kind":"enrichment"}',
fetched_at: 200,
});
await cache.upsertEntry({
place_id: 'p1',
lang: 'fr',
expanded: 2,
payload_json: '{"kind":"enrichment-fr"}',
fetched_at: 300,
});
const rows = await findRows(t, PlaceDetailsCache, { place_id: 'p1' }, { lang: 'asc', expanded: 'asc' });
expect(rows).toHaveLength(3);
});
});
// D-shape (Task 1 brief item): `findEntry` is `findOne`-based
// (`TrekRepository`'s `disableIdentityMap: true` default), filtered solely
// on the table's real composite PRIMARY KEY (`place_id`, `lang`, `expanded`)
// — a PK-only `findOne`, the class rule 20/21 targets directly.
describe('PlaceDetailsCacheRepository — D-shape', () => {
it('PDCREPO-008 (D-shape): a raw write after an unrelated identity-map read is visible in the next findEntry call, in one query (disableIdentityMap regression)', async () => {
await seedEntry('p1', 'en', 2, '{"v":"old"}', 100);
// Task 9 fix wave (B-M3): rule 20 requires the FIRST, wider setup read to
// opt out of the base default explicitly, SEPARATE from the method under
// test — `findEntry` itself always uses the base's own
// `disableIdentityMap: true` default, so calling it here could never
// populate an entry for the later assertion to prove stale (the D-shape
// claim would be vacuous, the same class of gap rule 20 exists to close).
await t.repo(PlaceDetailsCache).findOne({ place_id: 'p1', lang: 'en', expanded: 2 }, { disableIdentityMap: false });
await updateRows(
t,
PlaceDetailsCache,
{ place_id: 'p1', lang: 'en', expanded: 2 },
{ payload_json: '{"v":"new"}', fetched_at: 200 },
);
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
try {
expect(await cache.findEntry('p1', 'en', 2)).toEqual({ payload_json: '{"v":"new"}', fetched_at: 200 });
expect(spy.mock.calls.length).toBe(1);
} finally {
spy.mockRestore();
}
});
});
@@ -0,0 +1,200 @@
/**
* PlaceRatingsRepository.listForPlaces (Plan 3c Task 1, QH2): the batch
* ratings-by-place loader behind `QueryHelpersService.loadRatingsByPlaceIds`,
* moved off `query-helpers.service.ts`. `place_ratings` is a Plan 3c-owned
* table (inventory §14.6) with no repository test file before this one.
*/
import { PlaceRatings } from '../../../../src/db/entities/PlaceRatings.entity';
import { Places } from '../../../../src/db/entities/Places.entity';
import type { PlaceRatingsRepository } from '../../../../src/db/repositories/PlaceRatings.repository';
import { dbNow } from '../../../../src/db/types/db-timestamp.type';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createPlace, createTrip, createUser } from '../../../helpers/factories';
import { countRows, findRow, findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let placeRatings: PlaceRatingsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
placeRatings = t.repo(PlaceRatings);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function rate(placeId: number, userId: number, rating: number, createdAt: string): Promise<void> {
await insertRow(t, PlaceRatings, { place: placeId, user: userId, rating, created_at: createdAt });
}
async function withQueryCount<T>(fn: () => Promise<T>): Promise<{ value: T; queries: number }> {
const connection = t.orm.em.getConnection();
const spy = vi.spyOn(connection, 'execute');
try {
const value = await fn();
return { value, queries: spy.mock.calls.length };
} finally {
spy.mockRestore();
}
}
describe('PlaceRatingsRepository.listForPlaces', () => {
it('PLACERATINGSREPO-001: an empty placeIds array short-circuits to [] without querying', async () => {
const { value, queries } = await withQueryCount(() => placeRatings.listForPlaces([]));
expect(value).toEqual([]);
expect(queries).toBe(0);
});
it("PLACERATINGSREPO-002: joins the voter's username/avatar, ordered by created_at", async () => {
const { user: owner } = createUser(testDb);
const { user: voterA } = createUser(testDb, { username: 'alpha' });
const { user: voterB } = createUser(testDb, { username: 'beta' });
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id);
await rate(place.id, voterA.id, 4, '2026-01-01 00:00:00');
await rate(place.id, voterB.id, 2, '2026-01-02 00:00:00');
const rows = await placeRatings.listForPlaces([place.id]);
expect(rows).toEqual([
{ place_id: place.id, user_id: voterA.id, username: 'alpha', avatar: null, rating: 4 },
{ place_id: place.id, user_id: voterB.id, username: 'beta', avatar: null, rating: 2 },
]);
});
it('PLACERATINGSREPO-003: batches across several places, indexed by place_id in the caller', async () => {
const { user: owner } = createUser(testDb);
const { user: voter } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const placeA = createPlace(testDb, trip.id, { name: 'A' });
const placeB = createPlace(testDb, trip.id, { name: 'B' });
await rate(placeA.id, voter.id, 5, '2026-01-01 00:00:00');
await rate(placeB.id, voter.id, 1, '2026-01-01 00:00:00');
const rows = await placeRatings.listForPlaces([placeA.id, placeB.id]);
expect(rows.map((r) => r.place_id).sort()).toEqual([placeA.id, placeB.id].sort());
});
it('PLACERATINGSREPO-004: a place with no ratings contributes no rows', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id);
expect(await placeRatings.listForPlaces([place.id])).toEqual([]);
});
// Task 9 fix wave (B-M3): relabelled. `listForPlaces` is a
// `qb().execute('all', false)` projection, which never hydrates an entity
// into the identity map by construction (unlike `find`/`findOne`), and the
// base default leaves the identity map disabled for every read anyway —
// there is no live identity-map entry here to bypass. This proves a DB
// round-trip, not an identity-map bypass.
it('PLACERATINGSREPO-005 (fresh after a raw UPDATE, not D-shape): a rating written after an unrelated identity-map read is visible in the FIRST wider projection', async () => {
const { user: owner } = createUser(testDb);
const { user: seedVoter } = createUser(testDb, { username: 'seed-voter' });
const { user: voter } = createUser(testDb, { username: 'fresh-voter' });
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id);
await rate(place.id, seedVoter.id, 1, '2026-01-01 00:00:00');
// rule 20: the FIRST, wider setup read passes `disableIdentityMap: false`
// explicitly and carries the column the later write targets (`rating`) —
// `find({})` with the base default merged in populates nothing.
await t.repo(PlaceRatings).find({}, { disableIdentityMap: false });
await rate(place.id, voter.id, 3, '2026-01-02 00:00:00');
const rows = await placeRatings.listForPlaces([place.id]);
expect(rows).toEqual([
{ place_id: place.id, user_id: seedVoter.id, username: 'seed-voter', avatar: null, rating: 1 },
{ place_id: place.id, user_id: voter.id, username: 'fresh-voter', avatar: null, rating: 3 },
]);
});
});
// ---------------------------------------------------------------------------
// Plan 3c Task 4 — upsertRating (PL51) / deleteRating (PL50).
// ---------------------------------------------------------------------------
describe('PlaceRatingsRepository.upsertRating (PL51)', () => {
it('UPSERTRATINGREPO-001: inserts a new vote, then a re-vote replaces the rating via ON CONFLICT DO UPDATE', async () => {
const { user: owner } = createUser(testDb);
const { user: voter } = createUser(testDb, { username: 'voter1' });
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id);
await placeRatings.upsertRating(place.id, voter.id, 5);
let rows = (await findRows(t, PlaceRatings, { place: place.id, user: voter.id })).map((r) => ({
rating: r.rating,
}));
expect(rows).toEqual([{ rating: 5 }]);
await placeRatings.upsertRating(place.id, voter.id, 2);
rows = (await findRows(t, PlaceRatings, { place: place.id, user: voter.id })).map((r) => ({ rating: r.rating }));
expect(rows).toEqual([{ rating: 2 }]);
// Exactly one row for the (place, user) pair — the composite unique key held, not a duplicate insert.
expect(await countRows(t, PlaceRatings, { place: place.id, user: voter.id })).toBe(1);
});
it("UPSERTRATINGREPO-002 (PL51 ruling): a re-vote never touches places.updated_at — a vote must not 409 another member's If-Match", async () => {
const { user: owner } = createUser(testDb);
const { user: voter } = createUser(testDb, { username: 'voter2' });
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id);
await updateRows(t, Places, { id: place.id }, { updated_at: dbNow(new Date(Date.now() - 60 * 60 * 1000)) });
const before = (await findRow(t, Places, { id: place.id }))?.updated_at;
await placeRatings.upsertRating(place.id, voter.id, 4);
await placeRatings.upsertRating(place.id, voter.id, 1); // the conflict path
const after = (await findRow(t, Places, { id: place.id }))?.updated_at;
expect(after).toBe(before);
});
it('UPSERTRATINGREPO-003: two different voters on the same place both keep their own rating', async () => {
const { user: owner } = createUser(testDb);
const { user: voterA } = createUser(testDb, { username: 'va' });
const { user: voterB } = createUser(testDb, { username: 'vb' });
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id);
await placeRatings.upsertRating(place.id, voterA.id, 5);
await placeRatings.upsertRating(place.id, voterB.id, 1);
const rows = (await findRows(t, PlaceRatings, { place: place.id }, { user: 'asc' })).map((r) => ({
user_id: r.user_id,
rating: r.rating,
}));
expect(rows).toEqual([
{ user_id: Math.min(voterA.id, voterB.id), rating: voterA.id < voterB.id ? 5 : 1 },
{ user_id: Math.max(voterA.id, voterB.id), rating: voterA.id < voterB.id ? 1 : 5 },
]);
});
});
describe('PlaceRatingsRepository.deleteRating (PL50)', () => {
it("DELETERATINGREPO-001: removes exactly the (place, user) row, leaving another voter's row alone", async () => {
const { user: owner } = createUser(testDb);
const { user: voterA } = createUser(testDb, { username: 'da' });
const { user: voterB } = createUser(testDb, { username: 'db' });
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id);
await placeRatings.upsertRating(place.id, voterA.id, 5);
await placeRatings.upsertRating(place.id, voterB.id, 3);
await placeRatings.deleteRating(place.id, voterA.id);
expect((await findRows(t, PlaceRatings, { place: place.id })).map((r) => ({ user_id: r.user_id }))).toEqual([
{ user_id: voterB.id },
]);
});
it('DELETERATINGREPO-002: deleting a vote that does not exist is a no-op, not a throw', async () => {
const { user: owner } = createUser(testDb);
const { user: voter } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id);
await expect(placeRatings.deleteRating(place.id, voter.id)).resolves.toBeUndefined();
});
});
@@ -0,0 +1,223 @@
/**
* PlaceRegionsRepository — full-key parity (Plan 4 Task 8b-2, item 3: 3f
* Task 7 review's L6 carry, "Atlas and vacay read models without a full-key
* legacy-raw `toEqual`"). AT3, AT23, AT28, AT40, AT44 had no repository-level
* test at all (the review's side-by-side HTTP run showed the rows are
* identical to the legacy today, but nothing ratchets them). One seeded
* world, `toEqual(<legacy raw>)` per method.
*/
import { PlaceRegions } from '../../../../src/db/entities/PlaceRegions.entity';
import type { PlaceRegionsRepository } from '../../../../src/db/repositories/PlaceRegions.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createPlace, createTrip, createUser, addTripMember } from '../../../helpers/factories';
import { insertRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: PlaceRegionsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(PlaceRegions);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function insertPlaceRegion(
placeId: number,
countryCode: string,
regionCode: string,
regionName: string,
): Promise<void> {
await insertRow(t, PlaceRegions, {
place: placeId,
country_code: countryCode,
region_code: regionCode,
region_name: regionName,
});
}
describe('PlaceRegionsRepository.listCountryCodesForPlaceIds (AT3)', () => {
it('PLACEREGREPO-001: matches SELECT place_id, country_code FROM place_regions WHERE place_id IN (...) run raw', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const p1 = createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
const p2 = createPlace(testDb, trip.id, { name: 'Louvre' });
const p3 = createPlace(testDb, trip.id, { name: 'Not geocoded' });
await insertPlaceRegion(p1.id, 'FR', 'FR-IDF', 'Île-de-France');
await insertPlaceRegion(p2.id, 'FR', 'FR-IDF', 'Île-de-France');
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare(
`SELECT place_id, country_code FROM place_regions WHERE place_id IN (${[p1.id, p2.id, p3.id].join(',')})`,
)
.all();
const typed = await repo.listCountryCodesForPlaceIds([p1.id, p2.id, p3.id]);
expect(typed).toEqual(legacy);
expect(typed.map((r) => r.place_id).sort((a, b) => a - b)).toEqual([p1.id, p2.id].sort((a, b) => a - b));
});
it('PLACEREGREPO-002: an empty id array short-circuits to [] without a query', async () => {
expect(await repo.listCountryCodesForPlaceIds([])).toEqual([]);
});
});
describe('PlaceRegionsRepository.listForPlaceIds (AT28)', () => {
it('PLACEREGREPO-003: matches SELECT * FROM place_regions WHERE place_id IN (...) run raw, every column', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const p1 = createPlace(testDb, trip.id);
const p2 = createPlace(testDb, trip.id);
await insertPlaceRegion(p1.id, 'US', 'US-NY', 'New York');
await insertPlaceRegion(p2.id, 'US', 'US-CA', 'California');
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb.prepare(`SELECT * FROM place_regions WHERE place_id IN (${[p1.id, p2.id].join(',')})`).all();
const typed = await repo.listForPlaceIds([p1.id, p2.id]);
expect(typed).toEqual(legacy);
});
it('PLACEREGREPO-004: an empty id array short-circuits to []', async () => {
expect(await repo.listForPlaceIds([])).toEqual([]);
});
});
describe('PlaceRegionsRepository.listDistinctRegionCodesForCountryAndPlaces (AT23)', () => {
it('PLACEREGREPO-005: matches SELECT DISTINCT region_code ... run raw, deduped across places sharing the region', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const p1 = createPlace(testDb, trip.id);
const p2 = createPlace(testDb, trip.id);
const p3 = createPlace(testDb, trip.id);
await insertPlaceRegion(p1.id, 'FR', 'FR-IDF', 'Île-de-France');
await insertPlaceRegion(p2.id, 'FR', 'FR-IDF', 'Île-de-France'); // same region, dedup target
await insertPlaceRegion(p3.id, 'DE', 'DE-BY', 'Bavaria'); // different country, excluded
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare(
`SELECT DISTINCT region_code FROM place_regions WHERE country_code = ? AND place_id IN (${[p1.id, p2.id, p3.id].join(',')})`,
)
.all('FR');
const typed = await repo.listDistinctRegionCodesForCountryAndPlaces('FR', [p1.id, p2.id, p3.id]);
expect(typed).toEqual(legacy.map((r: unknown) => (r as { region_code: string }).region_code));
expect(typed).toEqual(['FR-IDF']);
});
it('PLACEREGREPO-006: an empty id array short-circuits to []', async () => {
expect(await repo.listDistinctRegionCodesForCountryAndPlaces('FR', [])).toEqual([]);
});
});
describe('PlaceRegionsRepository.countPlacesByCountryForTrip (AT40)', () => {
it('PLACEREGREPO-007: matches the legacy GROUP BY statement, ordered by count DESC then country ASC, NULL country excluded', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const fr1 = createPlace(testDb, trip.id);
const fr2 = createPlace(testDb, trip.id);
const de1 = createPlace(testDb, trip.id);
const noRegion = createPlace(testDb, trip.id);
await insertPlaceRegion(fr1.id, 'FR', 'FR-IDF', 'Île-de-France');
await insertPlaceRegion(fr2.id, 'FR', 'FR-PAC', 'Provence');
await insertPlaceRegion(de1.id, 'DE', 'DE-BY', 'Bavaria');
// A different trip's place must not leak in.
const foreign = createPlace(testDb, other.id);
await insertPlaceRegion(foreign.id, 'FR', 'FR-IDF', 'Île-de-France');
void noRegion;
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare(
`
SELECT pr.country_code, COUNT(DISTINCT p.id) AS places
FROM place_regions pr JOIN places p ON p.id = pr.place_id
WHERE p.trip_id = ? AND pr.country_code IS NOT NULL
GROUP BY pr.country_code ORDER BY places DESC, pr.country_code ASC`,
)
.all(trip.id);
const typed = await repo.countPlacesByCountryForTrip(trip.id);
expect(typed).toEqual(legacy);
expect(typed).toEqual([
{ country_code: 'FR', places: 2 },
{ country_code: 'DE', places: 1 },
]);
});
it('PLACEREGREPO-008: empty array for a trip with no geocoded places', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(await repo.countPlacesByCountryForTrip(trip.id)).toEqual([]);
});
});
describe('PlaceRegionsRepository.listVisitedCountryCodesForUser (AT44)', () => {
it('PLACEREGREPO-009: matches the legacy statement — owner and member trips count, only started trips, deduped, NULL country excluded', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const started = createTrip(testDb, owner.id, { start_date: '2020-01-01', end_date: '2020-01-10' });
const notStarted = createTrip(testDb, owner.id, { start_date: '2099-01-01', end_date: '2099-01-10' });
addTripMember(testDb, started.id, member.id);
const startedPlace = createPlace(testDb, started.id);
await insertPlaceRegion(startedPlace.id, 'FR', 'FR-IDF', 'Île-de-France');
const startedPlace2 = createPlace(testDb, started.id);
await insertPlaceRegion(startedPlace2.id, 'FR', 'FR-PAC', 'Provence'); // same country, dedup target
const notStartedPlace = createPlace(testDb, notStarted.id);
await insertPlaceRegion(notStartedPlace.id, 'DE', 'DE-BY', 'Bavaria'); // not started, excluded
const today = '2026-01-01';
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacy = testDb
.prepare(
`
SELECT DISTINCT pr.country_code
FROM place_regions pr
JOIN places p ON p.id = pr.place_id
JOIN trips t ON p.trip_id = t.id
LEFT JOIN trip_members tm ON t.id = tm.trip_id
WHERE (t.user_id = ? OR tm.user_id = ?)
AND pr.country_code IS NOT NULL
AND COALESCE(t.start_date, t.end_date) IS NOT NULL
AND COALESCE(t.start_date, t.end_date) <= ?`,
)
.all(owner.id, owner.id, today);
const typedOwner = await repo.listVisitedCountryCodesForUser(owner.id, today);
expect(typedOwner).toEqual(legacy.map((r: unknown) => (r as { country_code: string }).country_code));
expect(typedOwner).toEqual(['FR']);
// test-sql-allow: the raw statement is the legacy oracle this parity test holds the repository to.
const legacyMember = testDb
.prepare(
`
SELECT DISTINCT pr.country_code
FROM place_regions pr
JOIN places p ON p.id = pr.place_id
JOIN trips t ON p.trip_id = t.id
LEFT JOIN trip_members tm ON t.id = tm.trip_id
WHERE (t.user_id = ? OR tm.user_id = ?)
AND pr.country_code IS NOT NULL
AND COALESCE(t.start_date, t.end_date) IS NOT NULL
AND COALESCE(t.start_date, t.end_date) <= ?`,
)
.all(member.id, member.id, today);
const typedMember = await repo.listVisitedCountryCodesForUser(member.id, today);
expect(typedMember).toEqual(legacyMember.map((r: unknown) => (r as { country_code: string }).country_code));
expect(typedMember).toEqual(['FR']);
expect(await repo.listVisitedCountryCodesForUser(stranger.id, today)).toEqual([]);
});
});
@@ -0,0 +1,212 @@
/**
* PlaceShadowPicksRepository (Plan 3c Task 1, PS2–PS8): every statement
* `PlaceShadowService` used to issue raw, on real rows. `place_shadow_picks`
* has no other repository test file before this one.
*/
import { PlaceShadowPicks } from '../../../../src/db/entities/PlaceShadowPicks.entity';
import type {
PlaceShadowPicksRepository,
NewPlaceShadowPickRow,
} from '../../../../src/db/repositories/PlaceShadowPicks.repository';
import { dbNow } from '../../../../src/db/types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { findRow, findRows, updateRows } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let picks: PlaceShadowPicksRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
picks = t.repo(PlaceShadowPicks);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function row(overrides: Partial<NewPlaceShadowPickRow> = {}): NewPlaceShadowPickRow {
return {
query: 'louvre',
lang: null,
bias_lat: null,
bias_lng: null,
source: 'nominatim',
live_rank: 0,
live_count: 5,
picked_name: 'Louvre Museum',
picked_lat: 48.8606,
picked_lng: 2.3376,
picked_place_id: null,
...overrides,
};
}
function rawRow(id: number) {
return findRow(t, PlaceShadowPicks, { id });
}
/** Every stored pick, oldest first. */
function storedPicks() {
return findRows(t, PlaceShadowPicks, {}, { id: 'asc' });
}
/** `created_at` as `datetime('now', '-N seconds')` would write it. */
const secondsAgo = (seconds: number): string => dbNow(new Date(Date.now() - seconds * 1000));
describe('PlaceShadowPicksRepository.insertPick', () => {
it('PSPICKREPO-001: inserts exactly the given columns, nullable ones included', async () => {
await picks.insertPick(row());
const [stored] = await storedPicks();
expect(await rawRow(stored.id)).toMatchObject({
query: 'louvre',
source: 'nominatim',
live_rank: 0,
live_count: 5,
lang: null,
});
});
});
describe('PlaceShadowPicksRepository.page', () => {
it('PSPICKREPO-002: pages by id, oldest first, fetching size + 1 rows for the probe', async () => {
await picks.insertPick(row({ query: 'a' }));
await picks.insertPick(row({ query: 'b' }));
await picks.insertPick(row({ query: 'c' }));
const page = await picks.page(0, 2);
expect(page).toHaveLength(3); // size + 1 probe row
expect(page.map((r) => r.query)).toEqual(['a', 'b', 'c']);
});
it('PSPICKREPO-003: after excludes everything at or below that id', async () => {
await picks.insertPick(row({ query: 'a' }));
const firstId = (await storedPicks())[0].id;
await picks.insertPick(row({ query: 'b' }));
const page = await picks.page(firstId, 5);
expect(page.map((r) => r.query)).toEqual(['b']);
});
});
describe('PlaceShadowPicksRepository.totals / countBySource / countByLiveRank', () => {
it('PSPICKREPO-004: totals on an empty table reports 0/null/null', async () => {
expect(await picks.totals()).toEqual({ total: 0, oldest: null, newest: null });
});
it('PSPICKREPO-005: totals reports COUNT/MIN/MAX across every row', async () => {
await picks.insertPick(row());
await picks.insertPick(row());
const stored = await storedPicks();
await updateRows(t, PlaceShadowPicks, { id: stored[0].id }, { created_at: '2026-01-01 00:00:00' });
await updateRows(t, PlaceShadowPicks, { id: stored[stored.length - 1].id }, { created_at: '2026-06-01 00:00:00' });
const totals = await picks.totals();
expect(totals).toEqual({ total: 2, oldest: '2026-01-01 00:00:00', newest: '2026-06-01 00:00:00' });
});
it('PSPICKREPO-006: countBySource groups and orders by count DESC', async () => {
await picks.insertPick(row({ source: 'nominatim' }));
await picks.insertPick(row({ source: 'nominatim' }));
await picks.insertPick(row({ source: 'google' }));
expect(await picks.countBySource()).toEqual([
{ source: 'nominatim', count: 2 },
{ source: 'google', count: 1 },
]);
});
// Task 1 fix review M1: `GROUP BY source` hands rows to JS in ASCENDING
// source order (SQLite's GROUP BY temp b-tree); a stable JS
// `Array.prototype.sort((a, b) => b.count - a.count)` therefore leaves ties
// ascending by source, but SQLite's own (non-stable) `ORDER BY count DESC`
// sorter emits ties in DESCENDING source order on the same data — two
// different final row orders. `countBySource` orders in SQL, by the
// `COUNT(*)` expression, so it reproduces the legacy statement's tie order
// exactly instead of merely matching it on the (untied) case above.
it('PSPICKREPO-006b: countBySource orders ties the same way the legacy ORDER BY count DESC statement does', async () => {
for (const source of ['zeta', 'zeta', 'alpha', 'alpha', 'omega', 'omega', 'mid', 'beta']) {
await picks.insertPick(row({ source }));
}
const rows = await picks.countBySource();
const legacy = testDb
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
.prepare('SELECT source, COUNT(*) AS count FROM place_shadow_picks GROUP BY source ORDER BY count DESC')
.all();
expect(rows).toEqual(legacy);
expect(rows).toEqual([
{ source: 'zeta', count: 2 },
{ source: 'omega', count: 2 },
{ source: 'alpha', count: 2 },
{ source: 'mid', count: 1 },
{ source: 'beta', count: 1 },
]);
});
it('PSPICKREPO-007: countByLiveRank groups with no ORDER BY (caller buckets)', async () => {
await picks.insertPick(row({ live_rank: 0 }));
await picks.insertPick(row({ live_rank: 0 }));
await picks.insertPick(row({ live_rank: 3 }));
const rows = await picks.countByLiveRank();
expect(rows).toEqual(
expect.arrayContaining([
{ live_rank: 0, count: 2 },
{ live_rank: 3, count: 1 },
]),
);
expect(rows).toHaveLength(2);
});
});
describe('PlaceShadowPicksRepository.deleteAll / purgeOlderThan', () => {
it('PSPICKREPO-008: deleteAll wipes every row and returns the affected count', async () => {
await picks.insertPick(row());
await picks.insertPick(row());
expect(await picks.deleteAll()).toBe(2);
expect(await picks.totals()).toEqual({ total: 0, oldest: null, newest: null });
});
it('PSPICKREPO-009: purgeOlderThan removes exactly the rows older than the cutoff, proving the deleted set on a seeded table', async () => {
await picks.insertPick(row({ query: 'old' }));
await picks.insertPick(row({ query: 'new' }));
const [oldRow, newRow] = await storedPicks();
await updateRows(t, PlaceShadowPicks, { id: oldRow.id }, { created_at: secondsAgo(200 * 86_400) });
await updateRows(t, PlaceShadowPicks, { id: newRow.id }, { created_at: secondsAgo(86_400) });
const removed = await picks.purgeOlderThan(180);
expect(removed).toBe(1);
const survivors = await storedPicks();
expect(survivors.map((r) => r.query)).toEqual(['new']);
});
it('PSPICKREPO-010: purgeOlderThan(0) removes rows created before right now, leaving nothing newer than the boundary', async () => {
await picks.insertPick(row());
const [{ id }] = await storedPicks();
await updateRows(t, PlaceShadowPicks, { id }, { created_at: secondsAgo(1) });
expect(await picks.purgeOlderThan(0)).toBe(1);
});
});
// Task 9 fix wave (B-M3): relabelled. `page`/`totals`/`countBySource`/
// `countByLiveRank` all go through `find`/`qb().execute()`; `TrekRepository`
// applies `disableIdentityMap: true` to every read by default, so `page()`
// never has a live identity-map entry to bypass in the first place — this
// proves a DB round-trip (a row inserted after an unrelated wider read is
// visible), not an identity-map bypass.
describe('PlaceShadowPicksRepository — fresh after a raw UPDATE', () => {
it('PSPICKREPO-011 (fresh after a raw UPDATE, not D-shape): a row inserted after an unrelated identity-map read is visible in the FIRST wider projection (page)', async () => {
await picks.insertPick(row({ query: 'seed' }));
// rule 20: the FIRST, wider setup read passes `disableIdentityMap: false`
// explicitly and carries the column the later write targets (`query`) —
// `find({})` with the base default merged in populates nothing.
await t.repo(PlaceShadowPicks).find({}, { disableIdentityMap: false });
await picks.insertPick(row({ query: 'fresh' }));
const page = await picks.page(0, 10);
expect(page.map((r) => r.query)).toEqual(['seed', 'fresh']);
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,178 @@
/**
* `PluginOauthTokensRepository.storeToken` (Plan 3j Task 4, PO11 — R-oauth-upsert):
* the composite-key (`plugin_id`, `user_id`) upsert whose `refresh_token` column is
* COALESCE-preserving. This is the repository-level proof the task brief names as
* mandatory: `plugin-oauth.service.ts#getAccessToken`'s own refresh path pre-fills a
* missing `refresh_token` in JS before calling `storeToken` (so it never actually
* reaches this repository's COALESCE with a null), and a brand-new row has no
* existing value for COALESCE to fall back to either way — so neither of those two
* call sites, alone, proves the repository's own COALESCE branch. This file calls
* `storeToken` directly, against an EXISTING row, with a genuinely omitted
* `refresh_token`.
*/
import { currentTimestampKysely } from '../../../../src/db/dialect/kysely-functions';
import { PluginOauthTokens } from '../../../../src/db/entities/PluginOauthTokens.entity';
import type { PluginOauthTokensRepository } from '../../../../src/db/repositories/PluginOauthTokens.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { findRow } from '../../../helpers/factories/rows';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: PluginOauthTokensRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(PluginOauthTokens);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function storedRow(pluginId: string, userId: number) {
return findRow(t, PluginOauthTokens, { plugin_id: pluginId, user_id: userId });
}
describe('PluginOauthTokensRepository', () => {
describe('storeToken (PO11, R-oauth-upsert — the COALESCE-preserving composite upsert)', () => {
it('PO11REPO-001: pinned rendered SQL for the ON CONFLICT DO UPDATE target and SET clause', () => {
const platform = t.em.getPlatform();
const compiled = t.em
.getKysely<{ plugin_oauth_tokens: Record<string, unknown> }>()
.insertInto('plugin_oauth_tokens')
.values({
plugin_id: 'p',
user_id: 1,
access_token: 'AT',
refresh_token: 'RT',
expires_at: 111,
scope: 'read',
updated_at: currentTimestampKysely(platform),
})
.onConflict((oc) =>
oc.columns(['plugin_id', 'user_id']).doUpdateSet({
access_token: (eb) => eb.ref('excluded.access_token'),
refresh_token: (eb) =>
eb.fn.coalesce(eb.ref('excluded.refresh_token'), eb.ref('plugin_oauth_tokens.refresh_token')),
expires_at: (eb) => eb.ref('excluded.expires_at'),
scope: (eb) => eb.ref('excluded.scope'),
updated_at: () => currentTimestampKysely(platform),
}),
)
.compile();
// Pinned for the task report — the exact ON CONFLICT clause Kysely renders
// for this table. The COALESCE operand order is the load-bearing part
// (R-oauth-upsert): NEW value (excluded) first, EXISTING second.
expect(compiled.sql).toContain('on conflict ("plugin_id", "user_id") do update set');
expect(compiled.sql).toContain('"access_token" = "excluded"."access_token"');
expect(compiled.sql).toContain(
'"refresh_token" = coalesce("excluded"."refresh_token", "plugin_oauth_tokens"."refresh_token")',
);
expect(compiled.sql).toContain('"expires_at" = "excluded"."expires_at"');
expect(compiled.sql).toContain('"scope" = "excluded"."scope"');
expect(compiled.sql).toContain('"updated_at" = CURRENT_TIMESTAMP');
// Pinned in full, for the task report:
expect(compiled.sql).toBe(
'insert into "plugin_oauth_tokens" ("plugin_id", "user_id", "access_token", "refresh_token", "expires_at", "scope", "updated_at") values (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP) on conflict ("plugin_id", "user_id") do update set "access_token" = "excluded"."access_token", "refresh_token" = coalesce("excluded"."refresh_token", "plugin_oauth_tokens"."refresh_token"), "expires_at" = "excluded"."expires_at", "scope" = "excluded"."scope", "updated_at" = CURRENT_TIMESTAMP',
);
});
it('PO11REPO-002 (R-oauth-upsert parity): a refresh response that OMITS refresh_token keeps the existing stored value unchanged', async () => {
// Seed an existing token row with a non-null refresh_token — the state a
// previously-connected user is in when a later refresh comes back without one.
await repo.storeToken({
plugin_id: 'p',
user_id: 42,
access_token: 'AT-1',
refresh_token: 'RT-original',
expires_at: 1000,
scope: 'read',
});
expect(await storedRow('p', 42)).toMatchObject({ access_token: 'AT-1', refresh_token: 'RT-original' });
// A refresh response that omits refresh_token — the repository call the
// service makes when it has NOT pre-filled the field itself.
await repo.storeToken({
plugin_id: 'p',
user_id: 42,
access_token: 'AT-2',
refresh_token: null,
expires_at: 2000,
scope: 'read write',
});
const row = (await storedRow('p', 42))!;
// access_token/expires_at/scope always take the new value (plain excluded.* reassignment)...
expect(row.access_token).toBe('AT-2');
expect(row.expires_at).toBe(2000);
expect(row.scope).toBe('read write');
// ...but refresh_token is UNCHANGED — still the ORIGINAL value, not null, not overwritten.
expect(row.refresh_token).toBe('RT-original');
expect(row.refresh_token).not.toBeNull();
});
it('PO11REPO-003 (R-oauth-upsert, the other COALESCE direction): a refresh response that DOES supply a new refresh_token overwrites the stored one', async () => {
await repo.storeToken({
plugin_id: 'p',
user_id: 42,
access_token: 'AT-1',
refresh_token: 'RT-original',
expires_at: 1000,
scope: 'read',
});
await repo.storeToken({
plugin_id: 'p',
user_id: 42,
access_token: 'AT-2',
refresh_token: 'RT-rotated',
expires_at: 2000,
scope: 'read',
});
const row = (await storedRow('p', 42))!;
expect(row.refresh_token).toBe('RT-rotated');
});
it('PO11REPO-004: a brand-new row (no prior state) inserts plainly — no COALESCE fallback target to speak of yet', async () => {
expect(await storedRow('fresh', 7)).toBeNull();
await repo.storeToken({
plugin_id: 'fresh',
user_id: 7,
access_token: 'AT',
refresh_token: null,
expires_at: null,
scope: null,
});
const row = (await storedRow('fresh', 7))!;
expect(row.access_token).toBe('AT');
expect(row.refresh_token).toBeNull();
});
it('PO11REPO-005: the composite key isolates rows — a second user of the same plugin gets its own row, the first is untouched', async () => {
await repo.storeToken({
plugin_id: 'p',
user_id: 1,
access_token: 'AT-1',
refresh_token: 'RT-1',
expires_at: null,
scope: null,
});
await repo.storeToken({
plugin_id: 'p',
user_id: 2,
access_token: 'AT-2',
refresh_token: 'RT-2',
expires_at: null,
scope: null,
});
expect(await storedRow('p', 1)).toMatchObject({ access_token: 'AT-1', refresh_token: 'RT-1' });
expect(await storedRow('p', 2)).toMatchObject({ access_token: 'AT-2', refresh_token: 'RT-2' });
});
});
});

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