feat(documents): two-way sync with Paperless, Papra, Nextcloud, OpenCloud and Synology

A trip can be bound to a folder, tag or space in a self-hosted document store,
and documents then move in both directions: what someone uploads in TREK appears
there, and what someone files there appears in TREK.

Three decisions shape the rest.

The connection belongs to the TRIP, not to a person. Every other integration
here is per user, and photos are shared only through an opt-in flag; neither can
deliver "everyone on the trip sees the same documents", because visibility would
depend on whose credentials fetched a file, and a member without their own
Paperless account would see nothing. So the trip owner binds the trip once, the
server talks to the provider under that one identity, and TREK's own membership
decides who sees what. The provider never learns that TREK has members. When the
credential holder leaves the trip the binding goes to `orphaned` rather than
quietly carrying on with an ex-member's token.

TREK keeps the bytes. A synced document is an ordinary trip_files row, so
download, trash, offline cache, PDF export and backup keep working untouched,
and a provider outage does not blank out a trip that starts tomorrow.

Deletion never crosses the boundary on its own. A document that disappears
upstream is recorded as missing and waits for a human, and a run that sees more
than 40 percent of its known documents vanish at once refuses the whole listing
rather than acting on it: an unmounted share answers exactly like a mass delete.

The core reconciles by enumerating both sides, because the weakest provider sets
the model. A changed-since query cannot see a deletion, Papra does not move
updatedAt when a tag changes, a Paperless bulk edit leaves `modified` alone, and
Synology FileStation has no change feed at all. A webhook is therefore only ever
"look now", never a source of truth. Echo is caught by comparing content, not
timestamps: pushed_sha256 records what TREK itself wrote, so a provider
reporting TREK's own upload is not mistaken for a stranger's edit.

Provider differences are answered by capability data rather than by branching on
an id: stable ids where they exist (Paperless document id, oc:fileid, driveId)
and a normalised path where they do not, replace-in-place where the API offers
it, and a content hash from the listing only where the provider really supplies
one.

Admins switch providers on under Admin, Addons, Documents, mirroring how photo
providers hang off Journey, including the cascade and the 409 when the parent
addon is off. The per-trip setup lives in the file manager, where the person has
the context that makes the folder choice obvious.
This commit is contained in:
Maurice
2026-09-18 18:45:28 +02:00
parent 902dbbf84c
commit 2d7cb124b3
98 changed files with 20063 additions and 12 deletions
+152
View File
@@ -0,0 +1,152 @@
import type Database from 'better-sqlite3';
/**
* The five document providers and the fields their connection form asks for.
*
* Shared by the migration that introduces the tables and by `seeds.ts`, so a
* fresh install and an upgraded one end up with the same rows. Both call sites
* use INSERT OR IGNORE, which is what lets an operator rename or re-sort a row
* without a later boot undoing it.
*
* `label` and `hint` are i18n key suffixes, never display text — the client
* resolves them as `docsync.<label>`, the same way the photo provider form
* resolves `memories.<label>`.
*
* Nextcloud and OpenCloud are separate rows although one WebDAV adapter serves
* both: the fields differ (a Nextcloud login name and app password against a
* folder, an OpenCloud username and app token against a space), and an operator
* scanning the addon shelf should find the product they actually run.
*/
interface ProviderRow {
id: string;
name: string;
description: string;
icon: string;
sort_order: number;
}
interface ProviderFieldRow {
provider_id: string;
field_key: string;
label: string;
input_type: 'text' | 'url' | 'password' | 'checkbox';
placeholder: string | null;
hint: string | null;
required: 0 | 1;
secret: 0 | 1;
sort_order: number;
}
const PROVIDERS: ProviderRow[] = [
{
id: 'paperless',
name: 'Paperless-ngx',
description: 'Two-way document sync with a Paperless-ngx instance, scoped by tag',
icon: 'FileText',
sort_order: 0,
},
{
id: 'papra',
name: 'Papra',
description: 'Two-way document sync with a Papra organisation, scoped by tag',
icon: 'FileText',
sort_order: 1,
},
{
id: 'nextcloud',
name: 'Nextcloud',
description: 'Two-way document sync with a Nextcloud folder over WebDAV',
icon: 'Cloud',
sort_order: 2,
},
{
id: 'opencloud',
name: 'OpenCloud',
description: 'Two-way document sync with an OpenCloud space over WebDAV',
icon: 'Cloud',
sort_order: 3,
},
{
id: 'synologydrive',
name: 'Synology Drive',
description: 'Two-way document sync with a folder on a Synology NAS',
icon: 'HardDrive',
sort_order: 4,
},
];
/**
* `allow_insecure_tls` defaults to 0 on every provider — unlike the Synology
* photo provider, where skipping verification is the stored default. A LAN
* instance with a self-signed certificate is common enough to need the switch
* and not common enough to justify shipping it on.
*/
const FIELDS: ProviderFieldRow[] = [
// Paperless-ngx: token auth, tag scope.
{ provider_id: 'paperless', field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://paperless.example.com', hint: null, required: 1, secret: 0, sort_order: 0 },
{ provider_id: 'paperless', field_key: 'api_token', label: 'providerApiToken', input_type: 'password', placeholder: 'API token', hint: 'hintPaperlessToken', required: 1, secret: 1, sort_order: 1 },
{ provider_id: 'paperless', field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, sort_order: 2 },
// Papra: bearer key, and an organisation the key must already belong to.
{ provider_id: 'papra', field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://papra.example.com', hint: null, required: 1, secret: 0, sort_order: 0 },
{ provider_id: 'papra', field_key: 'api_key', label: 'providerApiKey', input_type: 'password', placeholder: 'ppapi_…', hint: 'hintPapraKey', required: 1, secret: 1, sort_order: 1 },
{ provider_id: 'papra', field_key: 'organization_id', label: 'providerOrganization', input_type: 'text', placeholder: 'org_…', hint: 'hintPapraOrg', required: 1, secret: 0, sort_order: 2 },
{ provider_id: 'papra', field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, sort_order: 3 },
// Nextcloud: an app password, never the account password — the latter breaks
// the moment the account turns on 2FA or logs in through OIDC.
{ provider_id: 'nextcloud', field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://cloud.example.com', hint: null, required: 1, secret: 0, sort_order: 0 },
{ provider_id: 'nextcloud', field_key: 'login_name', label: 'providerUsername', input_type: 'text', placeholder: 'username', hint: 'hintNextcloudLogin', required: 1, secret: 0, sort_order: 1 },
{ provider_id: 'nextcloud', field_key: 'app_password', label: 'providerAppPassword', input_type: 'password', placeholder: 'app password', hint: 'hintNextcloudAppPassword', required: 1, secret: 1, sort_order: 2 },
{ provider_id: 'nextcloud', field_key: 'base_path', label: 'providerBasePath', input_type: 'text', placeholder: '/TREK', hint: 'hintBasePath', required: 0, secret: 0, sort_order: 3 },
{ provider_id: 'nextcloud', field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, sort_order: 4 },
// OpenCloud: auth-app token, spaces instead of folders.
{ provider_id: 'opencloud', field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://opencloud.example.com', hint: null, required: 1, secret: 0, sort_order: 0 },
{ provider_id: 'opencloud', field_key: 'username', label: 'providerUsername', input_type: 'text', placeholder: 'username', hint: null, required: 1, secret: 0, sort_order: 1 },
{ provider_id: 'opencloud', field_key: 'app_token', label: 'providerAppToken', input_type: 'password', placeholder: 'app token', hint: 'hintOpenCloudToken', required: 1, secret: 1, sort_order: 2 },
{ provider_id: 'opencloud', field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, sort_order: 3 },
// Synology: DSM has no app tokens at all, so this is a real account. The OTP
// is used once to obtain a device token, which is what gets stored.
{ provider_id: 'synologydrive', field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://nas.example.com:5001', hint: 'hintSynologyUrl', required: 1, secret: 0, sort_order: 0 },
{ provider_id: 'synologydrive', field_key: 'username', label: 'providerUsername', input_type: 'text', placeholder: 'username', hint: 'hintSynologyUser', required: 1, secret: 0, sort_order: 1 },
{ provider_id: 'synologydrive', field_key: 'password', label: 'providerPassword', input_type: 'password', placeholder: 'password', hint: null, required: 1, secret: 1, sort_order: 2 },
{ provider_id: 'synologydrive', field_key: 'otp_code', label: 'providerOTP', input_type: 'text', placeholder: '123456', hint: 'hintSynologyOtp', required: 0, secret: 1, sort_order: 3 },
{ provider_id: 'synologydrive', field_key: 'base_path', label: 'providerBasePath', input_type: 'text', placeholder: '/trek', hint: 'hintBasePath', required: 0, secret: 0, sort_order: 4 },
{ provider_id: 'synologydrive', field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, sort_order: 5 },
];
export function seedDocumentProviders(db: Database.Database): void {
const insertProvider = db.prepare(
'INSERT OR IGNORE INTO document_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, ?, ?, 0, ?)',
);
for (const p of PROVIDERS) insertProvider.run(p.id, p.name, p.description, p.icon, p.sort_order);
const insertField = db.prepare(
`INSERT OR IGNORE INTO document_provider_fields
(provider_id, field_key, label, input_type, placeholder, hint, required, secret, settings_key, payload_key, sort_order)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
);
for (const f of FIELDS) {
// settings_key and payload_key both carry the field key: every value lands
// in one JSON column here, but the generic client form reads those two and
// would need a branch if they were null.
insertField.run(
f.provider_id,
f.field_key,
f.label,
f.input_type,
f.placeholder,
f.hint,
f.required,
f.secret,
f.secret === 1 ? null : f.field_key,
f.field_key,
f.sort_order,
);
}
}
export const DOCUMENT_PROVIDER_SEED_IDS = PROVIDERS.map((p) => p.id);
+176
View File
@@ -1,6 +1,7 @@
import { ROADTRIP_PREFERENCE_KEYS } from '@trek/shared';
import { readEnv } from '../app-config';
import { encrypt_api_key } from '../nest/common/crypto/apiKeyCrypto';
import { seedDocumentProviders } from './document-provider-seed';
import Database from 'better-sqlite3';
import fs from 'fs';
@@ -4949,6 +4950,181 @@ function runMigrations(db: Database.Database): void {
'CREATE INDEX IF NOT EXISTS idx_journey_entries_source_assignment ON journey_entries(source_place_id, source_assignment_id)',
);
},
/*
* Document providers, part 1 of 3: the registry (#214).
*
* Deliberately its own pair of tables rather than a `kind` column on
* `photo_providers`. The client filters on `type === 'photo_provider'`, the
* Journey cascade runs `UPDATE photo_providers SET enabled = 0` with no
* WHERE clause, and migrations are append-only — reusing those tables would
* change the behaviour of three existing paths, which is exactly what the
* no-breaking-changes rule forbids. The column set is copied verbatim so
* the same generic settings form renders both kinds without a special case,
* including `settings_key`/`payload_key`, which are redundant here (every
* value lands in one JSON column) but keep the client branch-free.
*/
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS document_providers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
icon TEXT DEFAULT 'FileText',
enabled INTEGER DEFAULT 0,
sort_order INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS document_provider_fields (
id INTEGER PRIMARY KEY AUTOINCREMENT,
provider_id TEXT NOT NULL REFERENCES document_providers(id) ON DELETE CASCADE,
field_key TEXT NOT NULL,
label TEXT NOT NULL,
input_type TEXT NOT NULL DEFAULT 'text',
placeholder TEXT,
hint TEXT,
required INTEGER DEFAULT 0,
secret INTEGER DEFAULT 0,
settings_key TEXT,
payload_key TEXT,
sort_order INTEGER DEFAULT 0,
UNIQUE(provider_id, field_key)
);
`);
seedDocumentProviders(db);
},
/*
* Document providers, part 2 of 3: the connection, and the trip binding.
*
* The connection carries a `trip_id`, and that is the one place this design
* departs from every integration already in the repo. Immich, Synology
* Photos, AirTrail and Dawarich all hang off a user, and even
* `trip_album_links` carries a `user_id`; photos become visible to the rest
* of a trip only through an opt-in `shared` flag. None of that can satisfy
* "everyone on the trip sees the same documents" — it would make a
* document's visibility depend on whose credentials fetched it. So the trip
* admin binds the trip once, the server talks to the provider under that
* single identity, and TREK's own membership decides who sees what.
*
* `owner_user_id` stays separate from `trip_id` so the credential holder is
* always explicit: when that person leaves the trip the binding goes to
* `orphaned` rather than silently continuing to use an ex-member's token.
*
* Secrets live in one encrypted JSON blob instead of per-provider columns:
* a sixth provider then needs no migration, and the key rotation in
* scripts/migrate-encryption.ts stays one line instead of a field list that
* someone will forget — and a forgotten column does not survive a rotation.
*/
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS document_connections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
provider_id TEXT NOT NULL REFERENCES document_providers(id) ON DELETE CASCADE,
owner_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
base_url TEXT NOT NULL,
secrets TEXT,
settings TEXT NOT NULL DEFAULT '{}',
allow_insecure_tls INTEGER NOT NULL DEFAULT 0,
capabilities TEXT,
last_probe_at TEXT,
last_probe_state TEXT NOT NULL DEFAULT 'never',
last_probe_error TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(trip_id, provider_id)
);
CREATE INDEX IF NOT EXISTS idx_document_connections_trip ON document_connections(trip_id);
CREATE INDEX IF NOT EXISTS idx_document_connections_owner ON document_connections(owner_user_id);
CREATE TABLE IF NOT EXISTS trip_document_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
connection_id INTEGER NOT NULL REFERENCES document_connections(id) ON DELETE CASCADE,
provider_id TEXT NOT NULL,
remote_scope_key TEXT NOT NULL,
remote_root_id TEXT,
remote_root_path TEXT,
remote_label TEXT NOT NULL DEFAULT '',
direction TEXT NOT NULL DEFAULT 'both',
delete_policy TEXT NOT NULL DEFAULT 'unlink',
conflict_policy TEXT NOT NULL DEFAULT 'manual',
sync_enabled INTEGER NOT NULL DEFAULT 1,
webhook_token TEXT,
webhook_secret TEXT,
webhook_subscription_id TEXT,
remote_cursor TEXT,
last_sync_at TEXT,
last_sync_state TEXT NOT NULL DEFAULT 'never',
last_sync_error TEXT,
failure_count INTEGER NOT NULL DEFAULT 0,
next_attempt_at TEXT,
created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(trip_id, connection_id, remote_scope_key)
);
CREATE INDEX IF NOT EXISTS idx_trip_document_links_trip ON trip_document_links(trip_id);
CREATE INDEX IF NOT EXISTS idx_trip_document_links_due ON trip_document_links(sync_enabled, next_attempt_at);
CREATE UNIQUE INDEX IF NOT EXISTS idx_trip_document_links_token
ON trip_document_links(webhook_token) WHERE webhook_token IS NOT NULL;
`);
},
/*
* Document providers, part 3 of 3: the pairing and its sync state.
*
* `content_sha256` and `pushed_sha256` are two columns on purpose. The
* first is the bytes both sides last agreed on, the second is what TREK
* itself last uploaded. Collapsing them into one is precisely the mistake
* that builds an echo loop: a webhook fires for TREK's own write, the core
* cannot tell it from a stranger's edit, and the file bounces.
*
* `remote_missing_at` records that something vanished upstream instead of
* acting on it — the rule Dawarich already follows with `source_missing_at`.
* An unmounted share answers with an empty listing, and reading that as
* "everything was deleted" would empty a trip.
*
* `file_id ON DELETE SET NULL` keeps a tombstone behind after a document is
* permanently deleted in TREK, so the next run does not cheerfully download
* it again.
*/
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS document_sync_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
link_id INTEGER NOT NULL REFERENCES trip_document_links(id) ON DELETE CASCADE,
trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
file_id INTEGER REFERENCES trip_files(id) ON DELETE SET NULL,
trek_doc_uid TEXT NOT NULL,
remote_id TEXT,
remote_name TEXT,
remote_version TEXT,
remote_size INTEGER,
remote_modified_at TEXT,
content_sha256 TEXT,
pushed_sha256 TEXT,
state TEXT NOT NULL DEFAULT 'pending',
error_code TEXT,
attempts INTEGER NOT NULL DEFAULT 0,
next_attempt_at TEXT,
remote_missing_at TEXT,
first_seen_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_seen_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
synced_at TEXT
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_document_sync_items_remote
ON document_sync_items(link_id, remote_id) WHERE remote_id IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_document_sync_items_file
ON document_sync_items(link_id, file_id) WHERE file_id IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_document_sync_items_uid
ON document_sync_items(link_id, trek_doc_uid);
CREATE INDEX IF NOT EXISTS idx_document_sync_items_trip_state ON document_sync_items(trip_id, state);
CREATE INDEX IF NOT EXISTS idx_document_sync_items_hash ON document_sync_items(link_id, content_sha256);
CREATE INDEX IF NOT EXISTS idx_document_sync_items_due ON document_sync_items(link_id, next_attempt_at);
`);
},
];
if (currentVersion < migrations.length) {
+8
View File
@@ -1,6 +1,7 @@
import Database from 'better-sqlite3';
import crypto from 'crypto';
import { readEnv } from '../app-config';
import { seedDocumentProviders } from './document-provider-seed';
// bcrypt cost factor for the seeded admin password — kept in sync with authService.
const BCRYPT_COST = 12;
@@ -164,6 +165,13 @@ function seedAddons(db: Database.Database): void {
for (const f of providerFields) {
insertProviderField.run(f.provider_id, f.field_key, f.label, f.input_type, f.placeholder, f.hint, f.required, f.secret, f.settings_key, f.payload_key, f.sort_order);
}
// Document providers live in their own pair of tables (see the migration
// for why they are not a `kind` column on photo_providers). Seeded from the
// same helper the migration uses, so a fresh install and an upgraded one
// agree.
seedDocumentProviders(db);
console.log('Default addons seeded');
} catch (err: unknown) {
console.error('Error seeding addons:', err instanceof Error ? err.message : err);