fix(docsync): switches that did not switch off, a webhook nobody could authenticate, and a counter that only grew

More from the audit, each checked against the code before it was touched.

The webhook obeyed neither the Documents addon nor the app_settings kill
switch, so "switch document sync off" stopped the poll while every provider
holding a webhook carried on driving full runs. Both are now read on arrival
and again when the debounce timer fires, so a switch thrown mid-window still
takes effect.

Nextcloud's subscription registered its secret under `X-TREK-Docsync-Signature`
while the endpoint reads `x-trek-docsync-secret`: the subscription existed, the
calls arrived, and every one of them was dropped for carrying no secret the
controller could find. The two names now agree, and the test pins the one the
endpoint actually reads.

A WebDAV create was an unconditional PUT, so a name already taken upstream was
silently overwritten — two trips bound to one folder, or a `receipt.pdf` a
person put there by hand, is enough. Creates now send `If-None-Match: *`.

The per-item retry bookkeeping was stuck at both ends: the backoff was computed
at step 1 every time, so three of the curve's four steps were unreachable, and
the attempt counter only ever grew, which shelved a row that failed once a
month after six months of otherwise healthy syncing. A successful pass now
clears it, which is what makes the limit mean six failures in a row.

Also: a manual run on an orphaned binding is refused with 409 (its credential
belongs to somebody no longer on the trip, and the scheduler already refuses
it, so the button was a way around that); a document deleted while a run is in
flight is no longer uploaded anyway; a path-shaped WebDAV id containing `..` is
rejected instead of addressing a file outside the bound folder; and Papra's
multipart part header no longer takes an unescaped media type, which a CR could
end early.

Client: three writes in useDocSync swallowed their failure into `void` call
sites, a load failure blanked the panel to "no providers available" whatever
the cause, and overlapping loads let the slowest response win. Writes now
report, only 403/404 blanks the panel, and a generation stamp keeps the newest
answer. The dead lastRun state went with them.
This commit is contained in:
Maurice
2026-09-19 00:31:13 +02:00
parent 4fa06c3483
commit 7237a1881d
14 changed files with 692 additions and 50 deletions
@@ -2,7 +2,10 @@ import { Controller, HttpCode, OnModuleDestroy, Param, Post, Req } from '@nestjs
import type { Request } from 'express';
import crypto from 'crypto';
import { Public } from '../auth/public.decorator';
import { WEBHOOK_NUDGE_DEBOUNCE_SECONDS } from './doc-sync.constants';
import { ADDON_IDS } from '../../addons';
import { AddonsService } from '../addons/addons.service';
import { DatabaseService } from '../database/database.service';
import { SETTING_SYNC_ENABLED, WEBHOOK_NUDGE_DEBOUNCE_SECONDS } from './doc-sync.constants';
import { DocSyncConfigService } from './doc-sync-config.service';
import { DocSyncService } from './doc-sync.service';
@@ -39,8 +42,29 @@ export class DocSyncWebhookController implements OnModuleDestroy {
constructor(
private readonly config: DocSyncConfigService,
private readonly sync: DocSyncService,
private readonly addons: AddonsService,
private readonly db: DatabaseService,
) {}
/**
* The same two switches the scheduler obeys.
*
* Without them "switch document sync off" meant "stop the poll", while every
* provider holding a webhook kept driving full runs — an admin turning the
* addon off would have watched it carry on. Checked when the timer fires as
* well as on arrival, so a switch thrown during the debounce window still
* takes effect.
*/
private syncIsOn(): boolean {
if (!this.addons.isAddonEnabled(ADDON_IDS.DOCUMENTS)) return false;
const killSwitch = this.db.get<{ value: string }>(
'SELECT value FROM app_settings WHERE key = ?', SETTING_SYNC_ENABLED,
)?.value;
// Unrecognised values mean ON: the setting is absent by default, and only an
// explicit 'false' stops the sync. Same rule as the job.
return killSwitch !== 'false';
}
onModuleDestroy(): void {
for (const timer of this.pending.values()) clearTimeout(timer);
this.pending.clear();
@@ -54,6 +78,7 @@ export class DocSyncWebhookController implements OnModuleDestroy {
// Always 200, even for an unknown token: a 404 here would let anyone probe
// which tokens exist, and a provider that gets an error will retry anyway.
if (!link || link.sync_enabled !== 1) return { received: true };
if (!this.syncIsOn()) return { received: true };
const secret = this.config.webhookSecret(link);
if (secret && !this.secretMatches(req, secret)) return { received: true };
@@ -81,6 +106,7 @@ export class DocSyncWebhookController implements OnModuleDestroy {
this.pending.delete(linkId);
const fresh = reload();
if (!fresh || fresh.sync_enabled !== 1) return;
if (!this.syncIsOn()) return;
void this.sync.syncLink(fresh);
}, WEBHOOK_NUDGE_DEBOUNCE_SECONDS * 1000);
// A pending nudge must not hold the process open at shutdown.
@@ -325,6 +325,13 @@ export class DocSyncController {
) {
const link = this.config.getLink(Number(linkId));
if (!link || link.trip_id !== Number(tripId)) throw new HttpException('Link not found', 404);
// An orphaned binding stays orphaned: its credential belongs to somebody who
// is no longer on this trip, and a manual run would use it anyway. The
// scheduler already refuses it (sync_enabled is 0), so without this the
// button was a way around that.
if (link.last_sync_state === 'orphaned') {
throw new HttpException({ error: 'This binding lost its owner and has to be reconnected' }, 409);
}
// A person asking for a run is also asking for the rows that gave up to be
// tried once more; the scheduler gets no such reprieve.
this.sync.retryShelvedItems(link.id);
@@ -288,6 +288,27 @@ export function planReconcile(input: ReconcileInput): ReconcilePlan {
continue;
}
/**
* Paired upstream, absent in TREK: the download never landed.
*
* A failed pull stores the remote's version alongside the error, so on the
* next run `remoteChanged` is false, there is no local file for the other
* branches to compare against, and the row fell through to `touch` — which
* refreshes it and changes nothing. Nothing anywhere planned a second
* attempt: the document never arrived, no retry ever happened, and pressing
* "Sync now" did not help either, because the plan was the same.
*
* A rejected type and an oversized file are left out on purpose. Those are
* not transport failures; they are answers, and they stay true until the
* document upstream changes — which the `remoteChanged` branch below picks
* up on its own.
*/
if (!l && it.fileId === null && direction !== 'push'
&& it.state !== 'rejected_type' && it.state !== 'too_large') {
add({ kind: 'pull_update', remote: r, itemId: it.id });
continue;
}
if (remoteChanged && !isEcho && localChanged) {
add({ kind: 'conflict', itemId: it.id, remote: r, local: l ?? null });
continue;
+113 -8
View File
@@ -363,6 +363,14 @@ export class DocSyncService {
return 'provider_error';
}
// What this row pointed at before, if anything: a pull_update replaces a
// document TREK already holds, and `createFile` only ever inserts.
const supersededId = itemId === null
? null
: (this.db.connection
.prepare('SELECT file_id FROM document_sync_items WHERE id = ?')
.get(itemId) as { file_id: number | null } | undefined)?.file_id ?? null;
const created = this.files.createFile(
ctx.link.trip_id,
{ filename: storageKey, originalname: name, size: bytes, mimetype: remote.mimeType || 'application/octet-stream' },
@@ -372,6 +380,22 @@ export class DocSyncService {
{},
);
/**
* Retire the copy this one replaces.
*
* Into the trash rather than out of existence: the bytes it holds are a
* version somebody may still want, and TREK's own delete works the same way.
* Leaving it in place was worse than untidy — the row's pairing moves to the
* new file, so the old one is left with no sync item at all, and the very
* next run reads it as a document TREK gained and pushes the superseded
* version back up. One upstream edit then ends as two documents on both
* sides, and it grows with every further edit.
*/
if (supersededId !== null && Number(supersededId) !== Number(created.id)) {
this.files.softDeleteFile(supersededId);
this.realtime.broadcast(ctx.link.trip_id, 'file:deleted', { fileId: supersededId });
}
this.upsertItem(ctx.link, {
itemId,
remote,
@@ -407,6 +431,11 @@ export class DocSyncService {
const file = this.files.getFileById(local.fileId, ctx.link.trip_id);
if (!file) return 'not_found';
// Re-read rather than trust the plan: a run walks a whole folder, and a
// document somebody deleted in the meantime would otherwise still be
// uploaded — a delete that looks ignored, and a document that reappears
// upstream after the person watched it go.
if ((file as { deleted_at?: string | null }).deleted_at) return 'not_found';
let sha256 = local.sha256;
let stream: Readable;
@@ -573,22 +602,38 @@ export class DocSyncService {
const failed = patch.state === 'error';
if (patch.itemId !== null) {
const attempts = failed ? 1 : 0;
/**
* The attempt counter, read before it is written.
*
* Two things needed it. The backoff was computed as
* `backoffSeconds(curve, 1)` — always the first step, so three of the
* four steps in the curve were unreachable and a provider that was down
* got asked again at the same short interval. And the counter only ever
* grew: a row that failed once a month reached the limit after six months
* of otherwise healthy syncing and was shelved for good. A successful
* pass now clears it, which is what makes the limit mean "six failures in
* a row" rather than "six failures ever".
*/
const before = (this.db.connection
.prepare('SELECT attempts FROM document_sync_items WHERE id = ?')
.get(patch.itemId) as { attempts: number } | undefined)?.attempts ?? 0;
const attempts = failed ? before + 1 : 0;
this.db.connection
.prepare(
`UPDATE document_sync_items
SET state = ?, error_code = ?, file_id = COALESCE(?, file_id),
-- see the giveUp() note below: a row that has run out of
-- attempts stops retrying and waits for a person
remote_id = COALESCE(?, remote_id), remote_version = COALESCE(?, remote_version),
remote_name = COALESCE(?, remote_name), remote_size = COALESCE(?, remote_size),
remote_modified_at = COALESCE(?, remote_modified_at),
content_sha256 = COALESCE(?, content_sha256),
pushed_sha256 = COALESCE(?, pushed_sha256),
attempts = attempts + ?,
attempts = ?,
-- A row that has used up its attempts stops retrying and waits
-- for a person; planReconcile skips it and a manual run clears
-- the counter (see retryShelvedItems).
next_attempt_at = CASE
WHEN ? = 1 AND attempts + 1 < ? THEN datetime('now', '+' || ? || ' seconds')
WHEN ? = 1 AND ? < ? THEN datetime('now', '+' || ? || ' seconds')
ELSE NULL
END,
remote_missing_at = NULL,
@@ -601,7 +646,9 @@ export class DocSyncService {
remoteId, remoteVersion,
patch.remote?.name ?? null, patch.remote?.size ?? null, patch.remote?.remoteModifiedAt ?? null,
patch.contentSha256 ?? null, patch.pushedSha256 ?? null,
attempts, failed ? 1 : 0, ITEM_MAX_ATTEMPTS, backoffSeconds(ITEM_BACKOFF_SECONDS, 1), patch.state,
attempts,
failed ? 1 : 0, attempts, ITEM_MAX_ATTEMPTS,
backoffSeconds(ITEM_BACKOFF_SECONDS, attempts), patch.state,
patch.itemId,
);
return;
@@ -633,7 +680,7 @@ export class DocSyncService {
remoteId, patch.remote?.name ?? null, remoteVersion, patch.remote?.size ?? null,
patch.remote?.remoteModifiedAt ?? null, patch.contentSha256 ?? null, patch.pushedSha256 ?? null,
patch.state, patch.errorCode ?? null, failed ? 1 : 0,
failed ? 1 : 0, backoffSeconds(ITEM_BACKOFF_SECONDS, 1),
failed ? 1 : 0, backoffSeconds(ITEM_BACKOFF_SECONDS, 1), // a new row is always at its first failure
patch.state,
);
}
@@ -681,6 +728,28 @@ export class DocSyncService {
* integer and nothing else tied the two together. Same rule as everywhere in
* this codebase: every referenced id must exist AND belong to the same trip.
*/
/**
* Rename the provider's copy, outside a run.
*
* Only `resolveConflict` needs this: every other rename is planned and
* executed by a run. A failure is not fatal here — the row is left for the
* next run to sort out rather than the owner's choice being refused.
*/
private async renameRemoteTo(link: LinkRow, remoteId: string, name: string, itemId: number): Promise<void> {
const conn = this.config.getConnection(link.connection_id);
const provider = this.registry.get(link.provider_id);
if (!conn || !provider) return;
const res = await provider.rename(this.config.toRef(conn), this.config.toScopeRef(link), remoteId, name);
if (docFailed(res)) {
this.logger.warn(`link ${link.id}: renaming ${remoteId} to "${name}" failed: ${res.error.code}`);
return;
}
this.db.connection
.prepare('UPDATE document_sync_items SET remote_name = ?, remote_version = ?, last_seen_at = CURRENT_TIMESTAMP WHERE id = ?')
.run(name, res.data.remoteVersion, itemId);
}
async resolveConflict(itemId: number, keep: 'trek' | 'provider' | 'both', tripId?: number): Promise<boolean> {
const item = this.db.connection
.prepare('SELECT * FROM document_sync_items WHERE id = ?')
@@ -690,6 +759,27 @@ export class DocSyncService {
const link = this.config.getLink(Number(item.link_id));
if (!link) return false;
/**
* The name has to be decided too, not only the bytes.
*
* The only conflict the planner can actually raise today is a double
* rename, and that is arbitrated entirely by `remote_name` — the name both
* sides last agreed on. Clearing a version marker leaves all three names
* exactly as they were, so the next run compared them again, found both
* sides changed again, and wrote the conflict straight back. Whatever the
* owner picked, the issue reappeared within minutes, forever.
*
* So each choice moves the arbiter to the side that won: keeping TREK's
* name makes the agreed name TREK's (the provider then reads as the one
* that renamed, and gets renamed back), keeping the provider's takes the
* local rename back (TREK then reads as unchanged, and follows).
*/
const localName = item.file_id === null
? null
: (this.db.connection
.prepare('SELECT original_name FROM trip_files WHERE id = ?')
.get(item.file_id) as { original_name: string } | undefined)?.original_name ?? null;
if (keep === 'trek') {
// Forget the provider's version marker, so the next run sees no upstream
// change and pushes TREK's copy. Clearing content_sha256 instead would do
@@ -698,10 +788,25 @@ export class DocSyncService {
this.db.connection
.prepare("UPDATE document_sync_items SET state = 'pending', remote_version = NULL, error_code = NULL WHERE id = ?")
.run(itemId);
// Carry the name over as well, here rather than by moving the arbiter:
// TREK winning means the provider's copy takes TREK's name, and the only
// way to say that through `remote_name` would be to write the provider's
// CURRENT name into it — which this method does not know without asking.
if (localName && item.remote_id && localName !== item.remote_name) {
await this.renameRemoteTo(link, String(item.remote_id), localName, itemId);
}
} else if (keep === 'provider') {
this.db.connection
.prepare("UPDATE document_sync_items SET state = 'pending', content_sha256 = NULL, error_code = NULL WHERE id = ?")
.run(itemId);
// Take the local rename back to the agreed name. Only the provider's
// rename is then left standing, and the next run follows it the ordinary
// way — through the planner, with no special case in it.
if (item.file_id !== null && item.remote_name && localName !== item.remote_name) {
this.db.connection
.prepare('UPDATE trip_files SET original_name = ? WHERE id = ?')
.run(item.remote_name, item.file_id);
}
} else {
// Detach the pairing and let the next run pull the provider copy as a new
// document. Both versions survive, under two rows.
@@ -329,12 +329,27 @@ function escapeFormValue(value: string): string {
return value.replace(/\r/g, '%0D').replace(/\n/g, '%0A').replace(/"/g, '%22');
}
/**
* A media type that is safe to put in a header.
*
* The value comes from `trip_files.mime_type`, which an upload can influence,
* and it went into the part header untouched while the filename beside it was
* escaped. A CR or LF in it ends the header early and lets whatever follows be
* read as headers of its own. Anything that is not a plain media type is
* replaced rather than repaired: a mangled type is not worth guessing at, and
* the generic one is what an unknown file gets anyway.
*/
function safeMimeType(raw: string): string {
const TOKEN = /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+$/;
return TOKEN.test(raw) ? raw : 'application/octet-stream';
}
/** The bytes before the file in a one-field multipart body. Exported so the tests can read them. */
export function multipartHeader(boundary: string, fileName: string, mimeType: string): Buffer {
return Buffer.from(
`--${boundary}\r\n` +
`Content-Disposition: form-data; name="file"; filename="${escapeFormValue(fileName)}"\r\n` +
`Content-Type: ${mimeType}\r\n\r\n`,
`Content-Type: ${safeMimeType(mimeType)}\r\n\r\n`,
'utf8',
);
}
@@ -126,6 +126,8 @@ export interface WebdavPutOptions {
sha256: string;
/** Optimistic concurrency. Both products answer a mismatch with 412. */
ifMatch?: string;
/** `*` refuses to create over an existing resource (RFC 9110 §13.1.2). */
ifNoneMatch?: string;
}
export interface WebdavPutResult {
@@ -625,6 +627,9 @@ export class WebdavClient {
if (creds.flavor === 'nextcloud' && /^[0-9a-f]{64}$/i.test(options.sha256)) {
headers['OC-Checksum'] = `SHA256:${options.sha256.toLowerCase()}`;
}
if (options.ifNoneMatch) {
headers['If-None-Match'] = options.ifNoneMatch;
}
if (options.ifMatch) {
headers['If-Match'] = options.ifMatch;
}
@@ -55,8 +55,16 @@ const WEBHOOK_EVENTS = [
'OCP\\Files\\Events\\Node\\NodeRenamedEvent',
] as const;
/** Header the subscription carries the shared secret in; the core verifies it. */
const WEBHOOK_SECRET_HEADER = 'X-TREK-Docsync-Signature';
/**
* Header the subscription carries the shared secret in.
*
* It has to be the one the endpoint reads — `doc-sync-webhook.controller.ts`
* looks for `x-trek-docsync-secret`. It used to say `X-TREK-Docsync-Signature`
* here, so every webhook Nextcloud actually sent arrived without a secret the
* controller could find and was silently dropped: the subscription existed, the
* calls arrived, and nothing ever came of them.
*/
const WEBHOOK_SECRET_HEADER = 'x-trek-docsync-secret';
/** Where a Nextcloud connection looks for trip folders when nobody said otherwise. */
const DEFAULT_BASE_PATH = '/TREK';
@@ -554,6 +562,11 @@ export class WebdavDocumentProvider implements DocumentProvider {
mtimeSeconds: req.mtimeSeconds,
sha256: req.sha256,
ifMatch: req.expectedRemoteVersion,
// Creating means creating: an unconditional PUT to a name that is
// already taken overwrites somebody else's document without a word.
// Two trips bound to one folder, or a person who put a `receipt.pdf`
// there by hand, are enough for that to happen.
ifNoneMatch: req.remoteId ? undefined : '*',
});
// Best effort, and deliberately not fatal: the bytes are already stored,
@@ -796,7 +809,12 @@ export class WebdavDocumentProvider implements DocumentProvider {
): Promise<string | null> {
if (remoteId.startsWith(PATH_ID_PREFIX)) {
const relative = remoteId.slice(PATH_ID_PREFIX.length);
return relative ? `${resolved.rootPath}/${encodePath(relative)}` : null;
// The path comes out of a listing, which is the provider's word and not
// TREK's. A `..` in it would address a file outside the folder the trip is
// bound to — every other id here is opaque, this one is a path and has to
// be treated like one.
if (!relative || relative.split('/').some(seg => seg === '..' || seg === '.')) return null;
return `${resolved.rootPath}/${encodePath(relative)}`;
}
const cached = this.hrefCache.get(this.cacheKey(conn, scope))?.get(remoteId);