The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
docs(db): Postgres 14 to 18, the database role, restore limits and the manual rollback
Maurice633e9bcdc1e2
diff --git a/README.md b/README.mdindex 7d90c3a1d..e20c42731 100644--- a/README.md+++ b/README.md@@ -321,7 +321,7 @@ docker compose up -dSee [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose)for the full walkthrough.-TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 17 database instead. The+TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 18 database instead. The[`docker-compose.postgres.yml`](docker-compose.postgres.yml) example starts one beside TREK, and the[Postgres guide](https://github.com/liketrek/TREK/wiki/Database-Postgres) covers the requirements and the backups.diff --git a/server/CLAUDE.md b/server/CLAUDE.mdindex 0d5a31989..bca0c0143 100644--- a/server/CLAUDE.md+++ b/server/CLAUDE.md@@ -81,7 +81,7 @@ Nest owns everything. Every domain is a DI module under `src/nest/<domain>/` (`c- **Plugins** (`src/nest/plugins/`): the child-process runtime (`supervisor/`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts`) is **intentionally not Nest**; it is the security boundary. `host/rpc-host.ts` registers an RPC method at spawn only if the plugin holds the unlocking permission (registration = authorization). Install-time gates live in `install/`; the manifest's `trek` version range fails closed, and `TREK_PLUGINS_IGNORE_TREK_RANGE` downgrades that to a warning. The protocol tables in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts`) are **generated** into `plugin-sdk/` and `shared/`: run `gen:plugin-facts` after touching them and commit the output. What a plugin gets back is `protocol/output-contract.ts`: every wire method has an entry, and an entity result (`trips.getById`, `todos.list`, `vacay.mine`, ...) is cut down to its published fields in `rpc-host.ts` on the way out, together with every child row it carries whose field is listed in `PLUGIN_ENTITY_NESTED` (a day's `notes_items`, a reservation's `endpoints`). A new column on any whole-row table behind those entities, child tables included, fails `tests/unit/plugins/output-contract.schema.test.ts` until it is listed as published or withheld (the SDK's `PLUGIN_ENTITY_FIELDS` and `PLUGIN_ENTITY_NESTED` are generated from it); a method left as `readModel` must return a value built field by field from named columns. A plugin's own SQL (`host/plugin-data.service.ts`) is held to a row cap, and `query`, `tx` and an `exec` script to a time budget checked between rows and statements (`migrate` is deliberately not timed). `runtime/egress-policy.ts` is a hand-kept mirror guarded by a parity test in `plugin-sdk/`; change both sides together.- **Storage**: `src/nest/storage/` is the upload driver abstraction (local / S3 / mirror behind one interface, with an admin surface and a usage job). Domain services never touch the filesystem or the S3 SDK directly. Where the data lives (`data/`, `uploads/`, backups, logs, key files, the DB file) is resolved in one place, `src/app-config/data-paths.ts`; a provider that reads one injects `DataPathsService`, plain helper modules shared with code outside the container call `resolveDataPaths()` (the list is in `src/app-config/README.md`), and nothing anchors a data path on its own `__dirname` or on `process.cwd()`.- **DB** (`src/db/`): `better-sqlite3`, WAL, FK on. `database.ts` only holds the connection and applies pragmas. It does not build a schema, and importing it opens nothing (the first reader does). The connection's lifecycle belongs to the `DatabaseLifecycle` provider (`nest/database/database-lifecycle.service.ts`): `buildApp()` opens it through `open()` (which binds the ORM to later swaps and runs the schema bootstrap below), the shutdown closes it through `close()`, and a restore or the demo reset swaps the file only through the database backup port, `DATABASE_BACKUP` (`nest/database/database-backup.interface.ts`; the SQLite implementation is `nest/backup/sqlite-database-backup.ts`: `VACUUM INTO` snapshot, close, atomic file swap, `reopen()`). The port works on `DatabaseLifecycle.file`, the one resolved path (`TREK_DB_FILE` or `data/travel.db`), and a snapshot that fails fails the backup rather than archiving the live file. `MaintenanceRepository` is provided only by `MaintenanceModule`'s factory and injected everywhere else; no consumer constructs it. A provider that has to follow every reopen (the demo reset job saves the first demo baseline after a restore's re-bootstrap seeded the example trips) registers with `DatabaseLifecycle.onReopened()`, which runs after the reopen's schema bootstrap; a listener contains its own failures, since one that throws fails the reopen. MikroORM's migrations (`db/migrations/`) are the only schema source, **including for tests**: the hand-kept `schema.ts`/`migrations.ts`/`seeds.ts` builders and the parity test that guarded them are gone. Seeding is the MikroORM seeders in `db/seeders/`, applied by `db/orm.ts` from `buildApp()` before anything reads. An install the retired positional runner migrated (a `schema_version` row, no `mikro_orm_migrations` rows) is baselined by `db/legacy-baseline.ts`: the migrations whose `Legacy migration step N` docstring is ≤ its version are recorded as executed (never replayed) in the same transaction as the migrator run, while the baseline migration itself still runs first, as the legacy runner's `createTables()` did on every boot. It refuses the boot when `schema_version` is not exactly one row holding an integer ≥ 1, or is above the last mapped step (258); a value from 1 to 258 is read as dev's steps of those numbers, so a pre-ORM feature-branch database whose steps differ is not detected (the Tours branch is the one case it cuts back). Recorded `mikro_orm_migrations` names this build does not ship refuse it too (`refuseNewerDatabase`), whether a newer release or a development build wrote them. 4.3.x and earlier have no such check and start on a database 5.x migrated. Before a boot applies pending migrations to a file database that holds anything, `db/pre-migrate-snapshot.ts` writes a `VACUUM INTO` copy next to it (`pre-migrate-<schema>-<time>.db`, `<schema>` being `legacy-<schema_version>` or the last recorded migration's timestamp; the newest `TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP` stay) and the newer-database refusal names the matching copy; a copy that cannot be written refuses the boot unless `TREK_DB_PRE_MIGRATE_SNAPSHOT=false`. It is off under `NODE_ENV=test` unless a suite sets that variable to true, and a restore's re-bootstrap skips it (the archive is the copy). After the migrator, `db/email-case-index.ts` creates the case-insensitive unique index on `users.email` that its migration had to defer on an install holding two accounts whose emails differ only in case (flag `email_case_index_pending`). `db/orm-driver.ts` binds the ORM to that same connection instead of opening a second one — with `:memory:` under test, a second connection is a second, empty database. Kysely statements (`this.kysely<...>()`) type against `DB` from `db/kysely/db.ts`, narrowed with `Pick<DB, 'trips' | 'days'>`; those files are generated from the migrated schema by `scripts/generate-db-types.ts`, so a migration that adds or changes a column is followed by `npm run gen:db-types`, never by a hand-written table interface. Every read and write goes through a repository in `db/repositories/` (each extends the shared `TrekRepository` base in `db/repositories/_shared/`, which validates the request context before delegating to MikroORM) and, for multi-statement writes, `UnitOfWork.transactional(...)` (`nest/database/unit-of-work.ts`, provided by the global `OrmModule`) — there is no `DatabaseService`/`DatabaseModule` to inject any more. Entrypoints outside an HTTP request — an MCP tool call, a plugin RPC dispatch, a WebSocket message, a cron job, boot-time seeding, a backup restore — open one explicitly with `withRequestContext()` (`nest/database/request-context.ts`), since only the pathless `mikroOrmRequestContext` middleware `buildApp()` mounts (with `@mikro-orm/nestjs`'s own `registerRequestContext` turned off in `app.module.ts`, UPLOADS-P16) forks an `EntityManager` per HTTP request. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker, opened from a snapshot `tests/global-setup.ts` migrates once per run; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).-- **Engines** (`src/db/engine/`): `TREK_DB_URL` (a `postgres://` URL) runs TREK on Postgres instead of the SQLite file; without it nothing changes. `resolveEngine()` picks the engine, and what differs by engine (the ORM options, opening and closing, how a database reaches the schema) is the engine's, behind the `DatabaseEngine` contract that `DatabaseLifecycle` calls; code elsewhere never checks which engine it runs on (`lint:engine-dispatch`). The Postgres driver (`src/db/engine/postgres/postgres-driver.ts`) reads `bigint` as a number. A Postgres database never replays the SQLite migrations: an empty one gets `assets/postgres/baseline.sql` (generated from the entities by `gen:pg-baseline`, with the triggers ported by hand in `POSTGRES_TRIGGERS`) and every migration up to its cut recorded as executed, in one transaction (`src/db/engine/postgres/schema-bootstrap.ts`); one holding tables without TREK's migration history is refused; one TREK migrated runs the newer-database refusal and the pending migrations. The migrations after the cut run on Postgres through the migrator, each with its schema change written once per engine through `engineDdl` (SQL dialect, Migrations, has the routine), and the baseline stays frozen for them. Before pending migrations the boot takes a `pg_dump` copy to `data/pre-migrate-<last migration>-<time>.pgdump` under the same `TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP)` policy as the SQLite file. The backup port's Postgres side (`src/nest/backup/postgres-database-backup.ts`) dumps with `pg_dump`; a restore turns the dump into a script with `pg_restore` and has `psql` clear the current schema and run it in one transaction (a dump only recreates what it holds, so `pg_restore --clean` would leave a later migration's tables behind); the restore refuses a pg_restore or psql older than 17.6/16.10/15.14/14.19, whose script would lack the `\restrict` line that keeps a psql meta-command smuggled into a dump from running (CVE-2025-8714). The tools run by absolute path (`src/db/engine/postgres/pg-tools.ts`, `TREK_DB_PG_BIN_DIR`) with the password in their environment, never on the command line; the image ships the version 17 client, which cannot dump a newer server. A restore refuses a SQLite archive or a newer TREK's dump before anything is replaced, and replaces everything in the schema, so TREK wants a database of its own and a role that is not a superuser. `RESTORE_FROM_BACKUP` loads the archive's dump the same way into a database that holds no table yet, and is ignored once it holds one. The Postgres lane (`vitest.pg.config.ts`, `npm run test:pg`, CI job `server-postgres`, once on Postgres 14 and once on 18) runs every suite that boots the app on the real database module, each file on its own copy of one template database migrated by the engine's bootstrap (`tests/postgres/global-setup.ts`), plus `tests/postgres/` (PARITY-PG: the comparator finds nothing between the bootstrapped database and the entities but the differences it lists with their reason; the write lock; case-insensitive search). `TREK_TEST_DB_URL` names a database it may create and drop databases from; without it the lane fails, and with `TREK_TEST_PG_MAJOR` set it refuses a server of another major. Nobody keeps the list: `tests/postgres/lane.ts` takes every test file that reaches `src/bootstrap.ts` or `src/nest/app.module.ts` through its imports (directly or through a helper under `tests/`, so `buildApp()`, `bootTestApp()` and the broadcast-parity harness all count) and does not `vi.mock` `src/db/database`. Its `SQLITE_ONLY` map names the suites that stay on SQLite by design, each with its reason (the two whose faked clock needs SQLite to answer synchronously, the two about the better-sqlite3 handle). A suite that boots the app over the SQLite snapshot mock can never run on Postgres; the ones that still do are listed in `tests/postgres/snapshot-suites-baseline.json`, which only shrinks. `tests/unit/postgres-lane.test.ts` (PGLANE, in the SQLite lane) fails on a new such suite (drop the mock and seed through `tests/helpers/factories` with `app.get(MikroORM)`, as `tests/e2e/packing-mcp.e2e.test.ts` does), on a baseline entry or exclusion that went stale, and on a suite that names `buildApp`/`bootTestApp`/`AppModule` without the discovery seeing it boot. The suites that build a partial module over `createTestOrm(db)`/`createTestMikroOrmModule(db)` bind the ORM to a better-sqlite3 handle and stay on SQLite; the probe is what checks their repositories' SQL on Postgres. Two processes starting on one Postgres database at once are not coordinated yet: the second fails its boot (the first one's schema transaction wins), so start one instance for a first boot or an upgrade before scaling out.+- **Engines** (`src/db/engine/`): `TREK_DB_URL` (a `postgres://` URL) runs TREK on Postgres instead of the SQLite file; without it nothing changes. `resolveEngine()` picks the engine, and what differs by engine (the ORM options, opening and closing, how a database reaches the schema) is the engine's, behind the `DatabaseEngine` contract that `DatabaseLifecycle` calls; code elsewhere never checks which engine it runs on (`lint:engine-dispatch`). The Postgres driver (`src/db/engine/postgres/postgres-driver.ts`) reads `bigint` as a number. A Postgres database never replays the SQLite migrations: an empty one gets `assets/postgres/baseline.sql` (generated from the entities by `gen:pg-baseline`, with the triggers ported by hand in `POSTGRES_TRIGGERS`) and every migration up to its cut recorded as executed, in one transaction (`src/db/engine/postgres/schema-bootstrap.ts`); one holding tables without TREK's migration history is refused; one TREK migrated runs the newer-database refusal and the pending migrations. The migrations after the cut run on Postgres through the migrator, each with its schema change written once per engine through `engineDdl` (SQL dialect, Migrations, has the routine), and the baseline stays frozen for them. Before pending migrations the boot takes a `pg_dump` copy to `data/pre-migrate-<last migration>-<time>.pgdump` under the same `TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP)` policy as the SQLite file. The backup port's Postgres side (`src/nest/backup/postgres-database-backup.ts`) dumps with `pg_dump`; a restore turns the dump into a script with `pg_restore` and has `psql` clear the current schema and run it in one transaction (a dump only recreates what it holds, so `pg_restore --clean` would leave a later migration's tables behind); the restore refuses a pg_restore or psql older than 18.0/17.6/16.10/15.14/14.19, whose script would lack the `\restrict` line that keeps a psql meta-command smuggled into a dump from running (CVE-2025-8714), streams the script to its work file and stops it past `BACKUP_MAX_DECOMPRESSED_MB`, and refuses a role that is a superuser or holds `pg_execute_server_program` or `pg_write_server_files` (the archive's SQL runs as that role; the boot warns about one). The tools run by absolute path (`src/db/engine/postgres/pg-tools.ts`, `TREK_DB_PG_BIN_DIR`, else `/usr/lib/postgresql/<major>/bin` newest first) with the password in their environment, never on the command line, and their stderr reaches an error only summarized, without the lines that quote rows. Supported servers are PostgreSQL 14 to 18 (`src/db/engine/postgres/server-checks.ts`): the boot refuses any other before it writes anything. The image ships the version 18 client from the PGDG apt repository (pinned major, key kept in `scripts/pgdg-apt-key.asc`), because a client handles every server up to its own major and refuses a newer one; a dump or a restore refuses a client older than the server, and `sslrootcert=system` (the default when the URL names an `sslmode` but no CA) only with a client from 16 on. The migration history lives in the current schema beside the tables (the bootstrap qualifies MikroORM's `migrations.tableName` with `current_schema()`), so the backups, which hold that schema, include it. A restore refuses a SQLite archive or a newer TREK's dump before anything is replaced, and replaces everything in the schema, so TREK wants a database of its own and a role that is not a superuser. `RESTORE_FROM_BACKUP` loads the archive's dump the same way into a database that holds no table yet, and is ignored once it holds one. The Postgres lane (`vitest.pg.config.ts`, `npm run test:pg`, CI job `server-postgres`, once on Postgres 14 and once on 18) runs every suite that boots the app on the real database module, each file on its own copy of one template database migrated by the engine's bootstrap (`tests/postgres/global-setup.ts`), plus `tests/postgres/` (PARITY-PG: the comparator finds nothing between the bootstrapped database and the entities but the differences it lists with their reason; the write lock; case-insensitive search). `TREK_TEST_DB_URL` names a database it may create and drop databases from; without it the lane fails, and with `TREK_TEST_PG_MAJOR` set it refuses a server of another major. Nobody keeps the list: `tests/postgres/lane.ts` takes every test file that reaches `src/bootstrap.ts` or `src/nest/app.module.ts` through its imports (directly or through a helper under `tests/`, so `buildApp()`, `bootTestApp()` and the broadcast-parity harness all count) and does not `vi.mock` `src/db/database`. Its `SQLITE_ONLY` map names the suites that stay on SQLite by design, each with its reason (the two whose faked clock needs SQLite to answer synchronously, the two about the better-sqlite3 handle). A suite that boots the app over the SQLite snapshot mock can never run on Postgres; the ones that still do are listed in `tests/postgres/snapshot-suites-baseline.json`, which only shrinks. `tests/unit/postgres-lane.test.ts` (PGLANE, in the SQLite lane) fails on a new such suite (drop the mock and seed through `tests/helpers/factories` with `app.get(MikroORM)`, as `tests/e2e/packing-mcp.e2e.test.ts` does), on a baseline entry or exclusion that went stale, and on a suite that names `buildApp`/`bootTestApp`/`AppModule` without the discovery seeing it boot. The suites that build a partial module over `createTestOrm(db)`/`createTestMikroOrmModule(db)` bind the ORM to a better-sqlite3 handle and stay on SQLite; the probe is what checks their repositories' SQL on Postgres. Two processes starting on one Postgres database at once are not coordinated yet: the second fails its boot (the first one's schema transaction wins), so start one instance for a first boot or an upgrade before scaling out.## Rules for new codediff --git a/server/src/db/engine/postgres/schema-bootstrap.ts b/server/src/db/engine/postgres/schema-bootstrap.tsindex 98b457769..1c71a2919 100644--- a/server/src/db/engine/postgres/schema-bootstrap.ts+++ b/server/src/db/engine/postgres/schema-bootstrap.ts@@ -216,8 +216,9 @@ export function postgresSafetyNet(const match = snapshots.find((snapshot) => path.basename(snapshot).startsWith(`${PREFIX}${thisRelease}-`));if (match) {return (- `The copy taken right before the newer TREK migrated it is ${match}: stop TREK, empty the database ` +- '(drop and recreate it), and restore it with pg_restore --no-owner --no-privileges --single-transaction.'+ `The copy taken right before the newer TREK migrated it is ${match}: stop TREK and load it as the wiki ` ++ 'page Updating describes ("Rolling back a Postgres update"), which clears the schema and runs ' ++ 'pg_restore --no-owner --no-privileges in one transaction with psql.');}if (snapshots.length > 0) {diff --git a/server/tests/unit/db/engine/postgres/clear-schema.test.ts b/server/tests/unit/db/engine/postgres/clear-schema.test.tsnew file mode 100644index 000000000..7b9dc7002--- /dev/null+++ b/server/tests/unit/db/engine/postgres/clear-schema.test.ts@@ -0,0 +1,38 @@+/**+ * The manual rollback in wiki/Updating.md ("Rolling back a Postgres update")+ * prints the statement TREK's restore clears the schema with+ * (src/db/engine/postgres/clear-schema.ts), so a rollback by hand clears the+ * same objects as the tested restore. The page holds a copy; this keeps it the+ * same as the code.+ */+import { CLEAR_SCHEMA_SQL } from '../../../../../src/db/engine/postgres/clear-schema';++import fs from 'node:fs';+import path from 'node:path';+import { describe, expect, it } from 'vitest';++const repoRoot = path.resolve(__dirname, '../../../../../..');++/** The `sql` code blocks of a Markdown text, with the indentation of their fence removed. */+function sqlBlocks(markdown: string): string[] {+ const blocks: string[] = [];+ const fence = /^( *)```sql\n([\s\S]*?)\n\1```$/gm;+ for (const match of markdown.replace(/\r\n?/g, '\n').matchAll(fence)) {+ const indent = match[1].length;+ blocks.push(+ match[2]+ .split('\n')+ .map((line) => line.slice(Math.min(indent, line.length - line.trimStart().length)))+ .join('\n'),+ );+ }+ return blocks;+}++describe('clear-schema', () => {+ it('CLEARSCHEMA-001: the manual rollback on the wiki clears the schema with the statement the restore runs', () => {+ const page = fs.readFileSync(path.join(repoRoot, 'wiki', 'Updating.md'), 'utf8');+ const section = page.slice(page.indexOf('### Rolling back a Postgres update'));+ expect(sqlBlocks(section)).toContain(CLEAR_SCHEMA_SQL.trimEnd());+ });+});diff --git a/server/tests/unit/db/engine/postgres/schema-bootstrap.test.ts b/server/tests/unit/db/engine/postgres/schema-bootstrap.test.tsindex e6c0c8b20..e654afb6a 100644--- a/server/tests/unit/db/engine/postgres/schema-bootstrap.test.ts+++ b/server/tests/unit/db/engine/postgres/schema-bootstrap.test.ts@@ -318,7 +318,7 @@ describe('postgresSafetyNet', () => {await expect(hint.restoreHint('20200101000100')).resolves.toMatch(/none of them from this release/);writeFileSync(path.join(dir, 'pre-migrate-20200101000100-20250102T000000Z.pgdump'), 'mine');await expect(hint.restoreHint('20200101000100')).resolves.toMatch(- /pre-migrate-20200101000100-20250102T000000Z\.pgdump: stop TREK, empty the database .*pg_restore --no-owner/,+ /pre-migrate-20200101000100-20250102T000000Z\.pgdump: stop TREK and load it as the wiki page Updating .*pg_restore --no-owner/,);});});diff --git a/wiki/Database-Postgres.md b/wiki/Database-Postgres.mdindex 363be8740..4783595ea 100644--- a/wiki/Database-Postgres.md+++ b/wiki/Database-Postgres.md@@ -12,12 +12,12 @@ Postgres does not make TREK scale out. TREK still runs as one process. See [Limi## Requirements-- **PostgreSQL 14 to 17.**+- **PostgreSQL 14 to 18.** TREK refuses to start on any other server version, before it writes anything.- **An empty database dedicated to TREK.** TREK creates its schema in an empty database. It refuses a database that holds tables it did not create, and a restore replaces everything in the schema it loads into. Do not share the database with another application.-- **A role that is not a superuser,** which owns the database or can create objects in its schema. A backup archive is a SQL script run by this role during a restore, so a role with fewer privileges limits what a crafted archive can do.+- **A role that is not a superuser,** which owns the database or can create objects in its schema. A backup archive is a SQL script run by this role during a restore, so a role with fewer privileges limits what a crafted archive can do. A restore refuses a superuser and a role that holds `pg_execute_server_program` or `pg_write_server_files`, and TREK warns about such a role when it starts. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).- **ICU support in the server.** The schema creates the collation `nocase` with `provider = icu`, so the server must be built with ICU. The official `postgres` images include it.-- **PostgreSQL client tools** (`pg_dump`, `pg_restore`, `psql`) for backups, restores and the copy TREK takes before a migration. The Docker image installs the version 17 client. The client cannot dump a server newer than 17, so a PostgreSQL 18 server needs a client of the same major version, installed on the host or in a custom image, and pointed at with `TREK_DB_PG_BIN_DIR`. See [Configuration](#configuration).-- **Client tool versions that carry the CVE-2025-8714 fix.** A restore refuses `pg_restore` or `psql` older than 17.6, 16.10, 15.14 or 14.19.+- **PostgreSQL client tools** (`pg_dump`, `pg_restore`, `psql`) for backups, restores and the copy TREK takes before a migration. The Docker image installs the version 18 client, which works with every supported server. A client works with servers up to its own major version, so a client outside the image must be at least as new as the server; TREK refuses an older one with a message that names both versions. See [Configuration](#configuration).+- **Client tool versions that carry the CVE-2025-8714 fix.** A restore refuses `pg_restore` or `psql` older than 18.0, 17.6, 16.10, 15.14 or 14.19.## Configuration@@ -45,24 +45,52 @@ The `sslmode` parameter in the URL selects how the connection is secured:Without `sslmode`, the connection pool uses no SSL. The client tools use the libpq default for an unset `sslmode`, so set `sslmode` explicitly. For the backup and restore tools, every mode other than `disable` verifies the server, including its host name.-`sslrootcert=` names the file holding the certificate authority that signs the server's certificate. It is needed when the server uses a certificate from a private CA, and it is valid only together with one of the verifying modes. The file must be readable inside the container, so mount it into the container and point the URL at the path inside the container. Without `sslrootcert`, the system's trusted certificate authorities are used.+`sslrootcert=` names the file holding the certificate authority that signs the server's certificate. It is needed when the server uses a certificate from a private CA, and it is valid only together with one of the verifying modes. The file must be readable inside the container, so mount it into the container and point the URL at the path inside the container. Without `sslrootcert`, the system's trusted certificate authorities are used. The client tools read the system's authorities only from version 16 on, so with an older client (outside the Docker image) set `sslrootcert`; TREK refuses a backup or restore with such a client otherwise and says so.### Where the client tools are foundTREK runs the tools by their absolute path. It does not search `PATH`. When `TREK_DB_PG_BIN_DIR` is unset, TREK looks in these directories, in order, and uses the first one that holds the tool:-1. `/usr/lib/postgresql/17/bin`-2. `/usr/lib/postgresql/16/bin`-3. `/usr/lib/postgresql/15/bin`-4. `/usr/lib/postgresql/14/bin`-5. `/usr/local/bin`-6. `/usr/bin`+1. `/usr/lib/postgresql/18/bin`+2. `/usr/lib/postgresql/17/bin`+3. `/usr/lib/postgresql/16/bin`+4. `/usr/lib/postgresql/15/bin`+5. `/usr/lib/postgresql/14/bin`+6. `/usr/local/bin`+7. `/usr/bin`++The newest version comes first, because a client works with every server up to its own major version and refuses a newer one.The password is passed to the tools in the `PGPASSWORD` environment variable of their process. It never appears on a command line, where other processes could read it.### Compose example-[`docker-compose.postgres.yml`](https://github.com/liketrek/TREK/blob/main/docker-compose.postgres.yml) runs a `postgres:17` service beside TREK, on a named volume, with the TREK container waiting for the database to pass its health check. Set `POSTGRES_PASSWORD` in a `.env` file beside it before the first start. See [Install: Docker Compose](Install-Docker-Compose#running-on-postgres).+[`docker-compose.postgres.yml`](https://github.com/liketrek/TREK/blob/main/docker-compose.postgres.yml) runs a `postgres:17` service beside TREK, on a named volume, with the TREK container waiting for the database to pass its health check. Set two passwords in a `.env` file beside it before the first start: `POSTGRES_ADMIN_PASSWORD` for the database's superuser `postgres`, and `POSTGRES_PASSWORD` for the role `trek` that TREK connects as. On the database's first start, the superuser creates the role `trek`, which owns TREK's database and is not a superuser. See [Install: Docker Compose](Install-Docker-Compose#running-on-postgres).++### A role that is not a superuser++TREK connects as the role in `TREK_DB_URL`. That role creates TREK's schema, and during a restore it runs the backup's SQL, so it should own TREK's database and nothing more. On a server you administer, create it as a superuser once:++```sql+CREATE ROLE trek LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '<a long random value>';+CREATE DATABASE trek OWNER trek;+\c trek+ALTER SCHEMA public OWNER TO trek;+```++Then use `postgres://trek:<password>@<host>:5432/trek` as `TREK_DB_URL`. A restore refuses a role that is a superuser, or that holds `pg_execute_server_program` or `pg_write_server_files`, because a crafted archive could use those to run commands or write files on the database server. TREK also logs a warning about such a role when it starts.++TREK creates its tables in the role's current schema, normally `public`. A role whose `search_path` points at a schema of its own works too: TREK keeps its tables and its migration history there, and backups and restores cover that schema.++### Moving a compose install off the superuser++An install that started from an older `docker-compose.postgres.yml` connects as `trek`, which the `postgres` image created as the superuser. Its backups work, but restores are refused until TREK runs as a role that is not a superuser. With the containers running:++1. Create a second superuser for administration, so the database keeps one: `docker exec -it trek-db psql -U trek -d trek -c "CREATE ROLE postgres LOGIN SUPERUSER PASSWORD '<a long random value>'"`.+2. Take the superuser right from `trek`: `docker exec -it trek-db psql -U postgres -d trek -c "ALTER ROLE trek NOSUPERUSER NOCREATEDB NOCREATEROLE"`.+3. Update `docker-compose.postgres.yml` to the current version. Set `POSTGRES_ADMIN_PASSWORD` to the password from step 1 in `.env`, and keep `POSTGRES_PASSWORD` as it is (it stays the password of `trek`). Then run `docker compose -f docker-compose.postgres.yml up -d`.++The database already exists, so the new init script does not run again, and TREK keeps its data.## First boot@@ -101,7 +129,9 @@ Restoring a backup on Postgres follows these rules:- **The current database is replaced.** TREK first keeps a copy of it as `data/pre-restore-<time>.pgdump`. `pg_restore` then turns the archive's dump into a SQL script, and `psql` clears the current schema, which drops its tables, views, sequences, functions, types and collations, and runs the script. Both steps run in one transaction, so a restore that fails leaves the database as it was.- **TREK checks the archive before it replaces anything.** The archive must hold a Postgres dump, not a SQLite file. The dump must carry TREK's migration history, and it must not come from a newer TREK. TREK refuses the restore with a message saying which check failed.-- **The client tools must be recent enough.** The restore refuses `pg_restore` or `psql` older than 17.6, 16.10, 15.14 or 14.19.+- **The client tools must be recent enough.** The restore refuses `pg_restore` or `psql` older than 18.0, 17.6, 16.10, 15.14 or 14.19, and tools older than the server.+- **The role must not be a superuser.** The restore refuses a role that is a superuser or holds `pg_execute_server_program` or `pg_write_server_files`. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).+- **The restore needs free space in the data directory.** `pg_restore` writes the dump out as a SQL script next to the unpacked archive before `psql` runs it, and the script is several times larger than the dump. It may grow to `BACKUP_MAX_DECOMPRESSED_MB` (5 GB by default); a larger one is stopped, nothing is replaced, and the work files are removed. Raise the limit for a genuine backup that needs more.`RESTORE_FROM_BACKUP` works on Postgres too. On the first start, TREK loads the archive's dump into the database when that database holds no tables. When the database already has tables, the variable is ignored and TREK logs a warning. See [Backups: Restoring on a new install, before setup](Backups#restoring-on-a-new-install-before-setup).@@ -110,7 +140,7 @@ Restoring a backup on Postgres follows these rules:- **No migration from SQLite to Postgres** in this first release. Start a new install on Postgres, or keep the SQLite install.- **No more than one TREK replica.** TREK keeps state in memory: rate limits, pending one-time codes, the permission cache and the WebSocket connections. Each process has its own copy, so two replicas would disagree with each other. Keep `replicas: 1` in the Helm chart and one `trek` container. Postgres does not change that.- **Two processes booting on one database at once are not coordinated.** Start one process for the first boot and for each upgrade, then continue with one.-- **Client tools for server version 18 and later.** The Docker image's client is version 17, which cannot dump a newer server. Point `TREK_DB_PG_BIN_DIR` at a matching client.+- **PostgreSQL 14 to 18 only.** A newer server is refused until a TREK release supports it, because the image's client tools would not be able to back it up.- **Writes are serialized.** TREK takes a database-wide advisory lock for each write transaction, as the SQLite engine does with its single writer. Heavy concurrent writes wait on that lock.## Supabase@@ -120,7 +150,7 @@ Supabase runs PostgreSQL and can host TREK's database. The checklist below has b- **Use the direct connection or the session pooler.** The direct connection uses port 5432. Its host resolves only to IPv6 unless the project has the IPv4 add-on. A container on a network without IPv6 (Docker Desktop's default network, for example) cannot reach it; use the session pooler there, which also listens on port 5432 on its own host.- **Do not use the transaction pooler** (port 6543) for TREK. `pg_dump` and `psql` need a session that lasts for the whole run, and the transaction pooler does not give one.- **Verify the server with Supabase's CA.** Supabase's certificate is signed by its own certificate authority, which the system's trusted authorities do not include, so `sslmode=require` alone fails for the backup and restore tools. Download the CA certificate from the project's database settings, mount it into the container, and use `sslmode=verify-full&sslrootcert=/certs/<file>.crt` with the path inside the container.-- **The `postgres` role works as TREK's role.** It is not a superuser, and it can create the schema and the `nocase` collation.+- **The `postgres` role works as TREK's role.** It is not a superuser, and it can create the schema and the `nocase` collation. If a restore refuses it because it holds `pg_execute_server_program` or `pg_write_server_files`, create a dedicated role as in [A role that is not a superuser](#a-role-that-is-not-a-superuser) (the `postgres` role may create roles) and connect TREK as that one.- **The database's `public` schema must hold no tables** when TREK first starts, because TREK refuses a database with tables it did not create. A new project's `public` schema is empty.- **Backups hold only TREK's schema.** The project's own schemas (`auth`, `storage` and the others Supabase manages) are left out of every backup, and a restore replaces only TREK's schema.- **Pick a region close to the TREK server.** Every statement crosses the network, so a distant region makes the first boot and a restore take minutes. During a restore, scheduled jobs that touch the database can log statement timeouts; they run again on their next schedule.diff --git a/wiki/Environment-Variables.md b/wiki/Environment-Variables.mdindex 1fd7a3e87..4ff51278d 100644--- a/wiki/Environment-Variables.md+++ b/wiki/Environment-Variables.md@@ -507,7 +507,7 @@ through environment variables. `TREK_PLACE_PHOTO_DIR` below is unaffected.| `BACKUP_UPLOAD_LIMIT_MB` | Maximum **compressed** size (in MB) of a restore-backup archive that may be uploaded. Raise it if your backups (which include the `uploads/` directory) exceed the default. Non-positive or invalid values abort startup. | `500` || `RESTORE_FROM_BACKUP` | Path to a backup ZIP to restore on the **first** start, before any setup. Only acts while no database exists; afterwards it is ignored with a warning. A backup that fails the restore checks stops the start. See [Backups](Backups#restoring-on-a-new-install-before-setup). | none || `BACKUP_MAX_DECOMPRESSED_MB` | Maximum **decompressed** size (in MB) of a restore-backup archive — the zip-bomb guard. Independent of `BACKUP_UPLOAD_LIMIT_MB` and enforced on both restore paths, so a restore that fits the upload cap can still be refused with `Backup exceeds the maximum decompressed size.` Raise both when restoring a very large instance. | `5120` (5 GB) |-| `TREK_DB_URL` | Run TREK on a PostgreSQL database instead of the SQLite file: `postgres://user:password@host:5432/database` (or `postgresql://`). Needs PostgreSQL 14 to 17 and an empty database of its own. Percent-encode special characters in the password. See [Database: Postgres](Database-Postgres). | unset (SQLite) |+| `TREK_DB_URL` | Run TREK on a PostgreSQL database instead of the SQLite file: `postgres://user:password@host:5432/database` (or `postgresql://`). Needs PostgreSQL 14 to 18, an empty database of its own and a role that is not a superuser. Percent-encode special characters in the password. See [Database: Postgres](Database-Postgres). | unset (SQLite) || `TREK_DB_POOL_MAX` | Most connections TREK opens to the PostgreSQL database, from 1 to 100. Unused on SQLite. | `10` || `TREK_DB_PG_BIN_DIR` | Directory holding `pg_dump`, `pg_restore` and `psql`, which back up and restore a PostgreSQL database. Unset, TREK looks in `/usr/lib/postgresql/17` to `14` (`bin`), `/usr/local/bin` and `/usr/bin`. Unused on SQLite. See [Database: Postgres](Database-Postgres#where-the-client-tools-are-found). | unset || `TREK_DB_FILE` | Explicit path of the SQLite database file. Unset, TREK uses `travel.db` in the data directory. Not used with `TREK_DB_URL`. | unset |diff --git a/wiki/Install-Docker-Compose.md b/wiki/Install-Docker-Compose.mdindex fb403a608..d9492bcfc 100644--- a/wiki/Install-Docker-Compose.md+++ b/wiki/Install-Docker-Compose.md@@ -120,14 +120,14 @@ See [Reverse-Proxy](Reverse-Proxy) for complete proxy configuration examples.[`docker-compose.postgres.yml`](https://github.com/liketrek/TREK/blob/main/docker-compose.postgres.yml) runs TREK beside a `postgres:17` service instead of the SQLite file. Its `db` service keeps the database in a named volume and publishes no port, and the `trek` service waits for the database's health check before it starts.-Put a password in a `.env` file beside the compose file, then start it:+Put two passwords in a `.env` file beside the compose file, then start it:```bash-echo 'POSTGRES_PASSWORD=<a long random value>' > .env+printf 'POSTGRES_ADMIN_PASSWORD=%s\nPOSTGRES_PASSWORD=%s\n' '<a long random value>' '<another long random value>' > .envdocker compose -f docker-compose.postgres.yml up -d```-The password goes into `TREK_DB_URL`, so use URL-safe characters or percent-encode it. Without `POSTGRES_PASSWORD` the database does not initialize and TREK does not start. To run it against a database that already exists elsewhere, use the plain `docker-compose.yml` and set `TREK_DB_URL` yourself.+`POSTGRES_ADMIN_PASSWORD` is the password of the database's superuser `postgres`, which on the first start only creates the role `trek`. `POSTGRES_PASSWORD` is the password of `trek`, the role TREK connects as: it owns TREK's database and is not a superuser, so a crafted backup restored into it cannot reach the database container. That password goes into `TREK_DB_URL`, so use URL-safe characters or percent-encode it. Without either password the database does not initialize and TREK does not start. An install made with an older version of the compose file connects as a superuser; [Database: Postgres](Database-Postgres#moving-a-compose-install-off-the-superuser) shows how to move it. To run it against a database that already exists elsewhere, use the plain `docker-compose.yml` and set `TREK_DB_URL` yourself.Read [Database: Postgres](Database-Postgres) before you use it. It covers the requirements, SSL, backups and restores, and the limits of a Postgres install.diff --git a/wiki/Troubleshooting.md b/wiki/Troubleshooting.mdindex 359feb46a..0ab02681c 100644--- a/wiki/Troubleshooting.md+++ b/wiki/Troubleshooting.md@@ -672,17 +672,33 @@ See [Notifications](Notifications#web-push) for the details.## Postgres: "pg_dump was not found" when backing up or restoring-**Cause:** The backup, restore or pre-migration copy runs `pg_dump`, `pg_restore` or `psql` by its absolute path. None of them is in the directories TREK searches (`/usr/lib/postgresql/17` down to `14`, `/usr/local/bin`, `/usr/bin`), and `PATH` is not searched.+**Cause:** The backup, restore or pre-migration copy runs `pg_dump`, `pg_restore` or `psql` by its absolute path. None of them is in the directories TREK searches (`/usr/lib/postgresql/18` down to `14`, `/usr/local/bin`, `/usr/bin`), and `PATH` is not searched.-**Fix:** Install the `postgresql-client` package, or set `TREK_DB_PG_BIN_DIR` to the directory that holds the three tools. The Docker image already includes the version 17 client. See [Database-Postgres](Database-Postgres#where-the-client-tools-are-found).+**Fix:** Install the `postgresql-client` package, or set `TREK_DB_PG_BIN_DIR` to the directory that holds the three tools. The Docker image already includes the version 18 client. See [Database-Postgres](Database-Postgres#where-the-client-tools-are-found).---## Postgres: a backup or restore fails with "server version mismatch" or a version error-**Cause:** Two different problems produce messages about versions. `pg_dump` from version 17 cannot dump a server running version 18 or later, and fails with `aborting because of server version mismatch`. A restore also refuses a `pg_restore` or `psql` older than 17.6, 16.10, 15.14 or 14.19, because those versions cannot restore a dump safely (CVE-2025-8714). The error names the version it found.+**Cause:** Three different problems produce messages about versions. A client tool works with servers up to its own major version, so TREK refuses a backup or restore with tools older than the server (`pg_dump is version 17, older than the PostgreSQL 18 server`). A restore also refuses a `pg_restore` or `psql` older than 18.0, 17.6, 16.10, 15.14 or 14.19, because those versions cannot restore a dump safely (CVE-2025-8714). And a client older than 16 cannot use the system's certificate authorities, so with `sslmode` set and no `sslrootcert` it is refused too. Each error names the version it found.-**Fix:** For a newer server, point `TREK_DB_PG_BIN_DIR` at client tools of the same major version as the server. For an old client, install a newer `postgresql-client` package, or use a newer image. The Docker image's client is version 17, so it works with servers 14 to 17.+**Fix:** Use the Docker image's tools, which are version 18 and work with every supported server (14 to 18), or point `TREK_DB_PG_BIN_DIR` at client tools at least as new as the server. For the certificate message, add `sslrootcert=<CA file>` to `TREK_DB_URL` or use newer tools.++---++## Postgres: TREK refuses to start because of the server version++**Cause:** TREK supports PostgreSQL 14 to 18 and refuses any other server before it writes anything (`the Postgres server is version 19; TREK supports PostgreSQL 14 to 18`).++**Fix:** Run TREK on a server of a supported version. A newer major is supported once a TREK release ships client tools for it.++---++## Postgres: a restore is refused because of the database role++**Cause:** `TREK_DB_URL` connects as a superuser, or as a role that holds `pg_execute_server_program` or `pg_write_server_files`. A backup is a SQL script that runs as this role, so TREK refuses to restore it with a role that could run commands or write files on the database server. TREK also logs a warning about such a role at startup.++**Fix:** Connect TREK as a role that owns its database and is not a superuser. See [Database-Postgres](Database-Postgres#a-role-that-is-not-a-superuser), which also shows how to move an install made with an older `docker-compose.postgres.yml`.---diff --git a/wiki/Updating.md b/wiki/Updating.mdindex 36ddb9b65..1e448f02e 100644--- a/wiki/Updating.md+++ b/wiki/Updating.md@@ -100,16 +100,62 @@ An image from 5.0 on that refuses a newer database names the copy it can run, ifOn a [PostgreSQL database](Database-Postgres) the copy TREK takes before a migration is `data/pre-migrate-<schema>-<time>.pgdump`, a `pg_dump` custom-format file, and the procedure is different from the SQLite one above. The copy holds the database only. Anything written after it was taken is lost when you roll back, and the uploads are not affected.+The copy cannot be loaded over the migrated schema: it recreates TREK's tables, its `nocase` collation, its trigger functions and its sequences, and every one of them still exists. Dropping only the tables is not enough, because the functions, the collation and the sequences a table does not own stay behind, and the load then stops at the first one that already exists. So the steps below clear the whole schema and load the copy in one transaction, the way TREK's own restore does: a load that fails leaves the database as it was.+1. Stop TREK.-2. Empty the database: drop it and create it again with the same owner, or drop the tables in its schema. `pg_restore` cannot load into a database that still holds the migrated tables.-3. Load the copy with the client tools of a version that carries the CVE-2025-8714 fix (17.6, 16.10, 15.14 or 14.19 at least):+2. Turn the copy into a SQL script, with client tools of a version that carries the CVE-2025-8714 fix (18.0, 17.6, 16.10, 15.14 or 14.19 at least) and that is at least as new as the server. Name the schema TREK's tables are in, normally `public`:++ ```bash+ pg_restore --no-owner --no-privileges --schema=public --file=restore.sql data/pre-migrate-<schema>-<time>.pgdump+ ```++3. Save this block as `clear-schema.sql`. It drops every table, view, sequence, function, collation and type in the current schema, which is what TREK's restore runs before it loads a backup:++ ```sql+ DO $clear$+ DECLARE r record;+ BEGIN+ FOR r IN SELECT c.oid::regclass AS name, c.relkind FROM pg_class c+ WHERE c.relnamespace = current_schema()::regnamespace AND c.relkind IN ('r', 'p', 'v', 'm', 'S', 'f')+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = c.oid AND d.deptype IN ('e', 'a', 'i'))+ LOOP+ EXECUTE format('DROP %s IF EXISTS %s CASCADE',+ CASE r.relkind WHEN 'v' THEN 'VIEW' WHEN 'm' THEN 'MATERIALIZED VIEW' WHEN 'S' THEN 'SEQUENCE'+ WHEN 'f' THEN 'FOREIGN TABLE' ELSE 'TABLE' END, r.name);+ END LOOP;+ FOR r IN SELECT p.oid::regprocedure AS sig FROM pg_proc p+ WHERE p.pronamespace = current_schema()::regnamespace+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e')+ LOOP+ EXECUTE format('DROP ROUTINE IF EXISTS %s CASCADE', r.sig);+ END LOOP;+ FOR r IN SELECT format('%I.%I', n.nspname, c.collname) AS name FROM pg_collation c+ JOIN pg_namespace n ON n.oid = c.collnamespace+ WHERE n.nspname = current_schema()+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = c.oid AND d.deptype = 'e')+ LOOP+ EXECUTE format('DROP COLLATION IF EXISTS %s CASCADE', r.name);+ END LOOP;+ FOR r IN SELECT t.oid::regtype AS name FROM pg_type t+ WHERE t.typnamespace = current_schema()::regnamespace AND t.typtype IN ('e', 'd', 'r')+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = t.oid AND d.deptype IN ('e', 'i'))+ LOOP+ EXECUTE format('DROP TYPE IF EXISTS %s CASCADE', r.name);+ END LOOP;+ END+ $clear$;+ ```++4. Clear the schema and load the script in one transaction, connected as TREK's own role (the URL in `TREK_DB_URL`):```bash- pg_restore --no-owner --no-privileges --single-transaction -d "postgres://user:password@host:5432/trek?sslmode=require" data/pre-migrate-<schema>-<time>.pgdump+ psql "postgres://user@host:5432/trek?sslmode=require" --no-psqlrc --single-transaction --set=ON_ERROR_STOP=1 --file=clear-schema.sql --file=restore.sql```- Use the same connection URL as `TREK_DB_URL`. The password can also come from the `PGPASSWORD` environment variable, which keeps it out of the command line.-4. Start the previous image with the same `TREK_DB_URL`.+ Put the password in the `PGPASSWORD` environment variable rather than in the URL, which keeps it out of the command line. Delete `restore.sql` afterwards: it holds the whole database in plain text.+5. Start the previous image with the same `TREK_DB_URL`.++On a server you administer, dropping the database and creating it again with the same owner, then loading the copy with `pg_restore --no-owner --no-privileges --single-transaction -d <url> <copy>`, works as well.A TREK image without PostgreSQL support cannot read this database at all. It would start on a new SQLite file instead. An image from 5.0 on that refuses a newer database names the copy it can run, if one is in the data directory.