mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
Merge pull request #2391 from liketrek/feat/document-providers
feat(documents): two-way sync with Paperless, Papra, Nextcloud, OpenCloud and Synology
This commit is contained in:
@@ -43,6 +43,11 @@ const { db } = vi.hoisted(() => {
|
||||
check_out TEXT, confirmation TEXT, notes TEXT, created_at TEXT DEFAULT (datetime('now')));`);
|
||||
tmp.exec(`CREATE TABLE assignment_participants (assignment_id INTEGER NOT NULL, user_id INTEGER NOT NULL,
|
||||
UNIQUE(assignment_id, user_id));`);
|
||||
// A start that reorders a day re-pins that day's vias in the same transaction, so
|
||||
// the sort reads this table whenever it moves a stop.
|
||||
tmp.exec(`CREATE TABLE roadtrip_vias (id INTEGER PRIMARY KEY AUTOINCREMENT, day_id INTEGER NOT NULL,
|
||||
after_order_index INTEGER NOT NULL, sequence INTEGER NOT NULL DEFAULT 0, lat REAL NOT NULL, lng REAL NOT NULL,
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP);`);
|
||||
tmp.exec(`CREATE TABLE tags (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, color TEXT, created_at TEXT);`);
|
||||
tmp.exec(`CREATE TABLE place_tags (place_id INTEGER NOT NULL, tag_id INTEGER NOT NULL);`);
|
||||
// StorageRegistryService (behind StorageModule, now in this module chain) reads
|
||||
@@ -55,7 +60,8 @@ const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
||||
vi.mock('../../src/db/database', () => ({
|
||||
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
||||
}));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
const { broadcast } = vi.hoisted(() => ({ broadcast: vi.fn() }));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast }));
|
||||
|
||||
const { reconcileTripSkeletons } = vi.hoisted(() => ({ reconcileTripSkeletons: vi.fn() }));
|
||||
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
|
||||
@@ -213,6 +219,77 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {
|
||||
expect(reconcileTripSkeletons).toHaveBeenCalledWith(5, undefined);
|
||||
});
|
||||
|
||||
describe('PUT /:id/time and the order of the day', () => {
|
||||
const seedDay = (times: (string | null)[]) => times.map((time, i) => {
|
||||
const id = seedAssignment(3, 2, i);
|
||||
if (time) db.prepare('UPDATE day_assignments SET assignment_time = ? WHERE id = ?').run(time, id);
|
||||
return id;
|
||||
});
|
||||
const dayOrder = () =>
|
||||
(db.prepare('SELECT id FROM day_assignments WHERE day_id = 3 ORDER BY order_index, id').all() as { id: number }[]).map(r => r.id);
|
||||
const eventsSent = () => broadcast.mock.calls.map(call => call[1]);
|
||||
|
||||
beforeEach(() => broadcast.mockClear());
|
||||
|
||||
it('keeps the untimed stops in front of the stop that gets a start', async () => {
|
||||
const [a, b, c] = seedDay([null, null, null]);
|
||||
const res = await request(server)
|
||||
.put(`/api/trips/5/assignments/${c}/time`)
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.set('X-Socket-Id', 'sock-1')
|
||||
.send({ place_time: '14:00', end_time: null });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.assignment).toMatchObject({ id: c, assignment_time: '14:00', order_index: 2 });
|
||||
expect(dayOrder()).toEqual([a, b, c]);
|
||||
expect(eventsSent()).toEqual(['assignment:updated']);
|
||||
});
|
||||
|
||||
it('sorts the timed stops, keeps the untimed head first and sends the whole day', async () => {
|
||||
const [a, b, c] = seedDay([null, '15:00', null]);
|
||||
const res = await request(server)
|
||||
.put(`/api/trips/5/assignments/${c}/time`)
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.set('X-Socket-Id', 'sock-1')
|
||||
.send({ place_time: '10:00', end_time: null });
|
||||
expect(res.status).toBe(200);
|
||||
expect(dayOrder()).toEqual([a, c, b]);
|
||||
// No socket left out, so the writer gets the order too.
|
||||
expect(broadcast).toHaveBeenCalledWith('5', 'assignment:reordered', { dayId: 3, orderedIds: [a, c, b] }, undefined);
|
||||
// No located stops and no vias on this day, so there is nothing to re-pin.
|
||||
expect(eventsSent()).not.toContain('roadtripVia:changed');
|
||||
});
|
||||
|
||||
it('stores the order it sends: a day with a gap in its keys is numbered from 0', async () => {
|
||||
// The gap a deleted stop leaves. Clients number the ids they are sent by position.
|
||||
const [a, b, c] = [0, 4, 7].map(key => seedAssignment(3, 2, key));
|
||||
db.prepare('UPDATE day_assignments SET assignment_time = ? WHERE id = ?').run('15:00', b);
|
||||
const res = await request(server)
|
||||
.put(`/api/trips/5/assignments/${c}/time`)
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.send({ place_time: '10:00', end_time: null });
|
||||
expect(res.status).toBe(200);
|
||||
const sent = broadcast.mock.calls.find(call => call[1] === 'assignment:reordered')?.[2] as { orderedIds: number[] };
|
||||
expect(sent.orderedIds).toEqual([a, c, b]);
|
||||
const keyOf = (id: number) => (db.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
|
||||
expect(sent.orderedIds.map(keyOf)).toEqual([0, 1, 2]);
|
||||
expect(res.body.assignment).toMatchObject({ id: c, order_index: 1 });
|
||||
});
|
||||
|
||||
it('leaves a day dragged out of time order alone when only the End changes', async () => {
|
||||
const [a, b] = seedDay(['14:00', '10:00']);
|
||||
db.prepare("UPDATE day_assignments SET assignment_end_time = '11:00' WHERE id = ?").run(b);
|
||||
const res = await request(server)
|
||||
.put(`/api/trips/5/assignments/${b}/time`)
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.set('X-Socket-Id', 'sock-1')
|
||||
.send({ place_time: '10:00', end_time: null });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.assignment).toMatchObject({ id: b, assignment_time: '10:00', assignment_end_time: null });
|
||||
expect(dayOrder()).toEqual([a, b]);
|
||||
expect(eventsSent()).toEqual(['assignment:updated']);
|
||||
});
|
||||
});
|
||||
|
||||
it('200 participants (access-only)', async () => {
|
||||
const id = seedAssignment();
|
||||
db.prepare('INSERT INTO assignment_participants (assignment_id, user_id) VALUES (?, 2)').run(id);
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
/**
|
||||
* Document sync e2e: drives /api/trips/:tripId/docsync through the REAL
|
||||
* AddonGuard, JwtAuthGuard and TripAccessGuard, over the real DI services
|
||||
* against a temp SQLite carrying the full schema.
|
||||
*
|
||||
* Two things are replaced and nothing else:
|
||||
*
|
||||
* - `AddonsService.isAddonEnabled`, because the gate is what is under test;
|
||||
* - every provider adapter, because a test must never open a socket to
|
||||
* somebody's document archive. Each one is a spy that fails loudly if a
|
||||
* route this file exercises turns out to reach a provider after all.
|
||||
*
|
||||
* What is pinned here is the access model, which is the part of this feature
|
||||
* that would hurt most if it drifted: the addon gate answering 404 before 401,
|
||||
* a stranger being unable to see that a trip exists, and a plain member being
|
||||
* able to READ where their documents go while only the owner may change it.
|
||||
* That last split is unusual for TREK (most trip routes treat members alike),
|
||||
* so it is worth a test that fails if someone "tidies" it away.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { sessionCookie } from './harness';
|
||||
|
||||
const { db } = vi.hoisted(() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const Database = require('better-sqlite3');
|
||||
const tmp = new Database(':memory:');
|
||||
tmp.exec('PRAGMA journal_mode = WAL');
|
||||
tmp.exec('PRAGMA foreign_keys = ON');
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => ({
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: (tripId: number | string, userId: number) =>
|
||||
db
|
||||
.prepare(
|
||||
'SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)',
|
||||
)
|
||||
.get(userId, tripId, userId),
|
||||
isOwner: () => false,
|
||||
}));
|
||||
|
||||
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) }));
|
||||
vi.mock('../../src/websocket', () => ({ broadcastToUser: vi.fn(), broadcast: vi.fn() }));
|
||||
|
||||
/**
|
||||
* The SSRF guard resolves DNS, and `paperless.example.com` does not exist. In
|
||||
* CI that is a lookup failure, which the guard correctly reports as "not
|
||||
* allowed". The guard is not what this file is testing, and a suite that needs
|
||||
* a working resolver is a suite that fails on someone's train.
|
||||
*/
|
||||
vi.mock('../../src/utils/ssrfGuard', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/utils/ssrfGuard')>();
|
||||
return {
|
||||
...actual,
|
||||
checkSsrf: vi.fn(async (url: string) => ({
|
||||
allowed: !url.includes('blocked.invalid'),
|
||||
isPrivate: false,
|
||||
error: url.includes('blocked.invalid') ? 'blocked in test' : undefined,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
import { createTables } from '../../src/db/schema';
|
||||
import { runMigrations } from '../../src/db/migrations';
|
||||
import { createTrip, createUser } from '../helpers/factories';
|
||||
import { DocSyncModule } from '../../src/nest/doc-sync/doc-sync.module';
|
||||
import { DocSyncMcp } from '../../src/nest/doc-sync/doc-sync.mcp';
|
||||
import type { McpContext } from '../../src/nest-mcp';
|
||||
import { DatabaseModule } from '../../src/nest/database/database.module';
|
||||
import { AddonsService } from '../../src/nest/addons/addons.service';
|
||||
import { DOCUMENT_PROVIDERS } from '../../src/nest/doc-sync/document-provider';
|
||||
import { PaperlessDocumentProvider } from '../../src/nest/doc-sync/providers/paperless.provider';
|
||||
import { PapraDocumentProvider } from '../../src/nest/doc-sync/providers/papra.provider';
|
||||
import { SynologyDriveDocumentProvider } from '../../src/nest/doc-sync/providers/synology-drive.provider';
|
||||
import { NextcloudDocumentProvider, OpencloudDocumentProvider } from '../../src/nest/doc-sync/providers/webdav.provider';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
|
||||
/** A provider that answers plausibly but never opens a socket. */
|
||||
function fakeProvider(id: string) {
|
||||
const caps = {
|
||||
push: 'none' as const,
|
||||
stableId: true,
|
||||
remoteTrash: true,
|
||||
replaceInPlace: true,
|
||||
contentHashInListing: true,
|
||||
maxUploadBytes: null,
|
||||
acceptedMimeTypes: null,
|
||||
canCreateScope: true,
|
||||
};
|
||||
return {
|
||||
id,
|
||||
capabilities: () => caps,
|
||||
probe: vi.fn(async () => ({ success: true as const, data: { account: `${id}-account`, capabilities: caps } })),
|
||||
listScopes: vi.fn(async () => ({
|
||||
success: true as const,
|
||||
data: [{ scopeKey: `tag:1`, label: 'Japan 2026', remoteRootId: '1', remoteRootPath: '/TREK/japan' }],
|
||||
})),
|
||||
createScope: vi.fn(async (_c: unknown, name: string) => ({
|
||||
success: true as const,
|
||||
data: { scopeKey: `tag:2`, label: name, remoteRootId: '2', remoteRootPath: `/TREK/${name}` },
|
||||
})),
|
||||
resolveScope: vi.fn(async () => ({
|
||||
success: true as const,
|
||||
data: { scopeKey: 'tag:1', label: 'Japan 2026', remoteRootId: '1', remoteRootPath: '/TREK/japan' },
|
||||
})),
|
||||
list: vi.fn(async () => ({ success: true as const, data: { documents: [], cursor: 'c1', cursorUnchanged: false, truncated: false } })),
|
||||
fetch: vi.fn(async () => ({ success: false as const, error: { code: 'not_found' as const } })),
|
||||
push: vi.fn(async () => ({ success: false as const, error: { code: 'not_found' as const } })),
|
||||
rename: vi.fn(async () => ({ success: true as const, data: { remoteVersion: 'v2' } })),
|
||||
trash: vi.fn(async () => ({ success: true as const, data: undefined })),
|
||||
};
|
||||
}
|
||||
|
||||
describe('Document sync e2e (real guards + real services + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
let ownerId: number;
|
||||
let memberId: number;
|
||||
let strangerId: number;
|
||||
let tripId: number;
|
||||
|
||||
async function build() {
|
||||
const providers = [
|
||||
[PaperlessDocumentProvider, 'paperless'],
|
||||
[PapraDocumentProvider, 'papra'],
|
||||
[NextcloudDocumentProvider, 'nextcloud'],
|
||||
[OpencloudDocumentProvider, 'opencloud'],
|
||||
[SynologyDriveDocumentProvider, 'synologydrive'],
|
||||
] as const;
|
||||
let builder = Test.createTestingModule({ imports: [DatabaseModule, DocSyncModule] })
|
||||
.overrideProvider(AddonsService)
|
||||
.useValue({ isAddonEnabled });
|
||||
const fakes = providers.map(([, id]) => fakeProvider(id));
|
||||
providers.forEach(([token], i) => {
|
||||
builder = builder.overrideProvider(token).useValue(fakes[i]);
|
||||
});
|
||||
builder = builder.overrideProvider(DOCUMENT_PROVIDERS).useValue(fakes);
|
||||
const moduleRef = await builder.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
createTables(db as never);
|
||||
runMigrations(db as never);
|
||||
ownerId = createUser(db as never, { username: 'owner', email: 'owner@test.local' }).user.id;
|
||||
memberId = createUser(db as never, { username: 'member', email: 'member@test.local' }).user.id;
|
||||
strangerId = createUser(db as never, { username: 'stranger', email: 'stranger@test.local' }).user.id;
|
||||
|
||||
tripId = createTrip(db as never, ownerId, { title: 'Japan', start_date: '2026-10-01', end_date: '2026-10-07' }).id;
|
||||
db.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, memberId);
|
||||
// Providers are off by default, exactly as a fresh install ships them.
|
||||
db.prepare("UPDATE document_providers SET enabled = 1 WHERE id IN ('paperless', 'nextcloud')").run();
|
||||
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
isAddonEnabled.mockReturnValue(true);
|
||||
});
|
||||
|
||||
it('answers 404 rather than 401 when the addon is off, to everyone alike', async () => {
|
||||
isAddonEnabled.mockReturnValue(false);
|
||||
await request(server).get(`/api/trips/${tripId}/docsync/status`).expect(404);
|
||||
await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/status`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.expect(404);
|
||||
});
|
||||
|
||||
it('refuses an unauthenticated caller', async () => {
|
||||
await request(server).get(`/api/trips/${tripId}/docsync/status`).expect(401);
|
||||
});
|
||||
|
||||
it('hides the trip from a stranger behind a 404', async () => {
|
||||
await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/status`)
|
||||
.set('Cookie', sessionCookie(strangerId))
|
||||
.expect(404);
|
||||
});
|
||||
|
||||
it('lists only the providers an admin switched on', async () => {
|
||||
const res = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/providers`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.expect(200);
|
||||
expect(res.body.map((p: { id: string }) => p.id).sort()).toEqual(['nextcloud', 'paperless']);
|
||||
// Every listed provider carries its form fields, so the client renders the
|
||||
// connection form from data rather than from a hard-coded list.
|
||||
expect(res.body[0].fields.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('lets a plain member read the status but not change the binding', async () => {
|
||||
await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/status`)
|
||||
.set('Cookie', sessionCookie(memberId))
|
||||
.expect(200);
|
||||
|
||||
await request(server)
|
||||
.put(`/api/trips/${tripId}/docsync/connections`)
|
||||
.set('Cookie', sessionCookie(memberId))
|
||||
.send({ providerId: 'paperless', baseUrl: 'https://paperless.example.com', credentials: { api_token: 'x' } })
|
||||
.expect(403);
|
||||
});
|
||||
|
||||
it('refuses a provider the admin has not switched on', async () => {
|
||||
await request(server)
|
||||
.put(`/api/trips/${tripId}/docsync/connections`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ providerId: 'papra', baseUrl: 'https://papra.example.com', credentials: { api_key: 'x', organization_id: 'org_1' } })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('rejects an unknown provider id at the contract, not in the handler', async () => {
|
||||
await request(server)
|
||||
.put(`/api/trips/${tripId}/docsync/connections`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ providerId: 'dropbox', baseUrl: 'https://example.com', credentials: {} })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('stores a connection and never gives the secret back', async () => {
|
||||
const res = await request(server)
|
||||
.put(`/api/trips/${tripId}/docsync/connections`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({
|
||||
providerId: 'paperless',
|
||||
baseUrl: 'https://paperless.example.com/',
|
||||
credentials: { api_token: 'super-secret-token' },
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
expect(res.body.baseUrl).toBe('https://paperless.example.com');
|
||||
expect(res.body.secrets.api_token).toBe('••••••••');
|
||||
expect(JSON.stringify(res.body)).not.toContain('super-secret-token');
|
||||
|
||||
// And it is encrypted at rest, not merely hidden on the way out.
|
||||
const row = db.prepare('SELECT secrets FROM document_connections WHERE trip_id = ?').get(tripId) as { secrets: string };
|
||||
expect(row.secrets).toMatch(/^enc:v1:/);
|
||||
expect(row.secrets).not.toContain('super-secret-token');
|
||||
});
|
||||
|
||||
it('keeps the stored secret when the form comes back with a blank field', async () => {
|
||||
await request(server)
|
||||
.put(`/api/trips/${tripId}/docsync/connections`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ providerId: 'paperless', baseUrl: 'https://paperless.example.com', credentials: { api_token: '' } })
|
||||
.expect(200);
|
||||
const row = db.prepare('SELECT secrets FROM document_connections WHERE trip_id = ?').get(tripId) as { secrets: string };
|
||||
expect(row.secrets).toMatch(/^enc:v1:/);
|
||||
});
|
||||
|
||||
it('creates a folder or tag through the connection the path names', async () => {
|
||||
const conns = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/connections`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.expect(200);
|
||||
const res = await request(server)
|
||||
.post(`/api/trips/${tripId}/docsync/connections/${conns.body[0].id}/scopes`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ name: 'Norway' })
|
||||
.expect(201);
|
||||
expect(res.body).toMatchObject({ scopeKey: 'tag:2', label: 'Norway' });
|
||||
});
|
||||
|
||||
it('still takes a scope request from a client that sends the connection in the body too', async () => {
|
||||
// The body field was dropped in favour of the path. A client from before
|
||||
// that change has it stripped by the contract instead of being refused.
|
||||
const conns = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/connections`)
|
||||
.set('Cookie', sessionCookie(ownerId));
|
||||
await request(server)
|
||||
.post(`/api/trips/${tripId}/docsync/connections/${conns.body[0].id}/scopes`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ connectionId: conns.body[0].id, name: 'Norway' })
|
||||
.expect(201);
|
||||
});
|
||||
|
||||
it('creates no scope through a connection that belongs to another trip', async () => {
|
||||
const otherTripId = createTrip(db as never, ownerId, { title: 'Elsewhere' }).id;
|
||||
const conns = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/connections`)
|
||||
.set('Cookie', sessionCookie(ownerId));
|
||||
await request(server)
|
||||
.post(`/api/trips/${otherTripId}/docsync/connections/${conns.body[0].id}/scopes`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ name: 'Norway' })
|
||||
.expect(404);
|
||||
});
|
||||
|
||||
it('does not let a plain member create a folder or tag', async () => {
|
||||
const conns = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/connections`)
|
||||
.set('Cookie', sessionCookie(ownerId));
|
||||
await request(server)
|
||||
.post(`/api/trips/${tripId}/docsync/connections/${conns.body[0].id}/scopes`)
|
||||
.set('Cookie', sessionCookie(memberId))
|
||||
.send({ name: 'Norway' })
|
||||
.expect(403);
|
||||
});
|
||||
|
||||
it('binds the trip to a scope and reports it to every member', async () => {
|
||||
const conns = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/connections`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.expect(200);
|
||||
const connectionId = conns.body[0].id;
|
||||
|
||||
await request(server)
|
||||
.post(`/api/trips/${tripId}/docsync/links`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ connectionId, scopeKey: 'tag:1', remoteLabel: 'Japan 2026', direction: 'both', deletePolicy: 'unlink', conflictPolicy: 'manual', syncEnabled: true })
|
||||
.expect(200);
|
||||
|
||||
const asMember = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/links`)
|
||||
.set('Cookie', sessionCookie(memberId))
|
||||
.expect(200);
|
||||
expect(asMember.body).toHaveLength(1);
|
||||
expect(asMember.body[0].remoteLabel).toBe('Japan 2026');
|
||||
// The shared secret behind the webhook URL is never handed out, not even to
|
||||
// the owner: it exists so a provider can prove itself, not to be read.
|
||||
expect(asMember.body[0].webhookSecret).toBe('••••••••');
|
||||
});
|
||||
|
||||
it('changes only the setting a patch names, through the real contract', async () => {
|
||||
// The unit tests call the handler directly and never see the pipe. Through
|
||||
// it, a schema that fills in defaults turns one switch into a full reset.
|
||||
const links = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/links`)
|
||||
.set('Cookie', sessionCookie(ownerId));
|
||||
const linkId = links.body[0].id;
|
||||
await request(server)
|
||||
.patch(`/api/trips/${tripId}/docsync/links/${linkId}`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ direction: 'pull', deletePolicy: 'trash' })
|
||||
.expect(200);
|
||||
|
||||
const paused = await request(server)
|
||||
.patch(`/api/trips/${tripId}/docsync/links/${linkId}`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ syncEnabled: false })
|
||||
.expect(200);
|
||||
|
||||
expect(paused.body).toMatchObject({
|
||||
syncEnabled: false,
|
||||
direction: 'pull',
|
||||
deletePolicy: 'trash',
|
||||
conflictPolicy: 'manual',
|
||||
remoteLabel: 'Japan 2026',
|
||||
});
|
||||
});
|
||||
|
||||
it('still names the store of a binding after the admin switches its provider off', async () => {
|
||||
// The providers list drops a provider that is off, so the binding itself is
|
||||
// the only thing left that can tell a member where the documents went.
|
||||
db.prepare("UPDATE document_providers SET enabled = 0 WHERE id = 'paperless'").run();
|
||||
try {
|
||||
const providers = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/providers`)
|
||||
.set('Cookie', sessionCookie(memberId))
|
||||
.expect(200);
|
||||
expect(providers.body.map((p: { id: string }) => p.id)).not.toContain('paperless');
|
||||
|
||||
const links = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/links`)
|
||||
.set('Cookie', sessionCookie(memberId))
|
||||
.expect(200);
|
||||
expect(links.body[0]).toMatchObject({ providerId: 'paperless', providerName: 'Paperless-ngx' });
|
||||
|
||||
// The assistant reads the same bindings through its own tool.
|
||||
const ctx = { userId: memberId, scopes: null, isStaticToken: false } as McpContext;
|
||||
const result = app.get(DocSyncMcp).getTripDocumentSync({ tripId }, ctx);
|
||||
const status = JSON.parse(result.content[0].text) as { links: Array<Record<string, unknown>> };
|
||||
expect(status.links[0]).toMatchObject({ providerId: 'paperless', providerName: 'Paperless-ngx' });
|
||||
} finally {
|
||||
db.prepare("UPDATE document_providers SET enabled = 1 WHERE id = 'paperless'").run();
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a binding whose connection belongs to another trip', async () => {
|
||||
const otherTripId = createTrip(db as never, ownerId, { title: 'Other' }).id;
|
||||
const conns = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/connections`)
|
||||
.set('Cookie', sessionCookie(ownerId));
|
||||
await request(server)
|
||||
.post(`/api/trips/${otherTripId}/docsync/links`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ connectionId: conns.body[0].id, scopeKey: 'tag:1' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('answers 200 with a verdict in the body when a probe fails, not an error status', async () => {
|
||||
// The settings form needs a field to render, not an exception: the same
|
||||
// contract the photo providers pin as CRITICAL in their own e2e suite.
|
||||
const res = await request(server)
|
||||
.post(`/api/trips/${tripId}/docsync/connections/test`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ providerId: 'paperless', baseUrl: 'https://blocked.invalid', credentials: {} })
|
||||
.expect(200);
|
||||
expect(res.body.connected).toBe(false);
|
||||
expect(typeof res.body.error).toBe('string');
|
||||
});
|
||||
|
||||
it('unbinds without deleting anything', async () => {
|
||||
const links = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/links`)
|
||||
.set('Cookie', sessionCookie(ownerId));
|
||||
const linkId = links.body[0].id;
|
||||
const res = await request(server)
|
||||
.delete(`/api/trips/${tripId}/docsync/links/${linkId}`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.expect(200);
|
||||
expect(res.body.documentsKept).toBe(true);
|
||||
expect(db.prepare('SELECT COUNT(*) AS n FROM trip_document_links WHERE id = ?').get(linkId)).toEqual({ n: 0 });
|
||||
});
|
||||
|
||||
it('accepts an unknown webhook token without revealing that it is unknown', async () => {
|
||||
// A 404 here would let anyone enumerate which bindings exist.
|
||||
await request(server).post('/api/docsync/webhook/definitely-not-a-token').expect(200);
|
||||
});
|
||||
});
|
||||
@@ -403,6 +403,75 @@ describe('Tool: update_assignment_time', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// Same service method as PUT /assignments/:id/time, so the same order and the same
|
||||
// three events. A: untimed, B: 15:00, C: untimed, D gets 10:00.
|
||||
it('keeps untimed stops in place, sorts the timed ones and sends the day and its vias like REST', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const [a, b, c, d] = [0, 1, 2, 3].map(i => createDayAssignment(testDb, day.id, place.id, { order_index: i }).id);
|
||||
testDb.prepare('UPDATE day_assignments SET assignment_time = ? WHERE id = ?').run('15:00', b);
|
||||
const via = Number(testDb.prepare(
|
||||
'INSERT INTO roadtrip_vias (day_id, after_order_index, sequence, lat, lng) VALUES (?, 1, 0, 48.1, 11.5)'
|
||||
).run(day.id).lastInsertRowid);
|
||||
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({ name: 'update_assignment_time', arguments: { tripId: trip.id, assignmentId: d, place_time: '10:00' } });
|
||||
expect((parseToolResult(result) as { assignment: { assignment_time: string } }).assignment.assignment_time).toBe('10:00');
|
||||
});
|
||||
|
||||
const order = (testDb.prepare('SELECT id FROM day_assignments WHERE day_id = ? ORDER BY order_index').all(day.id) as { id: number }[]).map(r => r.id);
|
||||
expect(order).toEqual([a, d, b, c]);
|
||||
expect(testDb.prepare('SELECT after_order_index FROM roadtrip_vias WHERE id = ?').get(via)).toEqual({ after_order_index: 2 });
|
||||
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'assignment:reordered', expect.objectContaining({ dayId: day.id, orderedIds: [a, d, b, c] }));
|
||||
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'roadtripVia:changed', expect.objectContaining({
|
||||
dayId: day.id,
|
||||
vias: [expect.objectContaining({ id: via, after_order_index: 2 })],
|
||||
}));
|
||||
});
|
||||
|
||||
it('sends only the row when the start leaves the day as it was', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const [a, b, c] = [0, 1, 2].map(i => createDayAssignment(testDb, day.id, place.id, { order_index: i }).id);
|
||||
|
||||
await withHarness(user.id, async (h) => {
|
||||
await h.client.callTool({ name: 'update_assignment_time', arguments: { tripId: trip.id, assignmentId: c, place_time: '14:00' } });
|
||||
});
|
||||
|
||||
const order = (testDb.prepare('SELECT id FROM day_assignments WHERE day_id = ? ORDER BY order_index').all(day.id) as { id: number }[]).map(r => r.id);
|
||||
expect(order).toEqual([a, b, c]);
|
||||
expect(broadcastMock.mock.calls.map(call => call[1])).toEqual(['assignment:updated']);
|
||||
});
|
||||
|
||||
it('leaves a day out of time order as it is when the call names only the end', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
// B starts before A and was put behind it on purpose.
|
||||
const [a, b] = [0, 1].map(i => createDayAssignment(testDb, day.id, place.id, { order_index: i }).id);
|
||||
testDb.prepare("UPDATE day_assignments SET assignment_time = '14:00' WHERE id = ?").run(a);
|
||||
testDb.prepare("UPDATE day_assignments SET assignment_time = '10:00' WHERE id = ?").run(b);
|
||||
const via = Number(testDb.prepare(
|
||||
'INSERT INTO roadtrip_vias (day_id, after_order_index, sequence, lat, lng) VALUES (?, 0, 0, 48.1, 11.5)'
|
||||
).run(day.id).lastInsertRowid);
|
||||
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({ name: 'update_assignment_time', arguments: { tripId: trip.id, assignmentId: b, end_time: '11:30' } });
|
||||
expect((parseToolResult(result) as { assignment: { assignment_time: string; assignment_end_time: string } }).assignment)
|
||||
.toMatchObject({ assignment_time: '10:00', assignment_end_time: '11:30' });
|
||||
});
|
||||
|
||||
const order = (testDb.prepare('SELECT id FROM day_assignments WHERE day_id = ? ORDER BY order_index').all(day.id) as { id: number }[]).map(r => r.id);
|
||||
expect(order).toEqual([a, b]);
|
||||
expect(testDb.prepare('SELECT after_order_index FROM roadtrip_vias WHERE id = ?').get(via)).toEqual({ after_order_index: 0 });
|
||||
expect(broadcastMock.mock.calls.map(call => call[1])).toEqual(['assignment:updated']);
|
||||
});
|
||||
|
||||
it('returns error when assignment not found', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
* (it replaced ADMIN-BR-001 when the old admin bridge died with the cron move).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
|
||||
import { ADDON_IDS, MCP_GATED_ADDON_IDS } from '../../../src/addons';
|
||||
|
||||
// ── DB setup ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -502,9 +503,19 @@ describe('updateAddon', () => {
|
||||
// real flip of an MCP-relevant addon → invalidate
|
||||
expect((updateAddon('packing', { enabled: false }) as any).mcpAffected).toBe(true);
|
||||
expect((updateAddon('packing', { enabled: true }) as any).mcpAffected).toBe(true);
|
||||
// real flip of an addon with no MCP surface → sessions survive
|
||||
// real flip of an addon with no MCP surface → sessions survive. Taken from
|
||||
// the list rather than named, because an addon that grows MCP tools joins it
|
||||
// and would otherwise turn this assertion false without changing anything
|
||||
// it is actually about (documents did, when document sync landed).
|
||||
const noMcp = Object.values(ADDON_IDS).find(id => !MCP_GATED_ADDON_IDS.includes(id));
|
||||
if (noMcp) {
|
||||
const flip = updateAddon(noMcp, { enabled: false }) as any;
|
||||
if (!flip.error) expect(flip.mcpAffected).toBe(false);
|
||||
}
|
||||
|
||||
// and the one this change put on the list carries the opposite verdict
|
||||
const docsFlip = updateAddon('documents', { enabled: false }) as any;
|
||||
if (!docsFlip.error) expect(docsFlip.mcpAffected).toBe(false);
|
||||
if (!docsFlip.error) expect(docsFlip.mcpAffected).toBe(true);
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-087 — refuses to enable a photo provider while journey is off', () => {
|
||||
|
||||
@@ -99,13 +99,32 @@ describe('AssignmentOpsController (parity with the per-assignment op routes)', (
|
||||
|
||||
it('PUT /:id/time 404 missing, else updates', () => {
|
||||
expect(thrown(() => new AssignmentOpsController(svc({ getAssignmentForTrip: vi.fn().mockReturnValue(undefined) } as Partial<AssignmentsService>)).time(user, '5', '9', {}))).toEqual({ status: 404, body: { error: 'Assignment not found' } });
|
||||
const updateTime = vi.fn().mockReturnValue({ id: 9 }); const broadcast = vi.fn(); const reconcile = vi.fn();
|
||||
const updateTime = vi.fn().mockReturnValue({ assignment: { id: 9 }, reordered: null, vias: null }); const broadcast = vi.fn(); const reconcile = vi.fn();
|
||||
const s = svc({ getAssignmentForTrip: vi.fn().mockReturnValue({ id: 9 }), updateTime, broadcast, reconcile } as Partial<AssignmentsService>);
|
||||
expect(new AssignmentOpsController(s).time(user, '5', '9', { place_time: '10:00' }, 'sock')).toEqual({ assignment: { id: 9 } });
|
||||
expect(updateTime).toHaveBeenCalledWith('9', '10:00', undefined);
|
||||
// Nothing moved, so the row is all collaborators hear about.
|
||||
expect(broadcast.mock.calls).toEqual([['5', 'assignment:updated', { assignment: { id: 9 } }, 'sock']]);
|
||||
expect(reconcile).toHaveBeenCalledWith('5', 'sock');
|
||||
});
|
||||
|
||||
it('PUT /:id/time sends the whole day and the re-pinned vias to every socket when a start moved stops', () => {
|
||||
const reordered = { dayId: 3, orderedIds: [7, 9, 8] };
|
||||
const vias = { dayId: 3, vias: [{ id: 40, day_id: 3, after_order_index: 1, sequence: 0, lat: 1, lng: 2 }] };
|
||||
const updateTime = vi.fn().mockReturnValue({ assignment: { id: 9 }, reordered, vias }); const broadcast = vi.fn();
|
||||
const s = svc({ getAssignmentForTrip: vi.fn().mockReturnValue({ id: 9 }), updateTime, broadcast } as Partial<AssignmentsService>);
|
||||
|
||||
expect(new AssignmentOpsController(s).time(user, '5', '9', { place_time: '10:00' }, 'sock')).toEqual({ assignment: { id: 9 } });
|
||||
|
||||
expect(broadcast.mock.calls).toEqual([
|
||||
['5', 'assignment:updated', { assignment: { id: 9 } }, 'sock'],
|
||||
// The writer's socket too, so the order and the vias pinned to it arrive
|
||||
// together there as well, a replayed offline save included.
|
||||
['5', 'assignment:reordered', reordered, undefined],
|
||||
['5', 'roadtripVia:changed', vias, undefined],
|
||||
]);
|
||||
});
|
||||
|
||||
it('PUT /:id/notes 404 missing, else updates + broadcasts (#2163)', () => {
|
||||
expect(thrown(() => new AssignmentOpsController(svc({ getAssignmentForTrip: vi.fn().mockReturnValue(undefined) } as Partial<AssignmentsService>)).notes(user, '5', '9', { notes: 'n' }))).toEqual({ status: 404, body: { error: 'Assignment not found' } });
|
||||
const updateNotes = vi.fn().mockReturnValue({ id: 9, notes: 'Book the 10:00 entry' }); const broadcast = vi.fn(); const reconcile = vi.fn();
|
||||
|
||||
@@ -348,25 +348,56 @@ describe('getParticipants / setParticipants', () => {
|
||||
// ── updateTime / setLegTransportMode ──────────────────────────────────────────
|
||||
|
||||
describe('updateTime', () => {
|
||||
const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
|
||||
/** The day the way every reader lists it: by order_index, then insertion. */
|
||||
const dayOrder = (dayId: number) =>
|
||||
(testDb.prepare('SELECT id FROM day_assignments WHERE day_id = ? ORDER BY order_index, created_at, id').all(dayId) as { id: number }[]).map(r => r.id);
|
||||
|
||||
/**
|
||||
* A day of stops at the given order_index keys, each with its own start (null for
|
||||
* none). Times go in by SQL so the setup itself never sorts anything.
|
||||
*/
|
||||
function dayOf(stops: [string | null, number][]) {
|
||||
const { trip, day, place } = fixture();
|
||||
const ids = stops.map(([time, orderIndex]) => {
|
||||
const a = createDayAssignment(testDb, day.id, place.id, { order_index: orderIndex });
|
||||
if (time) testDb.prepare('UPDATE day_assignments SET assignment_time = ? WHERE id = ?').run(time, a.id);
|
||||
return a.id;
|
||||
});
|
||||
return { trip, day, ids };
|
||||
}
|
||||
|
||||
function addVia(dayId: number, afterOrderIndex: number, sequence = 0): number {
|
||||
return Number(testDb.prepare(
|
||||
'INSERT INTO roadtrip_vias (day_id, after_order_index, sequence, lat, lng) VALUES (?, ?, ?, 48.1, 11.5)'
|
||||
).run(dayId, afterOrderIndex, sequence).lastInsertRowid);
|
||||
}
|
||||
const viaAnchors = (dayId: number) =>
|
||||
testDb.prepare('SELECT id, after_order_index, sequence FROM roadtrip_vias WHERE day_id = ? ORDER BY id').all(dayId);
|
||||
|
||||
it('ASG-SVC-021: persists both times and re-selects the nested shape', () => {
|
||||
const { day, place } = fixture();
|
||||
const a = createDayAssignment(testDb, day.id, place.id);
|
||||
const updated = svc.updateTime(a.id, '09:00', '11:30');
|
||||
expect(updated).toMatchObject({ id: a.id, assignment_time: '09:00', assignment_end_time: '11:30' });
|
||||
const { assignment } = svc.updateTime(a.id, '09:00', '11:30');
|
||||
expect(assignment).toMatchObject({ id: a.id, assignment_time: '09:00', assignment_end_time: '11:30' });
|
||||
});
|
||||
|
||||
it('ASG-SVC-022: a truthy place_time auto-sorts the day chronologically (untimed keep relative position)', () => {
|
||||
const { day, place } = fixture();
|
||||
const a = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
|
||||
const b = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
|
||||
const c = createDayAssignment(testDb, day.id, place.id, { order_index: 2 });
|
||||
it('ASG-SVC-022: a start sorts the timed stops and leaves every untimed stop behind the one it followed', () => {
|
||||
// The tester's day: two stops without a time, then a start on the last one. It
|
||||
// used to jump to the top, because every untimed stop was appended after it.
|
||||
const untimedHead = dayOf([[null, 0], [null, 1], [null, 2]]);
|
||||
svc.updateTime(untimedHead.ids[2], '14:00', null);
|
||||
expect(dayOrder(untimedHead.day.id)).toEqual(untimedHead.ids);
|
||||
|
||||
svc.updateTime(c.id, '08:00', null);
|
||||
const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
|
||||
expect([order(c.id), order(a.id), order(b.id)]).toEqual([0, 1, 2]);
|
||||
const between = dayOf([['09:00', 0], [null, 1], [null, 2]]);
|
||||
svc.updateTime(between.ids[2], '14:00', null);
|
||||
expect(dayOrder(between.day.id)).toEqual(between.ids);
|
||||
|
||||
svc.updateTime(a.id, '07:00', null);
|
||||
expect([order(a.id), order(c.id), order(b.id)]).toEqual([0, 1, 2]);
|
||||
// Timed stops still keep time order among themselves. A has nothing timed in
|
||||
// front of it and stays first.
|
||||
const [a, b, c] = dayOf([[null, 0], ['15:00', 1], [null, 2]]).ids;
|
||||
svc.updateTime(c, '10:00', null);
|
||||
expect([order(a), order(c), order(b)]).toEqual([0, 1, 2]);
|
||||
});
|
||||
|
||||
it('ASG-SVC-022b: a booked night sorts by its check-in, which is where its hour lives', () => {
|
||||
@@ -384,34 +415,33 @@ describe('updateTime', () => {
|
||||
|
||||
svc.updateTime(afternoon.id, '16:00', null);
|
||||
|
||||
const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
|
||||
expect(order(night.id)).toBeLessThan(order(afternoon.id));
|
||||
});
|
||||
|
||||
it('ASG-SVC-023: clearing with null persists but skips the auto-sort (falsy gate)', () => {
|
||||
const { day, place } = fixture();
|
||||
const a = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
|
||||
const b = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
|
||||
svc.updateTime(b.id, '06:00', null); // sorts b first
|
||||
const updated = svc.updateTime(b.id, null, null); // clear — no re-sort
|
||||
expect(updated!.assignment_time).toBeNull();
|
||||
const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
|
||||
expect(order(b.id)).toBe(0);
|
||||
expect(order(a.id)).toBe(1);
|
||||
const { day, ids: [a, b, c] } = dayOf([['09:00', 0], [null, 1], ['12:00', 2]]);
|
||||
svc.updateTime(b, '06:00', null); // sorts b first
|
||||
expect(dayOrder(day.id)).toEqual([b, a, c]);
|
||||
// Dragged back out of time order on purpose: a sort now would put b first again,
|
||||
// with c behind it.
|
||||
svc.reorderAssignments(day.id, [a, b, c]);
|
||||
|
||||
const { assignment } = svc.updateTime(c, null, null); // clear, no re-sort
|
||||
expect(assignment!.assignment_time).toBeNull();
|
||||
expect(dayOrder(day.id)).toEqual([a, b, c]);
|
||||
});
|
||||
|
||||
it('ASG-SVC-027: an empty-string time clears the override like null (and skips the auto-sort)', () => {
|
||||
const { day, place } = fixture();
|
||||
const a = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
|
||||
const b = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
|
||||
svc.updateTime(b.id, '06:00', '07:00'); // sorts b first
|
||||
const updated = svc.updateTime(b.id, '', '');
|
||||
expect(updated!.assignment_time).toBeNull();
|
||||
expect(updated!.assignment_end_time).toBeNull();
|
||||
expect(testDb.prepare('SELECT assignment_time FROM day_assignments WHERE id = ?').get(b.id)).toEqual({ assignment_time: null });
|
||||
const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
|
||||
expect(order(b.id)).toBe(0);
|
||||
expect(order(a.id)).toBe(1);
|
||||
const { day, ids: [a, b, c] } = dayOf([['09:00', 0], [null, 1], ['12:00', 2]]);
|
||||
svc.updateTime(b, '06:00', '07:00'); // sorts b first
|
||||
expect(dayOrder(day.id)).toEqual([b, a, c]);
|
||||
svc.reorderAssignments(day.id, [a, b, c]);
|
||||
|
||||
const { assignment } = svc.updateTime(c, '', '');
|
||||
expect(assignment!.assignment_time).toBeNull();
|
||||
expect(assignment!.assignment_end_time).toBeNull();
|
||||
expect(testDb.prepare('SELECT assignment_time FROM day_assignments WHERE id = ?').get(c)).toEqual({ assignment_time: null });
|
||||
expect(dayOrder(day.id)).toEqual([a, b, c]);
|
||||
});
|
||||
|
||||
it('ASG-SVC-024: a time without ":" sorts last among timed via the 99:99 sentinel', () => {
|
||||
@@ -420,10 +450,164 @@ describe('updateTime', () => {
|
||||
const b = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
|
||||
svc.updateTime(a.id, 'morning', null); // no colon → '99:99' in the sort
|
||||
svc.updateTime(b.id, '13:00', null);
|
||||
const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
|
||||
expect(order(b.id)).toBe(0);
|
||||
expect(order(a.id)).toBe(1);
|
||||
});
|
||||
|
||||
it('ASG-SVC-033: writes nothing but the time when the day is already in order', () => {
|
||||
// Keys with gaps, as a deleted stop leaves them. A day the start leaves in order
|
||||
// keeps them: nothing about it changed.
|
||||
const { day, ids: [a, b, c] } = dayOf([['09:00', 0], [null, 5], [null, 9]]);
|
||||
const via = addVia(day.id, 0);
|
||||
const changes = () => (testDb.prepare('SELECT total_changes() AS n').get() as { n: number }).n;
|
||||
const before = changes();
|
||||
|
||||
const update = svc.updateTime(c, '14:00', null);
|
||||
|
||||
expect(changes() - before).toBe(1);
|
||||
expect([order(a), order(b), order(c)]).toEqual([0, 5, 9]);
|
||||
expect(viaAnchors(day.id)).toEqual([{ id: via, after_order_index: 0, sequence: 0 }]);
|
||||
expect(update.reordered).toBeNull();
|
||||
expect(update.vias).toBeNull();
|
||||
});
|
||||
|
||||
it('ASG-SVC-034: numbers a reordered day from 0, the key each client gives a stop of the order it is sent', () => {
|
||||
// A gap, as a deleted stop leaves it. Kept, the writer would read 0, 4, 7 back and
|
||||
// everyone else would apply 0, 1, 2, and a note at 3 would sit behind a different
|
||||
// stop for each of them.
|
||||
const { day, ids: [a, b, c] } = dayOf([[null, 0], ['15:00', 4], [null, 7]]);
|
||||
const changes = () => (testDb.prepare('SELECT total_changes() AS n').get() as { n: number }).n;
|
||||
const before = changes();
|
||||
|
||||
const update = svc.updateTime(c, '10:00', null);
|
||||
|
||||
expect(update.reordered).toEqual({ dayId: day.id, orderedIds: [a, c, b] });
|
||||
expect(update.reordered!.orderedIds.map(order)).toEqual([0, 1, 2]);
|
||||
// The time, then c and b. A already holds 0 and is not written.
|
||||
expect(changes() - before).toBe(3);
|
||||
});
|
||||
|
||||
it('ASG-SVC-035: numbers a day with colliding keys from 0 again, since a shared key cannot hold an order', () => {
|
||||
// A move drops a stop in at order_index 0 next to the one already there.
|
||||
const { day, ids: [a, b, c] } = dayOf([[null, 0], ['15:00', 0], [null, 0]]);
|
||||
|
||||
svc.updateTime(c, '10:00', null);
|
||||
|
||||
expect(dayOrder(day.id)).toEqual([a, c, b]);
|
||||
expect([order(a), order(c), order(b)]).toEqual([0, 1, 2]);
|
||||
});
|
||||
|
||||
it('ASG-SVC-036: keeps each drawn road behind the stop it was drawn after, counting located stops only', () => {
|
||||
// X has no coordinates, so the router never sees it and the vias do not count it.
|
||||
const { trip, day, ids: [a, x, b, c, d] } = dayOf([[null, 0], [null, 1], ['15:00', 2], [null, 3], [null, 4]]);
|
||||
const unmapped = createPlace(testDb, trip.id, { name: 'Somewhere unmapped' });
|
||||
testDb.prepare('UPDATE places SET lat = NULL, lng = NULL WHERE id = ?').run(unmapped.id);
|
||||
testDb.prepare('UPDATE day_assignments SET place_id = ? WHERE id = ?').run(unmapped.id, x);
|
||||
const afterA = addVia(day.id, 0);
|
||||
const afterB = addVia(day.id, 1);
|
||||
const afterBToo = addVia(day.id, 1, 1);
|
||||
addVia(day.id, 2); // after C
|
||||
|
||||
// D at 10:00 goes in front of B at 15:00, and C stays behind B: A, X, D, B, C.
|
||||
const update = svc.updateTime(d, '10:00', null);
|
||||
|
||||
expect(dayOrder(day.id)).toEqual([a, x, d, b, c]);
|
||||
// A keeps its leg, B's two points follow B to 2 in their order, and C, now last,
|
||||
// has no leg left to bend.
|
||||
expect(viaAnchors(day.id)).toEqual([
|
||||
{ id: afterA, after_order_index: 0, sequence: 0 },
|
||||
{ id: afterB, after_order_index: 2, sequence: 0 },
|
||||
{ id: afterBToo, after_order_index: 2, sequence: 1 },
|
||||
]);
|
||||
expect(update.reordered).toEqual({ dayId: day.id, orderedIds: [a, x, d, b, c] });
|
||||
expect(update.vias?.dayId).toBe(day.id);
|
||||
expect(update.vias?.vias.map(v => [v.id, v.after_order_index])).toEqual([[afterA, 0], [afterB, 2], [afterBToo, 2]]);
|
||||
});
|
||||
|
||||
it('ASG-SVC-037: reports no vias when the reorder leaves every one on its stop', () => {
|
||||
const { day, ids: [a, b, c] } = dayOf([[null, 0], ['15:00', 1], [null, 2]]);
|
||||
const via = addVia(day.id, 0);
|
||||
|
||||
const update = svc.updateTime(c, '10:00', null);
|
||||
|
||||
expect(update.reordered).toEqual({ dayId: day.id, orderedIds: [a, c, b] });
|
||||
expect(viaAnchors(day.id)).toEqual([{ id: via, after_order_index: 0, sequence: 0 }]);
|
||||
expect(update.vias).toBeNull();
|
||||
});
|
||||
|
||||
it('ASG-SVC-038: leaves every via alone when the sort moves only stops without coordinates', () => {
|
||||
// X has no coordinates. It goes between A and B, and the located stops stay A, B.
|
||||
const { trip, day, ids: [a, b, x] } = dayOf([['09:00', 0], ['12:00', 1], [null, 2]]);
|
||||
const unmapped = createPlace(testDb, trip.id, { name: 'Somewhere unmapped' });
|
||||
testDb.prepare('UPDATE places SET lat = NULL, lng = NULL WHERE id = ?').run(unmapped.id);
|
||||
testDb.prepare('UPDATE day_assignments SET place_id = ? WHERE id = ?').run(unmapped.id, x);
|
||||
const afterA = addVia(day.id, 0);
|
||||
// Behind the day's last stop: the drive into the next day on a trip with connected
|
||||
// days. It was deleted here, since a last stop has no leg of its own.
|
||||
const intoTomorrow = addVia(day.id, 1);
|
||||
|
||||
const update = svc.updateTime(x, '10:00', null);
|
||||
|
||||
expect(dayOrder(day.id)).toEqual([a, x, b]);
|
||||
expect(update.reordered).toEqual({ dayId: day.id, orderedIds: [a, x, b] });
|
||||
expect(viaAnchors(day.id)).toEqual([
|
||||
{ id: afterA, after_order_index: 0, sequence: 0 },
|
||||
{ id: intoTomorrow, after_order_index: 1, sequence: 0 },
|
||||
]);
|
||||
expect(update.vias).toBeNull();
|
||||
});
|
||||
|
||||
it('ASG-SVC-039: keeps the via behind the last stop when that stop is still last', () => {
|
||||
const { day, ids: [a, b, c, d] } = dayOf([[null, 0], ['15:00', 1], [null, 2], ['18:00', 3]]);
|
||||
const afterB = addVia(day.id, 1);
|
||||
const intoTomorrow = addVia(day.id, 3);
|
||||
|
||||
// C at 10:00 goes in front of B. D stays last, and so does the drive out of it.
|
||||
const update = svc.updateTime(c, '10:00', null);
|
||||
|
||||
expect(dayOrder(day.id)).toEqual([a, c, b, d]);
|
||||
expect(viaAnchors(day.id)).toEqual([
|
||||
{ id: afterB, after_order_index: 2, sequence: 0 },
|
||||
{ id: intoTomorrow, after_order_index: 3, sequence: 0 },
|
||||
]);
|
||||
expect(update.vias?.vias.map(v => [v.id, v.after_order_index])).toEqual([[afterB, 2], [intoTomorrow, 3]]);
|
||||
});
|
||||
|
||||
it('ASG-SVC-040: an End saved with the start as it stood leaves a day dragged out of time order alone', () => {
|
||||
// B belongs first by time, and the traveller put it second on purpose.
|
||||
const { day, ids: [a, b, c] } = dayOf([['14:00', 0], ['10:00', 1], ['16:00', 2]]);
|
||||
testDb.prepare("UPDATE day_assignments SET assignment_end_time = '11:00' WHERE id = ?").run(b);
|
||||
const afterA = addVia(day.id, 0);
|
||||
|
||||
// The stay dialog taking the End off, then the place form setting a new one.
|
||||
for (const end of [null, '12:00']) {
|
||||
const update = svc.updateTime(b, '10:00', end);
|
||||
expect(update.assignment).toMatchObject({ assignment_time: '10:00', assignment_end_time: end });
|
||||
expect(update.reordered).toBeNull();
|
||||
expect(update.vias).toBeNull();
|
||||
expect(dayOrder(day.id)).toEqual([a, b, c]);
|
||||
expect(viaAnchors(day.id)).toEqual([{ id: afterA, after_order_index: 0, sequence: 0 }]);
|
||||
}
|
||||
|
||||
// A start that moves still sorts, and the via follows A.
|
||||
const update = svc.updateTime(b, '09:00', '12:00');
|
||||
expect(dayOrder(day.id)).toEqual([b, a, c]);
|
||||
expect(update.reordered).toEqual({ dayId: day.id, orderedIds: [b, a, c] });
|
||||
expect(viaAnchors(day.id)).toEqual([{ id: afterA, after_order_index: 1, sequence: 0 }]);
|
||||
});
|
||||
|
||||
it('ASG-SVC-041: a visit given the start its place already had does not sort either', () => {
|
||||
// The place form fills Start from the place when the visit has none of its own.
|
||||
const { trip, day, ids: [a, b] } = dayOf([['14:00', 0], [null, 1]]);
|
||||
const timedPlace = createPlace(testDb, trip.id, { name: 'Opens at ten' });
|
||||
testDb.prepare("UPDATE places SET place_time = '10:00' WHERE id = ?").run(timedPlace.id);
|
||||
testDb.prepare('UPDATE day_assignments SET place_id = ? WHERE id = ?').run(timedPlace.id, b);
|
||||
|
||||
const update = svc.updateTime(b, '10:00', '11:00');
|
||||
|
||||
expect(update.reordered).toBeNull();
|
||||
expect(dayOrder(day.id)).toEqual([a, b]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateNotes (#2163)', () => {
|
||||
@@ -451,7 +635,9 @@ describe('updateNotes (#2163)', () => {
|
||||
svc.updateTime(a.id, '09:00', '10:00');
|
||||
const updated = svc.updateNotes(a.id, 'note');
|
||||
expect(updated).toMatchObject({ assignment_time: '09:00', assignment_end_time: '10:00' });
|
||||
expect((testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(a.id) as { order_index: number }).order_index).toBe(0);
|
||||
// 3, not 0: a start on a day already in order no longer renumbers it, so the key
|
||||
// this note edit must not touch is still the one the stop was created with.
|
||||
expect((testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(a.id) as { order_index: number }).order_index).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,647 @@
|
||||
/**
|
||||
* The configuration half of document sync: the connection a trip admin creates
|
||||
* and the binding that points it at a folder or a tag.
|
||||
*
|
||||
* The database here is real in-memory SQLite with the full schema, and the
|
||||
* at-rest crypto is real too. Both are deliberate. Almost everything this
|
||||
* service owns is either a credential or a decision about one, and a spy on
|
||||
* `db.run` would only prove that some strings were handed along. Reading the
|
||||
* row back is the assertion. A stubbed `maybe_encrypt_api_key` would let a
|
||||
* regression that stores a Paperless token in plaintext pass every case below.
|
||||
*
|
||||
* Only the SSRF guard is faked, because it resolves DNS: the guard is not what
|
||||
* is under test, and a suite that needs a working resolver is a suite that
|
||||
* fails on someone's train.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
return {
|
||||
testDb: db,
|
||||
dbMock: {
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: () => undefined,
|
||||
isOwner: () => false,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../../../src/db/database', () => dbMock);
|
||||
|
||||
// The whole guard surface, not only `checkSsrf`: modules on the import graph
|
||||
// pull other names off it, and a factory mock that omits one throws on access
|
||||
// rather than falling back to the real export.
|
||||
const { checkSsrf } = vi.hoisted(() => ({ checkSsrf: vi.fn() }));
|
||||
vi.mock('../../../../src/utils/ssrfGuard', () => ({
|
||||
checkSsrf,
|
||||
safeFetch: vi.fn(),
|
||||
safeFetchFollow: vi.fn(),
|
||||
safeFetchAdminConfigured: vi.fn(),
|
||||
safeFetchLlm: vi.fn(),
|
||||
createPinnedDispatcher: vi.fn(() => ({})),
|
||||
SsrfBlockedError: class extends Error {},
|
||||
}));
|
||||
|
||||
import { DOCSYNC_SECRET_MASK, type DocsyncConnectionInput, type DocsyncLinkInput } from '@trek/shared';
|
||||
import { createTables } from '../../../../src/db/schema';
|
||||
import { runMigrations } from '../../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTrip, createUser } from '../../../helpers/factories';
|
||||
import { DatabaseService } from '../../../../src/nest/database/database.service';
|
||||
import {
|
||||
DocSyncConfigService,
|
||||
type ConnectionRow,
|
||||
type LinkRow,
|
||||
} from '../../../../src/nest/doc-sync/doc-sync-config.service';
|
||||
import type { DocumentProviderRegistry } from '../../../../src/nest/doc-sync/document-provider.registry';
|
||||
// `if (!result.success)` does not narrow in this workspace: strictNullChecks is
|
||||
// off, so the boolean discriminant stops discriminating. The domain's own
|
||||
// predicate is what every call site uses instead.
|
||||
import { docFailed } from '../../../../src/nest/doc-sync/document-provider';
|
||||
|
||||
const svc = new DocSyncConfigService(new DatabaseService(testDb), {} as DocumentProviderRegistry);
|
||||
|
||||
const TOKEN = 'paperless-token-1234';
|
||||
|
||||
let OWNER = 0;
|
||||
let MEMBER = 0;
|
||||
let TRIP = 0;
|
||||
|
||||
function connectionInput(over: Partial<DocsyncConnectionInput> = {}): DocsyncConnectionInput {
|
||||
return {
|
||||
providerId: 'paperless',
|
||||
baseUrl: 'https://paperless.example.com',
|
||||
credentials: { api_token: TOKEN },
|
||||
allowInsecureTls: false,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
async function connect(over: Partial<DocsyncConnectionInput> = {}, userId = OWNER): Promise<ConnectionRow> {
|
||||
const result = await svc.upsertConnection(TRIP, userId, connectionInput(over));
|
||||
if (docFailed(result)) throw new Error(`fixture connection refused: ${JSON.stringify(result.error)}`);
|
||||
return result.data;
|
||||
}
|
||||
|
||||
function linkInput(connectionId: number, over: Partial<DocsyncLinkInput> = {}): DocsyncLinkInput {
|
||||
return {
|
||||
connectionId,
|
||||
scopeKey: 'tag:1',
|
||||
remoteLabel: 'Japan 2026',
|
||||
direction: 'both',
|
||||
deletePolicy: 'unlink',
|
||||
conflictPolicy: 'manual',
|
||||
syncEnabled: true,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function link(connectionId: number, over: Partial<DocsyncLinkInput> = {}): LinkRow {
|
||||
const result = svc.createLink(TRIP, OWNER, linkInput(connectionId, over));
|
||||
if (docFailed(result)) throw new Error(`fixture link refused: ${JSON.stringify(result.error)}`);
|
||||
return result.data;
|
||||
}
|
||||
|
||||
function storedSecret(connectionId: number): string | undefined {
|
||||
const row = svc.getConnection(connectionId) as ConnectionRow;
|
||||
return svc.toRef(row).secrets.api_token;
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
// The document_* tables are not in resetTestDb's list, and they reference
|
||||
// trips and users, so they go first, before the rows they hang off vanish.
|
||||
testDb.exec('DELETE FROM document_sync_items; DELETE FROM trip_document_links; DELETE FROM document_connections;');
|
||||
resetTestDb(testDb);
|
||||
vi.clearAllMocks();
|
||||
checkSsrf.mockResolvedValue({ allowed: true, isPrivate: false, resolvedIp: '203.0.113.10' });
|
||||
OWNER = createUser(testDb, { username: 'owner', email: 'owner@test.local' }).user.id;
|
||||
MEMBER = createUser(testDb, { username: 'member', email: 'member@test.local' }).user.id;
|
||||
TRIP = createTrip(testDb, OWNER, { title: 'Japan' }).id;
|
||||
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(TRIP, MEMBER);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
describe('upsertConnection secrets', () => {
|
||||
it('keeps the stored credential when the form comes back with the field blank', async () => {
|
||||
const created = await connect();
|
||||
await connect({ credentials: { api_token: '' } });
|
||||
expect(storedSecret(created.id)).toBe(TOKEN);
|
||||
});
|
||||
|
||||
it('keeps it when the form posts back the mask it was shown', async () => {
|
||||
// This is what makes a GET-then-PUT round trip safe: the client renders the
|
||||
// form from the masked view and never has to hold the real credential.
|
||||
const created = await connect();
|
||||
await connect({ credentials: { api_token: DOCSYNC_SECRET_MASK } });
|
||||
expect(storedSecret(created.id)).toBe(TOKEN);
|
||||
});
|
||||
|
||||
it('keeps it when the field is missing from the payload altogether', async () => {
|
||||
const created = await connect();
|
||||
await connect({ credentials: {} });
|
||||
expect(storedSecret(created.id)).toBe(TOKEN);
|
||||
});
|
||||
|
||||
it('replaces it when a new credential actually arrives', async () => {
|
||||
const created = await connect();
|
||||
await connect({ credentials: { api_token: 'rotated-token' } });
|
||||
expect(storedSecret(created.id)).toBe('rotated-token');
|
||||
});
|
||||
|
||||
it('updates the trip\'s connection in place rather than adding a second one', async () => {
|
||||
const first = await connect();
|
||||
const second = await connect({ baseUrl: 'https://paperless.example.com/', credentials: {} });
|
||||
expect(second.id).toBe(first.id);
|
||||
const count = testDb
|
||||
.prepare('SELECT COUNT(*) AS n FROM document_connections WHERE trip_id = ?')
|
||||
.get(TRIP) as { n: number };
|
||||
expect(count.n).toBe(1);
|
||||
});
|
||||
|
||||
it('carries a non-secret setting forward when a later save omits it', async () => {
|
||||
const created = await svc.upsertConnection(TRIP, OWNER, {
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
credentials: { login_name: 'anna', app_password: 'app-pw', base_path: '/TREK' },
|
||||
allowInsecureTls: false,
|
||||
});
|
||||
expect(created.success).toBe(true);
|
||||
|
||||
await svc.upsertConnection(TRIP, OWNER, {
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
credentials: { login_name: 'anna' },
|
||||
allowInsecureTls: false,
|
||||
});
|
||||
const row = svc.listConnections(TRIP).find((c) => c.provider_id === 'nextcloud') as ConnectionRow;
|
||||
expect(svc.toRef(row).settings).toMatchObject({ login_name: 'anna', base_path: '/TREK' });
|
||||
expect(svc.toRef(row).secrets.app_password).toBe('app-pw');
|
||||
});
|
||||
});
|
||||
|
||||
describe('publicConnection', () => {
|
||||
it('reports that a secret is set without ever carrying its value', async () => {
|
||||
const created = await connect();
|
||||
const view = svc.publicConnection(svc.getConnection(created.id) as ConnectionRow);
|
||||
expect(view.secrets).toEqual({ api_token: DOCSYNC_SECRET_MASK });
|
||||
expect(JSON.stringify(view)).not.toContain(TOKEN);
|
||||
});
|
||||
|
||||
it('leaves a secret it has no value for out of the map entirely', async () => {
|
||||
// Masking an unset field would tell the client "already configured" and the
|
||||
// connection form would render an optional credential as one that is done.
|
||||
const created = await svc.upsertConnection(TRIP, OWNER, {
|
||||
providerId: 'synologydrive',
|
||||
baseUrl: 'https://nas.example.com:5001',
|
||||
credentials: { username: 'anna', password: 'nas-pw' },
|
||||
allowInsecureTls: false,
|
||||
});
|
||||
expect(created.success).toBe(true);
|
||||
const row = svc.listConnections(TRIP).find((c) => c.provider_id === 'synologydrive') as ConnectionRow;
|
||||
expect(svc.publicConnection(row).secrets).toEqual({ password: DOCSYNC_SECRET_MASK });
|
||||
});
|
||||
|
||||
it('reads a capabilities blob left behind by another build as unknown, not as a crash', async () => {
|
||||
const created = await connect();
|
||||
testDb.prepare('UPDATE document_connections SET capabilities = ? WHERE id = ?').run('{not json', created.id);
|
||||
const view = svc.publicConnection(svc.getConnection(created.id) as ConnectionRow);
|
||||
expect(view.capabilities).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('a secret the provider earned itself', () => {
|
||||
// The shape the Synology adapter stores: account digest, colon, DSM's token.
|
||||
const EARNED = 'a1b2c3:DEVICE-7';
|
||||
|
||||
function nas(credentials: Record<string, string> = { username: 'anna', password: 'nas-pw', otp_code: '123456' }) {
|
||||
return connect({ providerId: 'synologydrive', baseUrl: 'https://nas.example.com:5001', credentials });
|
||||
}
|
||||
|
||||
function secretsOf(connectionId: number): Readonly<Record<string, string>> {
|
||||
return svc.toRef(svc.getConnection(connectionId) as ConnectionRow).secrets;
|
||||
}
|
||||
|
||||
it('is stored through the ref the adapter was handed, encrypted with the form\'s secrets', async () => {
|
||||
const conn = await nas();
|
||||
svc.toRef(conn).saveSecret!('device_token', EARNED);
|
||||
|
||||
expect(secretsOf(conn.id)).toEqual({ password: 'nas-pw', otp_code: '123456', device_token: EARNED });
|
||||
expect((svc.getConnection(conn.id) as ConnectionRow).secrets).not.toContain('DEVICE-7');
|
||||
});
|
||||
|
||||
it('never reaches a client, not even as a mask', async () => {
|
||||
const conn = await nas();
|
||||
svc.saveEarnedSecret(conn.id, 'device_token', EARNED);
|
||||
const view = svc.publicConnection(svc.getConnection(conn.id) as ConnectionRow);
|
||||
|
||||
expect(view.secrets).toEqual({ password: DOCSYNC_SECRET_MASK, otp_code: DOCSYNC_SECRET_MASK });
|
||||
expect(JSON.stringify(view)).not.toContain('DEVICE-7');
|
||||
expect(JSON.stringify(view)).not.toContain('device_token');
|
||||
});
|
||||
|
||||
it('survives a form edit, whatever the form sends for the secrets it does show', async () => {
|
||||
const conn = await nas();
|
||||
svc.saveEarnedSecret(conn.id, 'device_token', EARNED);
|
||||
await nas({ username: 'anna', password: 'rotated', otp_code: '' });
|
||||
await nas({ username: 'anna', password: DOCSYNC_SECRET_MASK });
|
||||
|
||||
expect(secretsOf(conn.id)).toMatchObject({ password: 'rotated', device_token: EARNED });
|
||||
});
|
||||
|
||||
it('cannot be planted or overwritten through the form', async () => {
|
||||
const conn = await nas();
|
||||
await nas({ username: 'anna', device_token: 'a1b2c3:PLANTED' });
|
||||
expect(secretsOf(conn.id).device_token).toBeUndefined();
|
||||
|
||||
svc.saveEarnedSecret(conn.id, 'device_token', EARNED);
|
||||
await nas({ username: 'anna', device_token: 'a1b2c3:PLANTED' });
|
||||
expect(secretsOf(conn.id).device_token).toBe(EARNED);
|
||||
expect(svc.toRef(svc.getConnection(conn.id) as ConnectionRow).settings).not.toHaveProperty('device_token');
|
||||
});
|
||||
|
||||
it('is written against the row as it is now, so a run holding an old ref cannot undo a password edit', async () => {
|
||||
const conn = await nas();
|
||||
const ref = svc.toRef(conn);
|
||||
await nas({ username: 'anna', password: 'rotated' });
|
||||
ref.saveSecret!('device_token', EARNED);
|
||||
|
||||
expect(secretsOf(conn.id)).toMatchObject({ password: 'rotated', device_token: EARNED });
|
||||
});
|
||||
|
||||
it('is dropped with null, and the form\'s secrets stay', async () => {
|
||||
const conn = await nas();
|
||||
svc.saveEarnedSecret(conn.id, 'device_token', EARNED);
|
||||
svc.saveEarnedSecret(conn.id, 'device_token', null);
|
||||
|
||||
expect(secretsOf(conn.id)).toEqual({ password: 'nas-pw', otp_code: '123456' });
|
||||
});
|
||||
|
||||
it('brings back no connection that was deleted while a run still held its ref', async () => {
|
||||
const conn = await nas();
|
||||
const ref = svc.toRef(conn);
|
||||
svc.deleteConnection(conn.id);
|
||||
|
||||
ref.saveSecret!('device_token', EARNED);
|
||||
expect(svc.getConnection(conn.id)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateBaseUrl', () => {
|
||||
it('stores a private address, because a self-hosted instance is the point', async () => {
|
||||
checkSsrf.mockResolvedValue({ allowed: false, isPrivate: true, error: 'private network' });
|
||||
const verdict = await svc.validateBaseUrl('https://paperless.fritz.box');
|
||||
expect(verdict).toEqual({ success: true, data: { url: 'https://paperless.fritz.box', isPrivate: true } });
|
||||
|
||||
const created = await connect({ baseUrl: 'https://paperless.fritz.box' });
|
||||
expect(created.base_url).toBe('https://paperless.fritz.box');
|
||||
});
|
||||
|
||||
it('refuses an address the guard rejects for any other reason, and writes nothing', async () => {
|
||||
checkSsrf.mockResolvedValue({ allowed: false, isPrivate: false, error: 'Could not resolve hostname (ENOTFOUND)' });
|
||||
const result = await svc.upsertConnection(TRIP, OWNER, connectionInput({ baseUrl: 'https://nope.invalid' }));
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.success === false && result.error.code).toBe('ssrf_blocked');
|
||||
expect(svc.listConnections(TRIP)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('strips trailing slashes so the adapter can append its own path', async () => {
|
||||
const created = await connect({ baseUrl: 'https://paperless.example.com///' });
|
||||
expect(created.base_url).toBe('https://paperless.example.com');
|
||||
});
|
||||
|
||||
it('refuses an empty address before it asks the guard anything', async () => {
|
||||
const result = await svc.validateBaseUrl(' ');
|
||||
expect(result.success).toBe(false);
|
||||
expect(checkSsrf).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('upsertConnection required fields', () => {
|
||||
it('names the missing credential instead of storing a connection that cannot authenticate', async () => {
|
||||
const result = await svc.upsertConnection(TRIP, OWNER, connectionInput({ credentials: {} }));
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.success === false && result.error.detail).toContain('api_token');
|
||||
expect(svc.listConnections(TRIP)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('refuses a missing required field that is not a secret either', async () => {
|
||||
const result = await svc.upsertConnection(TRIP, OWNER, {
|
||||
providerId: 'papra',
|
||||
baseUrl: 'https://papra.example.com',
|
||||
credentials: { api_key: 'ppapi_x' },
|
||||
allowInsecureTls: false,
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.success === false && result.error.detail).toContain('organization_id');
|
||||
});
|
||||
|
||||
it('accepts a provider whose optional credential is left blank', async () => {
|
||||
// Synology's OTP is a one-time code, not a stored credential; demanding it
|
||||
// would make every save after the first one impossible.
|
||||
const result = await svc.upsertConnection(TRIP, OWNER, {
|
||||
providerId: 'synologydrive',
|
||||
baseUrl: 'https://nas.example.com:5001',
|
||||
credentials: { username: 'anna', password: 'nas-pw', otp_code: '' },
|
||||
allowInsecureTls: false,
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('enabledProviderIds', () => {
|
||||
it('names only the providers an admin switched on, in the order the shelf shows them', () => {
|
||||
// Every document provider ships OFF, so an empty answer on a fresh install
|
||||
// is the correct one and a non-empty one would be a policy change.
|
||||
expect(svc.enabledProviderIds()).toEqual([]);
|
||||
testDb.prepare("UPDATE document_providers SET enabled = 1 WHERE id IN ('nextcloud', 'paperless')").run();
|
||||
expect(svc.enabledProviderIds()).toEqual(['paperless', 'nextcloud']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordProbe', () => {
|
||||
it('keeps what the last good probe learned when a later one fails', async () => {
|
||||
// A token that expired overnight must not make TREK forget that this
|
||||
// instance can accept uploads; the capabilities describe the provider, not
|
||||
// the state of the credential.
|
||||
const conn = await connect();
|
||||
svc.recordProbe(conn.id, 'ok', null, { push: 'multipart' });
|
||||
svc.recordProbe(conn.id, 'failed', '401 Unauthorized', null);
|
||||
|
||||
const view = svc.publicConnection(svc.getConnection(conn.id) as ConnectionRow);
|
||||
expect(view).toMatchObject({
|
||||
lastProbeState: 'failed',
|
||||
lastProbeError: '401 Unauthorized',
|
||||
capabilities: { push: 'multipart' },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteConnection', () => {
|
||||
it('drops the bindings that hung off it and leaves the other connection alone', async () => {
|
||||
const doomed = await connect();
|
||||
const kept = await connect({
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
credentials: { login_name: 'anna', app_password: 'app-pw' },
|
||||
});
|
||||
const doomedLink = link(doomed.id, { scopeKey: 'tag:1' });
|
||||
const keptLink = link(kept.id, { scopeKey: 'folder:1' });
|
||||
testDb
|
||||
.prepare('INSERT INTO document_sync_items (link_id, trip_id, trek_doc_uid) VALUES (?, ?, ?)')
|
||||
.run(doomedLink.id, TRIP, 'uid-a');
|
||||
|
||||
svc.deleteConnection(doomed.id);
|
||||
|
||||
expect(svc.getConnection(doomed.id)).toBeUndefined();
|
||||
expect(svc.listLinks(TRIP).map((l) => l.id)).toEqual([keptLink.id]);
|
||||
expect(testDb.prepare('SELECT COUNT(*) AS n FROM document_sync_items').get()).toEqual({ n: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('toRef', () => {
|
||||
it('names the row and not only its id, which a backup restored in place hands out again', async () => {
|
||||
const first = await connect();
|
||||
testDb.prepare("UPDATE document_connections SET created_at = '2026-09-01 08:00:00' WHERE id = ?").run(first.id);
|
||||
const before = svc.toRef(svc.getConnection(first.id) as ConnectionRow);
|
||||
|
||||
// What the restore of an older backup does to this table: the row is gone
|
||||
// and the id sequence is back where it stood before the row was made.
|
||||
testDb.prepare('DELETE FROM document_connections WHERE id = ?').run(first.id);
|
||||
testDb.prepare("UPDATE sqlite_sequence SET seq = ? WHERE name = 'document_connections'").run(first.id - 1);
|
||||
const after = svc.toRef(await connect());
|
||||
|
||||
expect(after.connectionId).toBe(before.connectionId);
|
||||
expect(before.createdAt).toBe('2026-09-01 08:00:00');
|
||||
expect(after.createdAt).not.toBe(before.createdAt);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateLink', () => {
|
||||
it('changes only the fields the patch names', async () => {
|
||||
const conn = await connect();
|
||||
const created = link(conn.id, { direction: 'both', conflictPolicy: 'manual' });
|
||||
const patched = svc.updateLink(created.id, { direction: 'pull', syncEnabled: false });
|
||||
expect(patched).toMatchObject({
|
||||
direction: 'pull',
|
||||
sync_enabled: 0,
|
||||
conflict_policy: 'manual',
|
||||
remote_label: created.remote_label,
|
||||
});
|
||||
});
|
||||
|
||||
it('hands back the binding untouched when the patch is empty', async () => {
|
||||
const conn = await connect();
|
||||
const created = link(conn.id);
|
||||
expect(svc.updateLink(created.id, {})).toEqual(created);
|
||||
});
|
||||
});
|
||||
|
||||
describe('toScopeRef', () => {
|
||||
it('hands the adapter the anchor and the cursor of that binding, each in its own field', async () => {
|
||||
// The adapters take a ref object rather than positional arguments because
|
||||
// an id and a path swapped compile cleanly and then read the wrong folder.
|
||||
const conn = await connect();
|
||||
const created = svc.createLink(
|
||||
TRIP,
|
||||
OWNER,
|
||||
linkInput(conn.id, { scopeKey: 'fileid:437', remoteRootId: '437', remoteRootPath: '/TREK/japan' }),
|
||||
);
|
||||
expect(created.success).toBe(true);
|
||||
const row = created.success ? created.data : ({} as LinkRow);
|
||||
testDb.prepare('UPDATE trip_document_links SET remote_cursor = ? WHERE id = ?').run('etag-9', row.id);
|
||||
|
||||
expect(svc.toScopeRef(svc.getLink(row.id) as LinkRow)).toEqual({
|
||||
linkId: row.id,
|
||||
tripId: TRIP,
|
||||
scopeKey: 'fileid:437',
|
||||
remoteRootId: '437',
|
||||
remoteRootPath: '/TREK/japan',
|
||||
cursor: 'etag-9',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('createLink', () => {
|
||||
it('returns the binding that already exists rather than making a second one', async () => {
|
||||
const conn = await connect();
|
||||
const first = link(conn.id);
|
||||
const again = svc.createLink(TRIP, MEMBER, linkInput(conn.id, { remoteLabel: 'renamed' }));
|
||||
expect(again.success && again.data.id).toBe(first.id);
|
||||
expect(svc.listLinks(TRIP)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('binds a second scope of the same connection separately', async () => {
|
||||
const conn = await connect();
|
||||
const first = link(conn.id, { scopeKey: 'tag:1' });
|
||||
const second = link(conn.id, { scopeKey: 'tag:2' });
|
||||
expect(second.id).not.toBe(first.id);
|
||||
expect(svc.listLinks(TRIP)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('refuses a connection that belongs to somebody else\'s trip', async () => {
|
||||
const otherTrip = createTrip(testDb, MEMBER, { title: 'Not yours' }).id;
|
||||
const conn = await connect();
|
||||
const result = svc.createLink(otherTrip, MEMBER, linkInput(conn.id));
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.success === false && result.error.code).toBe('not_found');
|
||||
expect(svc.listLinks(otherTrip)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('refuses a connection id that does not exist at all', async () => {
|
||||
const result = svc.createLink(TRIP, OWNER, linkInput(9999));
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('stores the anchor the picker sent back with the scope key', async () => {
|
||||
const conn = await connect();
|
||||
const result = svc.createLink(
|
||||
TRIP,
|
||||
OWNER,
|
||||
linkInput(conn.id, { remoteRootId: '17', remoteRootPath: '/TREK/japan', remoteLabel: 'Japan 2026' }),
|
||||
);
|
||||
expect(result.success && result.data).toMatchObject({
|
||||
remote_scope_key: 'tag:1',
|
||||
remote_root_id: '17',
|
||||
remote_root_path: '/TREK/japan',
|
||||
remote_label: 'Japan 2026',
|
||||
});
|
||||
});
|
||||
|
||||
it('stores NULL for an anchor field the client left out', async () => {
|
||||
// Synology binds by path alone, so its options carry no root id at all.
|
||||
const conn = await connect();
|
||||
const result = svc.createLink(TRIP, OWNER, linkInput(conn.id));
|
||||
expect(result.success && result.data).toMatchObject({ remote_root_id: null, remote_root_path: null });
|
||||
});
|
||||
|
||||
it('gives every binding its own webhook token and keeps the secret out of the public view', async () => {
|
||||
// A leaked webhook URL has to identify exactly one binding, so revoking one
|
||||
// cannot be used to poke another.
|
||||
const conn = await connect();
|
||||
const first = link(conn.id, { scopeKey: 'tag:1' });
|
||||
const second = link(conn.id, { scopeKey: 'tag:2' });
|
||||
expect(first.webhook_token).toBeTruthy();
|
||||
expect(second.webhook_token).not.toBe(first.webhook_token);
|
||||
expect(svc.getLinkByToken(first.webhook_token as string)?.id).toBe(first.id);
|
||||
|
||||
const secret = svc.webhookSecret(first);
|
||||
expect(secret).toBeTruthy();
|
||||
const view = svc.publicLink(first, 'https://trek.example.com');
|
||||
expect(view.webhookSecret).toBe(DOCSYNC_SECRET_MASK);
|
||||
expect(JSON.stringify(view)).not.toContain(secret);
|
||||
});
|
||||
});
|
||||
|
||||
describe('publicLink', () => {
|
||||
it('names the store of a binding whose provider the admin has since switched off', async () => {
|
||||
// The client only learns names for the providers that are on, so this is
|
||||
// the one place a binding left behind can still get its name from.
|
||||
const conn = await connect();
|
||||
const bound = link(conn.id);
|
||||
testDb.prepare("UPDATE document_providers SET enabled = 0 WHERE id = 'paperless'").run();
|
||||
|
||||
expect(svc.publicLink(bound, null)).toMatchObject({ providerId: 'paperless', providerName: 'Paperless-ngx' });
|
||||
});
|
||||
|
||||
it('falls back to the provider id for a provider this build does not know', async () => {
|
||||
const conn = await connect();
|
||||
const bound = link(conn.id);
|
||||
expect(svc.publicLink({ ...bound, provider_id: 'dropbox' }, null).providerName).toBe('dropbox');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteLink', () => {
|
||||
it('takes the pairing rows with it and leaves the other binding\'s alone', async () => {
|
||||
const conn = await connect();
|
||||
const doomed = link(conn.id, { scopeKey: 'tag:1' });
|
||||
const kept = link(conn.id, { scopeKey: 'tag:2' });
|
||||
const insert = testDb.prepare(
|
||||
'INSERT INTO document_sync_items (link_id, trip_id, trek_doc_uid) VALUES (?, ?, ?)',
|
||||
);
|
||||
insert.run(doomed.id, TRIP, 'uid-a');
|
||||
insert.run(doomed.id, TRIP, 'uid-b');
|
||||
insert.run(kept.id, TRIP, 'uid-c');
|
||||
|
||||
svc.deleteLink(doomed.id);
|
||||
|
||||
expect(svc.getLink(doomed.id)).toBeUndefined();
|
||||
expect(svc.getLink(kept.id)).toBeDefined();
|
||||
const rows = testDb.prepare('SELECT link_id FROM document_sync_items').all() as { link_id: number }[];
|
||||
expect(rows.map((r) => r.link_id)).toEqual([kept.id]);
|
||||
});
|
||||
|
||||
it('leaves the connection behind, so unbinding one scope does not log the trip out', async () => {
|
||||
const conn = await connect();
|
||||
svc.deleteLink(link(conn.id).id);
|
||||
expect(svc.getConnection(conn.id)).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('markOrphanedLinks', () => {
|
||||
async function bind(ownerUserId: number, providerId: 'paperless' | 'nextcloud'): Promise<LinkRow> {
|
||||
const credentials =
|
||||
providerId === 'paperless' ? { api_token: TOKEN } : { login_name: 'anna', app_password: 'app-pw' };
|
||||
const conn = await connect({ providerId, credentials, baseUrl: `https://${providerId}.example.com` }, ownerUserId);
|
||||
return link(conn.id, { scopeKey: `scope:${providerId}` });
|
||||
}
|
||||
|
||||
it('disables the binding whose credential owner left the trip', async () => {
|
||||
const orphan = await bind(MEMBER, 'paperless');
|
||||
testDb.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(TRIP, MEMBER);
|
||||
|
||||
expect(svc.markOrphanedLinks()).toBe(1);
|
||||
expect(svc.getLink(orphan.id)).toMatchObject({ last_sync_state: 'orphaned', sync_enabled: 0 });
|
||||
});
|
||||
|
||||
it('counts the trip owner as being on the trip, although no membership row says so', async () => {
|
||||
// TREK's owner has no trip_members row; reading membership without the
|
||||
// owner would orphan every binding the trip admin created, which is most
|
||||
// of them.
|
||||
const mine = await bind(OWNER, 'paperless');
|
||||
expect(svc.markOrphanedLinks()).toBe(0);
|
||||
expect(svc.getLink(mine.id)).toMatchObject({ last_sync_state: 'never', sync_enabled: 1 });
|
||||
});
|
||||
|
||||
it('leaves a still-valid binding alone while orphaning the one beside it', async () => {
|
||||
const orphan = await bind(MEMBER, 'paperless');
|
||||
const kept = await bind(OWNER, 'nextcloud');
|
||||
testDb.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(TRIP, MEMBER);
|
||||
|
||||
expect(svc.markOrphanedLinks()).toBe(1);
|
||||
expect(svc.getLink(orphan.id)?.last_sync_state).toBe('orphaned');
|
||||
expect(svc.getLink(kept.id)).toMatchObject({ last_sync_state: 'never', sync_enabled: 1 });
|
||||
});
|
||||
|
||||
it('counts nothing on a second sweep, so the job stays quiet after the first one', async () => {
|
||||
await bind(MEMBER, 'paperless');
|
||||
testDb.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(TRIP, MEMBER);
|
||||
expect(svc.markOrphanedLinks()).toBe(1);
|
||||
expect(svc.markOrphanedLinks()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not touch a binding the user had already switched off', async () => {
|
||||
const paused = await bind(MEMBER, 'paperless');
|
||||
svc.updateLink(paused.id, { syncEnabled: false });
|
||||
testDb.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(TRIP, MEMBER);
|
||||
|
||||
expect(svc.markOrphanedLinks()).toBe(0);
|
||||
expect(svc.getLink(paused.id)?.last_sync_state).toBe('never');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,412 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import crypto from 'crypto';
|
||||
import type { Request } from 'express';
|
||||
|
||||
// Nothing here touches SQLite; the stub keeps the import chain from opening a
|
||||
// database and running 238 migrations for a handler that never queries one.
|
||||
vi.mock('../../../../src/db/database', () => ({
|
||||
db: {},
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: () => undefined,
|
||||
isOwner: () => false,
|
||||
}));
|
||||
|
||||
import { DocSyncWebhookController } from '../../../../src/nest/doc-sync/doc-sync-webhook.controller';
|
||||
import type { DocSyncConfigService, LinkRow } from '../../../../src/nest/doc-sync/doc-sync-config.service';
|
||||
import type { DocSyncService } from '../../../../src/nest/doc-sync/doc-sync.service';
|
||||
import type { DatabaseService } from '../../../../src/nest/database/database.service';
|
||||
|
||||
/**
|
||||
* The webhook endpoint, with both services stubbed.
|
||||
*
|
||||
* It is the only route in TREK a stranger on the internet can reach with a
|
||||
* guessed URL, so what matters is what it does NOT do: it never says whether a
|
||||
* token exists, never says whether a secret matched, and never acts on the
|
||||
* payload. Every case below therefore asserts two things: the answer, which is
|
||||
* always the same, and whether a run was scheduled, which is the only place the
|
||||
* decision is visible at all.
|
||||
*
|
||||
* The signature is computed here from a fixed id and timestamp, exactly as the
|
||||
* provider would. Timers are faked, because the endpoint now collects a burst
|
||||
* before it runs: providers fire once per document, and twenty files dropped
|
||||
* into a watched folder used to be twenty runs, nineteen of which the service
|
||||
* answered `busy` and threw away.
|
||||
*/
|
||||
|
||||
const SECRET = 'M7dQ2vLp5rTn8kYw1xZc4bJh';
|
||||
|
||||
const link = (over: Partial<LinkRow> = {}): LinkRow => ({
|
||||
id: 4,
|
||||
trip_id: 1,
|
||||
connection_id: 2,
|
||||
provider_id: 'papra',
|
||||
remote_scope_key: 'tag:1',
|
||||
remote_root_id: '1',
|
||||
remote_root_path: '/TREK/japan',
|
||||
remote_label: 'Japan 2026',
|
||||
direction: 'both',
|
||||
delete_policy: 'unlink',
|
||||
conflict_policy: 'manual',
|
||||
sync_enabled: 1,
|
||||
webhook_token: 'tok-live',
|
||||
webhook_secret: 'enc:v1:whatever',
|
||||
webhook_subscription_id: null,
|
||||
remote_cursor: null,
|
||||
last_sync_at: null,
|
||||
last_sync_state: 'never',
|
||||
last_sync_error: null,
|
||||
failure_count: 0,
|
||||
next_attempt_at: null,
|
||||
...over,
|
||||
});
|
||||
|
||||
const config = {
|
||||
getLinkByToken: vi.fn((token: string) => (token === 'tok-live' ? link() : undefined)),
|
||||
// Looked up again when the timer fires, so a binding switched off during the
|
||||
// window does not get one last run out of a stale row.
|
||||
getLink: vi.fn((id: number) => (id === 4 ? link() : undefined)),
|
||||
webhookSecret: vi.fn(() => SECRET),
|
||||
};
|
||||
|
||||
const settings = new Map<string, string>();
|
||||
const db = {
|
||||
get: vi.fn((_sql: string, key?: unknown) => {
|
||||
const value = settings.get(String(key));
|
||||
return value === undefined ? undefined : { value };
|
||||
}),
|
||||
};
|
||||
|
||||
const sync = {
|
||||
syncLink: vi.fn(async (_link: LinkRow) => ({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 })),
|
||||
// The Documents addon and the binding's provider, as one answer. What goes
|
||||
// into it is the service's business and tested there.
|
||||
isSwitchedOff: vi.fn((_link: LinkRow) => false),
|
||||
};
|
||||
|
||||
const controller = new DocSyncWebhookController(
|
||||
config as unknown as DocSyncConfigService,
|
||||
sync as unknown as DocSyncService,
|
||||
db as unknown as DatabaseService,
|
||||
);
|
||||
|
||||
/** Only what the handler reads: headers, the parsed body, and the raw bytes. */
|
||||
function makeReq(headers: Record<string, string> = {}, opts: { body?: unknown; rawBody?: Buffer | undefined } = {}): Request {
|
||||
return {
|
||||
headers,
|
||||
body: opts.body,
|
||||
rawBody: opts.rawBody,
|
||||
get: (name: string) => headers[name.toLowerCase()],
|
||||
} as unknown as Request;
|
||||
}
|
||||
|
||||
const WEBHOOK_ID = 'msg_2f8a';
|
||||
const WEBHOOK_TS = '1758200000';
|
||||
|
||||
function sign(payload: string, secret = SECRET, id = WEBHOOK_ID, ts = WEBHOOK_TS): string {
|
||||
return crypto.createHmac('sha256', Buffer.from(secret)).update(`${id}.${ts}.${payload}`).digest('base64');
|
||||
}
|
||||
|
||||
function papraReq(payload: string, signature: string, sent = payload): Request {
|
||||
return makeReq(
|
||||
{ 'webhook-id': WEBHOOK_ID, 'webhook-timestamp': WEBHOOK_TS, 'webhook-signature': `v1,${signature}` },
|
||||
{ rawBody: Buffer.from(sent, 'utf8') },
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useFakeTimers();
|
||||
settings.clear();
|
||||
sync.isSwitchedOff.mockReturnValue(false);
|
||||
config.getLinkByToken.mockImplementation((token: string) => (token === 'tok-live' ? link() : undefined));
|
||||
config.getLink.mockImplementation((id: number) => (id === 4 ? link() : undefined));
|
||||
config.webhookSecret.mockReturnValue(SECRET);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.runOnlyPendingTimers();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
/** Let the debounce window pass, so a scheduled run actually happens. */
|
||||
function settle() {
|
||||
vi.advanceTimersByTime(6000);
|
||||
}
|
||||
|
||||
describe('an unknown token', () => {
|
||||
it('answers as if it were known, so nobody can enumerate which tokens exist', () => {
|
||||
expect(controller.nudge('tok-guessed', makeReq())).toEqual({ received: true });
|
||||
});
|
||||
|
||||
it('schedules no run', () => {
|
||||
controller.nudge('tok-guessed', makeReq());
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('a binding whose sync is switched off', () => {
|
||||
it('is left alone, and says nothing about it', () => {
|
||||
config.getLinkByToken.mockReturnValue(link({ sync_enabled: 0 }));
|
||||
expect(controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }))).toEqual({ received: true });
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('a shared-secret header', () => {
|
||||
it('triggers the run when it matches', () => {
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
settle();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
settle();
|
||||
expect(sync.syncLink.mock.calls[0][0]).toMatchObject({ id: 4 });
|
||||
});
|
||||
|
||||
it('triggers nothing when it is wrong, and the answer looks identical', () => {
|
||||
const wrong = `${SECRET.slice(0, -1)}X`;
|
||||
expect(controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': wrong }))).toEqual({ received: true });
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('triggers nothing when the header is missing altogether', () => {
|
||||
controller.nudge('tok-live', makeReq());
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('is not demanded from a binding that carries no secret: the token alone authenticates there', () => {
|
||||
config.webhookSecret.mockReturnValue('');
|
||||
controller.nudge('tok-live', makeReq());
|
||||
settle();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a Papra standard-webhooks signature', () => {
|
||||
const payload = JSON.stringify({ event: 'document.created', documentId: 'doc_1' });
|
||||
|
||||
it('triggers the run when it covers the bytes that arrived', () => {
|
||||
controller.nudge('tok-live', papraReq(payload, sign(payload)));
|
||||
settle();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('triggers nothing when the payload was altered after it was signed', () => {
|
||||
const tampered = JSON.stringify({ event: 'document.created', documentId: 'doc_999' });
|
||||
expect(controller.nudge('tok-live', papraReq(payload, sign(payload), tampered))).toEqual({ received: true });
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('triggers nothing when the signature was made with another secret', () => {
|
||||
controller.nudge('tok-live', papraReq(payload, sign(payload, 'someone-elses-secret-value')));
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('triggers nothing when the id or timestamp does not match what was signed', () => {
|
||||
const req = makeReq(
|
||||
{ 'webhook-id': 'msg_other', 'webhook-timestamp': WEBHOOK_TS, 'webhook-signature': `v1,${sign(payload)}` },
|
||||
{ rawBody: Buffer.from(payload, 'utf8') },
|
||||
);
|
||||
controller.nudge('tok-live', req);
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('accepts a header carrying several signatures, as a key rotation sends', () => {
|
||||
const req = makeReq(
|
||||
{
|
||||
'webhook-id': WEBHOOK_ID,
|
||||
'webhook-timestamp': WEBHOOK_TS,
|
||||
'webhook-signature': `v1,${sign(payload, 'the-previous-secret')} v1,${sign(payload)}`,
|
||||
},
|
||||
{ rawBody: Buffer.from(payload, 'utf8') },
|
||||
);
|
||||
controller.nudge('tok-live', req);
|
||||
settle();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('verifies against the parsed body when a mount left no raw bytes behind', () => {
|
||||
const body = { event: 'document.created', documentId: 'doc_1' };
|
||||
const req = makeReq(
|
||||
{ 'webhook-id': WEBHOOK_ID, 'webhook-timestamp': WEBHOOK_TS, 'webhook-signature': `v1,${sign(JSON.stringify(body))}` },
|
||||
{ body },
|
||||
);
|
||||
controller.nudge('tok-live', req);
|
||||
settle();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('is ignored when the timestamp header is missing, rather than verified without it', () => {
|
||||
const req = makeReq(
|
||||
{ 'webhook-id': WEBHOOK_ID, 'webhook-signature': `v1,${sign(payload)}` },
|
||||
{ rawBody: Buffer.from(payload, 'utf8') },
|
||||
);
|
||||
controller.nudge('tok-live', req);
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('a credential of the wrong length', () => {
|
||||
// crypto.timingSafeEqual throws on buffers of unequal length, so a one-byte
|
||||
// header would turn into a 500 that tells a prober the secret is longer than
|
||||
// what they sent.
|
||||
it('is rejected rather than thrown over, whether it arrives as a header or as a signature', () => {
|
||||
expect(() => controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': 'a' }))).not.toThrow();
|
||||
expect(() =>
|
||||
controller.nudge('tok-live', papraReq('{}', 'short')),
|
||||
).not.toThrow();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('is rejected the same way when it is longer than the stored secret', () => {
|
||||
expect(() => controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': `${SECRET}extra` }))).not.toThrow();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A burst of calls is one run.
|
||||
*
|
||||
* Every provider here fires per document: a folder of twenty files is twenty
|
||||
* calls within a second or two. Each used to start its own run. The service's
|
||||
* in-flight guard then answered `busy` to nineteen of them, so nineteen
|
||||
* announcements were thrown away and the one run that did start had begun
|
||||
* before most of the changes landed.
|
||||
*/
|
||||
describe('a burst of nudges', () => {
|
||||
it('runs once for twenty calls rather than twenty times', () => {
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
}
|
||||
settle();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('answers every one of them immediately, before any run happens', () => {
|
||||
const answers = [];
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
answers.push(controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET })));
|
||||
}
|
||||
// Paperless gives the call five seconds before it counts it as failed.
|
||||
expect(answers).toEqual(Array.from({ length: 5 }, () => ({ received: true })));
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs again for a burst that arrives after the window closed', () => {
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
settle();
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
settle();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('keeps one window per binding, so a busy trip cannot starve a quiet one', () => {
|
||||
const other = link({ id: 9, webhook_token: 'tok-other' });
|
||||
config.getLinkByToken.mockImplementation((t: string) =>
|
||||
t === 'tok-live' ? link() : t === 'tok-other' ? other : undefined);
|
||||
config.getLink.mockImplementation((id: number) => (id === 4 ? link() : id === 9 ? other : undefined));
|
||||
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
controller.nudge('tok-other', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
settle();
|
||||
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(2);
|
||||
expect(sync.syncLink.mock.calls.map((c) => c[0].id).sort()).toEqual([4, 9]);
|
||||
});
|
||||
|
||||
it('drops the run when the binding is switched off inside the window', () => {
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
config.getLink.mockReturnValue(link({ sync_enabled: 0 }));
|
||||
settle();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('drops the run when the binding is deleted inside the window', () => {
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
config.getLink.mockReturnValue(undefined);
|
||||
settle();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('forgets its pending timers when the module goes down', () => {
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
controller.onModuleDestroy();
|
||||
settle();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The switches an admin expects to mean "off".
|
||||
*
|
||||
* The scheduler obeys the Documents addon, the binding's provider and the
|
||||
* app_settings kill switch; the webhook obeyed none of them, so switching
|
||||
* document sync off stopped the poll while every provider holding a webhook
|
||||
* carried on driving full runs.
|
||||
*/
|
||||
describe('the admin switches', () => {
|
||||
it('does nothing while the addon or the provider of the binding is switched off', () => {
|
||||
sync.isSwitchedOff.mockReturnValue(true);
|
||||
expect(controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }))).toEqual({ received: true });
|
||||
settle();
|
||||
expect(sync.isSwitchedOff.mock.calls[0][0]).toMatchObject({ id: 4, provider_id: 'papra' });
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does nothing while the kill switch is set', () => {
|
||||
settings.set('docsync_sync_enabled', 'false');
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
settle();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('drops a scheduled run when the provider goes off inside the window', () => {
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
sync.isSwitchedOff.mockReturnValue(true);
|
||||
settle();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs normally while both are on', () => {
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
settle();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A nudge that lands on a run already in flight.
|
||||
*
|
||||
* `syncLink` answers `busy` and returns, so the nudge was thrown away, and the
|
||||
* changes it was about may well have landed after the running pass read the
|
||||
* folder, which means waiting out a whole poll interval for them. Asked again
|
||||
* once, and only once, so two clients cannot keep each other going.
|
||||
*/
|
||||
describe('a nudge that arrives mid-run', () => {
|
||||
it('asks again once when the run was busy', async () => {
|
||||
sync.syncLink.mockResolvedValueOnce({ state: 'busy', pulled: 0, pushed: 0, conflicts: 0, missing: 0 });
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
settle();
|
||||
await Promise.resolve();
|
||||
settle();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('gives up after that one retry rather than chasing itself', async () => {
|
||||
sync.syncLink.mockResolvedValue({ state: 'busy', pulled: 0, pushed: 0, conflicts: 0, missing: 0 });
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
for (let i = 0; i < 5; i += 1) { settle(); await Promise.resolve(); }
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('does not retry a run that worked', async () => {
|
||||
// Set explicitly: clearAllMocks drops the calls but keeps the
|
||||
// implementation the previous case installed.
|
||||
sync.syncLink.mockResolvedValue({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 });
|
||||
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
|
||||
settle();
|
||||
await Promise.resolve();
|
||||
settle();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,836 @@
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
import { HttpException } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* DocSyncController built with `new`, against a real in-memory SQLite.
|
||||
*
|
||||
* The guards are e2e's job (tests/e2e/doc-sync.e2e.test.ts drives the real
|
||||
* AddonGuard, JwtAuthGuard and TripAccessGuard). What is left here is what the
|
||||
* handler itself decides once a request is through the door, and all of it is
|
||||
* the kind that would be expensive to notice late: who counts as the owner, a
|
||||
* form field that must not lose a secret it never saw, and a webhook whose
|
||||
* callback URL is derived from the request rather than from configuration.
|
||||
*
|
||||
* The config service and the provider registry are the real ones: the merge
|
||||
* this file pins runs through actual encryption and actual provider-field rows,
|
||||
* and a stub of either would only be a restatement of the controller. The
|
||||
* reconciler is a spy: a run is a side effect here, not the subject.
|
||||
*/
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
return {
|
||||
testDb: db,
|
||||
dbMock: {
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: () => undefined,
|
||||
isOwner: () => false,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../../../src/db/database', () => dbMock);
|
||||
vi.mock('../../../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
|
||||
|
||||
/**
|
||||
* The SSRF guard resolves DNS, and none of these hostnames exist. It is not
|
||||
* what this file tests, and a suite that needs a resolver is a suite that fails
|
||||
* on a train.
|
||||
*/
|
||||
const { checkSsrf } = vi.hoisted(() => ({
|
||||
checkSsrf: vi.fn(async (url: string) => ({
|
||||
allowed: !url.includes('blocked.invalid'),
|
||||
isPrivate: false,
|
||||
error: url.includes('blocked.invalid') ? 'blocked in test' : undefined,
|
||||
})),
|
||||
}));
|
||||
vi.mock('../../../../src/utils/ssrfGuard', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../../src/utils/ssrfGuard')>()),
|
||||
checkSsrf,
|
||||
}));
|
||||
|
||||
import { createTables } from '../../../../src/db/schema';
|
||||
import { runMigrations } from '../../../../src/db/migrations';
|
||||
import { createTrip, createUser } from '../../../helpers/factories';
|
||||
import { DatabaseService } from '../../../../src/nest/database/database.service';
|
||||
import { DocSyncController } from '../../../../src/nest/doc-sync/doc-sync.controller';
|
||||
import { DocSyncConfigService } from '../../../../src/nest/doc-sync/doc-sync-config.service';
|
||||
import { DocumentProviderRegistry } from '../../../../src/nest/doc-sync/document-provider.registry';
|
||||
import type {
|
||||
DocumentConnectionRef,
|
||||
DocumentProvider,
|
||||
DocumentScopeRef,
|
||||
} from '../../../../src/nest/doc-sync/document-provider';
|
||||
import type { LinkRow } from '../../../../src/nest/doc-sync/doc-sync-config.service';
|
||||
import type { DocSyncService } from '../../../../src/nest/doc-sync/doc-sync.service';
|
||||
import type { RealtimeService } from '../../../../src/nest/realtime/realtime.service';
|
||||
import type {
|
||||
DocsyncConnectionDto,
|
||||
DocsyncConnectionTestDto,
|
||||
DocsyncLinkDto,
|
||||
} from '../../../../src/nest/doc-sync/doc-sync.dto';
|
||||
import type { User } from '../../../../src/types';
|
||||
|
||||
const CAPS = {
|
||||
push: 'webhook-self-registered' as const,
|
||||
stableId: true,
|
||||
remoteTrash: true,
|
||||
replaceInPlace: true,
|
||||
contentHashInListing: true,
|
||||
maxUploadBytes: null,
|
||||
acceptedMimeTypes: null,
|
||||
canCreateScope: true,
|
||||
};
|
||||
|
||||
function fakeProvider(id: string) {
|
||||
return {
|
||||
id,
|
||||
capabilities: () => CAPS,
|
||||
probe: vi.fn(async (_conn: DocumentConnectionRef) => ({ success: true as const, data: { account: `${id}-account`, capabilities: CAPS } })),
|
||||
listScopes: vi.fn(async (_conn: DocumentConnectionRef, _query?: string) => ({ success: true as const, data: [] })),
|
||||
createScope: vi.fn(async () => ({ success: false as const, error: { code: 'provider_error' as const } })),
|
||||
resolveScope: vi.fn(async () => ({ success: false as const, error: { code: 'not_found' as const } })),
|
||||
list: vi.fn(async () => ({ success: true as const, data: { documents: [], cursor: null, cursorUnchanged: false, truncated: false } })),
|
||||
fetch: vi.fn(async () => ({ success: false as const, error: { code: 'not_found' as const } })),
|
||||
push: vi.fn(async () => ({ success: false as const, error: { code: 'not_found' as const } })),
|
||||
rename: vi.fn(async () => ({ success: true as const, data: { remoteVersion: 'v2' } })),
|
||||
trash: vi.fn(async () => ({ success: true as const, data: undefined })),
|
||||
registerWebhook: vi.fn(async (_conn: DocumentConnectionRef, _scope: DocumentScopeRef, _callbackUrl: string, _secret: string) => ({
|
||||
success: true as const,
|
||||
data: { subscriptionId: 'sub-7' },
|
||||
})),
|
||||
unregisterWebhook: vi.fn(async (_conn: DocumentConnectionRef, _subscriptionId: string) => ({ success: true as const, data: undefined })),
|
||||
};
|
||||
}
|
||||
|
||||
const paperless = fakeProvider('paperless');
|
||||
const nextcloud = fakeProvider('nextcloud');
|
||||
|
||||
const sync = {
|
||||
syncLink: vi.fn(async (_link: LinkRow, _opts?: { full?: boolean }) => ({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 })),
|
||||
retryShelvedItems: vi.fn((_linkId: number) => {}),
|
||||
isSwitchedOff: vi.fn((_link: LinkRow) => false),
|
||||
status: vi.fn(() => ({ links: [], items: {} })),
|
||||
resolveConflict: vi.fn(async () => true),
|
||||
};
|
||||
|
||||
const registry = new DocumentProviderRegistry([paperless, nextcloud] as unknown as DocumentProvider[]);
|
||||
const dbs = new DatabaseService(testDb);
|
||||
const config = new DocSyncConfigService(dbs, registry);
|
||||
const realtime = { broadcast: vi.fn() };
|
||||
const controller = new DocSyncController(config, sync as unknown as DocSyncService, registry, dbs, realtime as unknown as RealtimeService);
|
||||
|
||||
/** Only what publicOrigin reads: header lookup plus the connection's own scheme. */
|
||||
function makeReq(headers: Record<string, string> = {}, protocol = 'http'): Request {
|
||||
return {
|
||||
protocol,
|
||||
headers,
|
||||
get: (name: string) => headers[name.toLowerCase()],
|
||||
} as unknown as Request;
|
||||
}
|
||||
|
||||
function connBody(over: Partial<DocsyncConnectionDto> = {}): DocsyncConnectionDto {
|
||||
return {
|
||||
providerId: 'paperless',
|
||||
baseUrl: 'https://paperless.example.com',
|
||||
credentials: {},
|
||||
allowInsecureTls: false,
|
||||
...over,
|
||||
} as DocsyncConnectionDto;
|
||||
}
|
||||
|
||||
function linkBody(connectionId: number, over: Partial<DocsyncLinkDto> = {}): DocsyncLinkDto {
|
||||
return {
|
||||
connectionId,
|
||||
scopeKey: 'tag:1',
|
||||
remoteRootId: '1',
|
||||
remoteRootPath: '/TREK/japan',
|
||||
remoteLabel: 'Japan 2026',
|
||||
direction: 'both',
|
||||
deletePolicy: 'unlink',
|
||||
conflictPolicy: 'manual',
|
||||
syncEnabled: true,
|
||||
...over,
|
||||
} as DocsyncLinkDto;
|
||||
}
|
||||
|
||||
async function thrown(fn: () => unknown): Promise<HttpException> {
|
||||
try {
|
||||
await fn();
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(HttpException);
|
||||
return err as HttpException;
|
||||
}
|
||||
throw new Error('expected the handler to throw');
|
||||
}
|
||||
|
||||
let owner: User;
|
||||
let member: User;
|
||||
let admin: User;
|
||||
let tripId: number;
|
||||
let otherTripId: number;
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
const o = createUser(testDb, { username: 'owner', email: 'owner@test.local' }).user;
|
||||
const m = createUser(testDb, { username: 'member', email: 'member@test.local' }).user;
|
||||
const a = createUser(testDb, { username: 'admin', email: 'admin@test.local', role: 'admin' }).user;
|
||||
owner = { id: o.id, role: 'user' } as User;
|
||||
member = { id: m.id, role: 'user' } as User;
|
||||
admin = { id: a.id, role: 'admin' } as User;
|
||||
tripId = createTrip(testDb, o.id, { title: 'Japan' }).id;
|
||||
otherTripId = createTrip(testDb, m.id, { title: 'Norway' }).id;
|
||||
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, m.id);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
testDb.exec('DELETE FROM document_sync_items; DELETE FROM trip_document_links; DELETE FROM document_connections; DELETE FROM trip_files');
|
||||
// Providers ship switched off; these three are what the cases below need.
|
||||
testDb.prepare("UPDATE document_providers SET enabled = 0").run();
|
||||
testDb.prepare("UPDATE document_providers SET enabled = 1 WHERE id IN ('paperless', 'nextcloud', 'papra')").run();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
async function storedPaperless(credentials: Record<string, string> = { api_token: 'stored-token' }) {
|
||||
const res = await config.upsertConnection(tripId, Number(owner.id), connBody({ credentials }));
|
||||
if ('error' in res) throw new Error(`fixture failed: ${res.error.code} ${res.error.detail ?? ''}`);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
describe('who may change a trip binding', () => {
|
||||
it('lets the trip owner through', async () => {
|
||||
await expect(controller.resolve(String(tripId), '1', owner, { keep: 'trek' })).resolves.toEqual({ success: true });
|
||||
});
|
||||
|
||||
it('lets an instance admin through on a trip they neither own nor joined', async () => {
|
||||
await expect(controller.resolve(String(otherTripId), '1', admin, { keep: 'trek' })).resolves.toEqual({ success: true });
|
||||
});
|
||||
|
||||
it('refuses a plain member with the message the client renders', async () => {
|
||||
const err = await thrown(() => controller.resolve(String(tripId), '1', member, { keep: 'trek' }));
|
||||
expect(err.getStatus()).toBe(403);
|
||||
expect(err.message).toBe('Only the trip owner can change document sync');
|
||||
});
|
||||
|
||||
it('answers 404 for a trip that does not exist, rather than the 403 that would confirm it', async () => {
|
||||
const err = await thrown(() => controller.resolve('999999', '1', member, { keep: 'trek' }));
|
||||
expect(err.getStatus()).toBe(404);
|
||||
expect(err.message).toBe('Trip not found');
|
||||
});
|
||||
});
|
||||
|
||||
describe('providers', () => {
|
||||
it('reports an enabled provider with no registered adapter as unavailable instead of hiding it', () => {
|
||||
const rows = controller.providers() as Array<{ id: string; available: boolean }>;
|
||||
const byId = Object.fromEntries(rows.map((r) => [r.id, r.available]));
|
||||
// papra is switched on in the DB, but no adapter is registered in this suite.
|
||||
expect(byId.papra).toBe(false);
|
||||
expect(byId.paperless).toBe(true);
|
||||
expect(byId.nextcloud).toBe(true);
|
||||
});
|
||||
|
||||
it('hands the form flags to the client as booleans rather than the 0/1 the column stores', () => {
|
||||
const rows = controller.providers() as Array<{ id: string; fields: Array<{ field_key: string; secret: boolean; required: boolean }> }>;
|
||||
const fields = rows.find((r) => r.id === 'paperless')!.fields;
|
||||
const token = fields.find((f) => f.field_key === 'api_token')!;
|
||||
expect(token.secret).toBe(true);
|
||||
expect(token.required).toBe(true);
|
||||
expect(fields.find((f) => f.field_key === 'allow_insecure_tls')!.secret).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('storing a connection', () => {
|
||||
it('hands the stored connection back with the secret masked instead of echoed', async () => {
|
||||
const res = (await controller.upsertConnection(
|
||||
String(tripId),
|
||||
owner,
|
||||
connBody({ credentials: { api_token: 'super-secret' } }),
|
||||
)) as { id: number; secrets: Record<string, string> };
|
||||
|
||||
expect(res.secrets.api_token).not.toContain('super-secret');
|
||||
|
||||
const listed = controller.listConnections(String(tripId)) as Array<{ id: number; secrets: Record<string, string> }>;
|
||||
expect(listed).toHaveLength(1);
|
||||
expect(listed[0].id).toBe(res.id);
|
||||
// The list is what the form renders from, so the secret must not survive
|
||||
// the round trip either.
|
||||
expect(listed[0].secrets.api_token).not.toContain('super-secret');
|
||||
});
|
||||
|
||||
it('refuses a base URL the SSRF guard turns down', async () => {
|
||||
const err = await thrown(() => controller.upsertConnection(String(tripId), owner, connBody({ baseUrl: 'https://blocked.invalid' })));
|
||||
expect(err.getStatus()).toBe(400);
|
||||
expect(config.listConnections(tripId)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('refuses a provider the instance admin has not switched on, and names it', async () => {
|
||||
testDb.prepare("UPDATE document_providers SET enabled = 0 WHERE id = 'papra'").run();
|
||||
const err = await thrown(() =>
|
||||
controller.upsertConnection(String(tripId), owner, connBody({ providerId: 'papra', credentials: { api_key: 'k', organization_id: 'org_1' } })),
|
||||
);
|
||||
expect(err.getStatus()).toBe(400);
|
||||
expect(err.message).toBe('Provider: "papra" is not enabled, contact server administrator');
|
||||
});
|
||||
});
|
||||
|
||||
describe('probing form values', () => {
|
||||
it('keeps the stored secret when the form leaves the field blank', async () => {
|
||||
await storedPaperless();
|
||||
await controller.testConnection(String(tripId), owner, connBody({ credentials: { api_token: '' } }) as DocsyncConnectionTestDto);
|
||||
expect(paperless.probe.mock.calls[0][0]).toMatchObject({ secrets: { api_token: 'stored-token' } });
|
||||
});
|
||||
|
||||
it('takes a freshly typed secret over the stored one', async () => {
|
||||
await storedPaperless();
|
||||
await controller.testConnection(String(tripId), owner, connBody({ credentials: { api_token: 'typed-now' } }) as DocsyncConnectionTestDto);
|
||||
expect(paperless.probe.mock.calls[0][0]).toMatchObject({ secrets: { api_token: 'typed-now' } });
|
||||
});
|
||||
|
||||
it('keeps a stored non-secret setting the form did not resend', async () => {
|
||||
const res = await config.upsertConnection(tripId, Number(owner.id), connBody({
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
credentials: { login_name: 'alice', app_password: 'app-pw', base_path: '/TREK' },
|
||||
}));
|
||||
expect('error' in res).toBe(false);
|
||||
|
||||
await controller.testConnection(String(tripId), owner, connBody({
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
credentials: { app_password: '' },
|
||||
}) as DocsyncConnectionTestDto);
|
||||
|
||||
expect(nextcloud.probe.mock.calls[0][0]).toMatchObject({
|
||||
settings: { login_name: 'alice', base_path: '/TREK' },
|
||||
secrets: { app_password: 'app-pw' },
|
||||
});
|
||||
});
|
||||
|
||||
it('takes a freshly typed setting over the stored one', async () => {
|
||||
const res = await config.upsertConnection(tripId, Number(owner.id), connBody({
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
credentials: { login_name: 'alice', app_password: 'app-pw' },
|
||||
}));
|
||||
expect('error' in res).toBe(false);
|
||||
|
||||
await controller.testConnection(String(tripId), owner, connBody({
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
credentials: { login_name: 'bob' },
|
||||
}) as DocsyncConnectionTestDto);
|
||||
|
||||
expect(nextcloud.probe.mock.calls[0][0]).toMatchObject({ settings: { login_name: 'bob' } });
|
||||
});
|
||||
|
||||
it('answers with a body instead of throwing when no adapter is registered', async () => {
|
||||
await expect(
|
||||
controller.testConnection(String(tripId), owner, connBody({ providerId: 'papra', credentials: { api_key: 'k' } }) as DocsyncConnectionTestDto),
|
||||
).resolves.toEqual({ connected: false, error: 'unknown_provider' });
|
||||
});
|
||||
|
||||
it('answers with a body instead of throwing when the URL is refused', async () => {
|
||||
await expect(
|
||||
controller.testConnection(String(tripId), owner, connBody({ baseUrl: 'https://blocked.invalid' }) as DocsyncConnectionTestDto),
|
||||
).resolves.toEqual({ connected: false, error: 'ssrf_blocked' });
|
||||
expect(paperless.probe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('answers with a body instead of throwing when the provider rejects the credentials', async () => {
|
||||
paperless.probe.mockResolvedValueOnce({ success: false, error: { code: 'unauthorized', detail: 'token expired' } } as never);
|
||||
await expect(
|
||||
controller.testConnection(String(tripId), owner, connBody({ credentials: { api_token: 'nope' } }) as DocsyncConnectionTestDto),
|
||||
).resolves.toEqual({ connected: false, error: 'unauthorized', detail: 'token expired' });
|
||||
});
|
||||
|
||||
it('writes a successful probe onto the stored connection, so the status panel has something to show', async () => {
|
||||
const conn = await storedPaperless();
|
||||
await controller.testConnection(String(tripId), owner, connBody({ credentials: { api_token: '' } }) as DocsyncConnectionTestDto);
|
||||
const row = config.getConnection(conn.id)!;
|
||||
expect(row.last_probe_state).toBe('ok');
|
||||
expect(JSON.parse(row.capabilities!)).toMatchObject({ push: 'webhook-self-registered' });
|
||||
});
|
||||
|
||||
it('leaves no probe record behind when the form values belong to no stored connection yet', async () => {
|
||||
await controller.testConnection(String(tripId), owner, connBody({ credentials: { api_token: 'first-try' } }) as DocsyncConnectionTestDto);
|
||||
expect(config.listConnections(tripId)).toHaveLength(0);
|
||||
expect(paperless.probe.mock.calls[0][0]).toMatchObject({ connectionId: 0, secrets: { api_token: 'first-try' } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('a secret the adapter earned itself', () => {
|
||||
const EARNED = 'a1b2c3:DEVICE-SECRET';
|
||||
|
||||
it('is in neither connection payload the form is rendered from', async () => {
|
||||
testDb.prepare("UPDATE document_providers SET enabled = 1 WHERE id = 'synologydrive'").run();
|
||||
const nas = connBody({
|
||||
providerId: 'synologydrive',
|
||||
baseUrl: 'https://nas.example.com:5001',
|
||||
credentials: { username: 'anna', password: 'nas-pw' },
|
||||
});
|
||||
const created = (await controller.upsertConnection(String(tripId), owner, nas)) as { id: number };
|
||||
config.saveEarnedSecret(created.id, 'device_token', EARNED);
|
||||
|
||||
const listed = JSON.stringify(controller.listConnections(String(tripId)));
|
||||
const edited = JSON.stringify(
|
||||
await controller.upsertConnection(String(tripId), owner, { ...nas, credentials: { username: 'anna', password: 'rotated' } }),
|
||||
);
|
||||
for (const payload of [listed, edited]) {
|
||||
expect(payload).not.toContain('DEVICE-SECRET');
|
||||
expect(payload).not.toContain('device_token');
|
||||
}
|
||||
expect(config.toRef(config.getConnection(created.id)!).secrets.device_token).toBe(EARNED);
|
||||
});
|
||||
|
||||
it('reaches a probe of the saved form, which gets no way to write', async () => {
|
||||
const conn = await storedPaperless();
|
||||
config.saveEarnedSecret(conn.id, 'device_token', EARNED);
|
||||
const res = await controller.testConnection(String(tripId), owner, connBody({ credentials: { api_token: '' } }) as DocsyncConnectionTestDto);
|
||||
|
||||
const ref = paperless.probe.mock.calls[0][0];
|
||||
// The row as well as its id: together they are where the saved connection keeps its device token.
|
||||
expect(ref).toMatchObject({ connectionId: conn.id, createdAt: conn.created_at, secrets: { device_token: EARNED } });
|
||||
expect(ref.createdAt).not.toBe('');
|
||||
expect(ref.saveSecret).toBeUndefined();
|
||||
expect(JSON.stringify(res)).not.toContain('DEVICE-SECRET');
|
||||
});
|
||||
|
||||
it('gives a probe of an unsaved form no way to write either', async () => {
|
||||
await controller.testConnection(String(tripId), owner, connBody({ credentials: { api_token: 'first-try' } }) as DocsyncConnectionTestDto);
|
||||
const ref = paperless.probe.mock.calls[0][0];
|
||||
expect(ref.connectionId).toBe(0);
|
||||
expect(ref.createdAt).toBe('');
|
||||
expect(ref.saveSecret).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('reading the trip state', () => {
|
||||
it('asks the reconciler with a number, because the path hands the handler a string', () => {
|
||||
controller.status(String(tripId));
|
||||
expect(sync.status).toHaveBeenCalledWith(tripId);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removing a connection', () => {
|
||||
it('unbinds without touching the documents that came through it', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const fileId = Number(
|
||||
testDb.prepare('INSERT INTO trip_files (trip_id, filename, original_name) VALUES (?, ?, ?)')
|
||||
.run(tripId, 'stored.pdf', 'boarding.pdf').lastInsertRowid,
|
||||
);
|
||||
|
||||
expect(controller.deleteConnection(String(tripId), String(conn.id), owner)).toEqual({ success: true });
|
||||
expect(config.getConnection(conn.id)).toBeUndefined();
|
||||
expect(testDb.prepare('SELECT id FROM trip_files WHERE id = ?').get(fileId)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('refuses a connection that belongs to a different trip', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const err = await thrown(() => controller.deleteConnection(String(otherTripId), String(conn.id), admin));
|
||||
expect(err.getStatus()).toBe(404);
|
||||
expect(config.getConnection(conn.id)).toBeTruthy();
|
||||
expect(realtime.broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('pings the trip once for every binding that went with it, and for no other', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const cloud = await config.upsertConnection(tripId, Number(owner.id), connBody({
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
credentials: { login_name: 'alice', app_password: 'app-pw', base_path: '/TREK' },
|
||||
}));
|
||||
if ('error' in cloud) throw new Error(`fixture failed: ${cloud.error.code}`);
|
||||
const bind = (connectionId: number, scopeKey: string) => {
|
||||
const res = config.createLink(tripId, Number(owner.id), linkBody(connectionId, { scopeKey }));
|
||||
if ('error' in res) throw new Error(`fixture failed: ${res.error.code}`);
|
||||
return res.data.id;
|
||||
};
|
||||
const first = bind(conn.id, 'tag:1');
|
||||
const second = bind(conn.id, 'tag:2');
|
||||
bind(cloud.data.id, 'folder:1');
|
||||
|
||||
controller.deleteConnection(String(tripId), String(conn.id), owner);
|
||||
|
||||
expect(realtime.broadcast.mock.calls).toEqual([
|
||||
[tripId, 'docsync:changed', { linkId: first, pulled: 0, pushed: 0 }],
|
||||
[tripId, 'docsync:changed', { linkId: second, pulled: 0, pushed: 0 }],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the scope picker', () => {
|
||||
it('passes the search text to the adapter and hands back what it offers', async () => {
|
||||
const conn = await storedPaperless();
|
||||
paperless.listScopes.mockResolvedValueOnce({
|
||||
success: true,
|
||||
data: [{ scopeKey: 'tag:1', label: 'Japan 2026', remoteRootId: '1', remoteRootPath: '/TREK/japan' }],
|
||||
} as never);
|
||||
|
||||
const res = await controller.listScopes(String(tripId), String(conn.id), owner, 'japan');
|
||||
|
||||
expect(paperless.listScopes.mock.calls[0][1]).toBe('japan');
|
||||
expect(res).toMatchObject({ scopes: [{ scopeKey: 'tag:1' }] });
|
||||
});
|
||||
|
||||
it('reports a provider failure in the body, so the picker can say why it is empty', async () => {
|
||||
const conn = await storedPaperless();
|
||||
paperless.listScopes.mockResolvedValueOnce({ success: false, error: { code: 'unauthorized' } } as never);
|
||||
await expect(controller.listScopes(String(tripId), String(conn.id), owner)).resolves.toEqual({ scopes: [], error: 'unauthorized' });
|
||||
});
|
||||
|
||||
it('refuses a connection whose provider has no adapter on this instance', async () => {
|
||||
const id = Number(
|
||||
testDb.prepare('INSERT INTO document_connections (trip_id, provider_id, owner_user_id, base_url) VALUES (?, ?, ?, ?)')
|
||||
.run(tripId, 'papra', Number(owner.id), 'https://papra.example.com').lastInsertRowid,
|
||||
);
|
||||
const err = await thrown(() => controller.listScopes(String(tripId), String(id), owner));
|
||||
expect(err.getStatus()).toBe(400);
|
||||
expect(err.message).toBe('Provider not available');
|
||||
});
|
||||
|
||||
it('refuses a connection that belongs to a different trip', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const err = await thrown(() => controller.listScopes(String(otherTripId), String(conn.id), admin));
|
||||
expect(err.getStatus()).toBe(404);
|
||||
expect(paperless.listScopes).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('hands back the container the adapter created', async () => {
|
||||
const conn = await storedPaperless();
|
||||
paperless.createScope.mockResolvedValueOnce({
|
||||
success: true,
|
||||
data: { scopeKey: 'tag:9', label: 'Norway', remoteRootId: '9', remoteRootPath: '/TREK/norway' },
|
||||
} as never);
|
||||
|
||||
await expect(controller.createScope(String(tripId), String(conn.id), owner, { name: 'Norway' }))
|
||||
.resolves.toMatchObject({ scopeKey: 'tag:9', label: 'Norway' });
|
||||
expect(paperless.createScope).toHaveBeenCalledWith(expect.objectContaining({ connectionId: conn.id }), 'Norway');
|
||||
});
|
||||
|
||||
it('creates nothing through a connection that belongs to a different trip', async () => {
|
||||
// The connection comes from the path and nowhere else, so the path is what
|
||||
// has to match the trip the caller was admitted to.
|
||||
const conn = await storedPaperless();
|
||||
const err = await thrown(() => controller.createScope(String(otherTripId), String(conn.id), admin, { name: 'Norway' }));
|
||||
expect(err.getStatus()).toBe(404);
|
||||
expect(paperless.createScope).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('turns a refused creation into a 400 carrying the provider code', async () => {
|
||||
const conn = await storedPaperless();
|
||||
paperless.createScope.mockResolvedValueOnce({ success: false, error: { code: 'forbidden' } } as never);
|
||||
const err = await thrown(() => controller.createScope(String(tripId), String(conn.id), owner, { name: 'Norway' }));
|
||||
expect(err.getStatus()).toBe(400);
|
||||
expect(err.message).toBe('forbidden');
|
||||
});
|
||||
});
|
||||
|
||||
describe('creating a binding', () => {
|
||||
it('subscribes at the provider and remembers the subscription id', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const link = (await controller.createLink(
|
||||
String(tripId),
|
||||
owner,
|
||||
linkBody(conn.id),
|
||||
makeReq({ 'x-forwarded-proto': 'https', 'x-forwarded-host': 'trek.example' }),
|
||||
)) as { id: number };
|
||||
|
||||
const row = config.getLink(link.id)!;
|
||||
expect(row.webhook_subscription_id).toBe('sub-7');
|
||||
expect(paperless.registerWebhook.mock.calls[0][2]).toBe(`https://trek.example/api/docsync/webhook/${row.webhook_token}`);
|
||||
// The secret handed to the provider is the plaintext one, not the stored blob.
|
||||
expect(paperless.registerWebhook.mock.calls[0][3]).toBe(config.webhookSecret(row));
|
||||
});
|
||||
|
||||
it('keeps the binding when the provider refuses the subscription, because polling still carries it', async () => {
|
||||
const conn = await storedPaperless();
|
||||
paperless.registerWebhook.mockResolvedValueOnce({ success: false, error: { code: 'forbidden' } } as never);
|
||||
|
||||
const link = (await controller.createLink(
|
||||
String(tripId),
|
||||
owner,
|
||||
linkBody(conn.id),
|
||||
makeReq({ 'x-forwarded-host': 'trek.example' }),
|
||||
)) as { id: number; syncEnabled: boolean };
|
||||
|
||||
const row = config.getLink(link.id)!;
|
||||
expect(row.webhook_subscription_id).toBeNull();
|
||||
expect(row.sync_enabled).toBe(1);
|
||||
});
|
||||
|
||||
it('does not offer a webhook when no host reaches TREK', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const link = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { webhookUrl: string | null };
|
||||
expect(paperless.registerWebhook).not.toHaveBeenCalled();
|
||||
expect(link.webhookUrl).toBeNull();
|
||||
});
|
||||
|
||||
it('starts a first run at once instead of letting the user wait out a poll interval', async () => {
|
||||
const conn = await storedPaperless();
|
||||
await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq({ host: 'trek.example' }));
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
expect(sync.syncLink.mock.calls[0][1]).toEqual({ full: true });
|
||||
});
|
||||
|
||||
it('pings the whole trip, so a member already on the Files tab gets the sync button', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const link = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { id: number };
|
||||
|
||||
// Three arguments: no socket is skipped, the owner's own button reads it too.
|
||||
expect(realtime.broadcast).toHaveBeenCalledWith(tripId, 'docsync:changed', { linkId: link.id, pulled: 0, pushed: 0 });
|
||||
});
|
||||
|
||||
it('refuses a binding for a connection that belongs to a different trip', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const err = await thrown(() =>
|
||||
controller.createLink(String(otherTripId), admin, linkBody(conn.id), makeReq({ host: 'trek.example' })),
|
||||
);
|
||||
expect(err.getStatus()).toBe(400);
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
expect(realtime.broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('changing a binding', () => {
|
||||
it('writes only the fields the request carried', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const created = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { id: number };
|
||||
|
||||
const res = controller.updateLink(String(tripId), String(created.id), owner, { syncEnabled: false }, makeReq()) as {
|
||||
syncEnabled: boolean;
|
||||
direction: string;
|
||||
remoteLabel: string;
|
||||
};
|
||||
|
||||
expect(res.syncEnabled).toBe(false);
|
||||
expect(res.direction).toBe('both');
|
||||
expect(res.remoteLabel).toBe('Japan 2026');
|
||||
});
|
||||
|
||||
it('refuses a link that belongs to a different trip', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const created = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { id: number };
|
||||
const err = await thrown(() => controller.updateLink(String(otherTripId), String(created.id), admin, { syncEnabled: false }, makeReq()));
|
||||
expect(err.getStatus()).toBe(404);
|
||||
expect(config.getLink(created.id)!.sync_enabled).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a manual run', () => {
|
||||
it('passes the full flag through to the reconciler', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const created = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { id: number };
|
||||
sync.syncLink.mockClear();
|
||||
|
||||
await controller.syncNow(String(tripId), String(created.id), { full: true });
|
||||
|
||||
expect(sync.syncLink.mock.calls[0][0]).toMatchObject({ id: created.id });
|
||||
expect(sync.syncLink.mock.calls[0][1]).toEqual({ full: true });
|
||||
});
|
||||
|
||||
it('refuses a link that belongs to a different trip', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const created = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { id: number };
|
||||
sync.syncLink.mockClear();
|
||||
|
||||
const err = await thrown(() => controller.syncNow(String(otherTripId), String(created.id), { full: false }));
|
||||
expect(err.getStatus()).toBe(404);
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses a binding an admin switched off with a code, and touches nothing', async () => {
|
||||
// A code rather than a sentence so the client can say it in the reader's
|
||||
// language; the MCP tool answers with the same one. Refused before the
|
||||
// shelved rows are cleared, so the binding resumes exactly as it was.
|
||||
const conn = await storedPaperless();
|
||||
const created = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { id: number };
|
||||
sync.syncLink.mockClear();
|
||||
sync.isSwitchedOff.mockReturnValueOnce(true);
|
||||
|
||||
const err = await thrown(() => controller.syncNow(String(tripId), String(created.id), { full: false }));
|
||||
|
||||
expect(err.getStatus()).toBe(409);
|
||||
expect(err.getResponse()).toEqual({ error: 'provider_disabled' });
|
||||
expect(sync.isSwitchedOff.mock.calls[0][0]).toMatchObject({ id: created.id });
|
||||
expect(sync.retryShelvedItems).not.toHaveBeenCalled();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the document list', () => {
|
||||
async function seedItems() {
|
||||
const conn = await storedPaperless();
|
||||
const fileId = Number(
|
||||
testDb.prepare('INSERT INTO trip_files (trip_id, filename, original_name) VALUES (?, ?, ?)')
|
||||
.run(tripId, 'stored.pdf', 'boarding.pdf').lastInsertRowid,
|
||||
);
|
||||
const linkId = Number(
|
||||
testDb.prepare(
|
||||
`INSERT INTO trip_document_links (trip_id, connection_id, provider_id, remote_scope_key)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
).run(tripId, conn.id, 'paperless', 'tag:1').lastInsertRowid,
|
||||
);
|
||||
const insert = testDb.prepare('INSERT INTO document_sync_items (link_id, trip_id, file_id, trek_doc_uid, state) VALUES (?, ?, ?, ?, ?)');
|
||||
insert.run(linkId, tripId, fileId, 'uid-1', 'synced');
|
||||
insert.run(linkId, tripId, null, 'uid-2', 'conflict');
|
||||
// Another trip's row, which must never appear in this trip's list.
|
||||
insert.run(linkId, otherTripId, null, 'uid-3', 'conflict');
|
||||
}
|
||||
|
||||
it('carries the local file name, so the list reads as documents rather than as ids', async () => {
|
||||
await seedItems();
|
||||
const rows = controller.items(String(tripId)) as Array<{ trek_doc_uid: string; file_name: string | null }>;
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows.find((r) => r.trek_doc_uid === 'uid-1')!.file_name).toBe('boarding.pdf');
|
||||
});
|
||||
|
||||
it('narrows to one state when asked, and never leaves the trip', async () => {
|
||||
await seedItems();
|
||||
const rows = controller.items(String(tripId), 'conflict') as Array<{ trek_doc_uid: string }>;
|
||||
expect(rows.map((r) => r.trek_doc_uid)).toEqual(['uid-2']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolving a conflict', () => {
|
||||
it('refuses an item that is not in conflict rather than pretending it did something', async () => {
|
||||
sync.resolveConflict.mockResolvedValueOnce(false);
|
||||
const err = await thrown(() => controller.resolve(String(tripId), '5', owner, { keep: 'provider' }));
|
||||
expect(err.getStatus()).toBe(400);
|
||||
expect(err.message).toBe('Item is not in conflict');
|
||||
});
|
||||
});
|
||||
|
||||
describe('removing a binding', () => {
|
||||
it('unsubscribes at the provider and keeps both copies of the documents', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const created = (await controller.createLink(
|
||||
String(tripId),
|
||||
owner,
|
||||
linkBody(conn.id),
|
||||
makeReq({ host: 'trek.example' }),
|
||||
)) as { id: number };
|
||||
const fileId = Number(
|
||||
testDb.prepare('INSERT INTO trip_files (trip_id, filename, original_name) VALUES (?, ?, ?)')
|
||||
.run(tripId, 'stored.pdf', 'boarding.pdf').lastInsertRowid,
|
||||
);
|
||||
testDb
|
||||
.prepare('INSERT INTO document_sync_items (link_id, trip_id, file_id, trek_doc_uid, state) VALUES (?, ?, ?, ?, ?)')
|
||||
.run(created.id, tripId, fileId, 'uid-1', 'synced');
|
||||
|
||||
const res = await controller.deleteLink(String(tripId), String(created.id), owner);
|
||||
|
||||
expect(res).toEqual({ success: true, documentsKept: true });
|
||||
expect(paperless.unregisterWebhook.mock.calls[0][1]).toBe('sub-7');
|
||||
expect(config.getLink(created.id)).toBeUndefined();
|
||||
expect(testDb.prepare('SELECT id FROM trip_files WHERE id = ?').get(fileId)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('pings the trip that the binding is gone', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const created = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { id: number };
|
||||
realtime.broadcast.mockClear();
|
||||
|
||||
await controller.deleteLink(String(tripId), String(created.id), owner);
|
||||
|
||||
expect(realtime.broadcast.mock.calls).toEqual([
|
||||
[tripId, 'docsync:changed', { linkId: created.id, pulled: 0, pushed: 0 }],
|
||||
]);
|
||||
});
|
||||
|
||||
it('refuses a link that belongs to a different trip', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const created = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { id: number };
|
||||
realtime.broadcast.mockClear();
|
||||
const err = await thrown(() => controller.deleteLink(String(otherTripId), String(created.id), admin));
|
||||
expect(err.getStatus()).toBe(404);
|
||||
expect(config.getLink(created.id)).toBeTruthy();
|
||||
expect(realtime.broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the callback origin a provider is given', () => {
|
||||
async function linkedTrip() {
|
||||
const conn = await storedPaperless();
|
||||
const created = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { id: number };
|
||||
return config.getLink(created.id)!;
|
||||
}
|
||||
|
||||
it('builds the callback URL from the forwarded proto and host', async () => {
|
||||
const row = await linkedTrip();
|
||||
const [link] = controller.listLinks(String(tripId), makeReq({ 'x-forwarded-proto': 'https', 'x-forwarded-host': 'docs.example' })) as Array<{ webhookUrl: string }>;
|
||||
expect(link.webhookUrl).toBe(`https://docs.example/api/docsync/webhook/${row.webhook_token}`);
|
||||
});
|
||||
|
||||
it('takes the first hop when a proxy chain appends its own protocol', async () => {
|
||||
await linkedTrip();
|
||||
const [link] = controller.listLinks(String(tripId), makeReq({ 'x-forwarded-proto': 'https, http', 'x-forwarded-host': 'docs.example' })) as Array<{ webhookUrl: string }>;
|
||||
expect(link.webhookUrl).toMatch(/^https:\/\/docs\.example\//);
|
||||
});
|
||||
|
||||
it('falls back to the Host header and the connection scheme when nothing is forwarded', async () => {
|
||||
await linkedTrip();
|
||||
const [link] = controller.listLinks(String(tripId), makeReq({ host: 'trek.lan:3001' }, 'http')) as Array<{ webhookUrl: string }>;
|
||||
expect(link.webhookUrl).toMatch(/^http:\/\/trek\.lan:3001\//);
|
||||
});
|
||||
|
||||
it('offers no callback URL when a proxy strips the host', async () => {
|
||||
await linkedTrip();
|
||||
const [link] = controller.listLinks(String(tripId), makeReq()) as Array<{ webhookUrl: string | null }>;
|
||||
expect(link.webhookUrl).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A manual run is also a request to try the given-up rows once more.
|
||||
*
|
||||
* The scheduler must never do this: the attempt limit exists precisely so a
|
||||
* document a provider refuses is not re-uploaded on every tick. A person
|
||||
* pressing the button is the signal that something changed.
|
||||
*/
|
||||
describe('a manual run and the shelved rows', () => {
|
||||
it('clears the attempt counters of the link it runs', async () => {
|
||||
const conn = await storedPaperless();
|
||||
const created = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { id: number };
|
||||
sync.retryShelvedItems.mockClear();
|
||||
|
||||
await controller.syncNow(String(tripId), String(created.id), { full: false });
|
||||
|
||||
expect(sync.retryShelvedItems).toHaveBeenCalledWith(created.id);
|
||||
});
|
||||
|
||||
it('does not clear them for a link the caller does not own', async () => {
|
||||
sync.retryShelvedItems.mockClear();
|
||||
await expect(controller.syncNow(String(tripId), '999999', { full: false })).rejects.toThrow();
|
||||
expect(sync.retryShelvedItems).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The trip the route was authorised against is now passed on to the service.
|
||||
*
|
||||
* `assertCanManage` proves the caller may manage the trip in the URL and says
|
||||
* nothing about whether the item id in the path belongs to that trip: the id is
|
||||
* a plain integer, and nothing tied the two together. The check itself lives in
|
||||
* the service (where the row is), so what belongs here is that the trip reaches
|
||||
* it at all.
|
||||
*/
|
||||
describe('resolving a conflict carries its trip', () => {
|
||||
it('passes the trip from the URL to the service', async () => {
|
||||
sync.resolveConflict.mockClear();
|
||||
await controller.resolve(String(tripId), '42', owner, { keep: 'trek' } as never);
|
||||
expect(sync.resolveConflict).toHaveBeenCalledWith(42, 'trek', tripId);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,492 @@
|
||||
/**
|
||||
* The scheduling shell around document sync, built with `new` and plain mocks:
|
||||
* no container, no timer, no provider.
|
||||
*
|
||||
* What the job itself decides is small, and all of it is the kind that breaks
|
||||
* silently. The addon gate and the kill switch are re-read per tick, which is
|
||||
* the promise the docblock makes an admin ("toggle it and it takes effect")
|
||||
* and the only thing that makes the difference between this job and the
|
||||
* Dawarich one visible. The interval is typed by a human into app_settings, so
|
||||
* '5' and '999999' both have to land somewhere the cron parser accepts. And one
|
||||
* unreachable NAS must not take the other trips' bindings down with it.
|
||||
*
|
||||
* The last block is the exception: an admin's provider switch lives in the
|
||||
* service's query, so it runs the tick over the real service and a database.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
|
||||
import Database from 'better-sqlite3';
|
||||
|
||||
const log = vi.hoisted(() => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
}));
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', () => log);
|
||||
|
||||
import { ADDON_IDS } from '../../../../src/addons';
|
||||
import { DocSyncJob } from '../../../../src/nest/doc-sync/doc-sync.job';
|
||||
import { SETTING_POLL_INTERVAL, SETTING_SYNC_ENABLED } from '../../../../src/nest/doc-sync/doc-sync.constants';
|
||||
import { DocSyncConfigService, type LinkRow } from '../../../../src/nest/doc-sync/doc-sync-config.service';
|
||||
import { DocSyncService } from '../../../../src/nest/doc-sync/doc-sync.service';
|
||||
import { DocumentProviderRegistry } from '../../../../src/nest/doc-sync/document-provider.registry';
|
||||
import type { DocumentProvider } from '../../../../src/nest/doc-sync/document-provider';
|
||||
import type { AddonsService } from '../../../../src/nest/addons/addons.service';
|
||||
import { DatabaseService } from '../../../../src/nest/database/database.service';
|
||||
import type { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
|
||||
import { AllowedFileTypesService } from '../../../../src/nest/files/allowed-file-types.service';
|
||||
import type { FilesService } from '../../../../src/nest/files/files.service';
|
||||
import type { StorageService } from '../../../../src/nest/storage/storage.service';
|
||||
import type { RealtimeService } from '../../../../src/nest/realtime/realtime.service';
|
||||
import { createTables } from '../../../../src/db/schema';
|
||||
import { runMigrations } from '../../../../src/db/migrations';
|
||||
import { createTrip, createUser } from '../../../helpers/factories';
|
||||
|
||||
const link = (id: number): LinkRow => ({ id, provider_id: 'paperless' } as LinkRow);
|
||||
|
||||
const RUN = { state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 };
|
||||
|
||||
interface Setup {
|
||||
/** Absent means no app_settings row at all, which is the shipped state. */
|
||||
interval?: string;
|
||||
killSwitch?: string;
|
||||
addonOn: boolean;
|
||||
registrarEnabled: boolean;
|
||||
links: LinkRow[];
|
||||
orphaned: number;
|
||||
}
|
||||
|
||||
function makeJob(over: Partial<Setup> = {}) {
|
||||
const setup: Setup = { addonOn: true, registrarEnabled: true, links: [], orphaned: 0, ...over };
|
||||
|
||||
const settings = new Map<string, string>();
|
||||
if (setup.interval !== undefined) settings.set(SETTING_POLL_INTERVAL, setup.interval);
|
||||
if (setup.killSwitch !== undefined) settings.set(SETTING_SYNC_ENABLED, setup.killSwitch);
|
||||
|
||||
// Shaped like the real `get<T>(sql, ...params)` so the stub cannot drift from
|
||||
// the signature the job calls, and so a case can tell the two keys apart.
|
||||
const db = {
|
||||
get: vi.fn((_sql: string, key?: unknown) => {
|
||||
const value = settings.get(String(key));
|
||||
return value === undefined ? undefined : { value };
|
||||
}),
|
||||
};
|
||||
|
||||
let onTick: (() => void | Promise<void>) | undefined;
|
||||
const registrar = {
|
||||
isEnabled: vi.fn(() => setup.registrarEnabled),
|
||||
register: vi.fn((_name: string, _expression: string, cb: () => void | Promise<void>) => {
|
||||
onTick = cb;
|
||||
return setup.registrarEnabled;
|
||||
}),
|
||||
unregister: vi.fn(),
|
||||
};
|
||||
|
||||
// Both stubs carry the real signatures, so a case can read back which link a
|
||||
// run was asked for instead of only that some run happened.
|
||||
const sync = {
|
||||
dueLinks: vi.fn((_limit?: number) => setup.links),
|
||||
syncLink: vi.fn(async (_link: LinkRow, _opts?: { full?: boolean }) => RUN),
|
||||
};
|
||||
const config = { markOrphanedLinks: vi.fn(() => setup.orphaned) };
|
||||
const addons = { isAddonEnabled: vi.fn(() => setup.addonOn) };
|
||||
|
||||
const job = new DocSyncJob(
|
||||
db as unknown as DatabaseService,
|
||||
sync as unknown as DocSyncService,
|
||||
config as unknown as DocSyncConfigService,
|
||||
addons as unknown as AddonsService,
|
||||
registrar as unknown as CronRegistrarService,
|
||||
);
|
||||
return { job, db, registrar, sync, config, addons, takeTick: () => onTick };
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('DocSyncJob bootstrap', () => {
|
||||
it('schedules nothing, reads nothing and logs nothing while the registrar is off', () => {
|
||||
// The test gate. A job that registered past it would have every suite boot
|
||||
// start polling whatever document store sits in the fixture database.
|
||||
const { job, registrar, db } = makeJob({ registrarEnabled: false });
|
||||
job.onApplicationBootstrap();
|
||||
expect(registrar.register).not.toHaveBeenCalled();
|
||||
expect(db.get).not.toHaveBeenCalled();
|
||||
expect(log.logInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('registers one cron under a name of its own, on the minute', () => {
|
||||
// Every minute, with the tick deciding whether it is due. Baking the
|
||||
// interval into the expression at bootstrap meant a changed setting did
|
||||
// nothing until a restart, which is the opposite of what this job's own
|
||||
// comment promises, and nothing re-registers it (auto-backup has a start()
|
||||
// its settings save calls; this has no such path).
|
||||
const { job, registrar } = makeJob();
|
||||
job.onApplicationBootstrap();
|
||||
expect(registrar.register).toHaveBeenCalledWith('docsync', '* * * * *', expect.any(Function));
|
||||
expect(log.logInfo).toHaveBeenCalledWith('Document sync: polling every 300s');
|
||||
});
|
||||
|
||||
it('reads the interval from its own app_settings key', () => {
|
||||
const { job, db } = makeJob({ interval: '600' });
|
||||
job.onApplicationBootstrap();
|
||||
expect(db.get).toHaveBeenCalledWith('SELECT value FROM app_settings WHERE key = ?', SETTING_POLL_INTERVAL);
|
||||
});
|
||||
|
||||
it('hands the registrar the tick itself, so a fired cron reaches the sync', async () => {
|
||||
const { job, sync, takeTick } = makeJob({ links: [link(1)] });
|
||||
job.onApplicationBootstrap();
|
||||
const tick = takeTick();
|
||||
expect(tick).toBeTypeOf('function');
|
||||
await tick?.();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not decide at bootstrap whether the addon is on', () => {
|
||||
// Asking here would freeze the answer for the life of the process, and the
|
||||
// bug would read as "the documents toggle needs a restart".
|
||||
const { job, addons } = makeJob();
|
||||
job.onApplicationBootstrap();
|
||||
expect(addons.isAddonEnabled).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DocSyncJob tick', () => {
|
||||
it('does nothing at all while the documents addon is off', async () => {
|
||||
const { job, sync, config, db } = makeJob({ addonOn: false, links: [link(1)] });
|
||||
await job.tick();
|
||||
expect(sync.dueLinks).not.toHaveBeenCalled();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
expect(config.markOrphanedLinks).not.toHaveBeenCalled();
|
||||
expect(db.get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('asks the addon gate again on every tick, so switching it on needs no restart', async () => {
|
||||
const { job, addons, sync } = makeJob({ addonOn: false, links: [link(1)] });
|
||||
await job.tick();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
|
||||
addons.isAddonEnabled.mockReturnValue(true);
|
||||
await job.tick();
|
||||
expect(addons.isAddonEnabled).toHaveBeenCalledTimes(2);
|
||||
expect(addons.isAddonEnabled).toHaveBeenLastCalledWith(ADDON_IDS.DOCUMENTS);
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('stops the run on the kill switch, without touching the bindings', async () => {
|
||||
const { job, sync, config, db } = makeJob({ killSwitch: 'false', links: [link(1)] });
|
||||
await job.tick();
|
||||
expect(db.get).toHaveBeenCalledWith('SELECT value FROM app_settings WHERE key = ?', SETTING_SYNC_ENABLED);
|
||||
expect(config.markOrphanedLinks).not.toHaveBeenCalled();
|
||||
expect(sync.dueLinks).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps syncing on anything that is not exactly the string false', async () => {
|
||||
// The setting is absent by default, so an unrecognised value has to mean ON.
|
||||
// Treating '0' or 'off' as a stop would silently disable sync for anyone who
|
||||
// typed the switch by hand into app_settings.
|
||||
for (const value of [undefined, '', '0', 'off', 'no', 'FALSE', 'true']) {
|
||||
vi.clearAllMocks();
|
||||
const { job, sync } = makeJob({ killSwitch: value, links: [link(1)] });
|
||||
await job.tick();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
});
|
||||
|
||||
it('re-reads the kill switch per tick instead of remembering the first answer', async () => {
|
||||
const { job, db } = makeJob({ links: [link(1)] });
|
||||
await job.tick();
|
||||
await job.tick();
|
||||
const killSwitchReads = db.get.mock.calls.filter((c) => c[1] === SETTING_SYNC_ENABLED).length;
|
||||
expect(killSwitchReads).toBe(2);
|
||||
});
|
||||
|
||||
it('sweeps bindings whose credential owner left the trip before it syncs anything', async () => {
|
||||
const { job, config, sync } = makeJob({ orphaned: 2, links: [link(1)] });
|
||||
await job.tick();
|
||||
expect(config.markOrphanedLinks).toHaveBeenCalledTimes(1);
|
||||
expect(config.markOrphanedLinks.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
sync.dueLinks.mock.invocationCallOrder[0],
|
||||
);
|
||||
expect(log.logInfo).toHaveBeenCalledWith('Document sync: 2 link(s) orphaned, owner no longer on the trip');
|
||||
});
|
||||
|
||||
it('stays quiet when the sweep found nothing', async () => {
|
||||
const { job, config } = makeJob({ orphaned: 0 });
|
||||
await job.tick();
|
||||
expect(config.markOrphanedLinks).toHaveBeenCalledTimes(1);
|
||||
expect(log.logInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs the remaining bindings after one of them throws', async () => {
|
||||
// An unreachable NAS on one trip is not a reason to skip a Paperless
|
||||
// binding on another, and the two are ordinary neighbours in one list.
|
||||
const { job, sync } = makeJob({ links: [link(1), link(2), link(3)] });
|
||||
sync.syncLink.mockRejectedValueOnce(new Error('EHOSTUNREACH'));
|
||||
await expect(job.tick()).resolves.toBeUndefined();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(3);
|
||||
expect(log.logError).toHaveBeenCalledWith('Document sync: link 1 failed: EHOSTUNREACH');
|
||||
});
|
||||
|
||||
it('logs a non-Error rejection by value rather than as an empty message', async () => {
|
||||
const { job, sync } = makeJob({ links: [link(7)] });
|
||||
sync.syncLink.mockRejectedValueOnce('ECONNREFUSED');
|
||||
await job.tick();
|
||||
expect(log.logError).toHaveBeenCalledWith('Document sync: link 7 failed: ECONNREFUSED');
|
||||
});
|
||||
|
||||
it('never rejects, so a failure inside it cannot escape into the scheduler', async () => {
|
||||
const { job, sync } = makeJob();
|
||||
sync.dueLinks.mockImplementation(() => {
|
||||
throw new Error('database is locked');
|
||||
});
|
||||
await expect(job.tick()).resolves.toBeUndefined();
|
||||
expect(log.logError).toHaveBeenCalledWith('Document sync tick failed: database is locked');
|
||||
});
|
||||
|
||||
it('logs a failure thrown as a bare value by what it printed, not as an empty message', async () => {
|
||||
const { job, addons } = makeJob();
|
||||
addons.isAddonEnabled.mockImplementation(() => {
|
||||
throw 'SQLITE_BUSY';
|
||||
});
|
||||
await expect(job.tick()).resolves.toBeUndefined();
|
||||
expect(log.logError).toHaveBeenCalledWith('Document sync tick failed: SQLITE_BUSY');
|
||||
});
|
||||
|
||||
it('recovers on the next due tick after a failed one', async () => {
|
||||
// A failed pass still spends its interval, on purpose: a tick that throws
|
||||
// every time would otherwise run on every minute the cron fires. It does not
|
||||
// block anything permanently: the next due tick works normally.
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
vi.setSystemTime(new Date(10_000_000));
|
||||
const { job, sync } = makeJob({ links: [link(1)], interval: '300' });
|
||||
sync.dueLinks.mockImplementationOnce(() => {
|
||||
throw new Error('down');
|
||||
});
|
||||
await job.tick();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
expect(log.logError).toHaveBeenCalledTimes(1);
|
||||
|
||||
vi.setSystemTime(new Date(10_300_000));
|
||||
await job.tick();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves the choice of what is due to the sync service', async () => {
|
||||
// The job passes the rows through untouched: the backoff, the circuit
|
||||
// breaker and the ordering all live in dueLinks, and a filter copied up
|
||||
// here would be a second place to keep them in step with.
|
||||
const links = [link(4), link(5)];
|
||||
const { job, sync } = makeJob({ links });
|
||||
await job.tick();
|
||||
expect(sync.syncLink.mock.calls.map((c) => c[0])).toEqual(links);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The interval, now that the cron fires every minute.
|
||||
*
|
||||
* It used to be baked into the cron expression at bootstrap, so the setting did
|
||||
* nothing until a restart while this file's own header said otherwise. The tick
|
||||
* now decides, which also means the clamp has to hold here instead of in the
|
||||
* expression: an interval of 0 must not turn the minute cron into a run every
|
||||
* minute, and a huge one must not park the job for a day.
|
||||
*/
|
||||
describe('DocSyncJob due-ness', () => {
|
||||
// Fake system time rather than a Date.now spy: the spy has to be re-applied
|
||||
// after the suite-wide clearAllMocks, and a cleared spy answers undefined,
|
||||
// which reads as "no time has passed" and fails the case for the wrong reason.
|
||||
const at = (ms: number) => vi.setSystemTime(new Date(ms));
|
||||
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('runs the first tick it is given', async () => {
|
||||
const { job, sync } = makeJob({ links: [link(1)] });
|
||||
at(1_000_000);
|
||||
await job.tick();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does nothing on a tick inside the interval', async () => {
|
||||
const { job, sync } = makeJob({ links: [link(1)], interval: '300' });
|
||||
at(1_000_000);
|
||||
await job.tick();
|
||||
at(1_000_000 + 299_000);
|
||||
await job.tick();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('runs again once the interval has passed', async () => {
|
||||
const { job, sync } = makeJob({ links: [link(1)], interval: '300' });
|
||||
at(1_000_000);
|
||||
await job.tick();
|
||||
at(1_000_000 + 300_000);
|
||||
await job.tick();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('keeps the floor: a zero or negative setting still waits a minute', async () => {
|
||||
for (const setting of ['0', '-300', '10']) {
|
||||
const { job, sync } = makeJob({ links: [link(1)], interval: setting });
|
||||
at(2_000_000);
|
||||
await job.tick();
|
||||
at(2_000_000 + 59_000);
|
||||
await job.tick();
|
||||
expect(sync.syncLink, `interval=${setting} ran again inside the floor`).toHaveBeenCalledTimes(1);
|
||||
at(2_000_000 + 60_000);
|
||||
await job.tick();
|
||||
expect(sync.syncLink, `interval=${setting} did not run at the floor`).toHaveBeenCalledTimes(2);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the ceiling: an absurd setting waits an hour, not a day', async () => {
|
||||
const { job, sync } = makeJob({ links: [link(1)], interval: '86400' });
|
||||
at(3_000_000);
|
||||
await job.tick();
|
||||
at(3_000_000 + 3_600_000);
|
||||
await job.tick();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('takes a changed setting without a restart, which is the whole point', async () => {
|
||||
const settings = new Map<string, string>([[SETTING_POLL_INTERVAL, '3600']]);
|
||||
const db = {
|
||||
get: vi.fn((_sql: string, key?: unknown) => {
|
||||
const value = settings.get(String(key));
|
||||
return value === undefined ? undefined : { value };
|
||||
}),
|
||||
};
|
||||
const sync = {
|
||||
dueLinks: vi.fn(() => [link(1)]),
|
||||
syncLink: vi.fn(async () => RUN),
|
||||
};
|
||||
const job = new DocSyncJob(
|
||||
db as unknown as DatabaseService,
|
||||
sync as unknown as DocSyncService,
|
||||
{ markOrphanedLinks: vi.fn(() => 0) } as unknown as DocSyncConfigService,
|
||||
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
|
||||
{ isEnabled: vi.fn(() => true), register: vi.fn(), unregister: vi.fn() } as unknown as CronRegistrarService,
|
||||
);
|
||||
|
||||
at(4_000_000);
|
||||
await job.tick();
|
||||
at(4_000_000 + 120_000);
|
||||
await job.tick();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1); // still inside the hour
|
||||
|
||||
settings.set(SETTING_POLL_INTERVAL, '60');
|
||||
await job.tick();
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('does not count a tick the kill switch stopped, so switching back on runs at once', async () => {
|
||||
const { job, sync } = makeJob({ links: [link(1)], interval: '3600', killSwitch: 'false' });
|
||||
at(5_000_000);
|
||||
await job.tick();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A provider an admin switched off, over the real service and a real database.
|
||||
*
|
||||
* The job leaves what is due to `dueLinks` (see "leaves the choice of what is
|
||||
* due to the sync service" above), so the switch is a property of that query
|
||||
* and only shows with the query running. A stubbed `dueLinks` would restate
|
||||
* whatever this file told it.
|
||||
*/
|
||||
describe('DocSyncJob and a provider switched off in the admin panel', () => {
|
||||
const testDb = new Database(':memory:');
|
||||
const dbs = new DatabaseService(testDb);
|
||||
let paperlessLink: number;
|
||||
let nextcloudLink: number;
|
||||
|
||||
const fakeProvider = (id: string) => ({
|
||||
id,
|
||||
capabilities: () => ({
|
||||
push: 'none', stableId: true, remoteTrash: true, replaceInPlace: true, contentHashInListing: true,
|
||||
maxUploadBytes: null, acceptedMimeTypes: null, canCreateScope: true,
|
||||
}),
|
||||
resolveScope: vi.fn(async () => ({ success: true, data: { scopeKey: 'tag:1', label: 'Japan', remoteRootId: '1', remoteRootPath: null } })),
|
||||
list: vi.fn(async () => ({ success: true, data: { documents: [], cursor: null, cursorUnchanged: false, truncated: false } })),
|
||||
});
|
||||
const paperless = fakeProvider('paperless');
|
||||
const nextcloud = fakeProvider('nextcloud');
|
||||
|
||||
const addons = { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService;
|
||||
const registry = new DocumentProviderRegistry([paperless, nextcloud] as unknown as DocumentProvider[]);
|
||||
const config = new DocSyncConfigService(dbs, registry);
|
||||
const service = new DocSyncService(
|
||||
dbs, config, registry,
|
||||
{} as StorageService, {} as FilesService, new AllowedFileTypesService(dbs),
|
||||
{ broadcast: vi.fn() } as unknown as RealtimeService,
|
||||
addons,
|
||||
);
|
||||
const registrar = { isEnabled: () => false } as unknown as CronRegistrarService;
|
||||
/** A job of its own per pass, so the interval never decides whether a tick runs. */
|
||||
const tick = () => new DocSyncJob(dbs, service, config, addons, registrar).tick();
|
||||
|
||||
const switchProvider = (id: string, on: boolean) =>
|
||||
testDb.prepare('UPDATE document_providers SET enabled = ? WHERE id = ?').run(on ? 1 : 0, id);
|
||||
const linkRow = (id: number) => testDb.prepare('SELECT * FROM trip_document_links WHERE id = ?').get(id);
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
const ownerId = createUser(testDb, { username: 'owner', email: 'owner@docsync-job.test' }).user.id;
|
||||
const tripId = createTrip(testDb, ownerId, { title: 'Japan' }).id;
|
||||
const bind = (providerId: string) => {
|
||||
const conn = testDb
|
||||
.prepare(
|
||||
`INSERT INTO document_connections (trip_id, provider_id, owner_user_id, base_url, secrets, settings)
|
||||
VALUES (?, ?, ?, 'https://docs.example.com', NULL, '{}')`,
|
||||
)
|
||||
.run(tripId, providerId, ownerId);
|
||||
return Number(testDb
|
||||
.prepare(
|
||||
`INSERT INTO trip_document_links
|
||||
(trip_id, connection_id, provider_id, remote_scope_key, remote_label, direction, delete_policy,
|
||||
conflict_policy, sync_enabled, created_by)
|
||||
VALUES (?, ?, ?, 'tag:1', 'Japan', 'both', 'unlink', 'manual', 1, ?)`,
|
||||
)
|
||||
.run(tripId, conn.lastInsertRowid, providerId, ownerId).lastInsertRowid);
|
||||
};
|
||||
paperlessLink = bind('paperless');
|
||||
nextcloudLink = bind('nextcloud');
|
||||
});
|
||||
|
||||
afterAll(() => testDb.close());
|
||||
|
||||
beforeEach(() => {
|
||||
switchProvider('paperless', false);
|
||||
switchProvider('nextcloud', true);
|
||||
});
|
||||
|
||||
it('runs the bindings that may run and leaves the switched-off one exactly as it was', async () => {
|
||||
const before = linkRow(paperlessLink);
|
||||
|
||||
await tick();
|
||||
|
||||
expect(nextcloud.list).toHaveBeenCalledTimes(1);
|
||||
expect(paperless.resolveScope).not.toHaveBeenCalled();
|
||||
expect(paperless.list).not.toHaveBeenCalled();
|
||||
expect(linkRow(paperlessLink)).toEqual(before);
|
||||
expect(linkRow(nextcloudLink)).toMatchObject({ last_sync_state: 'ok' });
|
||||
});
|
||||
|
||||
it('picks the binding up again on the next tick once the provider is back on', async () => {
|
||||
await tick();
|
||||
expect(paperless.list).not.toHaveBeenCalled();
|
||||
|
||||
switchProvider('paperless', true);
|
||||
await tick();
|
||||
|
||||
expect(paperless.list).toHaveBeenCalledTimes(1);
|
||||
expect(linkRow(paperlessLink)).toMatchObject({ last_sync_state: 'ok', failure_count: 0 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* The MCP half of document sync, built with `new` and plain mocks: no registry,
|
||||
* no MCP server, no container.
|
||||
*
|
||||
* The tool bodies are three lines each, and what is worth pinning about them is
|
||||
* not the plumbing but the decisions around it. The access check is the whole
|
||||
* security story: there is no guard in front of an MCP tool, so a dropped
|
||||
* `verifyTripAccess` is a stranger reading where somebody's documents live. The
|
||||
* absence of a connect tool is a decision too: setting a connection up means
|
||||
* handing over a credential that usually reaches a person's entire document
|
||||
* archive, and a decision nobody asserts is one somebody re-adds by accident.
|
||||
* And the refusal for an unconnected trip is the only thing standing between an
|
||||
* assistant and answering "nothing to sync" to a question about someone's
|
||||
* boarding pass.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { z, type ZodRawShape } from 'zod';
|
||||
|
||||
import { ADDON_IDS } from '../../../../src/addons';
|
||||
import { DocSyncMcp } from '../../../../src/nest/doc-sync/doc-sync.mcp';
|
||||
import type { DocSyncConfigService, LinkRow } from '../../../../src/nest/doc-sync/doc-sync-config.service';
|
||||
import type { DocSyncService } from '../../../../src/nest/doc-sync/doc-sync.service';
|
||||
import type { AddonsService } from '../../../../src/nest/addons/addons.service';
|
||||
import type { FilesService } from '../../../../src/nest/files/files.service';
|
||||
import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';
|
||||
import type { McpContext, McpTextResult, ToolOptions } from '../../../../src/nest-mcp';
|
||||
|
||||
const ctx = { userId: 7, scopes: null, isStaticToken: false } as McpContext;
|
||||
|
||||
const link = (id: number, providerId = 'paperless'): LinkRow =>
|
||||
({ id, provider_id: providerId, trip_id: 3 } as LinkRow);
|
||||
|
||||
const RUN = { state: 'ok', pulled: 2, pushed: 1, conflicts: 0, missing: 0 };
|
||||
|
||||
interface Setup {
|
||||
/** `undefined` is what canAccessTrip answers for a trip the user cannot see. */
|
||||
access: boolean;
|
||||
links: LinkRow[];
|
||||
status: Record<string, unknown>;
|
||||
issues: Array<Record<string, unknown>>;
|
||||
addonOn: boolean;
|
||||
/** Bindings whose provider an admin has switched off. */
|
||||
off: number[];
|
||||
}
|
||||
|
||||
function makeMcp(over: Partial<Setup> = {}) {
|
||||
const setup: Setup = { access: true, links: [], status: {}, issues: [], addonOn: true, off: [], ...over };
|
||||
const files = { verifyTripAccess: vi.fn(() => (setup.access ? { id: 3, user_id: 7 } : undefined)) };
|
||||
const config = { listLinks: vi.fn(() => setup.links) };
|
||||
const sync = {
|
||||
status: vi.fn(() => setup.status),
|
||||
issues: vi.fn(() => setup.issues),
|
||||
syncLink: vi.fn(async () => RUN),
|
||||
retryShelvedItems: vi.fn(),
|
||||
isSwitchedOff: vi.fn((l: LinkRow) => setup.off.includes(l.id)),
|
||||
};
|
||||
const addons = { isAddonEnabled: vi.fn(() => setup.addonOn) };
|
||||
const mcp = new DocSyncMcp(
|
||||
config as unknown as DocSyncConfigService,
|
||||
sync as unknown as DocSyncService,
|
||||
files as unknown as FilesService,
|
||||
addons as unknown as AddonsService,
|
||||
);
|
||||
return { mcp, files, config, sync, addons };
|
||||
}
|
||||
|
||||
/** A success is one JSON text block and carries no error flag. */
|
||||
function payload(result: McpTextResult): Record<string, unknown> {
|
||||
expect(result.isError).toBeUndefined();
|
||||
return JSON.parse(result.content[0].text) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function refusal(result: McpTextResult): string {
|
||||
expect(result.isError).toBe(true);
|
||||
return result.content[0].text;
|
||||
}
|
||||
|
||||
function toolOptions(method: string): ToolOptions {
|
||||
const entry = getEntry(DocSyncMcp as unknown as ClassRef, method);
|
||||
if (!entry || entry.kind !== 'tool') throw new Error(`${method} is not a registered MCP tool`);
|
||||
return entry.options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read off the prototype rather than listed here, so a fourth tool fails the
|
||||
* set assertion below instead of quietly slipping past a table this file keeps.
|
||||
*/
|
||||
function registeredMethods(): string[] {
|
||||
return Object.getOwnPropertyNames(DocSyncMcp.prototype)
|
||||
.filter((name) => getEntry(DocSyncMcp as unknown as ClassRef, name) !== undefined)
|
||||
.sort();
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('DocSyncMcp surface', () => {
|
||||
it('offers three tools, none of which can create or change a connection', () => {
|
||||
expect(registeredMethods()).toEqual(['getTripDocumentSync', 'listIssues', 'syncNow']);
|
||||
expect(registeredMethods().map((m) => toolOptions(m).name).sort()).toEqual([
|
||||
'get_trip_document_sync',
|
||||
'list_trip_document_sync_issues',
|
||||
'sync_trip_documents',
|
||||
]);
|
||||
});
|
||||
|
||||
it('asks for nothing but a trip id and a full-run flag', () => {
|
||||
// The other half of the same decision: a credential surface could arrive
|
||||
// bolted onto an existing schema rather than as a tool of its own.
|
||||
const fields = registeredMethods().flatMap((m) => Object.keys(toolOptions(m).inputSchema as ZodRawShape));
|
||||
expect([...new Set(fields)].sort()).toEqual(['full', 'tripId']);
|
||||
});
|
||||
|
||||
it.each(registeredMethods())('%s disappears while the documents addon is off', (method) => {
|
||||
const { mcp, addons } = makeMcp({ addonOn: false });
|
||||
const { when } = toolOptions(method);
|
||||
expect(typeof when).toBe('function');
|
||||
expect(when?.(ctx, mcp)).toBe(false);
|
||||
expect(addons.isAddonEnabled).toHaveBeenCalledWith(ADDON_IDS.DOCUMENTS);
|
||||
|
||||
addons.isAddonEnabled.mockReturnValue(true);
|
||||
expect(when?.(ctx, mcp)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['getTripDocumentSync', 'read'],
|
||||
['listIssues', 'read'],
|
||||
['syncNow', 'write'],
|
||||
])('%s claims files:%s, so a read-scoped token cannot move files', (method, mode) => {
|
||||
expect(toolOptions(method).access).toEqual({ group: 'files', mode });
|
||||
});
|
||||
|
||||
it('advertises the run as a write even though it creates nothing itself', () => {
|
||||
// It moves bytes in both directions, and a host that trusts readOnlyHint
|
||||
// would otherwise call it unattended.
|
||||
expect(toolOptions('syncNow').annotations).toMatchObject({ readOnlyHint: false, destructiveHint: false });
|
||||
expect(toolOptions('getTripDocumentSync').annotations).toMatchObject({ readOnlyHint: true });
|
||||
expect(toolOptions('listIssues').annotations).toMatchObject({ readOnlyHint: true });
|
||||
});
|
||||
|
||||
it('refuses a trip id that is not a positive integer before a handler sees it', () => {
|
||||
const schema = z.object(toolOptions('getTripDocumentSync').inputSchema as ZodRawShape);
|
||||
expect(schema.safeParse({ tripId: 3 }).success).toBe(true);
|
||||
expect(schema.safeParse({ tripId: 0 }).success).toBe(false);
|
||||
expect(schema.safeParse({ tripId: -1 }).success).toBe(false);
|
||||
expect(schema.safeParse({ tripId: 1.5 }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DocSyncMcp access', () => {
|
||||
it.each([
|
||||
['get_trip_document_sync', (m: DocSyncMcp) => m.getTripDocumentSync({ tripId: 3 }, ctx)],
|
||||
['list_trip_document_sync_issues', (m: DocSyncMcp) => m.listIssues({ tripId: 3 }, ctx)],
|
||||
['sync_trip_documents', (m: DocSyncMcp) => m.syncNow({ tripId: 3 }, ctx)],
|
||||
])('%s tells a user who cannot see the trip nothing beyond that', async (_name, call) => {
|
||||
const { mcp, files } = makeMcp({ access: false, links: [link(1)] });
|
||||
const result = await call(mcp);
|
||||
expect(refusal(result as McpTextResult)).toBe('Trip not found or access denied.');
|
||||
expect(files.verifyTripAccess).toHaveBeenCalledWith(3, ctx.userId);
|
||||
});
|
||||
|
||||
it('does not reach the sync service at all for a trip the user cannot see', async () => {
|
||||
const { mcp, sync, config } = makeMcp({ access: false, links: [link(1)] });
|
||||
await mcp.syncNow({ tripId: 3 }, ctx);
|
||||
mcp.listIssues({ tripId: 3 }, ctx);
|
||||
mcp.getTripDocumentSync({ tripId: 3 }, ctx);
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
expect(sync.status).not.toHaveBeenCalled();
|
||||
expect(sync.issues).not.toHaveBeenCalled();
|
||||
expect(config.listLinks).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('get_trip_document_sync', () => {
|
||||
it('hands back the trip status as the service reports it', () => {
|
||||
const status = { links: [{ id: 1, remoteLabel: 'Japan 2026' }], items: { synced: 4, conflict: 1 } };
|
||||
const { mcp, sync } = makeMcp({ status });
|
||||
expect(payload(mcp.getTripDocumentSync({ tripId: 3 }, ctx))).toEqual(status);
|
||||
expect(sync.status).toHaveBeenCalledWith(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('list_trip_document_sync_issues', () => {
|
||||
it('says the trip is not configured rather than answering with an empty list', () => {
|
||||
// An empty list and no connection at all read identically to an assistant,
|
||||
// and "everything is in step" is the wrong answer to give about documents
|
||||
// that were never being synced.
|
||||
const { mcp, sync } = makeMcp({ links: [] });
|
||||
expect(payload(mcp.listIssues({ tripId: 3 }, ctx))).toEqual({ configured: false, issues: [] });
|
||||
expect(sync.issues).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports an empty list for a configured trip with nothing to decide', () => {
|
||||
const { mcp } = makeMcp({ links: [link(1)], issues: [] });
|
||||
expect(payload(mcp.listIssues({ tripId: 3 }, ctx))).toEqual({ configured: true, issues: [] });
|
||||
});
|
||||
|
||||
it('passes the open issues through for a configured trip', () => {
|
||||
const issues = [{ id: 9, state: 'conflict', remote_name: 'boarding.pdf' }];
|
||||
const { mcp, sync } = makeMcp({ links: [link(1)], issues });
|
||||
expect(payload(mcp.listIssues({ tripId: 3 }, ctx))).toEqual({ configured: true, issues });
|
||||
expect(sync.issues).toHaveBeenCalledWith(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sync_trip_documents', () => {
|
||||
it('refuses an unconnected trip with the step that would fix it', async () => {
|
||||
const { mcp, sync } = makeMcp({ links: [] });
|
||||
const text = refusal(await mcp.syncNow({ tripId: 3 }, ctx));
|
||||
expect(text).toContain('not connected to a document store');
|
||||
expect(text).toContain('file manager');
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs every binding of the trip and reports each one separately', async () => {
|
||||
// A trip can be bound to more than one store, and collapsing the runs into
|
||||
// one total would hide which of them failed.
|
||||
const links = [link(1, 'paperless'), link(2, 'nextcloud')];
|
||||
const { mcp, sync } = makeMcp({ links });
|
||||
const body = payload(await mcp.syncNow({ tripId: 3 }, ctx));
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(2);
|
||||
expect(body.runs).toEqual([
|
||||
{ linkId: 1, provider: 'paperless', ...RUN },
|
||||
{ linkId: 2, provider: 'nextcloud', ...RUN },
|
||||
]);
|
||||
});
|
||||
|
||||
it('un-shelves the documents that gave up before running, as the REST route does', async () => {
|
||||
// "Run it now" means "try again", including the items parked after too many
|
||||
// failures. A tool that skipped this reported "in sync" while leaving them
|
||||
// parked, and the only way out was the button in the web UI.
|
||||
const links = [link(1, 'paperless'), link(2, 'nextcloud')];
|
||||
const { mcp, sync } = makeMcp({ links });
|
||||
await mcp.syncNow({ tripId: 3 }, ctx);
|
||||
expect(sync.retryShelvedItems.mock.calls).toEqual([[1], [2]]);
|
||||
});
|
||||
|
||||
it('refuses with the same code as the REST route when every binding is switched off', async () => {
|
||||
const { mcp, sync } = makeMcp({ links: [link(1)], off: [1] });
|
||||
const text = refusal(await mcp.syncNow({ tripId: 3 }, ctx));
|
||||
expect(text.startsWith('provider_disabled:')).toBe(true);
|
||||
expect(text).toContain('switched back on');
|
||||
// Nothing un-shelved, nothing run: the binding resumes as it was left.
|
||||
expect(sync.retryShelvedItems).not.toHaveBeenCalled();
|
||||
expect(sync.syncLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs the bindings that are on and reports the switched-off one by its code', async () => {
|
||||
const links = [link(1, 'paperless'), link(2, 'nextcloud')];
|
||||
const { mcp, sync } = makeMcp({ links, off: [1] });
|
||||
const body = payload(await mcp.syncNow({ tripId: 3 }, ctx));
|
||||
expect(body.runs).toEqual([
|
||||
{ linkId: 1, provider: 'paperless', state: 'disabled', errorCode: 'provider_disabled' },
|
||||
{ linkId: 2, provider: 'nextcloud', ...RUN },
|
||||
]);
|
||||
expect(sync.retryShelvedItems.mock.calls).toEqual([[2]]);
|
||||
expect(sync.syncLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('asks for the cheap incremental run unless the caller says otherwise', async () => {
|
||||
const { mcp, sync } = makeMcp({ links: [link(1)] });
|
||||
await mcp.syncNow({ tripId: 3 }, ctx);
|
||||
expect(sync.syncLink).toHaveBeenCalledWith(link(1), { full: false });
|
||||
|
||||
await mcp.syncNow({ tripId: 3, full: true }, ctx);
|
||||
expect(sync.syncLink).toHaveBeenLastCalledWith(link(1), { full: true });
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,939 @@
|
||||
/**
|
||||
* The Paperless-ngx adapter: PAPERLESS-001..095.
|
||||
*
|
||||
* Two things are pinned here. What the client puts on the wire: the pinned API
|
||||
* version (an unpinned Accept header is how the `checksum` field silently moved
|
||||
* out of the document serializer between two `docker pull`s), the token header,
|
||||
* the `original=true` on every download, and the one JSON object the custom
|
||||
* fields have to arrive in. And what the adapter makes of the answers: the
|
||||
* error code for each way a self-hosted instance disappoints, the newest
|
||||
* revision's hash rather than the root one, and the document id surviving a
|
||||
* replace although the consume task names a different one.
|
||||
*
|
||||
* `safeFetch` and the capped readers are mocked: the SSRF guard does a real DNS
|
||||
* lookup and the reader wants a real stream. The readCappedJson stub still
|
||||
* parses the bytes it is handed, so "Paperless answered an HTML login page"
|
||||
* stays a genuine parse failure instead of a mock returning undefined on
|
||||
* command. The behaviour asserted here was measured against a live
|
||||
* Paperless-ngx 3.1.3 first; see BEFUND-paperless.md in the test lab.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { Readable } from 'node:stream';
|
||||
|
||||
const {
|
||||
safeFetchMock,
|
||||
readCappedJsonMock,
|
||||
readCappedTextMock,
|
||||
discardBodyMock,
|
||||
FakeSsrfBlockedError,
|
||||
} = vi.hoisted(() => {
|
||||
// Declared inside the hoisted block: a class at module level is not hoisted
|
||||
// with the vi.mock factory and would be read before it exists.
|
||||
class FakeSsrfBlockedError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'SsrfBlockedError';
|
||||
}
|
||||
}
|
||||
return {
|
||||
safeFetchMock: vi.fn(),
|
||||
readCappedJsonMock: vi.fn(),
|
||||
readCappedTextMock: vi.fn(),
|
||||
discardBodyMock: vi.fn(),
|
||||
FakeSsrfBlockedError,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../../../src/utils/ssrfGuard', () => ({
|
||||
safeFetch: safeFetchMock,
|
||||
SsrfBlockedError: FakeSsrfBlockedError,
|
||||
}));
|
||||
vi.mock('../../../../src/utils/cappedFetch', () => ({
|
||||
readCappedJson: readCappedJsonMock,
|
||||
readCappedText: readCappedTextMock,
|
||||
discardBody: discardBodyMock,
|
||||
}));
|
||||
|
||||
import {
|
||||
PaperlessClient,
|
||||
PaperlessError,
|
||||
apiBase,
|
||||
buildMultipart,
|
||||
currentVersion,
|
||||
sha256OrNull,
|
||||
DOCUMENT_PAGE_SIZE,
|
||||
} from '../../../../src/nest/doc-sync/providers/paperless.client';
|
||||
import {
|
||||
PaperlessDocumentProvider,
|
||||
PAPERLESS_WEBHOOK_SECRET_HEADER,
|
||||
TRIP_UID_FIELD_NAME,
|
||||
documentFileName,
|
||||
normalizeMime,
|
||||
parseScopeKey,
|
||||
titleFromFileName,
|
||||
} from '../../../../src/nest/doc-sync/providers/paperless.provider';
|
||||
import { PROVIDER_MAX_PAGES } from '../../../../src/nest/doc-sync/doc-sync.constants';
|
||||
import type {
|
||||
DocResult,
|
||||
DocumentConnectionRef,
|
||||
DocumentScopeRef,
|
||||
PushRequest,
|
||||
} from '../../../../src/nest/doc-sync/document-provider';
|
||||
import { docFailed } from '../../../../src/nest/doc-sync/document-provider';
|
||||
|
||||
const TOKEN = 'ba17f0c4d2e94f118a6c0d3b7e5a9c21f4d6b8e0';
|
||||
const BASE = 'https://papers.example.org';
|
||||
|
||||
const CONN: DocumentConnectionRef = {
|
||||
connectionId: 4,
|
||||
createdAt: '2026-09-01 08:00:00',
|
||||
ownerId: 9,
|
||||
baseUrl: BASE,
|
||||
secrets: { api_token: TOKEN },
|
||||
settings: {},
|
||||
allowInsecureTls: false,
|
||||
};
|
||||
|
||||
const SCOPE: DocumentScopeRef = {
|
||||
linkId: 7,
|
||||
tripId: 42,
|
||||
scopeKey: 'tag:3',
|
||||
remoteRootId: '3',
|
||||
remoteRootPath: '/documents?tags__id__all=3',
|
||||
cursor: null,
|
||||
};
|
||||
|
||||
const HASH_A = 'a'.repeat(64);
|
||||
const HASH_B = 'b'.repeat(64);
|
||||
|
||||
interface Reply {
|
||||
ok: boolean;
|
||||
status: number;
|
||||
headers: Headers;
|
||||
body: ReadableStream<Uint8Array> | null;
|
||||
text(): Promise<string>;
|
||||
}
|
||||
|
||||
interface Recorded {
|
||||
url: URL;
|
||||
init: RequestInit;
|
||||
options?: { rejectUnauthorized?: boolean };
|
||||
body: string;
|
||||
}
|
||||
|
||||
let calls: Recorded[] = [];
|
||||
let routes: Map<string, Reply[]>;
|
||||
|
||||
function reply(body: unknown, status = 200, headers: Record<string, string> = {}): Reply {
|
||||
const raw = typeof body === 'string' ? body : JSON.stringify(body);
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
headers: new Headers(headers),
|
||||
body: null,
|
||||
text: async () => raw,
|
||||
};
|
||||
}
|
||||
|
||||
/** A streaming answer, for the download path. */
|
||||
function streamReply(bytes: string, headers: Record<string, string> = {}): Reply {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: new Headers(headers),
|
||||
body: new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(bytes));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
text: async () => bytes,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Stub one route. Several replies are consumed in order and the last one
|
||||
* repeats, which is what the pagination cases want.
|
||||
*/
|
||||
function on(route: string, ...replies: Reply[]): void {
|
||||
routes.set(route, replies);
|
||||
}
|
||||
|
||||
function requests(route: string): Recorded[] {
|
||||
return calls.filter((call) => `${(call.init.method ?? 'GET').toUpperCase()} ${call.url.pathname}` === route);
|
||||
}
|
||||
|
||||
function lastRequest(route: string): Recorded {
|
||||
const matching = requests(route);
|
||||
const last = matching[matching.length - 1];
|
||||
if (last === undefined) throw new Error(`no request was made to ${route}`);
|
||||
return last;
|
||||
}
|
||||
|
||||
function headerOf(call: Recorded, name: string): string | undefined {
|
||||
const headers = call.init.headers as Record<string, string> | undefined;
|
||||
return headers?.[name];
|
||||
}
|
||||
|
||||
function tagRow(id: number, name: string, documentCount = 0): unknown {
|
||||
return { id, name, slug: name, color: '#a6cee3', document_count: documentCount, owner: 2 };
|
||||
}
|
||||
|
||||
function docRow(over: Record<string, unknown> = {}): unknown {
|
||||
return {
|
||||
id: 11,
|
||||
title: 'Hotelrechnung Kyoto',
|
||||
tags: [3],
|
||||
mime_type: 'application/pdf',
|
||||
original_file_name: 'rechnung.pdf',
|
||||
modified: '2026-09-18T17:30:00.000000+02:00',
|
||||
added: '2026-09-18T17:29:00.000000+02:00',
|
||||
deleted_at: null,
|
||||
custom_fields: [{ field: 1, value: 'trip-uid-42' }],
|
||||
versions: [{ id: 11, checksum: HASH_A, added: '2026-09-18T15:29:00.000000Z', is_root: true }],
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function page(results: unknown[], next: string | null = null, count?: number): unknown {
|
||||
return { count: count ?? results.length, next, previous: null, results };
|
||||
}
|
||||
|
||||
function taskRow(over: Record<string, unknown> = {}): unknown {
|
||||
return {
|
||||
id: 3,
|
||||
task_id: 'task-uuid-1',
|
||||
status: 'success',
|
||||
result_data: { document_id: 11 },
|
||||
related_document_ids: [11],
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function pushRequest(over: Partial<PushRequest> = {}): PushRequest {
|
||||
const bytes = Buffer.from('%PDF-1.4 hotel\n');
|
||||
return {
|
||||
body: Readable.from(bytes),
|
||||
fileName: 'rechnung.pdf',
|
||||
mimeType: 'application/pdf',
|
||||
size: bytes.length,
|
||||
sha256: HASH_A,
|
||||
mtimeSeconds: 1_789_000_000,
|
||||
trekDocUid: 'doc-uid-1',
|
||||
trekTripUid: 'trip-uid-42',
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
// `!result.success` does not narrow: the server workspace compiles with
|
||||
// `strict: false`, so a boolean discriminant stops discriminating. docFailed is
|
||||
// the predicate the production code uses for the same reason.
|
||||
function expectFail(result: DocResult<unknown>): { code: string; detail?: string; status?: number } {
|
||||
if (!docFailed(result)) throw new Error('expected a failure, got success');
|
||||
return result.error;
|
||||
}
|
||||
|
||||
function expectOk<T>(result: DocResult<T>): T {
|
||||
if (docFailed(result)) {
|
||||
throw new Error(`expected success, got ${result.error.code}: ${result.error.detail ?? ''}`);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
let client: PaperlessClient;
|
||||
let provider: PaperlessDocumentProvider;
|
||||
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
routes = new Map();
|
||||
client = new PaperlessClient();
|
||||
provider = new PaperlessDocumentProvider(client);
|
||||
|
||||
safeFetchMock.mockReset();
|
||||
readCappedJsonMock.mockReset();
|
||||
readCappedTextMock.mockReset();
|
||||
discardBodyMock.mockReset();
|
||||
|
||||
readCappedJsonMock.mockImplementation(async (res: { text(): Promise<string> }) => {
|
||||
const text = await res.text();
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
readCappedTextMock.mockImplementation(async (res: { text(): Promise<string> }) => ({
|
||||
text: await res.text(),
|
||||
truncated: false,
|
||||
}));
|
||||
|
||||
safeFetchMock.mockImplementation(
|
||||
async (url: string, init: RequestInit, options?: { rejectUnauthorized?: boolean }) => {
|
||||
const parsed = new URL(url);
|
||||
const method = (init.method ?? 'GET').toUpperCase();
|
||||
const body = typeof init.body === 'string'
|
||||
? init.body
|
||||
: Buffer.isBuffer(init.body)
|
||||
? init.body.toString('latin1')
|
||||
: '';
|
||||
calls.push({ url: parsed, init, options, body });
|
||||
const queue = routes.get(`${method} ${parsed.pathname}`);
|
||||
if (queue === undefined || queue.length === 0) {
|
||||
throw new Error(`no stubbed reply for ${method} ${parsed.pathname}`);
|
||||
}
|
||||
return (queue.length > 1 ? queue.shift() : queue[0]) as unknown as Response;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('PaperlessClient: the request it builds', () => {
|
||||
it('PAPERLESS-001: appends /api to whatever the operator pasted', () => {
|
||||
expect(apiBase(BASE)).toBe(`${BASE}/api`);
|
||||
expect(apiBase(`${BASE}/`)).toBe(`${BASE}/api`);
|
||||
expect(apiBase(`${BASE}/api`)).toBe(`${BASE}/api`);
|
||||
expect(apiBase(`${BASE}/api/`)).toBe(`${BASE}/api`);
|
||||
expect(apiBase(' https://home.example.org/paperless/ ')).toBe('https://home.example.org/paperless/api');
|
||||
expect(apiBase('http://192.168.178.9:8000')).toBe('http://192.168.178.9:8000/api');
|
||||
});
|
||||
|
||||
it('PAPERLESS-002: sends the token as a Token header and pins the API version', async () => {
|
||||
on('GET /api/ui_settings/', reply({ user: { username: 'admin' }, settings: {}, permissions: [] }));
|
||||
await provider.probe(CONN);
|
||||
const call = lastRequest('GET /api/ui_settings/');
|
||||
expect(headerOf(call, 'Authorization')).toBe(`Token ${TOKEN}`);
|
||||
expect(headerOf(call, 'Accept')).toBe('application/json; version=10');
|
||||
});
|
||||
|
||||
it('PAPERLESS-003: never puts the token in the query string', async () => {
|
||||
on('GET /api/ui_settings/', reply({ user: { username: 'admin' }, settings: {}, permissions: [] }));
|
||||
on('GET /api/tags/', reply(page([tagRow(3, 'japan')])));
|
||||
on('GET /api/documents/', reply(page([docRow()])));
|
||||
await provider.probe(CONN);
|
||||
await provider.listScopes(CONN);
|
||||
await provider.list(CONN, SCOPE);
|
||||
expect(calls.length).toBeGreaterThanOrEqual(3);
|
||||
for (const call of calls) {
|
||||
expect(call.url.search).not.toContain(TOKEN);
|
||||
expect(call.url.search).not.toMatch(/token|api_key/i);
|
||||
}
|
||||
});
|
||||
|
||||
it('PAPERLESS-004: maps allowInsecureTls onto rejectUnauthorized and bounds the call', async () => {
|
||||
on('GET /api/ui_settings/', reply({ user: { username: 'admin' }, settings: {}, permissions: [] }));
|
||||
await provider.probe(CONN);
|
||||
await provider.probe({ ...CONN, allowInsecureTls: true });
|
||||
expect(calls[0]?.options).toEqual({ rejectUnauthorized: true });
|
||||
expect(calls[1]?.options).toEqual({ rejectUnauthorized: false });
|
||||
expect(calls[0]?.init.signal).toBeInstanceOf(AbortSignal);
|
||||
});
|
||||
|
||||
it('PAPERLESS-005: reads the profile that does not echo the token back', async () => {
|
||||
on('GET /api/ui_settings/', reply({
|
||||
user: { username: 'admin' },
|
||||
settings: { version: '3.1.3' },
|
||||
permissions: ['add_workflow', 'add_document'],
|
||||
}));
|
||||
const probed = expectOk(await provider.probe(CONN));
|
||||
expect(probed.account).toBe('admin');
|
||||
expect(requests('GET /api/profile/')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PaperlessProvider: probing a connection', () => {
|
||||
it('PAPERLESS-010: reports the self-registering webhook when the token may create workflows', async () => {
|
||||
on('GET /api/ui_settings/', reply({
|
||||
user: { username: 'admin' },
|
||||
settings: { version: '3.1.3' },
|
||||
permissions: ['add_workflow'],
|
||||
}));
|
||||
const probed = expectOk(await provider.probe(CONN));
|
||||
expect(probed.capabilities.push).toBe('webhook-self-registered');
|
||||
expect(probed.capabilities.stableId).toBe(true);
|
||||
expect(probed.capabilities.contentHashInListing).toBe(true);
|
||||
expect(probed.capabilities.replaceInPlace).toBe(true);
|
||||
expect(probed.capabilities.remoteTrash).toBe(true);
|
||||
});
|
||||
|
||||
it('PAPERLESS-011: downgrades to a manual webhook when the token may not create one', async () => {
|
||||
on('GET /api/ui_settings/', reply({
|
||||
user: { username: 'reisender' },
|
||||
settings: { version: '3.1.3' },
|
||||
permissions: ['view_document', 'add_document'],
|
||||
}));
|
||||
const probed = expectOk(await provider.probe(CONN));
|
||||
expect(probed.capabilities.push).toBe('webhook-manual');
|
||||
// The capability the CORE reads stays the provider's own answer; only the
|
||||
// probe reflects this token's narrower rights.
|
||||
expect(provider.capabilities(CONN).push).toBe('webhook-self-registered');
|
||||
});
|
||||
|
||||
it('PAPERLESS-012: a wrong token is unauthorized, a forbidden one is forbidden', async () => {
|
||||
on('GET /api/ui_settings/', reply({ detail: 'Invalid token.' }, 401));
|
||||
expect(expectFail(await provider.probe(CONN)).code).toBe('unauthorized');
|
||||
on('GET /api/ui_settings/', reply({ detail: 'no' }, 403));
|
||||
expect(expectFail(await provider.probe(CONN)).code).toBe('forbidden');
|
||||
});
|
||||
|
||||
it('PAPERLESS-013: an HTML login page is a provider error, not a crash', async () => {
|
||||
on('GET /api/ui_settings/', reply('<!doctype html><title>Sign in</title>'));
|
||||
const error = expectFail(await provider.probe(CONN));
|
||||
expect(error.code).toBe('provider_error');
|
||||
expect(error.detail).toContain('Paperless itself');
|
||||
});
|
||||
|
||||
it('PAPERLESS-014: a connection without a token never reaches the network', async () => {
|
||||
const error = expectFail(await provider.probe({ ...CONN, secrets: {} }));
|
||||
expect(error.code).toBe('unauthorized');
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('PAPERLESS-015: the SSRF guard, a timeout and a self-signed certificate each get their own code', async () => {
|
||||
safeFetchMock.mockImplementationOnce(async () => {
|
||||
throw new FakeSsrfBlockedError('Requests to loopback and link-local addresses are not allowed');
|
||||
});
|
||||
expect(expectFail(await provider.probe(CONN)).code).toBe('ssrf_blocked');
|
||||
|
||||
safeFetchMock.mockImplementationOnce(async () => {
|
||||
const err = new Error('The operation was aborted due to timeout');
|
||||
err.name = 'TimeoutError';
|
||||
throw err;
|
||||
});
|
||||
expect(expectFail(await provider.probe(CONN)).code).toBe('timeout');
|
||||
|
||||
safeFetchMock.mockImplementationOnce(async () => {
|
||||
const cause = Object.assign(new Error('self-signed certificate'), {
|
||||
code: 'DEPTH_ZERO_SELF_SIGNED_CERT',
|
||||
});
|
||||
throw Object.assign(new TypeError('fetch failed'), { cause });
|
||||
});
|
||||
expect(expectFail(await provider.probe(CONN)).code).toBe('tls_untrusted');
|
||||
|
||||
safeFetchMock.mockImplementationOnce(async () => {
|
||||
throw Object.assign(new TypeError('fetch failed'), {
|
||||
cause: Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' }),
|
||||
});
|
||||
});
|
||||
expect(expectFail(await provider.probe(CONN)).code).toBe('unreachable');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PaperlessProvider: scopes are tags', () => {
|
||||
it('PAPERLESS-020: a tag becomes a scope key, a label and the instance filter URL', async () => {
|
||||
on('GET /api/tags/', reply(page([tagRow(3, 'japan-2026', 4), tagRow(9, 'privat')])));
|
||||
const options = expectOk(await provider.listScopes(CONN));
|
||||
expect(options).toEqual([
|
||||
{ scopeKey: 'tag:3', label: 'japan-2026', remoteRootId: '3', remoteRootPath: '/documents?tags__id__all=3' },
|
||||
{ scopeKey: 'tag:9', label: 'privat', remoteRootId: '9', remoteRootPath: '/documents?tags__id__all=9' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('PAPERLESS-021: follows the pages of a long tag list', async () => {
|
||||
on(
|
||||
'GET /api/tags/',
|
||||
reply(page([tagRow(1, 'a')], 'https://papers.example.org/api/tags/?page=2', 2)),
|
||||
reply(page([tagRow(2, 'b')], null, 2)),
|
||||
);
|
||||
const options = expectOk(await provider.listScopes(CONN));
|
||||
expect(options.map((option) => option.scopeKey)).toEqual(['tag:1', 'tag:2']);
|
||||
expect(requests('GET /api/tags/')).toHaveLength(2);
|
||||
expect(requests('GET /api/tags/')[1]?.url.searchParams.get('page')).toBe('2');
|
||||
});
|
||||
|
||||
it('PAPERLESS-022: a search narrows server-side, an empty one is not sent at all', async () => {
|
||||
on('GET /api/tags/', reply(page([tagRow(3, 'japan-2026')])));
|
||||
await provider.listScopes(CONN, ' japan ');
|
||||
await provider.listScopes(CONN, ' ');
|
||||
expect(requests('GET /api/tags/')[0]?.url.searchParams.get('name__icontains')).toBe('japan');
|
||||
expect(requests('GET /api/tags/')[1]?.url.searchParams.has('name__icontains')).toBe(false);
|
||||
});
|
||||
|
||||
it('PAPERLESS-023: creating a tag that exists is a conflict, never a silent adoption', async () => {
|
||||
on('POST /api/tags/', reply({ error: 'Object violates owner / name unique constraint' }, 400));
|
||||
expect(expectFail(await provider.createScope(CONN, 'japan-2026')).code).toBe('conflict');
|
||||
});
|
||||
|
||||
it('PAPERLESS-024: a tag that is gone is scope_missing, not a bare 404', async () => {
|
||||
on('GET /api/tags/3/', reply({ detail: 'No Tag matches the given query.' }, 404));
|
||||
const error = expectFail(await provider.resolveScope(CONN, SCOPE));
|
||||
expect(error.code).toBe('scope_missing');
|
||||
expect(error.status).toBe(404);
|
||||
});
|
||||
|
||||
it('PAPERLESS-025: another provider’s scope key is refused before any request', async () => {
|
||||
for (const scopeKey of ['path:/trek', 'tag:', 'tag:abc', 'tag:-1', 'fileid:437']) {
|
||||
const error = expectFail(await provider.resolveScope(CONN, { ...SCOPE, scopeKey }));
|
||||
expect(error.code).toBe('scope_missing');
|
||||
}
|
||||
expect(calls).toHaveLength(0);
|
||||
expect(parseScopeKey('tag:12')).toBe(12);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PaperlessProvider: listing a scope', () => {
|
||||
it('PAPERLESS-030: maps a document onto the core’s shape', async () => {
|
||||
on('GET /api/documents/', reply(page([docRow()])));
|
||||
const listed = expectOk(await provider.list(CONN, SCOPE));
|
||||
expect(listed.documents).toEqual([
|
||||
{
|
||||
remoteId: '11',
|
||||
name: 'Hotelrechnung Kyoto.pdf',
|
||||
size: null,
|
||||
mimeType: 'application/pdf',
|
||||
remoteVersion: '2026-09-18T17:30:00.000000+02:00',
|
||||
contentHash: HASH_A,
|
||||
remoteModifiedAt: '2026-09-18T17:30:00.000000+02:00',
|
||||
isDeleted: false,
|
||||
},
|
||||
]);
|
||||
const call = lastRequest('GET /api/documents/');
|
||||
expect(call.url.searchParams.get('tags__id__all')).toBe('3');
|
||||
expect(call.url.searchParams.get('ordering')).toBe('id');
|
||||
expect(call.url.searchParams.get('page_size')).toBe(String(DOCUMENT_PAGE_SIZE));
|
||||
});
|
||||
|
||||
it('PAPERLESS-031: a checksum that is not sha256 is reported as no hash at all', async () => {
|
||||
on('GET /api/documents/', reply(page([
|
||||
docRow({ versions: [{ id: 1, checksum: 'a91fe3f8e2cf4b2b5560b2222d65d60c', added: null, is_root: true }] }),
|
||||
])));
|
||||
const listed = expectOk(await provider.list(CONN, SCOPE));
|
||||
expect(listed.documents[0]?.contentHash).toBeNull();
|
||||
expect(sha256OrNull('A'.repeat(64))).toBe('a'.repeat(64));
|
||||
expect(sha256OrNull('zz')).toBeNull();
|
||||
});
|
||||
|
||||
it('PAPERLESS-032: after a replace the hash is the newest revision, not the root one', async () => {
|
||||
on('GET /api/documents/', reply(page([
|
||||
docRow({
|
||||
versions: [
|
||||
{ id: 12, checksum: HASH_B, added: '2026-09-18T15:40:00.000000Z', is_root: false },
|
||||
{ id: 11, checksum: HASH_A, added: '2026-09-18T15:29:00.000000Z', is_root: true },
|
||||
],
|
||||
}),
|
||||
])));
|
||||
const listed = expectOk(await provider.list(CONN, SCOPE));
|
||||
expect(listed.documents[0]?.contentHash).toBe(HASH_B);
|
||||
// Independent of the order the instance happens to send them in.
|
||||
expect(currentVersion({
|
||||
id: 1,
|
||||
title: '',
|
||||
originalFileName: null,
|
||||
mimeType: null,
|
||||
modified: null,
|
||||
added: null,
|
||||
deletedAt: null,
|
||||
tagIds: [],
|
||||
versions: [
|
||||
{ id: 11, checksum: HASH_A, added: '2026-09-18T15:29:00.000000Z', isRoot: true },
|
||||
{ id: 12, checksum: HASH_B, added: '2026-09-18T15:40:00.000000Z', isRoot: false },
|
||||
],
|
||||
})?.checksum).toBe(HASH_B);
|
||||
});
|
||||
|
||||
it('PAPERLESS-033: a listing that hits the page cap says so and claims nothing about the cursor', async () => {
|
||||
const endless = reply(page([docRow()], 'https://papers.example.org/api/documents/?page=2', 9999));
|
||||
on('GET /api/documents/', endless);
|
||||
const listed = expectOk(await provider.list(CONN, { ...SCOPE, cursor: 'v1:9999:x' }));
|
||||
expect(listed.truncated).toBe(true);
|
||||
expect(listed.cursorUnchanged).toBe(false);
|
||||
expect(requests('GET /api/documents/')).toHaveLength(PROVIDER_MAX_PAGES);
|
||||
});
|
||||
|
||||
it('PAPERLESS-034: an unchanged scope is recognised, a changed one is not', async () => {
|
||||
on('GET /api/documents/', reply(page([docRow()])));
|
||||
const first = expectOk(await provider.list(CONN, SCOPE));
|
||||
expect(first.cursorUnchanged).toBe(false);
|
||||
const second = expectOk(await provider.list(CONN, { ...SCOPE, cursor: first.cursor }));
|
||||
expect(second.cursorUnchanged).toBe(true);
|
||||
|
||||
// A document leaving the tag moves no timestamp: only the count notices.
|
||||
on('GET /api/documents/', reply(page([], null, 0)));
|
||||
const third = expectOk(await provider.list(CONN, { ...SCOPE, cursor: first.cursor }));
|
||||
expect(third.cursorUnchanged).toBe(false);
|
||||
expect(third.documents).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('PAPERLESS-035: a document without a title still gets a usable name', async () => {
|
||||
on('GET /api/documents/', reply(page([
|
||||
docRow({ id: 5, title: '', original_file_name: 'scan_2026.PDF' }),
|
||||
docRow({ id: 6, title: '', original_file_name: null, mime_type: 'image/png' }),
|
||||
docRow({ id: 7, title: 'Bordkarte.pdf', original_file_name: 'bordkarte.pdf' }),
|
||||
])));
|
||||
const listed = expectOk(await provider.list(CONN, SCOPE));
|
||||
expect(listed.documents.map((doc) => doc.name)).toEqual([
|
||||
'scan_2026.PDF',
|
||||
'document-6.png',
|
||||
// An extension the title already carries is not doubled.
|
||||
'Bordkarte.pdf',
|
||||
]);
|
||||
expect(documentFileName({
|
||||
id: 8,
|
||||
title: 'Notiz',
|
||||
originalFileName: null,
|
||||
mimeType: 'text/plain',
|
||||
modified: null,
|
||||
added: null,
|
||||
deletedAt: null,
|
||||
tagIds: [],
|
||||
versions: [],
|
||||
})).toBe('Notiz.txt');
|
||||
});
|
||||
|
||||
it('PAPERLESS-036: an answer that is not a listing is a provider error', async () => {
|
||||
on('GET /api/documents/', reply({ unexpected: true }));
|
||||
expect(expectFail(await provider.list(CONN, SCOPE)).code).toBe('provider_error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PaperlessProvider: fetching bytes', () => {
|
||||
it('PAPERLESS-040: asks for the original file and hands back the stream with its version', async () => {
|
||||
on('GET /api/documents/11/', reply(docRow()));
|
||||
on('GET /api/documents/11/download/', streamReply('%PDF-1.4 hotel', {
|
||||
'content-length': '14',
|
||||
'content-type': 'application/pdf',
|
||||
}));
|
||||
const fetched = expectOk(await provider.fetch(CONN, SCOPE, '11'));
|
||||
expect(lastRequest('GET /api/documents/11/download/').url.searchParams.get('original')).toBe('true');
|
||||
expect(fetched.size).toBe(14);
|
||||
expect(fetched.mimeType).toBe('application/pdf');
|
||||
expect(fetched.remoteVersion).toBe('2026-09-18T17:30:00.000000+02:00');
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of fetched.body) chunks.push(Buffer.from(chunk));
|
||||
expect(Buffer.concat(chunks).toString()).toBe('%PDF-1.4 hotel');
|
||||
});
|
||||
|
||||
it('PAPERLESS-041: a missing content-length is an unknown size, never zero', async () => {
|
||||
on('GET /api/documents/11/', reply(docRow()));
|
||||
on('GET /api/documents/11/download/', streamReply('%PDF-1.4 hotel'));
|
||||
const fetched = expectOk(await provider.fetch(CONN, SCOPE, '11'));
|
||||
expect(fetched.size).toBeNull();
|
||||
});
|
||||
|
||||
it('PAPERLESS-042: a deleted document is not_found, and a nonsense id never leaves the process', async () => {
|
||||
on('GET /api/documents/11/', reply({ detail: 'No Document matches the given query.' }, 404));
|
||||
expect(expectFail(await provider.fetch(CONN, SCOPE, '11')).code).toBe('not_found');
|
||||
const before = calls.length;
|
||||
expect(expectFail(await provider.fetch(CONN, SCOPE, '../../etc/passwd')).code).toBe('not_found');
|
||||
expect(calls).toHaveLength(before);
|
||||
});
|
||||
|
||||
it('PAPERLESS-043: a download without a body is a provider error, not an empty file', async () => {
|
||||
on('GET /api/documents/11/', reply(docRow()));
|
||||
on('GET /api/documents/11/download/', reply(''));
|
||||
expect(expectFail(await provider.fetch(CONN, SCOPE, '11'))).toMatchObject({
|
||||
code: 'provider_error',
|
||||
detail: 'Paperless sent no body for the document',
|
||||
});
|
||||
});
|
||||
|
||||
it('PAPERLESS-044: a download announcing more than TREK transfers is refused before it is read', async () => {
|
||||
on('GET /api/documents/11/', reply(docRow()));
|
||||
on('GET /api/documents/11/download/', streamReply('%PDF', { 'content-length': String(3 * 1024 ** 3) }));
|
||||
expect(expectFail(await provider.fetch(CONN, SCOPE, '11'))).toMatchObject({
|
||||
code: 'too_large',
|
||||
detail: `content_length=${3 * 1024 ** 3}`,
|
||||
});
|
||||
expect(discardBodyMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PaperlessProvider: pushing bytes', () => {
|
||||
function stubSuccessfulCreate(): void {
|
||||
on('GET /api/custom_fields/', reply(page([{ id: 1, name: TRIP_UID_FIELD_NAME, data_type: 'string' }])));
|
||||
on('POST /api/documents/post_document/', reply('"task-uuid-1"'));
|
||||
on('GET /api/tasks/', reply(page([taskRow()])));
|
||||
on('GET /api/documents/11/', reply(docRow()));
|
||||
}
|
||||
|
||||
it('PAPERLESS-050: an unaccepted type is refused before a single byte is uploaded', async () => {
|
||||
const error = expectFail(await provider.push(CONN, SCOPE, pushRequest({
|
||||
fileName: 'tour.gpx',
|
||||
mimeType: 'application/gpx+xml',
|
||||
})));
|
||||
expect(error.code).toBe('unsupported_type');
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('PAPERLESS-050b: a stored Content-Type with parameters is still the type it names', async () => {
|
||||
on('GET /api/custom_fields/', reply(page([{ id: 1, name: TRIP_UID_FIELD_NAME, data_type: 'string' }])));
|
||||
on('POST /api/documents/post_document/', reply('"task-uuid-1"'));
|
||||
on('GET /api/tasks/', reply(page([taskRow()])));
|
||||
on('GET /api/documents/11/', reply(docRow({ mime_type: 'text/plain' })));
|
||||
expectOk(await provider.push(CONN, SCOPE, pushRequest({
|
||||
fileName: 'notiz.txt',
|
||||
mimeType: 'Text/Plain; charset=utf-8',
|
||||
})));
|
||||
expect(lastRequest('POST /api/documents/post_document/').body).toContain('Content-Type: text/plain\r\n');
|
||||
expect(normalizeMime('application/pdf')).toBe('application/pdf');
|
||||
});
|
||||
|
||||
it('PAPERLESS-051: an upload carries the tag, the title and the custom field in one request', async () => {
|
||||
stubSuccessfulCreate();
|
||||
const pushed = expectOk(await provider.push(CONN, SCOPE, pushRequest()));
|
||||
expect(pushed).toEqual({
|
||||
remoteId: '11',
|
||||
remoteVersion: '2026-09-18T17:30:00.000000+02:00',
|
||||
remoteModifiedAt: '2026-09-18T17:30:00.000000+02:00',
|
||||
// Paperless stores duplicate bytes twice, so nothing here may claim a
|
||||
// deduplication happened.
|
||||
deduplicated: false,
|
||||
});
|
||||
const upload = lastRequest('POST /api/documents/post_document/');
|
||||
expect(headerOf(upload, 'Content-Type')).toMatch(/^multipart\/form-data; boundary=/);
|
||||
// Content-Length is undici's business; setting it makes it refuse the call.
|
||||
expect(headerOf(upload, 'Content-Length')).toBeUndefined();
|
||||
expect(upload.body).toContain('name="tags"\r\n\r\n3');
|
||||
expect(upload.body).toContain('name="title"\r\n\r\nrechnung');
|
||||
expect(upload.body).toContain('name="custom_fields"\r\n\r\n{"1":"trip-uid-42"}');
|
||||
expect(upload.body).toContain('filename="rechnung.pdf"');
|
||||
expect(upload.body).toContain('%PDF-1.4 hotel');
|
||||
});
|
||||
|
||||
it('PAPERLESS-052: the trip anchor field is created when the instance has none', async () => {
|
||||
on('GET /api/custom_fields/', reply(page([])));
|
||||
on('POST /api/custom_fields/', reply({ id: 4, name: TRIP_UID_FIELD_NAME, data_type: 'string' }));
|
||||
on('POST /api/documents/post_document/', reply('"task-uuid-1"'));
|
||||
on('GET /api/tasks/', reply(page([taskRow()])));
|
||||
on('GET /api/documents/11/', reply(docRow()));
|
||||
expectOk(await provider.push(CONN, SCOPE, pushRequest()));
|
||||
expect(lastRequest('POST /api/custom_fields/').body).toContain(TRIP_UID_FIELD_NAME);
|
||||
expect(lastRequest('POST /api/documents/post_document/').body).toContain('{"4":"trip-uid-42"}');
|
||||
});
|
||||
|
||||
it('PAPERLESS-053: a custom field list from a build that ignores the filter is not trusted', async () => {
|
||||
on('GET /api/custom_fields/', reply(page([
|
||||
{ id: 8, name: 'rechnungsnummer', data_type: 'string' },
|
||||
{ id: 9, name: 'TREK_TRIP_ID', data_type: 'string' },
|
||||
])));
|
||||
on('POST /api/documents/post_document/', reply('"task-uuid-1"'));
|
||||
on('GET /api/tasks/', reply(page([taskRow()])));
|
||||
on('GET /api/documents/11/', reply(docRow()));
|
||||
expectOk(await provider.push(CONN, SCOPE, pushRequest()));
|
||||
expect(lastRequest('POST /api/documents/post_document/').body).toContain('{"9":"trip-uid-42"}');
|
||||
expect(requests('POST /api/custom_fields/')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('PAPERLESS-054: a consume that fails is a provider error, a duplicate one a conflict', async () => {
|
||||
on('GET /api/custom_fields/', reply(page([{ id: 1, name: TRIP_UID_FIELD_NAME, data_type: 'string' }])));
|
||||
on('POST /api/documents/post_document/', reply('"task-uuid-1"'));
|
||||
on('GET /api/tasks/', reply(page([taskRow({
|
||||
status: 'failure',
|
||||
related_document_ids: [],
|
||||
result_data: { error_type: 'ConsumerError', error_message: 'kaputt.pdf: InputFileError' },
|
||||
})])));
|
||||
const failed = expectFail(await provider.push(CONN, SCOPE, pushRequest()));
|
||||
expect(failed.code).toBe('provider_error');
|
||||
expect(failed.detail).toContain('InputFileError');
|
||||
|
||||
on('GET /api/tasks/', reply(page([taskRow({
|
||||
status: 'FAILURE',
|
||||
related_document_ids: [],
|
||||
result_data: { error_message: 'It is a duplicate of Rechnung (#4)' },
|
||||
})])));
|
||||
expect(expectFail(await provider.push(CONN, SCOPE, pushRequest())).code).toBe('conflict');
|
||||
});
|
||||
|
||||
it('PAPERLESS-055: the task filter is not trusted either, so a foreign task is ignored', async () => {
|
||||
on('GET /api/custom_fields/', reply(page([{ id: 1, name: TRIP_UID_FIELD_NAME, data_type: 'string' }])));
|
||||
on('POST /api/documents/post_document/', reply('"task-uuid-1"'));
|
||||
on('GET /api/tasks/', reply(page([taskRow({ task_id: 'someone-elses-task', status: 'success' })])));
|
||||
vi.spyOn(client, 'awaitConsume');
|
||||
// The only way out is the poll budget, so the client is asked directly with
|
||||
// a short one rather than holding the test for two minutes.
|
||||
const creds = { baseUrl: BASE, token: TOKEN, allowInsecureTls: false };
|
||||
await expect(
|
||||
client.awaitConsume(creds, 'task-uuid-1', { intervalMs: 1, timeoutMs: 5 }),
|
||||
).rejects.toMatchObject({ code: 'timeout' });
|
||||
});
|
||||
|
||||
it('PAPERLESS-056: an upload whose task outlives the budget is found again by its checksum', async () => {
|
||||
vi.spyOn(client, 'awaitConsume').mockRejectedValue(
|
||||
new PaperlessError('timeout', 'Paperless is still processing the uploaded file'),
|
||||
);
|
||||
on('GET /api/custom_fields/', reply(page([{ id: 1, name: TRIP_UID_FIELD_NAME, data_type: 'string' }])));
|
||||
on('POST /api/documents/post_document/', reply('"task-uuid-1"'));
|
||||
// One document with the same bytes in another tag, one in ours: the tagged
|
||||
// one is the upload we just made.
|
||||
on('GET /api/documents/', reply(page([
|
||||
docRow({ id: 21, tags: [99] }),
|
||||
docRow({ id: 11, tags: [3] }),
|
||||
])));
|
||||
on('GET /api/documents/11/', reply(docRow()));
|
||||
const pushed = expectOk(await provider.push(CONN, SCOPE, pushRequest()));
|
||||
expect(pushed.remoteId).toBe('11');
|
||||
expect(lastRequest('GET /api/documents/').url.searchParams.get('checksum__iexact')).toBe(HASH_A);
|
||||
});
|
||||
|
||||
it('PAPERLESS-057a: a document with the same bytes but another tag is not adopted', async () => {
|
||||
// The tag goes on at upload, so only a tagged document can be the one this
|
||||
// push made. Taking the untagged twin instead put a stranger's document in
|
||||
// the trip, and delete-through would have trashed it on a later run.
|
||||
vi.spyOn(client, 'awaitConsume').mockRejectedValue(
|
||||
new PaperlessError('timeout', 'Paperless is still processing the uploaded file'),
|
||||
);
|
||||
on('GET /api/custom_fields/', reply(page([{ id: 1, name: TRIP_UID_FIELD_NAME, data_type: 'string' }])));
|
||||
on('POST /api/documents/post_document/', reply('"task-uuid-1"'));
|
||||
on('GET /api/documents/', reply(page([docRow({ id: 21, tags: [99] })])));
|
||||
expect(expectFail(await provider.push(CONN, SCOPE, pushRequest())).code).toBe('timeout');
|
||||
expect(requests('GET /api/documents/21/')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('PAPERLESS-057: when the checksum finds nothing either, the timeout is reported', async () => {
|
||||
vi.spyOn(client, 'awaitConsume').mockRejectedValue(
|
||||
new PaperlessError('timeout', 'Paperless is still processing the uploaded file'),
|
||||
);
|
||||
on('GET /api/custom_fields/', reply(page([{ id: 1, name: TRIP_UID_FIELD_NAME, data_type: 'string' }])));
|
||||
on('POST /api/documents/post_document/', reply('"task-uuid-1"'));
|
||||
on('GET /api/documents/', reply(page([])));
|
||||
expect(expectFail(await provider.push(CONN, SCOPE, pushRequest())).code).toBe('timeout');
|
||||
});
|
||||
|
||||
it('PAPERLESS-058: a replace keeps the id it was given, not the one the task names', async () => {
|
||||
on('POST /api/documents/11/update_version/', reply('"task-uuid-2"'));
|
||||
// update_version files the new revision under a fresh internal id that
|
||||
// answers 404 on its own. Adopting it would break the mapping.
|
||||
on('GET /api/tasks/', reply(page([taskRow({ task_id: 'task-uuid-2', related_document_ids: [77] })])));
|
||||
on('GET /api/documents/11/', reply(docRow({
|
||||
modified: '2026-09-18T18:00:00.000000+02:00',
|
||||
versions: [
|
||||
{ id: 12, checksum: HASH_A, added: '2026-09-18T16:00:00.000000Z', is_root: false },
|
||||
{ id: 11, checksum: HASH_B, added: '2026-09-18T15:29:00.000000Z', is_root: true },
|
||||
],
|
||||
})));
|
||||
const pushed = expectOk(await provider.push(CONN, SCOPE, pushRequest({ remoteId: '11' })));
|
||||
expect(pushed.remoteId).toBe('11');
|
||||
expect(pushed.remoteVersion).toBe('2026-09-18T18:00:00.000000+02:00');
|
||||
expect(requests('POST /api/documents/post_document/')).toHaveLength(0);
|
||||
expect(requests('GET /api/documents/77/')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('PAPERLESS-059: a file larger than it claimed is refused without being uploaded', async () => {
|
||||
const error = expectFail(await provider.push(CONN, SCOPE, pushRequest({ size: 4 })));
|
||||
expect(error.code).toBe('too_large');
|
||||
expect(requests('POST /api/documents/post_document/')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('PAPERLESS-060: a type the instance refuses comes back as the same code as the local check', async () => {
|
||||
on('GET /api/custom_fields/', reply(page([{ id: 1, name: TRIP_UID_FIELD_NAME, data_type: 'string' }])));
|
||||
on('POST /api/documents/post_document/', reply({ document: ['File type text/xml not supported'] }, 400));
|
||||
expect(expectFail(await provider.push(CONN, SCOPE, pushRequest())).code).toBe('unsupported_type');
|
||||
});
|
||||
|
||||
it('PAPERLESS-061: bytes that arrived differently are reported and the new document is trashed', async () => {
|
||||
on('GET /api/custom_fields/', reply(page([{ id: 1, name: TRIP_UID_FIELD_NAME, data_type: 'string' }])));
|
||||
on('POST /api/documents/post_document/', reply('"task-uuid-1"'));
|
||||
on('GET /api/tasks/', reply(page([taskRow()])));
|
||||
on('GET /api/documents/11/', reply(docRow({
|
||||
versions: [{ id: 11, checksum: HASH_B, added: '2026-09-18T15:29:00.000000Z', is_root: true }],
|
||||
})));
|
||||
on('DELETE /api/documents/11/', reply('', 204));
|
||||
const error = expectFail(await provider.push(CONN, SCOPE, pushRequest({ sha256: HASH_A })));
|
||||
expect(error.code).toBe('checksum_mismatch');
|
||||
expect(requests('DELETE /api/documents/11/')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('PAPERLESS-062: a mismatch after a replace leaves the existing document alone', async () => {
|
||||
on('POST /api/documents/11/update_version/', reply('"task-uuid-2"'));
|
||||
on('GET /api/tasks/', reply(page([taskRow({ task_id: 'task-uuid-2' })])));
|
||||
on('GET /api/documents/11/', reply(docRow({
|
||||
versions: [{ id: 12, checksum: HASH_B, added: '2026-09-18T16:00:00.000000Z', is_root: false }],
|
||||
})));
|
||||
const error = expectFail(await provider.push(CONN, SCOPE, pushRequest({ remoteId: '11', sha256: HASH_A })));
|
||||
expect(error.code).toBe('checksum_mismatch');
|
||||
expect(requests('DELETE /api/documents/11/')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PaperlessProvider: renaming and trashing', () => {
|
||||
it('PAPERLESS-070: renaming sets the title without the extension it would add back', async () => {
|
||||
on('PATCH /api/documents/11/', reply(docRow({ modified: '2026-09-18T19:00:00.000000+02:00' })));
|
||||
const renamed = expectOk(await provider.rename(CONN, SCOPE, '11', ' Hotelrechnung Kyoto.pdf '));
|
||||
expect(lastRequest('PATCH /api/documents/11/').body).toBe('{"title":"Hotelrechnung Kyoto"}');
|
||||
expect(renamed.remoteVersion).toBe('2026-09-18T19:00:00.000000+02:00');
|
||||
// An extension this adapter would never have added stays part of the name.
|
||||
expect(titleFromFileName('Vertrag 2026.2')).toBe('Vertrag 2026.2');
|
||||
expect(titleFromFileName('bordkarte.PDF')).toBe('bordkarte');
|
||||
});
|
||||
|
||||
it('PAPERLESS-071: renaming a document that is gone is not_found', async () => {
|
||||
on('PATCH /api/documents/11/', reply({ detail: 'No Document matches the given query.' }, 404));
|
||||
expect(expectFail(await provider.rename(CONN, SCOPE, '11', 'neu.pdf')).code).toBe('not_found');
|
||||
});
|
||||
|
||||
it('PAPERLESS-080: trashing is a soft delete, and doing it twice is still success', async () => {
|
||||
on('DELETE /api/documents/11/', reply('', 204), reply({ detail: 'No Document matches the given query.' }, 404));
|
||||
expectOk(await provider.trash(CONN, SCOPE, '11'));
|
||||
expectOk(await provider.trash(CONN, SCOPE, '11'));
|
||||
expect(requests('DELETE /api/documents/11/')).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PaperlessProvider: the self-registered webhook', () => {
|
||||
it('PAPERLESS-090: subscribes both triggers, filtered on the tag, with the secret in a header', async () => {
|
||||
on('POST /api/workflows/', reply({ id: 6 }, 201));
|
||||
const registered = expectOk(
|
||||
await provider.registerWebhook(CONN, SCOPE, 'https://trek.example.org/api/docsync/hook/7', 'sh4red'),
|
||||
);
|
||||
expect(registered.subscriptionId).toBe('6');
|
||||
|
||||
const sent = JSON.parse(lastRequest('POST /api/workflows/').body) as {
|
||||
triggers: Array<{ type: number; filter_has_tags: number[]; sources: number[] }>;
|
||||
actions: Array<{ type: number; webhook: Record<string, unknown> }>;
|
||||
};
|
||||
expect(sent.triggers.map((trigger) => trigger.type)).toEqual([2, 3]);
|
||||
for (const trigger of sent.triggers) {
|
||||
expect(trigger.filter_has_tags).toEqual([3]);
|
||||
// Including the web UI, or a document dropped in by hand fires nothing.
|
||||
expect(trigger.sources).toEqual([1, 2, 3, 4]);
|
||||
}
|
||||
expect(sent.actions[0]?.type).toBe(4);
|
||||
expect(sent.actions[0]?.webhook).toMatchObject({
|
||||
url: 'https://trek.example.org/api/docsync/hook/7',
|
||||
use_params: true,
|
||||
as_json: true,
|
||||
include_document: false,
|
||||
params: { linkId: '7', tripId: '42' },
|
||||
headers: { [PAPERLESS_WEBHOOK_SECRET_HEADER]: 'sh4red' },
|
||||
});
|
||||
// The secret travels in a header, never in the URL or the body.
|
||||
expect(lastRequest('POST /api/workflows/').url.search).not.toContain('sh4red');
|
||||
expect(JSON.stringify(sent.actions[0]?.webhook.params)).not.toContain('sh4red');
|
||||
});
|
||||
|
||||
it('PAPERLESS-091: a callback URL Paperless cannot store is refused here, not upstream', async () => {
|
||||
const long = `https://trek.example.org/api/docsync/hook/${'x'.repeat(240)}`;
|
||||
const error = expectFail(await provider.registerWebhook(CONN, SCOPE, long, 's'));
|
||||
expect(error.code).toBe('provider_error');
|
||||
expect(error.detail).toContain('limit 256');
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('PAPERLESS-092: unsubscribing twice is success, and a nonsense id never leaves the process', async () => {
|
||||
on('DELETE /api/workflows/6/', reply('', 204), reply({ detail: 'Not found.' }, 404));
|
||||
expectOk(await provider.unregisterWebhook(CONN, '6'));
|
||||
expectOk(await provider.unregisterWebhook(CONN, '6'));
|
||||
const before = calls.length;
|
||||
expect(expectFail(await provider.unregisterWebhook(CONN, 'workflow-6')).code).toBe('not_found');
|
||||
expect(calls).toHaveLength(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the multipart body', () => {
|
||||
it('PAPERLESS-095: a file name cannot break out of the Content-Disposition header', () => {
|
||||
const { body, contentType } = buildMultipart(
|
||||
[{ name: 'tags', value: '3' }],
|
||||
{
|
||||
fileName: 'a";\r\nX-Injected: 1\r\n\r\nevil.pdf',
|
||||
mimeType: 'application/pdf',
|
||||
bytes: Buffer.from('bytes'),
|
||||
},
|
||||
);
|
||||
const text = body.toString('latin1');
|
||||
expect(text).not.toContain('X-Injected: 1\r\n');
|
||||
// Quote, CR and LF each become an underscore; everything else survives, so
|
||||
// the name stays recognisable in the archive.
|
||||
expect(text).toContain('filename="a_;__X-Injected: 1____evil.pdf"');
|
||||
const boundary = /boundary=(.+)$/.exec(contentType)?.[1] ?? '';
|
||||
expect(boundary.length).toBeGreaterThan(16);
|
||||
expect(text.endsWith(`--${boundary}--\r\n`)).toBe(true);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* The transport the four document clients share.
|
||||
*
|
||||
* The clients' own suites pin what each product puts on the wire; this one
|
||||
* pins the pieces they all stand on, because a regression here breaks five
|
||||
* providers at once: which failures read as a timeout, a certificate or a dead
|
||||
* host, that the timeout and the self-signed switch reach the fetch, and that
|
||||
* a download can neither announce nor stream its way past its ceiling.
|
||||
*
|
||||
* Only `safeFetch` is mocked. `cappedFetch` runs for real, so releasing an
|
||||
* oversized body is the release that ships.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { safeFetchMock, SsrfBlockedErrorMock } = vi.hoisted(() => {
|
||||
class SsrfBlockedError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'SsrfBlockedError';
|
||||
}
|
||||
}
|
||||
return { safeFetchMock: vi.fn(), SsrfBlockedErrorMock: SsrfBlockedError };
|
||||
});
|
||||
vi.mock('../../../../src/utils/ssrfGuard', () => ({
|
||||
safeFetch: safeFetchMock,
|
||||
SsrfBlockedError: SsrfBlockedErrorMock,
|
||||
}));
|
||||
|
||||
import {
|
||||
classifyTransportFailure,
|
||||
declaredLength,
|
||||
guardDownload,
|
||||
providerFetch,
|
||||
statusErrorCode,
|
||||
type TransportFailure,
|
||||
} from '../../../../src/nest/doc-sync/providers/provider-http';
|
||||
|
||||
/** `TypeError: fetch failed` with the real reason underneath, the way undici reports it. */
|
||||
function wrapped(cause: Error): Error {
|
||||
return new TypeError('fetch failed', { cause });
|
||||
}
|
||||
|
||||
function coded(message: string, code: string): Error {
|
||||
return Object.assign(new Error(message), { code });
|
||||
}
|
||||
|
||||
function named(message: string, name: string): Error {
|
||||
return Object.assign(new Error(message), { name });
|
||||
}
|
||||
|
||||
class TransportError extends Error {
|
||||
constructor(readonly failure: TransportFailure) {
|
||||
super(`transport: ${failure.code}`);
|
||||
}
|
||||
}
|
||||
|
||||
const OPTIONS = {
|
||||
timeoutMs: 5000,
|
||||
allowInsecureTls: false,
|
||||
onTransportFailure: (failure: TransportFailure) => new TransportError(failure),
|
||||
};
|
||||
|
||||
/** A body that hands out `chunk`-sized pieces until `total` bytes, recording a cancel. */
|
||||
function source(chunk: number, total: number): { stream: ReadableStream<Uint8Array>; cancelled: () => boolean } {
|
||||
let sent = 0;
|
||||
let cancelled = false;
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
if (sent >= total) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
sent += chunk;
|
||||
controller.enqueue(new Uint8Array(chunk).fill(97));
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true;
|
||||
},
|
||||
});
|
||||
return { stream, cancelled: () => cancelled };
|
||||
}
|
||||
|
||||
function download(body: ReadableStream<Uint8Array> | null, headers: Record<string, string> = {}): Response {
|
||||
return { ok: true, status: 200, headers: new Headers(headers), body } as unknown as Response;
|
||||
}
|
||||
|
||||
class TooLarge extends Error {
|
||||
constructor(readonly declared: number) {
|
||||
super('too large');
|
||||
}
|
||||
}
|
||||
|
||||
const GUARD = {
|
||||
maxBytes: 4096,
|
||||
tooLarge: (declared: number) => new TooLarge(declared),
|
||||
noBody: () => new Error('no body'),
|
||||
};
|
||||
|
||||
async function drain(stream: NodeJS.ReadableStream): Promise<Buffer> {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of stream) chunks.push(Buffer.from(chunk as Uint8Array));
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
safeFetchMock.mockReset();
|
||||
});
|
||||
|
||||
describe('classifyTransportFailure', () => {
|
||||
it('PROVIDER-HTTP-001: the SSRF guard is its own verdict and keeps its reason', () => {
|
||||
expect(classifyTransportFailure(new SsrfBlockedErrorMock('Requests to loopback are not allowed'))).toEqual({
|
||||
code: 'ssrf_blocked',
|
||||
detail: 'Requests to loopback are not allowed',
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['TimeoutError, as AbortSignal.timeout rejects', named('The operation was aborted due to timeout', 'TimeoutError')],
|
||||
['AbortError', named('This operation was aborted', 'AbortError')],
|
||||
['TimeoutError under undici\'s wrapper', wrapped(named('aborted', 'TimeoutError'))],
|
||||
['UND_ERR_HEADERS_TIMEOUT', wrapped(coded('Headers Timeout Error', 'UND_ERR_HEADERS_TIMEOUT'))],
|
||||
['UND_ERR_BODY_TIMEOUT', wrapped(coded('Body Timeout Error', 'UND_ERR_BODY_TIMEOUT'))],
|
||||
['ABORT_ERR', wrapped(coded('The operation was aborted', 'ABORT_ERR'))],
|
||||
])('PROVIDER-HTTP-002: a timeout, spelled as %s', (_label, error) => {
|
||||
expect(classifyTransportFailure(error).code).toBe('timeout');
|
||||
});
|
||||
|
||||
it.each([
|
||||
'DEPTH_ZERO_SELF_SIGNED_CERT',
|
||||
'SELF_SIGNED_CERT_IN_CHAIN',
|
||||
// The private-CA case: the chain is fine, the issuer is simply unknown here.
|
||||
'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
|
||||
'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
|
||||
'CERT_HAS_EXPIRED',
|
||||
'CERT_SIGNATURE_FAILURE',
|
||||
'ERR_TLS_CERT_ALTNAME_INVALID',
|
||||
'HOSTNAME_MISMATCH',
|
||||
// A leaf without serverAuth, signed by a CA this host does trust.
|
||||
'INVALID_PURPOSE',
|
||||
'INVALID_CA',
|
||||
'PATH_LENGTH_EXCEEDED',
|
||||
])('PROVIDER-HTTP-003: %s is an untrusted certificate', (code) => {
|
||||
expect(classifyTransportFailure(wrapped(coded('certificate verdict', code))).code).toBe('tls_untrusted');
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-004: a protocol failure in the handshake is not offered as a certificate problem', () => {
|
||||
// https against a plain http port. The self-signed switch cannot fix it.
|
||||
const error = wrapped(coded('wrong version number', 'ERR_SSL_WRONG_VERSION_NUMBER'));
|
||||
expect(classifyTransportFailure(error).code).toBe('unreachable');
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-005: everything else is a host that cannot be reached, with the whole chain as detail', () => {
|
||||
const error = wrapped(coded('connect ECONNREFUSED 192.168.1.9:5001', 'ECONNREFUSED'));
|
||||
expect(classifyTransportFailure(error)).toEqual({
|
||||
code: 'unreachable',
|
||||
detail: 'fetch failed: connect ECONNREFUSED 192.168.1.9:5001',
|
||||
});
|
||||
expect(classifyTransportFailure('socket hang up')).toEqual({ code: 'unreachable', detail: 'socket hang up' });
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-006: the cause chain is followed five levels and no further', () => {
|
||||
let error: Error = coded('self-signed certificate', 'DEPTH_ZERO_SELF_SIGNED_CERT');
|
||||
for (let level = 0; level < 4; level++) error = wrapped(error);
|
||||
expect(classifyTransportFailure(error).code).toBe('tls_untrusted');
|
||||
expect(classifyTransportFailure(wrapped(error)).code).toBe('unreachable');
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-007: a host that never takes the connection is unreachable, not slow', () => {
|
||||
// undici gives up on the handshake after ten seconds, before the request's
|
||||
// own timeout does: a NAS that is switched off, or a firewall that drops the SYN.
|
||||
const error = wrapped(
|
||||
Object.assign(new Error('Connect Timeout Error'), { name: 'ConnectTimeoutError', code: 'UND_ERR_CONNECT_TIMEOUT' }),
|
||||
);
|
||||
expect(classifyTransportFailure(error).code).toBe('unreachable');
|
||||
});
|
||||
});
|
||||
|
||||
describe('providerFetch', () => {
|
||||
it('PROVIDER-HTTP-010: hands the request to the SSRF guard with a timeout and the certificate check on', async () => {
|
||||
const answer = { ok: true, status: 200 };
|
||||
safeFetchMock.mockResolvedValue(answer);
|
||||
const body = new URLSearchParams({ a: '1' });
|
||||
|
||||
const response = await providerFetch(
|
||||
'https://nas.example.org:5001/webapi/entry.cgi',
|
||||
{ method: 'POST', headers: { Accept: 'application/json' }, body, duplex: 'half' } as RequestInit,
|
||||
OPTIONS,
|
||||
);
|
||||
|
||||
expect(response).toBe(answer);
|
||||
const [url, init, options] = safeFetchMock.mock.calls[0] as [string, RequestInit & { duplex?: string }, unknown];
|
||||
expect(url).toBe('https://nas.example.org:5001/webapi/entry.cgi');
|
||||
expect(init).toMatchObject({ method: 'POST', headers: { Accept: 'application/json' }, body, duplex: 'half' });
|
||||
expect(init.signal).toBeInstanceOf(AbortSignal);
|
||||
expect(options).toEqual({ rejectUnauthorized: true });
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-011: relaxes the certificate check only when the connection says so', async () => {
|
||||
safeFetchMock.mockResolvedValue({ ok: true, status: 200 });
|
||||
await providerFetch('https://nas.example.org', {}, { ...OPTIONS, allowInsecureTls: true });
|
||||
expect(safeFetchMock.mock.calls[0][2]).toEqual({ rejectUnauthorized: false });
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-012: an instance that never answers is cut off at the timeout', async () => {
|
||||
safeFetchMock.mockImplementation(
|
||||
(_url: string, init: RequestInit) =>
|
||||
new Promise((_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', () => reject(init.signal?.reason));
|
||||
}),
|
||||
);
|
||||
|
||||
const pending = providerFetch('https://nas.example.org', {}, { ...OPTIONS, timeoutMs: 20 });
|
||||
|
||||
await expect(pending).rejects.toBeInstanceOf(TransportError);
|
||||
await expect(pending).rejects.toMatchObject({ failure: { code: 'timeout' } });
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-013: a refusal becomes the client\'s own error, built from the classified failure', async () => {
|
||||
safeFetchMock.mockRejectedValue(new SsrfBlockedErrorMock('Requests to link-local addresses are not allowed'));
|
||||
const onTransportFailure = vi.fn((failure: TransportFailure) => new TransportError(failure));
|
||||
|
||||
const pending = providerFetch('http://169.254.169.254/', {}, { ...OPTIONS, onTransportFailure });
|
||||
|
||||
await expect(pending).rejects.toMatchObject({
|
||||
failure: { code: 'ssrf_blocked', detail: 'Requests to link-local addresses are not allowed' },
|
||||
});
|
||||
expect(onTransportFailure).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('statusErrorCode', () => {
|
||||
it('PROVIDER-HTTP-020: maps the statuses every product answers alike', () => {
|
||||
const expected: Array<[number, string]> = [
|
||||
[401, 'unauthorized'],
|
||||
[403, 'forbidden'],
|
||||
[404, 'not_found'],
|
||||
[409, 'conflict'],
|
||||
[413, 'too_large'],
|
||||
[415, 'unsupported_type'],
|
||||
[429, 'rate_limited'],
|
||||
[507, 'quota_exceeded'],
|
||||
[500, 'provider_error'],
|
||||
[418, 'provider_error'],
|
||||
];
|
||||
for (const [status, code] of expected) expect(statusErrorCode(status), `http ${status}`).toBe(code);
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-021: a client\'s own reading of a status wins, and its fallback answers the rest', () => {
|
||||
expect(statusErrorCode(412, { 412: 'conflict' })).toBe('conflict');
|
||||
expect(statusErrorCode(404, { 404: 'scope_missing' })).toBe('scope_missing');
|
||||
expect(statusErrorCode(418, {}, 'unknown')).toBe('unknown');
|
||||
expect(statusErrorCode(401, {}, 'unknown')).toBe('unauthorized');
|
||||
});
|
||||
});
|
||||
|
||||
describe('declaredLength', () => {
|
||||
it('PROVIDER-HTTP-030: an absent or unreadable header is an unknown size, never zero', () => {
|
||||
expect(declaredLength(null)).toBeNull();
|
||||
expect(declaredLength('')).toBeNull();
|
||||
expect(declaredLength(' ')).toBeNull();
|
||||
expect(declaredLength('many')).toBeNull();
|
||||
expect(declaredLength('-1')).toBeNull();
|
||||
expect(declaredLength('0')).toBe(0);
|
||||
expect(declaredLength('4096')).toBe(4096);
|
||||
});
|
||||
});
|
||||
|
||||
describe('guardDownload', () => {
|
||||
it('PROVIDER-HTTP-040: streams a body within the limit and reports what it announced', async () => {
|
||||
const { stream } = source(1024, 3072);
|
||||
const guarded = guardDownload(download(stream, { 'content-length': '3072' }), GUARD);
|
||||
|
||||
expect(guarded.size).toBe(3072);
|
||||
expect((await drain(guarded.body)).length).toBe(3072);
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-041: refuses an announced length over the limit before reading, and lets the socket go', () => {
|
||||
const { stream, cancelled } = source(1024, 8192);
|
||||
let thrown: unknown;
|
||||
try {
|
||||
guardDownload(download(stream, { 'content-length': '8192' }), GUARD);
|
||||
} catch (error: unknown) {
|
||||
thrown = error;
|
||||
}
|
||||
|
||||
expect(thrown).toBeInstanceOf(TooLarge);
|
||||
expect((thrown as TooLarge).declared).toBe(8192);
|
||||
expect(cancelled()).toBe(true);
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-042: a body that announces nothing and runs past the limit fails mid-stream', async () => {
|
||||
const { stream, cancelled } = source(1024, 64 * 1024);
|
||||
const guarded = guardDownload(download(stream), GUARD);
|
||||
|
||||
expect(guarded.size).toBeNull();
|
||||
await expect(drain(guarded.body)).rejects.toThrow(/exceeded 4096 bytes/);
|
||||
await vi.waitFor(() => expect(cancelled()).toBe(true));
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-043: a body that lies about its length is held to the limit all the same', async () => {
|
||||
const { stream } = source(1024, 64 * 1024);
|
||||
const guarded = guardDownload(download(stream, { 'content-length': '100' }), GUARD);
|
||||
await expect(drain(guarded.body)).rejects.toThrow(/exceeded/);
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-044: a consumer that stops reading releases the source', async () => {
|
||||
const { stream, cancelled } = source(1024, 64 * 1024);
|
||||
const guarded = guardDownload(download(stream), { ...GUARD, maxBytes: 1024 * 1024 });
|
||||
|
||||
guarded.body.destroy();
|
||||
await vi.waitFor(() => expect(cancelled()).toBe(true));
|
||||
});
|
||||
|
||||
it('PROVIDER-HTTP-045: an answer without a body is the client\'s own error', () => {
|
||||
expect(() => guardDownload(download(null, { 'content-length': '10' }), GUARD)).toThrow('no body');
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,906 @@
|
||||
/**
|
||||
* The WebDAV adapter for Nextcloud and OpenCloud: what it puts on the wire, and
|
||||
* what it makes of what comes back.
|
||||
*
|
||||
* The cases here are the ones that cost real debugging against the two
|
||||
* products, so they are pinned rather than described: Nextcloud's `OC-FileId`
|
||||
* header is not its `oc:fileid` and a naive adapter re-uploads every file
|
||||
* forever; `OC-Checksum: SHA256` is fine on Nextcloud and a hard 400 on
|
||||
* OpenCloud; a PROPFIND answers one propstat block per status and the 404 block
|
||||
* is not data; an OpenCloud drive describes its own WebDAV URL on a host the
|
||||
* admin never entered.
|
||||
*
|
||||
* `safeFetch` and the capped readers are mocked, for the reason
|
||||
* dawarich.client.test.ts gives: the SSRF guard does a real DNS lookup and the
|
||||
* readers want a real stream. The responses are genuine `Response` objects, so
|
||||
* headers, status and body behave as they do in production.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { safeFetchMock } = vi.hoisted(() => ({ safeFetchMock: vi.fn() }));
|
||||
|
||||
vi.mock('../../../../src/utils/ssrfGuard', () => ({
|
||||
safeFetch: safeFetchMock,
|
||||
SsrfBlockedError: class SsrfBlockedError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'SsrfBlockedError';
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../../src/utils/cappedFetch', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../../src/utils/cappedFetch')>()),
|
||||
readCappedText: async (res: Response) => {
|
||||
const text = await res.text();
|
||||
return { text: text.slice(0, capBytes), truncated: text.length > capBytes };
|
||||
},
|
||||
readCappedJson: async (res: Response) => {
|
||||
try {
|
||||
return JSON.parse(await res.text()) as unknown;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
import { Readable } from 'node:stream';
|
||||
import { SsrfBlockedError } from '../../../../src/utils/ssrfGuard';
|
||||
import {
|
||||
NextcloudDocumentProvider,
|
||||
OpencloudDocumentProvider,
|
||||
flavorOf,
|
||||
} from '../../../../src/nest/doc-sync/providers/webdav.provider';
|
||||
import { WebdavClient } from '../../../../src/nest/doc-sync/providers/webdav.client';
|
||||
import type {
|
||||
DocumentConnectionRef,
|
||||
DocumentScopeRef,
|
||||
PushRequest,
|
||||
} from '../../../../src/nest/doc-sync/document-provider';
|
||||
|
||||
/** Raised by the truncation test only; everything else stays under the cap. */
|
||||
let capBytes = 1_000_000;
|
||||
|
||||
const NC_ORIGIN = 'https://cloud.example.org';
|
||||
const OC_ORIGIN = 'https://opencloud.example.org';
|
||||
const NC_ROOT = '/remote.php/dav/files/admin';
|
||||
const OC_DRIVE = 'storage-1$space-9';
|
||||
const OC_ROOT = `/dav/spaces/${OC_DRIVE}`;
|
||||
|
||||
const ncConn: DocumentConnectionRef = {
|
||||
connectionId: 7,
|
||||
createdAt: '2026-09-01 08:00:00',
|
||||
ownerId: 3,
|
||||
baseUrl: NC_ORIGIN,
|
||||
secrets: { app_password: 'app-pw' },
|
||||
settings: { login_name: 'admin', base_path: '/TREK' },
|
||||
allowInsecureTls: false,
|
||||
};
|
||||
|
||||
const ocConn: DocumentConnectionRef = {
|
||||
connectionId: 8,
|
||||
createdAt: '2026-09-01 08:00:00',
|
||||
ownerId: 3,
|
||||
baseUrl: OC_ORIGIN,
|
||||
secrets: { app_token: 'app-token' },
|
||||
settings: { username: 'admin' },
|
||||
allowInsecureTls: true,
|
||||
};
|
||||
|
||||
const ncScope: DocumentScopeRef = {
|
||||
linkId: 1,
|
||||
tripId: 42,
|
||||
scopeKey: 'fileid:60',
|
||||
remoteRootId: '60',
|
||||
remoteRootPath: '/TREK/trip 42',
|
||||
cursor: null,
|
||||
};
|
||||
|
||||
const ocScope: DocumentScopeRef = {
|
||||
linkId: 2,
|
||||
tripId: 42,
|
||||
scopeKey: `drive:${OC_DRIVE}`,
|
||||
remoteRootId: OC_DRIVE,
|
||||
remoteRootPath: `${OC_ORIGIN}${OC_ROOT}`,
|
||||
cursor: null,
|
||||
};
|
||||
|
||||
interface Recorded {
|
||||
url: string;
|
||||
method: string;
|
||||
headers: Record<string, string>;
|
||||
body: string | undefined;
|
||||
rejectUnauthorized: boolean | undefined;
|
||||
}
|
||||
|
||||
let calls: Recorded[] = [];
|
||||
|
||||
/** `METHOD /path` → the answer, or a function of the request. */
|
||||
type Answer = Response | ((req: Recorded) => Response);
|
||||
let routes: Map<string, Answer[]>;
|
||||
|
||||
function route(key: string, ...answers: Answer[]): void {
|
||||
routes.set(key, answers);
|
||||
}
|
||||
|
||||
function reply(body: string | null, init: ResponseInit = {}): Response {
|
||||
return new Response(body, init);
|
||||
}
|
||||
|
||||
/** A PROPFIND answer built from the props each entry declares. */
|
||||
function multistatus(
|
||||
entries: Array<{
|
||||
href: string;
|
||||
collection?: boolean;
|
||||
etag?: string;
|
||||
fileid?: string;
|
||||
size?: number;
|
||||
type?: string;
|
||||
modified?: string;
|
||||
checksums?: string;
|
||||
}>,
|
||||
): Response {
|
||||
const body = entries
|
||||
.map((entry) => {
|
||||
const found: string[] = [];
|
||||
const missing: string[] = [];
|
||||
found.push(`<d:getetag>${entry.etag ?? '"etag"'}</d:getetag>`);
|
||||
found.push(`<d:getlastmodified>${entry.modified ?? 'Fri, 18 Sep 2026 15:15:54 GMT'}</d:getlastmodified>`);
|
||||
found.push(entry.collection ? '<d:resourcetype><d:collection/></d:resourcetype>' : '<d:resourcetype/>');
|
||||
if (entry.fileid) found.push(`<oc:fileid>${entry.fileid}</oc:fileid>`);
|
||||
if (entry.size === undefined) missing.push('<d:getcontentlength/>');
|
||||
else found.push(`<d:getcontentlength>${entry.size}</d:getcontentlength>`);
|
||||
if (entry.type === undefined) missing.push('<d:getcontenttype/>');
|
||||
else found.push(`<d:getcontenttype>${entry.type}</d:getcontenttype>`);
|
||||
if (entry.checksums === undefined) missing.push('<oc:checksums/>');
|
||||
else found.push(`<oc:checksums><oc:checksum>${entry.checksums}</oc:checksum></oc:checksums>`);
|
||||
|
||||
const blocks = [`<d:propstat><d:prop>${found.join('')}</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>`];
|
||||
if (missing.length > 0) {
|
||||
blocks.push(
|
||||
`<d:propstat><d:prop>${missing.join('')}</d:prop><d:status>HTTP/1.1 404 Not Found</d:status></d:propstat>`,
|
||||
);
|
||||
}
|
||||
return `<d:response><d:href>${entry.href}</d:href>${blocks.join('')}</d:response>`;
|
||||
})
|
||||
.join('');
|
||||
|
||||
return reply(
|
||||
`<?xml version="1.0"?><d:multistatus xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">${body}</d:multistatus>`,
|
||||
{ status: 207, headers: { 'content-type': 'application/xml' } },
|
||||
);
|
||||
}
|
||||
|
||||
function drive(id: string, name: string, driveType: string, webDavUrl: string): unknown {
|
||||
return { id, name, driveType, root: { id, webDavUrl } };
|
||||
}
|
||||
|
||||
function requests(method?: string): Recorded[] {
|
||||
return method ? calls.filter((call) => call.method === method) : calls;
|
||||
}
|
||||
|
||||
function pathOf(call: Recorded): string {
|
||||
return new URL(call.url).pathname;
|
||||
}
|
||||
|
||||
function pushRequest(overrides: Partial<PushRequest> = {}): PushRequest {
|
||||
return {
|
||||
body: Readable.from([Buffer.from('bytes')]),
|
||||
fileName: 'reiseplan.pdf',
|
||||
mimeType: 'application/pdf',
|
||||
size: 5,
|
||||
sha256: 'a'.repeat(64),
|
||||
mtimeSeconds: 1_700_000_000,
|
||||
trekDocUid: 'doc-1',
|
||||
trekTripUid: 'trip-1',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
let nextcloud: NextcloudDocumentProvider;
|
||||
let opencloud: OpencloudDocumentProvider;
|
||||
|
||||
beforeEach(() => {
|
||||
capBytes = 1_000_000;
|
||||
calls = [];
|
||||
routes = new Map();
|
||||
const client = new WebdavClient();
|
||||
nextcloud = new NextcloudDocumentProvider(client);
|
||||
opencloud = new OpencloudDocumentProvider(client);
|
||||
|
||||
safeFetchMock.mockImplementation(
|
||||
async (url: string, init: RequestInit, options?: { rejectUnauthorized?: boolean }) => {
|
||||
const headers: Record<string, string> = {};
|
||||
new Headers(init.headers).forEach((value, key) => {
|
||||
headers[key] = value;
|
||||
});
|
||||
const record: Recorded = {
|
||||
url,
|
||||
method: init.method ?? 'GET',
|
||||
headers,
|
||||
body: typeof init.body === 'string' ? init.body : undefined,
|
||||
rejectUnauthorized: options?.rejectUnauthorized,
|
||||
};
|
||||
calls.push(record);
|
||||
|
||||
const key = `${record.method} ${new URL(url).pathname}`;
|
||||
const queued = routes.get(key);
|
||||
if (!queued || queued.length === 0) {
|
||||
return reply('<d:error/>', { status: 404 });
|
||||
}
|
||||
const answer = queued.length > 1 ? queued.shift() : queued[0];
|
||||
if (!answer) return reply(null, { status: 404 });
|
||||
return typeof answer === 'function' ? answer(record) : answer.clone();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('flavour detection', () => {
|
||||
it('reads the product off the connection rather than off the registered id', () => {
|
||||
expect(flavorOf(ncConn)).toBe('nextcloud');
|
||||
expect(flavorOf(ocConn)).toBe('opencloud');
|
||||
expect(flavorOf({ ...ncConn, settings: {}, secrets: {} })).toBeNull();
|
||||
});
|
||||
|
||||
it('answers the same capabilities whichever class asks, because the connection decides', () => {
|
||||
expect(nextcloud.capabilities(ocConn).push).toBe('none');
|
||||
expect(opencloud.capabilities(ncConn).push).toBe('webhook-manual');
|
||||
});
|
||||
|
||||
it('never claims a content hash it cannot stand behind', () => {
|
||||
const caps = nextcloud.capabilities(ncConn);
|
||||
expect(caps.contentHashInListing).toBe(false);
|
||||
expect(caps.stableId).toBe(true);
|
||||
expect(caps.remoteTrash).toBe(true);
|
||||
expect(caps.replaceInPlace).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('probe', () => {
|
||||
it('checks the WebDAV home and upgrades push when the account may manage webhooks', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}`, multistatus([{ href: NC_ROOT, collection: true, fileid: '1' }]));
|
||||
route('GET /ocs/v2.php/apps/webhook_listeners/api/v1/webhooks', reply('{"ocs":{"data":[]}}'));
|
||||
|
||||
const result = await nextcloud.probe(ncConn);
|
||||
|
||||
expect(result).toMatchObject({ success: true, data: { account: 'admin' } });
|
||||
expect(result.success && result.data.capabilities.push).toBe('webhook-self-registered');
|
||||
expect(calls[0].headers.authorization).toBe(`Basic ${Buffer.from('admin:app-pw').toString('base64')}`);
|
||||
});
|
||||
|
||||
it('keeps push at webhook-manual when the webhook endpoint is closed to this account', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}`, multistatus([{ href: NC_ROOT, collection: true, fileid: '1' }]));
|
||||
route('GET /ocs/v2.php/apps/webhook_listeners/api/v1/webhooks', reply('{}', { status: 403 }));
|
||||
|
||||
const result = await nextcloud.probe(ncConn);
|
||||
|
||||
expect(result.success && result.data.capabilities.push).toBe('webhook-manual');
|
||||
});
|
||||
|
||||
it('separates a wrong login name from a wrong password', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}`, reply('<d:error/>', { status: 404 }));
|
||||
const missing = await nextcloud.probe(ncConn);
|
||||
expect(missing).toMatchObject({ success: false, error: { code: 'not_found' } });
|
||||
expect(missing.success === false && missing.error.detail).toContain('admin');
|
||||
|
||||
calls = [];
|
||||
route(`PROPFIND ${NC_ROOT}`, reply('<d:error/>', { status: 401 }));
|
||||
expect(await nextcloud.probe(ncConn)).toMatchObject({ success: false, error: { code: 'unauthorized' } });
|
||||
});
|
||||
|
||||
it('names the OpenCloud account from Graph and passes the TLS opt-in through', async () => {
|
||||
route('GET /graph/v1.0/me', reply('{"onPremisesSamAccountName":"admin","displayName":"Admin"}'));
|
||||
|
||||
const result = await opencloud.probe(ocConn);
|
||||
|
||||
expect(result).toMatchObject({ success: true, data: { account: 'admin' } });
|
||||
expect(result.success && result.data.capabilities.push).toBe('none');
|
||||
expect(calls[0].rejectUnauthorized).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses a half-filled connection without going near the network', async () => {
|
||||
const result = await nextcloud.probe({ ...ncConn, secrets: {}, settings: { login_name: 'admin' } });
|
||||
|
||||
expect(result).toMatchObject({ success: false, error: { code: 'unauthorized' } });
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scopes', () => {
|
||||
it('offers the folders under the base path and keys them by oc:fileid', async () => {
|
||||
route(
|
||||
`PROPFIND ${NC_ROOT}/TREK`,
|
||||
multistatus([
|
||||
{ href: `${NC_ROOT}/TREK/`, collection: true, fileid: '59' },
|
||||
{ href: `${NC_ROOT}/TREK/trip%2042/`, collection: true, fileid: '60' },
|
||||
{ href: `${NC_ROOT}/TREK/notes.txt`, fileid: '61', size: 3, type: 'text/plain' },
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await nextcloud.listScopes(ncConn);
|
||||
|
||||
expect(result).toEqual({
|
||||
success: true,
|
||||
data: [{ scopeKey: 'fileid:60', label: 'trip 42', remoteRootId: '60', remoteRootPath: '/TREK/trip 42' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('answers an empty picker rather than an error when the base folder does not exist yet', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK`, reply('<d:error/>', { status: 404 }));
|
||||
|
||||
expect(await nextcloud.listScopes(ncConn)).toEqual({ success: true, data: [] });
|
||||
});
|
||||
|
||||
it('filters the picker by the query', async () => {
|
||||
route(
|
||||
`PROPFIND ${NC_ROOT}/TREK`,
|
||||
multistatus([
|
||||
{ href: `${NC_ROOT}/TREK/`, collection: true, fileid: '59' },
|
||||
{ href: `${NC_ROOT}/TREK/Japan/`, collection: true, fileid: '60' },
|
||||
{ href: `${NC_ROOT}/TREK/Peru/`, collection: true, fileid: '61' },
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await nextcloud.listScopes(ncConn, 'jap');
|
||||
|
||||
expect(result.success && result.data.map((option) => option.label)).toEqual(['Japan']);
|
||||
});
|
||||
|
||||
it('re-bases an OpenCloud space on the entered origin and drops the virtual share drive', async () => {
|
||||
route(
|
||||
'GET /graph/v1.0/me/drives',
|
||||
reply(
|
||||
JSON.stringify({
|
||||
value: [
|
||||
drive('shares$1', 'Shares', 'virtual', 'https://internal.lan:9200/dav/spaces/shares$1'),
|
||||
drive(OC_DRIVE, 'TREK Trip 42', 'project', `https://internal.lan:9200${OC_ROOT}`),
|
||||
],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = await opencloud.listScopes(ocConn);
|
||||
|
||||
expect(result).toEqual({
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
scopeKey: `drive:${OC_DRIVE}`,
|
||||
label: 'TREK Trip 42',
|
||||
remoteRootId: OC_DRIVE,
|
||||
remoteRootPath: `${OC_ORIGIN}${OC_ROOT}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('creates the base folder when it is missing and reads the new id back', async () => {
|
||||
route(
|
||||
`MKCOL ${NC_ROOT}/TREK/Japan%202026`,
|
||||
reply(null, { status: 409 }),
|
||||
reply(null, { status: 201 }),
|
||||
);
|
||||
route(`MKCOL ${NC_ROOT}/TREK`, reply(null, { status: 201 }));
|
||||
route(
|
||||
`PROPFIND ${NC_ROOT}/TREK/Japan%202026`,
|
||||
multistatus([{ href: `${NC_ROOT}/TREK/Japan%202026/`, collection: true, fileid: '73' }]),
|
||||
);
|
||||
|
||||
const result = await nextcloud.createScope(ncConn, 'Japan 2026');
|
||||
|
||||
expect(result).toMatchObject({ success: true, data: { scopeKey: 'fileid:73', remoteRootPath: '/TREK/Japan 2026' } });
|
||||
expect(requests('MKCOL').map(pathOf)).toEqual([
|
||||
`${NC_ROOT}/TREK/Japan%202026`,
|
||||
`${NC_ROOT}/TREK`,
|
||||
`${NC_ROOT}/TREK/Japan%202026`,
|
||||
]);
|
||||
});
|
||||
|
||||
it('refuses to hand back a folder somebody else already made', async () => {
|
||||
route(`MKCOL ${NC_ROOT}/TREK/Japan`, reply(null, { status: 405 }));
|
||||
|
||||
expect(await nextcloud.createScope(ncConn, 'Japan')).toMatchObject({
|
||||
success: false,
|
||||
error: { code: 'conflict' },
|
||||
});
|
||||
});
|
||||
|
||||
it('replaces the characters Nextcloud refuses instead of failing the whole folder', async () => {
|
||||
route(`MKCOL ${NC_ROOT}/TREK/Japan-%202026`, reply(null, { status: 201 }));
|
||||
route(
|
||||
`PROPFIND ${NC_ROOT}/TREK/Japan-%202026`,
|
||||
multistatus([{ href: `${NC_ROOT}/TREK/Japan-%202026/`, collection: true, fileid: '74' }]),
|
||||
);
|
||||
|
||||
const result = await nextcloud.createScope(ncConn, 'Japan: 2026');
|
||||
|
||||
expect(result.success && result.data.label).toBe('Japan- 2026');
|
||||
});
|
||||
|
||||
it('creates an OpenCloud space as a project drive', async () => {
|
||||
route(
|
||||
'POST /graph/v1.0/drives',
|
||||
reply(JSON.stringify(drive('storage-1$new', 'Japan', 'project', `https://internal.lan:9200/dav/spaces/storage-1$new`)), {
|
||||
status: 201,
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await opencloud.createScope(ocConn, 'Japan');
|
||||
|
||||
expect(result).toMatchObject({ success: true, data: { scopeKey: 'drive:storage-1$new' } });
|
||||
expect(JSON.parse(calls[0].body ?? '{}')).toEqual({ name: 'Japan', driveType: 'project' });
|
||||
});
|
||||
|
||||
it('calls a folder with the same path but a different id scope_missing', async () => {
|
||||
route(
|
||||
`PROPFIND ${NC_ROOT}/TREK/trip%2042`,
|
||||
multistatus([{ href: `${NC_ROOT}/TREK/trip%2042/`, collection: true, fileid: '99' }]),
|
||||
);
|
||||
|
||||
const result = await nextcloud.resolveScope(ncConn, ncScope);
|
||||
|
||||
expect(result).toMatchObject({ success: false, error: { code: 'scope_missing' } });
|
||||
expect(result.success === false && result.error.detail).toContain('99');
|
||||
});
|
||||
|
||||
it('reports a deleted space as scope_missing rather than as a broken connection', async () => {
|
||||
route(`GET /graph/v1.0/drives/${encodeURIComponent(OC_DRIVE)}`, reply('{"error":{}}', { status: 404 }));
|
||||
|
||||
expect(await opencloud.resolveScope(ocConn, ocScope)).toMatchObject({
|
||||
success: false,
|
||||
error: { code: 'scope_missing' },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a scope key that belongs to another provider', async () => {
|
||||
const result = await nextcloud.list(ncConn, { ...ncScope, scopeKey: 'drive:storage$x' });
|
||||
|
||||
expect(result).toMatchObject({ success: false, error: { code: 'scope_missing' } });
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('list', () => {
|
||||
const listing = () =>
|
||||
multistatus([
|
||||
{ href: `${NC_ROOT}/TREK/trip%2042/`, collection: true, fileid: '60', etag: '"root-1"' },
|
||||
{
|
||||
href: `${NC_ROOT}/TREK/trip%2042/sub/`,
|
||||
collection: true,
|
||||
fileid: '62',
|
||||
etag: '"sub-1"',
|
||||
},
|
||||
{
|
||||
href: `${NC_ROOT}/TREK/trip%2042/pass.pdf`,
|
||||
fileid: '61',
|
||||
etag: '"doc-1"',
|
||||
size: 1234,
|
||||
type: 'application/pdf',
|
||||
modified: 'Tue, 14 Nov 2023 22:13:20 GMT',
|
||||
checksums: `SHA256:${'b'.repeat(64)}`,
|
||||
},
|
||||
]);
|
||||
|
||||
it('enumerates documents only, never the root and never a sub-folder', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, listing());
|
||||
|
||||
const result = await nextcloud.list(ncConn, ncScope);
|
||||
|
||||
expect(result.success && result.data.documents).toEqual([
|
||||
{
|
||||
remoteId: '61',
|
||||
name: 'pass.pdf',
|
||||
size: 1234,
|
||||
mimeType: 'application/pdf',
|
||||
remoteVersion: '"doc-1"',
|
||||
contentHash: 'b'.repeat(64),
|
||||
remoteModifiedAt: '2023-11-14T22:13:20.000Z',
|
||||
isDeleted: false,
|
||||
},
|
||||
]);
|
||||
expect(result.success && result.data.cursor).toBe('"root-1"');
|
||||
expect(result.success && result.data.truncated).toBe(false);
|
||||
});
|
||||
|
||||
it('skips the walk entirely when the root ETag has not moved', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, multistatus([
|
||||
{ href: `${NC_ROOT}/TREK/trip%2042/`, collection: true, fileid: '60', etag: '"root-1"' },
|
||||
]));
|
||||
|
||||
const result = await nextcloud.list(ncConn, { ...ncScope, cursor: '"root-1"' });
|
||||
|
||||
expect(result).toEqual({
|
||||
success: true,
|
||||
data: { documents: [], cursor: '"root-1"', cursorUnchanged: true, truncated: false },
|
||||
});
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0].headers.depth).toBe('0');
|
||||
});
|
||||
|
||||
it('walks after the cursor probe shows a different root ETag', async () => {
|
||||
route(
|
||||
`PROPFIND ${NC_ROOT}/TREK/trip%2042`,
|
||||
multistatus([{ href: `${NC_ROOT}/TREK/trip%2042/`, collection: true, fileid: '60', etag: '"root-2"' }]),
|
||||
listing(),
|
||||
);
|
||||
|
||||
const result = await nextcloud.list(ncConn, { ...ncScope, cursor: '"root-1"' });
|
||||
|
||||
expect(result.success && result.data.cursorUnchanged).toBe(false);
|
||||
expect(calls.map((call) => call.headers.depth)).toEqual(['0', '1']);
|
||||
});
|
||||
|
||||
it('reads a checksum only when it really is a SHA256, so OpenCloud reports none', async () => {
|
||||
route(
|
||||
`PROPFIND ${OC_ROOT}`,
|
||||
multistatus([
|
||||
{ href: `${OC_ROOT}/`, collection: true, fileid: `${OC_DRIVE}!root`, etag: '"root"' },
|
||||
{
|
||||
href: `${OC_ROOT}/pass.pdf`,
|
||||
fileid: `${OC_DRIVE}!doc`,
|
||||
etag: '"doc"',
|
||||
size: 10,
|
||||
type: 'application/pdf',
|
||||
checksums: 'SHA1:2117 MD5:eebe ADLER32:5f9f',
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await opencloud.list(ocConn, ocScope);
|
||||
|
||||
expect(result.success && result.data.documents[0]).toMatchObject({
|
||||
remoteId: `${OC_DRIVE}!doc`,
|
||||
contentHash: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('reports a listing cut off at the size cap instead of failing the run', async () => {
|
||||
capBytes = 620;
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, listing());
|
||||
|
||||
const result = await nextcloud.list(ncConn, ncScope);
|
||||
|
||||
expect(result.success && result.data.truncated).toBe(true);
|
||||
expect(result.success && result.data.documents.length).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('turns a vanished folder into scope_missing rather than an empty trip', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, reply('<d:error/>', { status: 404 }));
|
||||
|
||||
expect(await nextcloud.list(ncConn, ncScope)).toMatchObject({
|
||||
success: false,
|
||||
error: { code: 'scope_missing' },
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps a document without an oc:fileid addressable instead of dropping it', async () => {
|
||||
route(
|
||||
`PROPFIND ${NC_ROOT}/TREK/trip%2042`,
|
||||
multistatus([
|
||||
{ href: `${NC_ROOT}/TREK/trip%2042/`, collection: true, fileid: '60', etag: '"root"' },
|
||||
{ href: `${NC_ROOT}/TREK/trip%2042/pass.pdf`, etag: '"doc"', size: 1, type: 'application/pdf' },
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await nextcloud.list(ncConn, ncScope);
|
||||
|
||||
expect(result.success && result.data.documents[0].remoteId).toBe('path:pass.pdf');
|
||||
});
|
||||
});
|
||||
|
||||
describe('push', () => {
|
||||
const uploaded = (req: Recorded) =>
|
||||
reply(null, {
|
||||
status: 201,
|
||||
headers: { 'oc-fileid': '00000062oc9fy1g5e2cj', 'oc-etag': `"${req.headers['x-oc-mtime']}"` },
|
||||
});
|
||||
|
||||
it('pins the modification time and the checksum, and normalises the id Nextcloud answers with', async () => {
|
||||
route(`PUT ${NC_ROOT}/TREK/trip%2042/reiseplan.pdf`, uploaded);
|
||||
route(`PROPPATCH ${NC_ROOT}/TREK/trip%2042/reiseplan.pdf`, multistatus([
|
||||
{ href: `${NC_ROOT}/TREK/trip%2042/reiseplan.pdf`, etag: '"x"' },
|
||||
]));
|
||||
|
||||
const result = await nextcloud.push(ncConn, ncScope, pushRequest());
|
||||
|
||||
const put = requests('PUT')[0];
|
||||
expect(put.headers['x-oc-mtime']).toBe('1700000000');
|
||||
expect(put.headers['oc-checksum']).toBe(`SHA256:${'a'.repeat(64)}`);
|
||||
expect(put.headers['content-length']).toBe('5');
|
||||
// The header spells the id 00000062oc9fy1g5e2cj; the listing spells it 62,
|
||||
// and a mismatch here is a duplicate document on every run.
|
||||
expect(result).toMatchObject({
|
||||
success: true,
|
||||
data: { remoteId: '62', remoteModifiedAt: '2023-11-14T22:13:20.000Z', deduplicated: false },
|
||||
});
|
||||
});
|
||||
|
||||
it('never sends a SHA256 checksum to OpenCloud, which answers 400 to one', async () => {
|
||||
route(`PUT ${OC_ROOT}/reiseplan.pdf`, reply(null, { status: 201, headers: { 'oc-fileid': 'd1', 'oc-etag': '"e1"' } }));
|
||||
route(`PROPPATCH ${OC_ROOT}/reiseplan.pdf`, multistatus([{ href: `${OC_ROOT}/reiseplan.pdf`, etag: '"e1"' }]));
|
||||
|
||||
await opencloud.push(ocConn, ocScope, pushRequest());
|
||||
|
||||
expect(requests('PUT')[0].headers['oc-checksum']).toBeUndefined();
|
||||
expect(requests('PUT')[0].headers['x-oc-mtime']).toBe('1700000000');
|
||||
});
|
||||
|
||||
it('writes the TREK anchors as dead properties without letting a refusal undo the upload', async () => {
|
||||
route(`PUT ${NC_ROOT}/TREK/trip%2042/reiseplan.pdf`, uploaded);
|
||||
route(`PROPPATCH ${NC_ROOT}/TREK/trip%2042/reiseplan.pdf`, reply('<d:error/>', { status: 403 }));
|
||||
|
||||
const result = await nextcloud.push(ncConn, ncScope, pushRequest());
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(requests('PROPPATCH')[0].body).toContain('doc-1');
|
||||
expect(requests('PROPPATCH')[0].body).toContain('trip-1');
|
||||
});
|
||||
|
||||
it('asks for the id and version a proxy stripped from the response', async () => {
|
||||
route(`PUT ${NC_ROOT}/TREK/trip%2042/reiseplan.pdf`, reply(null, { status: 201 }));
|
||||
route(`PROPPATCH ${NC_ROOT}/TREK/trip%2042/reiseplan.pdf`, multistatus([
|
||||
{ href: `${NC_ROOT}/TREK/trip%2042/reiseplan.pdf`, etag: '"x"' },
|
||||
]));
|
||||
route(
|
||||
`PROPFIND ${NC_ROOT}/TREK/trip%2042/reiseplan.pdf`,
|
||||
multistatus([{ href: `${NC_ROOT}/TREK/trip%2042/reiseplan.pdf`, fileid: '62', etag: '"stored"', size: 5 }]),
|
||||
);
|
||||
|
||||
const result = await nextcloud.push(ncConn, ncScope, pushRequest());
|
||||
|
||||
expect(result).toMatchObject({ success: true, data: { remoteId: '62', remoteVersion: '"stored"' } });
|
||||
});
|
||||
|
||||
it('sends If-Match when the core knows which version it is replacing, and reports 412 as a conflict', async () => {
|
||||
route(
|
||||
`PROPFIND ${NC_ROOT}/TREK/trip%2042`,
|
||||
multistatus([
|
||||
{ href: `${NC_ROOT}/TREK/trip%2042/`, collection: true, fileid: '60', etag: '"root"' },
|
||||
{ href: `${NC_ROOT}/TREK/trip%2042/pass.pdf`, fileid: '61', etag: '"doc-1"', size: 1, type: 'application/pdf' },
|
||||
]),
|
||||
);
|
||||
route(`PUT ${NC_ROOT}/TREK/trip%2042/pass.pdf`, reply('<d:error/>', { status: 412 }));
|
||||
|
||||
const result = await nextcloud.push(
|
||||
ncConn,
|
||||
ncScope,
|
||||
pushRequest({ remoteId: '61', expectedRemoteVersion: '"doc-1"', fileName: 'pass.pdf' }),
|
||||
);
|
||||
|
||||
expect(requests('PUT')[0].headers['if-match']).toBe('"doc-1"');
|
||||
expect(result).toMatchObject({ success: false, error: { code: 'conflict', status: 412 } });
|
||||
});
|
||||
|
||||
it('refuses to recreate a document that disappeared upstream', async () => {
|
||||
route(
|
||||
`PROPFIND ${NC_ROOT}/TREK/trip%2042`,
|
||||
multistatus([{ href: `${NC_ROOT}/TREK/trip%2042/`, collection: true, fileid: '60', etag: '"root"' }]),
|
||||
);
|
||||
|
||||
const result = await nextcloud.push(ncConn, ncScope, pushRequest({ remoteId: '61' }));
|
||||
|
||||
expect(result).toMatchObject({ success: false, error: { code: 'not_found' } });
|
||||
expect(requests('PUT')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('maps a full quota to quota_exceeded rather than a generic failure', async () => {
|
||||
route(`PUT ${NC_ROOT}/TREK/trip%2042/reiseplan.pdf`, reply('<d:error/>', { status: 507 }));
|
||||
|
||||
expect(await nextcloud.push(ncConn, ncScope, pushRequest())).toMatchObject({
|
||||
success: false,
|
||||
error: { code: 'quota_exceeded' },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetch, rename and trash', () => {
|
||||
const folder = () =>
|
||||
multistatus([
|
||||
{ href: `${NC_ROOT}/TREK/trip%2042/`, collection: true, fileid: '60', etag: '"root"' },
|
||||
{
|
||||
href: `${NC_ROOT}/TREK/trip%2042/pass%20scan.pdf`,
|
||||
fileid: '61',
|
||||
etag: '"doc-1"',
|
||||
size: 5,
|
||||
type: 'application/pdf',
|
||||
},
|
||||
]);
|
||||
|
||||
it('streams a document back and reports the version it came with', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, folder());
|
||||
route(
|
||||
`GET ${NC_ROOT}/TREK/trip%2042/pass%20scan.pdf`,
|
||||
reply('the bytes', { headers: { 'content-length': '9', 'content-type': 'application/pdf', etag: '"doc-1"' } }),
|
||||
);
|
||||
|
||||
const result = await nextcloud.fetch(ncConn, ncScope, '61');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
if (!result.success) return;
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of result.data.body) chunks.push(Buffer.from(chunk));
|
||||
expect(Buffer.concat(chunks).toString()).toBe('the bytes');
|
||||
expect(result.data).toMatchObject({ size: 9, mimeType: 'application/pdf', remoteVersion: '"doc-1"' });
|
||||
});
|
||||
|
||||
it('re-uses the listing it already walked instead of re-walking per document', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, folder());
|
||||
route(`GET ${NC_ROOT}/TREK/trip%2042/pass%20scan.pdf`, reply('x', { headers: { etag: '"doc-1"' } }));
|
||||
|
||||
await nextcloud.list(ncConn, ncScope);
|
||||
await nextcloud.fetch(ncConn, ncScope, '61');
|
||||
|
||||
expect(requests('PROPFIND')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('refuses a download announcing more than TREK transfers, and one that arrives without a body', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, folder());
|
||||
route(
|
||||
`GET ${NC_ROOT}/TREK/trip%2042/pass%20scan.pdf`,
|
||||
reply('x', { headers: { 'content-length': String(3 * 1024 ** 3) } }),
|
||||
reply(null, { status: 200 }),
|
||||
);
|
||||
|
||||
expect(await nextcloud.fetch(ncConn, ncScope, '61')).toMatchObject({
|
||||
success: false,
|
||||
error: { code: 'too_large', status: 200 },
|
||||
});
|
||||
expect(await nextcloud.fetch(ncConn, ncScope, '61')).toMatchObject({
|
||||
success: false,
|
||||
error: { code: 'provider_error', status: 200 },
|
||||
});
|
||||
});
|
||||
|
||||
it('says not_found for an id the folder no longer holds', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, folder());
|
||||
|
||||
expect(await nextcloud.fetch(ncConn, ncScope, '999')).toMatchObject({
|
||||
success: false,
|
||||
error: { code: 'not_found' },
|
||||
});
|
||||
});
|
||||
|
||||
it('renames inside the same folder and refuses to overwrite a namesake', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, folder());
|
||||
route(`MOVE ${NC_ROOT}/TREK/trip%2042/pass%20scan.pdf`, reply(null, { status: 201, headers: { 'oc-etag': '"doc-2"' } }));
|
||||
|
||||
const result = await nextcloud.rename(ncConn, ncScope, '61', 'Reisepass 2026.pdf');
|
||||
|
||||
const move = requests('MOVE')[0];
|
||||
expect(move.headers.destination).toBe(`${NC_ORIGIN}${NC_ROOT}/TREK/trip%2042/Reisepass%202026.pdf`);
|
||||
expect(move.headers.overwrite).toBe('F');
|
||||
expect(result).toEqual({ success: true, data: { remoteVersion: '"doc-2"' } });
|
||||
});
|
||||
|
||||
it('reports a rename onto an existing name as a conflict', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, folder());
|
||||
route(`MOVE ${NC_ROOT}/TREK/trip%2042/pass%20scan.pdf`, reply('<d:error/>', { status: 412 }));
|
||||
|
||||
expect(await nextcloud.rename(ncConn, ncScope, '61', 'anders.pdf')).toMatchObject({
|
||||
success: false,
|
||||
error: { code: 'conflict' },
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes into the recycle bin and treats an already-deleted document as done', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, folder());
|
||||
route(`DELETE ${NC_ROOT}/TREK/trip%2042/pass%20scan.pdf`, reply(null, { status: 204 }), reply('<d:error/>', { status: 404 }));
|
||||
|
||||
expect(await nextcloud.trash(ncConn, ncScope, '61')).toEqual({ success: true, data: undefined });
|
||||
expect(await nextcloud.trash(ncConn, ncScope, '61')).toEqual({ success: true, data: undefined });
|
||||
});
|
||||
});
|
||||
|
||||
describe('webhooks', () => {
|
||||
const OCS = '/ocs/v2.php/apps/webhook_listeners/api/v1/webhooks';
|
||||
|
||||
it('registers one unfiltered subscription per event, form-encoded, with the secret as a header', async () => {
|
||||
route(`GET ${OCS}`, reply('{"ocs":{"data":[]}}'));
|
||||
let next = 10;
|
||||
route(`POST ${OCS}`, () => reply(JSON.stringify({ ocs: { data: { id: next++ } } })));
|
||||
|
||||
const result = await nextcloud.registerWebhook(ncConn, ncScope, 'https://trek.example/hook', 's3cret');
|
||||
|
||||
expect(result).toEqual({ success: true, data: { subscriptionId: '10,11,12,13' } });
|
||||
const bodies = requests('POST').map((call) => new URLSearchParams(call.body ?? ''));
|
||||
expect(requests('POST')[0].headers['content-type']).toBe('application/x-www-form-urlencoded');
|
||||
expect(bodies[0].get('httpMethod')).toBe('POST');
|
||||
expect(bodies[0].get('uri')).toBe('https://trek.example/hook');
|
||||
expect(bodies[0].get('authMethod')).toBe('header');
|
||||
// The header the endpoint actually reads. It used to be registered as
|
||||
// `X-TREK-Docsync-Signature` while doc-sync-webhook.controller looks for
|
||||
// `x-trek-docsync-secret`, so every webhook Nextcloud sent was dropped
|
||||
// without a trace: the subscription existed and the calls arrived.
|
||||
expect(bodies[0].get('authData[x-trek-docsync-secret]')).toBe('s3cret');
|
||||
// A $regex filter is not merely ignored upstream: it throws inside the
|
||||
// listener and stops delivery for every other webhook on that event.
|
||||
expect(bodies.every((body) => [...body.keys()].every((key) => !key.startsWith('eventFilter')))).toBe(true);
|
||||
expect(bodies.map((body) => body.get('event'))).toEqual([
|
||||
'OCP\\Files\\Events\\Node\\NodeCreatedEvent',
|
||||
'OCP\\Files\\Events\\Node\\NodeWrittenEvent',
|
||||
'OCP\\Files\\Events\\Node\\NodeDeletedEvent',
|
||||
'OCP\\Files\\Events\\Node\\NodeRenamedEvent',
|
||||
]);
|
||||
});
|
||||
|
||||
it('answers a non-admin account with forbidden and leaves the link polling', async () => {
|
||||
route(`GET ${OCS}`, reply('{}', { status: 403 }));
|
||||
|
||||
const result = await nextcloud.registerWebhook(ncConn, ncScope, 'https://trek.example/hook', 's');
|
||||
|
||||
expect(result).toMatchObject({ success: false, error: { code: 'forbidden' } });
|
||||
expect(requests('POST')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('rolls back the subscriptions it already made when a later one fails', async () => {
|
||||
route(`GET ${OCS}`, reply('{"ocs":{"data":[]}}'));
|
||||
route(
|
||||
`POST ${OCS}`,
|
||||
reply(JSON.stringify({ ocs: { data: { id: 10 } } })),
|
||||
reply(JSON.stringify({ ocs: { data: { id: 11 } } })),
|
||||
reply('<ocs/>', { status: 500 }),
|
||||
);
|
||||
route(`DELETE ${OCS}/10`, reply(null, { status: 200 }));
|
||||
route(`DELETE ${OCS}/11`, reply(null, { status: 200 }));
|
||||
|
||||
const result = await nextcloud.registerWebhook(ncConn, ncScope, 'https://trek.example/hook', 's');
|
||||
|
||||
expect(result).toMatchObject({ success: false, error: { code: 'provider_error' } });
|
||||
expect(requests('DELETE').map(pathOf)).toEqual([`${OCS}/10`, `${OCS}/11`]);
|
||||
});
|
||||
|
||||
it('tells an OpenCloud admin there is nothing to subscribe to instead of failing the connection', async () => {
|
||||
const result = await opencloud.registerWebhook(ocConn, ocScope, 'https://trek.example/hook', 's');
|
||||
|
||||
expect(result).toMatchObject({ success: false, error: { code: 'forbidden' } });
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('removes every subscription the id list names, tolerating one that is already gone', async () => {
|
||||
route(`DELETE ${OCS}/10`, reply(null, { status: 200 }));
|
||||
route(`DELETE ${OCS}/11`, reply('<ocs/>', { status: 404 }));
|
||||
|
||||
expect(await nextcloud.unregisterWebhook(ncConn, '10,11')).toEqual({ success: true, data: undefined });
|
||||
expect(requests('DELETE')).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('failure classification', () => {
|
||||
it('separates a timeout, an untrusted certificate and a blocked host', async () => {
|
||||
const timeout = Object.assign(new TypeError('fetch failed'), {
|
||||
cause: Object.assign(new Error('The operation was aborted'), { name: 'TimeoutError' }),
|
||||
});
|
||||
safeFetchMock.mockRejectedValueOnce(timeout);
|
||||
expect(await nextcloud.probe(ncConn)).toMatchObject({ success: false, error: { code: 'timeout' } });
|
||||
|
||||
const tls = Object.assign(new TypeError('fetch failed'), {
|
||||
cause: Object.assign(new Error('self-signed certificate'), { code: 'DEPTH_ZERO_SELF_SIGNED_CERT' }),
|
||||
});
|
||||
safeFetchMock.mockRejectedValueOnce(tls);
|
||||
expect(await nextcloud.probe(ncConn)).toMatchObject({ success: false, error: { code: 'tls_untrusted' } });
|
||||
|
||||
safeFetchMock.mockRejectedValueOnce(new SsrfBlockedError('Requests to loopback are not allowed'));
|
||||
expect(await nextcloud.probe(ncConn)).toMatchObject({ success: false, error: { code: 'ssrf_blocked' } });
|
||||
|
||||
safeFetchMock.mockRejectedValueOnce(new TypeError('fetch failed'));
|
||||
expect(await nextcloud.probe(ncConn)).toMatchObject({ success: false, error: { code: 'unreachable' } });
|
||||
});
|
||||
|
||||
it('keeps the upstream text in detail and out of the code', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}`, reply('<s:message>Username or password was incorrect</s:message>', { status: 401 }));
|
||||
|
||||
const result = await nextcloud.probe(ncConn);
|
||||
|
||||
expect(result).toMatchObject({ success: false, error: { code: 'unauthorized' } });
|
||||
expect(result.success === false && result.error.detail).toContain('incorrect');
|
||||
});
|
||||
|
||||
it('refuses a body that is not a multistatus instead of reading it as an empty folder', async () => {
|
||||
route(`PROPFIND ${NC_ROOT}/TREK/trip%2042`, reply('<html><body>Please log in</body></html>', { status: 207 }));
|
||||
|
||||
expect(await nextcloud.list(ncConn, ncScope)).toMatchObject({
|
||||
success: false,
|
||||
error: { code: 'provider_error' },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* RoadtripPlanService against the worker's real SQLite schema.
|
||||
*
|
||||
* The planning SELECT is the one place the server reads a visit's times for the road
|
||||
* trip, and the tests beside the MCP tools hand the service its rows by hand, so a
|
||||
* column the statement never selects would go unnoticed there. These run the statement.
|
||||
*/
|
||||
import { db } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { RoadtripPlanService } from '../../../src/nest/roadtrip/roadtrip-plan.service';
|
||||
import { createDay, createDayAssignment, createPlace, createTrip, createUser } from '../../helpers/factories';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/** Every leg an hour and 60 km, whatever it joins. */
|
||||
function hourlyRouter() {
|
||||
return {
|
||||
profiles: () => ['driving'],
|
||||
route: vi.fn(async (_user: number, _trip: number, _day: number, points: { lat: number; lng: number }[]) => ({
|
||||
parts: points.slice(1).map(() => ({ distance: 60000, duration: 3600 })),
|
||||
avoidMissed: [],
|
||||
leg: {
|
||||
line: points.map((p) => [p.lat, p.lng]),
|
||||
vias: [],
|
||||
seg: {
|
||||
from: [points[0].lat, points[0].lng],
|
||||
to: [points[points.length - 1].lat, points[points.length - 1].lng],
|
||||
mid: [points[0].lat, points[0].lng],
|
||||
distance: 60000 * (points.length - 1),
|
||||
duration: 3600 * (points.length - 1),
|
||||
mode: 'driving',
|
||||
distanceText: '',
|
||||
drivingText: '',
|
||||
walkingText: '',
|
||||
},
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const { user } = createUser(db);
|
||||
const trip = createTrip(db, user.id);
|
||||
const day = createDay(db, trip.id);
|
||||
const visits = ['Hamburg', 'Lueneburg', 'Celle'].map((name, i) => {
|
||||
const place = createPlace(db, trip.id, { name, lat: 53 - i * 0.3, lng: 10 });
|
||||
db.prepare('UPDATE places SET duration_minutes = ? WHERE id = ?').run(i === 0 ? 0 : 30, place.id);
|
||||
return createDayAssignment(db, day.id, place.id);
|
||||
});
|
||||
db.prepare("UPDATE day_assignments SET assignment_time = '09:00' WHERE id = ?").run(visits[0].id);
|
||||
const plans = new RoadtripPlanService(
|
||||
new DatabaseService(db),
|
||||
{ getUserSettings: () => ({}) } as never,
|
||||
{ read: () => ({}) } as never,
|
||||
hourlyRouter() as never,
|
||||
{ listForTrip: () => [], tracksForTrip: () => [] } as never,
|
||||
{ list: () => [] } as never,
|
||||
);
|
||||
return { user, trip, visits, plans };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
});
|
||||
|
||||
describe('a visit end time on the road trip', () => {
|
||||
it('is read from the visit, and from the place when the visit has none', () => {
|
||||
const { user, trip, visits, plans } = setup();
|
||||
db.prepare("UPDATE day_assignments SET assignment_end_time = '14:00' WHERE id = ?").run(visits[1].id);
|
||||
db.prepare(
|
||||
"UPDATE places SET end_time = '18:00' WHERE id = (SELECT place_id FROM day_assignments WHERE id = ?)",
|
||||
).run(visits[2].id);
|
||||
|
||||
const context = plans.context(trip.id, user.id);
|
||||
|
||||
expect(context.visits.map((v) => [v.name, v.end_time])).toEqual([
|
||||
['Hamburg', null],
|
||||
['Lueneburg', '14:00'],
|
||||
['Celle', '18:00'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('is when the drive leaves the stop, in place of its stay', async () => {
|
||||
const { user, trip, visits, plans } = setup();
|
||||
db.prepare("UPDATE day_assignments SET assignment_end_time = '14:00' WHERE id = ?").run(visits[1].id);
|
||||
|
||||
const { calculated } = await plans.calculate(trip.id, user.id);
|
||||
const day = calculated.days[0];
|
||||
|
||||
expect(day.stops[1]).toMatchObject({ name: 'Lueneburg', leaveAt: '14:00' });
|
||||
expect(day.schedule.entries.map((e) => [e.arrival, e.departure])).toEqual([
|
||||
['09:00', '09:00'],
|
||||
['10:00', '14:00'],
|
||||
['15:00', '15:30'],
|
||||
]);
|
||||
expect(day.schedule.warnings).toEqual([]);
|
||||
});
|
||||
|
||||
it('is reported when the drive gets there after it', async () => {
|
||||
const { user, trip, visits, plans } = setup();
|
||||
db.prepare("UPDATE day_assignments SET assignment_end_time = '09:30' WHERE id = ?").run(visits[1].id);
|
||||
|
||||
const { calculated } = await plans.calculate(trip.id, user.id);
|
||||
|
||||
expect(calculated.days[0].schedule.warnings).toEqual([{ index: 1, code: 'missedLeave', minutes: 30 }]);
|
||||
expect(calculated.days[0].schedule.entries[1]).toMatchObject({ arrival: '10:00', departure: '10:00' });
|
||||
});
|
||||
|
||||
it('leaves a stop without one to its stay', async () => {
|
||||
const { user, trip, plans } = setup();
|
||||
|
||||
const { calculated } = await plans.calculate(trip.id, user.id);
|
||||
|
||||
expect(calculated.days[0].schedule.entries[1]).toMatchObject({ arrival: '10:00', departure: '10:30' });
|
||||
expect(calculated.days[0].stops[1].leaveAt).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -176,6 +176,24 @@ describe('browser-independent roadtrip calculation', () => {
|
||||
const plan = await s.plans.calculate(10, 5);
|
||||
expect(plan.omittedVisits).toEqual([2]);
|
||||
});
|
||||
it('hands calculate_roadtrip the end time of a visit as the moment the drive leaves it', async () => {
|
||||
const s = setup();
|
||||
// Stop 1 is left at 07:30 and the road takes two hours, so stop 2 is reached half an
|
||||
// hour after the 09:00 it was meant to be left at. Stop 3 is left at noon, whatever
|
||||
// its stay says.
|
||||
Object.assign(s.visits[1], { end_time: '09:00' });
|
||||
Object.assign(s.visits[2], { end_time: '12:00' });
|
||||
const mcp = new RoadtripPlanningMcp(s.plans, {} as never, {} as never);
|
||||
const answer = await mcp.calculate(
|
||||
{ tripId: 10, includeGeometry: false, settings: { roadtrip_day_start: '', roadtrip_day_end: '' } },
|
||||
ctx,
|
||||
);
|
||||
const body = JSON.parse(answer.content[0].text as string);
|
||||
const [day] = body.days;
|
||||
expect(day.stops.map((stop: { leaveAt: string | null }) => stop.leaveAt)).toEqual([undefined, '09:00', '12:00']);
|
||||
expect(day.schedule.entries.map((e: { departure: string }) => e.departure)).toEqual(['07:30', '09:30', '12:00']);
|
||||
expect(day.schedule.warnings).toEqual([{ index: 1, code: 'missedLeave', minutes: 30 }]);
|
||||
});
|
||||
it('keeps explicit end-day visits and manual boundaries in the shared planning path', async () => {
|
||||
const s = setup();
|
||||
s.visits[0].end_day = 1;
|
||||
|
||||
Reference in New Issue
Block a user