refactor(vacay, admin, doc-sync): async DB-touching methods; transactions through UnitOfWork

This commit is contained in:
jubnl
2026-09-22 03:29:33 +02:00
parent 567593a259
commit cb177ce655
28 changed files with 1400 additions and 1356 deletions
+2 -2
View File
@@ -184,7 +184,7 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
daysService,
permissionsService,
budgetService,
new VacayService(dbService, realtimeService, notificationsStub()),
new VacayService(dbService, realtimeService, notificationsStub(), await createTestUnitOfWork(dbService.connection)),
realtimeService,
new UnsplashService(dbService, new RuntimeEnvService(), generalStorage),
generalStorage,
@@ -229,7 +229,7 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
new AccommodationsMcp(accommodationsService, dbService, placesService, authService, guards, await createTestUnitOfWork(dbService.connection)),
new AssignmentsMcp(assignmentsService, daysService, authService, guards),
new CollabMcp(collabService, authService, addonsService, guards),
new VacayMcp(new VacayService(dbService, realtimeService, notificationsStub()), authService, addonsService),
new VacayMcp(new VacayService(dbService, realtimeService, notificationsStub(), await createTestUnitOfWork(dbService.connection)), authService, addonsService),
new SchoolHolidaysMcp(new SchoolHolidaysService(dbService, await createTestUnitOfWork(dbService.connection)), guards),
new TripsMcp(tripsService, todoService, collabService, authService, calendarService, membersService, readModelService, addonsService, guards),
new TripPromptsMcp(tripsService, readModelService, packingService, addonsService),
+1 -1
View File
@@ -97,7 +97,7 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise<
const packing = new PackingService(dbs, permissions, realtime, notificationsStub(), await createTestUnitOfWork(dbs.connection));
const files = new FilesService(dbs, permissions, realtime, new EphemeralTokenService(), generalStorage);
const collab = new CollabService(dbs, permissions, realtime, notificationsStub(), generalStorage, new RateLimitService(), await createTestUnitOfWork(dbs.connection));
const vacay = new VacayService(dbs, realtime, notificationsStub());
const vacay = new VacayService(dbs, realtime, notificationsStub(), await createTestUnitOfWork(dbs.connection));
const days = new DaysService(dbs, permissions, realtime, queryHelpers, await createTestUnitOfWork(dbs.connection));
const photoCache = new PlacePhotoCacheService(dbs, makeStorageFixture('photos/google/').storage);
const unsplash = new UnsplashService(dbs, new RuntimeEnvService(), generalStorage);
@@ -84,7 +84,7 @@ afterEach(() => { delete process.env.NODE_ENV; });
describe('AdminController users', () => {
it('lists, creates (201 + audit), maps an error', async () => {
expect(adminCtl(svc({ listUsers: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listUsers()).toEqual({ users: [{ id: 1 }] });
expect(await adminCtl(svc({ listUsers: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listUsers()).toEqual({ users: [{ id: 1 }] });
expect(await thrown(() => adminCtl(svc({ createUser: vi.fn().mockReturnValue({ error: 'Email taken', status: 409 }) } as Partial<AdminService>)).createUser(user, {}, req))).toEqual({ status: 409, body: { error: 'Email taken' } });
const c = adminCtl(svc({ createUser: vi.fn().mockReturnValue({ user: { id: 2 }, insertedId: 2, auditDetails: {} }) } as Partial<AdminService>));
expect(await c.createUser(user, { email: 'a@b.c' }, req)).toEqual({ user: { id: 2 } });
@@ -184,12 +184,12 @@ describe('AdminController error envelope fallbacks', () => {
describe('AdminController read-only getters', () => {
it('return service values verbatim', async () => {
expect(await adminCtl(svc({ resetUserPasskeys: vi.fn().mockReturnValue({ email: 'a@b.c', deleted: 2 }) } as Partial<AdminService>)).resetUserPasskeys(user, '4', req)).toEqual({ success: true, deleted: 2 });
expect(adminCtl(svc({ getStats: vi.fn().mockReturnValue({ users: 3 }) } as Partial<AdminService>)).stats()).toEqual({ users: 3 });
expect(await adminCtl(svc({ getStats: vi.fn().mockReturnValue({ users: 3 }) } as Partial<AdminService>)).stats()).toEqual({ users: 3 });
expect(await adminCtl(svc({ getPermissions: vi.fn().mockReturnValue({ a: 1 }) } as Partial<AdminService>)).permissions()).toEqual({ a: 1 });
expect(adminCtl(svc({ getAuditLog: vi.fn().mockReturnValue({ entries: [] }) } as Partial<AdminService>)).auditLog({})).toEqual({ entries: [] });
expect(await adminCtl(svc({ getAuditLog: vi.fn().mockReturnValue({ entries: [] }) } as Partial<AdminService>)).auditLog({})).toEqual({ entries: [] });
await expect(adminCtl(svc({ checkVersion: vi.fn().mockResolvedValue({ current: '1' }) } as Partial<AdminService>)).versionCheck()).resolves.toEqual({ current: '1' });
expect(await adminCtl(svc(), undefined, undefined, {}, { listInvites: vi.fn().mockReturnValue([{ id: 1 }]) }).listInvites()).toEqual({ invites: [{ id: 1 }] });
expect(adminCtl(svc({ listAddons: vi.fn().mockReturnValue([{ id: 'mcp' }]) } as Partial<AdminService>)).listAddons()).toEqual({ addons: [{ id: 'mcp' }] });
expect(await adminCtl(svc({ listAddons: vi.fn().mockReturnValue([{ id: 'mcp' }]) } as Partial<AdminService>)).listAddons()).toEqual({ addons: [{ id: 'mcp' }] });
expect(await adminCtl(svc(), undefined, undefined, { listAllMcpTokens: vi.fn().mockReturnValue([{ id: 1 }]) }).listMcpTokens()).toEqual({ tokens: [{ id: 1 }] });
expect(await adminCtl(svc(), undefined, undefined, {}, {}, { listAllOAuthSessions: vi.fn().mockResolvedValue([{ id: 1 }]) }).listOAuthSessions()).toEqual({ sessions: [{ id: 1 }] });
});
+58 -57
View File
@@ -112,6 +112,7 @@ beforeAll(async () => {
await makeNotificationsService(dbs, realtime),
userCleanup,
realtime,
await createTestUnitOfWork(dbs.connection),
);
});
@@ -147,10 +148,10 @@ afterAll(() => {
// ── listUsers ─────────────────────────────────────────────────────────────────
describe('listUsers', () => {
it('ADMIN-SVC-001 — returns all users with online:false', () => {
it('ADMIN-SVC-001 — returns all users with online:false', async () => {
createUser(testDb);
createUser(testDb);
const users = listUsers() as any[];
const users = (await listUsers()) as any[];
expect(users.length).toBeGreaterThanOrEqual(2);
expect(users.every((u: any) => u.online === false)).toBe(true);
});
@@ -159,38 +160,38 @@ describe('listUsers', () => {
// ── createUser ────────────────────────────────────────────────────────────────
describe('createUser (service)', () => {
it('ADMIN-SVC-002 — creates a user successfully', () => {
const result = svcCreateUser({ username: 'newuser', email: 'new@test.com', password: 'ValidPass1!' }) as any;
it('ADMIN-SVC-002 — creates a user successfully', async () => {
const result = (await svcCreateUser({ username: 'newuser', email: 'new@test.com', password: 'ValidPass1!' })) as any;
expect(result.user).toBeDefined();
expect(result.user.email).toBe('new@test.com');
});
it('ADMIN-SVC-003 — returns 400 when username is missing', () => {
const result = svcCreateUser({ username: '', email: 'x@x.com', password: 'ValidPass1!' }) as any;
it('ADMIN-SVC-003 — returns 400 when username is missing', async () => {
const result = (await svcCreateUser({ username: '', email: 'x@x.com', password: 'ValidPass1!' })) as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-004 — returns 400 for invalid role', () => {
const result = svcCreateUser({ username: 'u1', email: 'u1@test.com', password: 'ValidPass1!', role: 'superuser' }) as any;
it('ADMIN-SVC-004 — returns 400 for invalid role', async () => {
const result = (await svcCreateUser({ username: 'u1', email: 'u1@test.com', password: 'ValidPass1!', role: 'superuser' })) as any;
expect(result.status).toBe(400);
expect(result.error).toMatch(/invalid role/i);
});
it('ADMIN-SVC-005 — returns 409 for duplicate username', () => {
it('ADMIN-SVC-005 — returns 409 for duplicate username', async () => {
createUser(testDb);
const { user } = createUser(testDb);
const result = svcCreateUser({ username: user.username, email: 'unique@test.com', password: 'ValidPass1!' }) as any;
const result = (await svcCreateUser({ username: user.username, email: 'unique@test.com', password: 'ValidPass1!' })) as any;
expect(result.status).toBe(409);
});
it('ADMIN-SVC-006 — returns 409 for duplicate email', () => {
it('ADMIN-SVC-006 — returns 409 for duplicate email', async () => {
const { user } = createUser(testDb);
const result = svcCreateUser({ username: 'uniqueuser', email: user.email, password: 'ValidPass1!' }) as any;
const result = (await svcCreateUser({ username: 'uniqueuser', email: user.email, password: 'ValidPass1!' })) as any;
expect(result.status).toBe(409);
});
it('ADMIN-SVC-007 — returns 400 for weak password', () => {
const result = svcCreateUser({ username: 'weakpwuser', email: 'weakpw@test.com', password: 'short' }) as any;
it('ADMIN-SVC-007 — returns 400 for weak password', async () => {
const result = (await svcCreateUser({ username: 'weakpwuser', email: 'weakpw@test.com', password: 'short' })) as any;
expect(result.status).toBe(400);
});
});
@@ -198,47 +199,47 @@ describe('createUser (service)', () => {
// ── updateUser ────────────────────────────────────────────────────────────────
describe('updateUser', () => {
it('ADMIN-SVC-008 — updates username successfully', () => {
it('ADMIN-SVC-008 — updates username successfully', async () => {
const { user } = createUser(testDb);
const result = updateUser(String(user.id), { username: 'updatedname' }) as any;
const result = (await updateUser(String(user.id), { username: 'updatedname' })) as any;
expect(result.user).toBeDefined();
expect(result.user.username).toBe('updatedname');
});
it('ADMIN-SVC-009 — returns 404 for non-existent user', () => {
const result = updateUser('99999', { username: 'ghost' }) as any;
it('ADMIN-SVC-009 — returns 404 for non-existent user', async () => {
const result = (await updateUser('99999', { username: 'ghost' })) as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-010 — returns 400 for invalid role', () => {
it('ADMIN-SVC-010 — returns 400 for invalid role', async () => {
const { user } = createUser(testDb);
const result = updateUser(String(user.id), { role: 'superadmin' }) as any;
const result = (await updateUser(String(user.id), { role: 'superadmin' })) as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-011 — returns 409 when username is taken', () => {
it('ADMIN-SVC-011 — returns 409 when username is taken', async () => {
const { user: u1 } = createUser(testDb);
const { user: u2 } = createUser(testDb);
const result = updateUser(String(u2.id), { username: u1.username }) as any;
const result = (await updateUser(String(u2.id), { username: u1.username })) as any;
expect(result.status).toBe(409);
});
it('ADMIN-SVC-012 — returns 409 when email is taken', () => {
it('ADMIN-SVC-012 — returns 409 when email is taken', async () => {
const { user: u1 } = createUser(testDb);
const { user: u2 } = createUser(testDb);
const result = updateUser(String(u2.id), { email: u1.email }) as any;
const result = (await updateUser(String(u2.id), { email: u1.email })) as any;
expect(result.status).toBe(409);
});
it('ADMIN-SVC-013 — returns 400 for weak password', () => {
it('ADMIN-SVC-013 — returns 400 for weak password', async () => {
const { user } = createUser(testDb);
const result = updateUser(String(user.id), { password: 'weak' }) as any;
const result = (await updateUser(String(user.id), { password: 'weak' })) as any;
expect(result.status).toBe(400);
});
it('ADMIN-SVC-014 — tracks changed fields in result', () => {
it('ADMIN-SVC-014 — tracks changed fields in result', async () => {
const { user } = createUser(testDb);
const result = updateUser(String(user.id), { username: 'newname', role: 'admin' }) as any;
const result = (await updateUser(String(user.id), { username: 'newname', role: 'admin' })) as any;
expect(result.changed).toContain('username');
expect(result.changed).toContain('role');
});
@@ -270,8 +271,8 @@ describe('deleteUser', () => {
// ── getStats ──────────────────────────────────────────────────────────────────
describe('getStats', () => {
it('ADMIN-SVC-018 — returns numeric counts for all stats', () => {
const stats = getStats() as any;
it('ADMIN-SVC-018 — returns numeric counts for all stats', async () => {
const stats = (await getStats()) as any;
expect(typeof stats.totalUsers).toBe('number');
expect(typeof stats.totalTrips).toBe('number');
expect(typeof stats.totalPlaces).toBe('number');
@@ -299,22 +300,22 @@ describe('Permissions', () => {
// ── getAuditLog ───────────────────────────────────────────────────────────────
describe('getAuditLog', () => {
it('ADMIN-SVC-021 — returns entries array with total', () => {
const result = getAuditLog({}) as any;
it('ADMIN-SVC-021 — returns entries array with total', async () => {
const result = (await getAuditLog({})) as any;
expect(Array.isArray(result.entries)).toBe(true);
expect(typeof result.total).toBe('number');
expect(result.limit).toBe(100);
expect(result.offset).toBe(0);
});
it('ADMIN-SVC-022 — respects limit and offset params', () => {
const result = getAuditLog({ limit: '10', offset: '0' }) as any;
it('ADMIN-SVC-022 — respects limit and offset params', async () => {
const result = (await getAuditLog({ limit: '10', offset: '0' })) as any;
expect(result.limit).toBe(10);
expect(result.offset).toBe(0);
});
it('ADMIN-SVC-023 — caps limit at 500', () => {
const result = getAuditLog({ limit: '9999' }) as any;
it('ADMIN-SVC-023 — caps limit at 500', async () => {
const result = (await getAuditLog({ limit: '9999' })) as any;
expect(result.limit).toBe(500);
});
});
@@ -322,24 +323,24 @@ describe('getAuditLog', () => {
// ── getAuditLog — JSON details parsing ───────────────────────────────────────
describe('getAuditLog — JSON details', () => {
it('ADMIN-SVC-045 — parses JSON details when present', () => {
it('ADMIN-SVC-045 — parses JSON details when present', async () => {
const { user } = createUser(testDb);
testDb.prepare('INSERT INTO audit_log (user_id, action, details) VALUES (?, ?, ?)').run(
user.id, 'test_action', JSON.stringify({ key: 'val' })
);
const result = getAuditLog({}) as any;
const result = (await getAuditLog({})) as any;
expect(result.entries.length).toBeGreaterThanOrEqual(1);
const entry = result.entries.find((e: any) => e.action === 'test_action');
expect(entry).toBeDefined();
expect(entry.details).toEqual({ key: 'val' });
});
it('ADMIN-SVC-046 — falls back to the raw string when details are not valid JSON', () => {
it('ADMIN-SVC-046 — falls back to the raw string when details are not valid JSON', async () => {
const { user } = createUser(testDb);
testDb.prepare('INSERT INTO audit_log (user_id, action, details) VALUES (?, ?, ?)').run(
user.id, 'bad_json_action', 'not-valid-json{'
);
const result = getAuditLog({}) as any;
const result = (await getAuditLog({})) as any;
const entry = result.entries.find((e: any) => e.action === 'bad_json_action');
expect(entry).toBeDefined();
// Was { _parse_error: true } before the 2026-08 quirk fix — the admin UI
@@ -477,8 +478,8 @@ describe('checkVersion', () => {
// ── listAddons ────────────────────────────────────────────────────────────────
describe('listAddons', () => {
it('ADMIN-SVC-065 — listAddons returns array containing seeded addon entries', () => {
const result = listAddons() as any[];
it('ADMIN-SVC-065 — listAddons returns array containing seeded addon entries', async () => {
const result = (await listAddons()) as any[];
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBeGreaterThan(0);
const addonIds = result.map((a: any) => a.id);
@@ -597,10 +598,10 @@ describe('version-check job', () => {
describe('admin quirk fixes (post-fold)', () => {
it('ADMIN-SVC-072 — updateUser rejects an empty username/email instead of silently no-opping', () => {
it('ADMIN-SVC-072 — updateUser rejects an empty username/email instead of silently no-opping', async () => {
const { user } = createUser(testDb);
expect(updateUser(String(user.id), { username: '' }) as any).toMatchObject({ status: 400, error: 'Username cannot be empty' });
expect(updateUser(String(user.id), { email: ' ' }) as any).toMatchObject({ status: 400, error: 'Email cannot be empty' });
expect((await updateUser(String(user.id), { username: '' })) as any).toMatchObject({ status: 400, error: 'Username cannot be empty' });
expect((await updateUser(String(user.id), { email: ' ' })) as any).toMatchObject({ status: 400, error: 'Email cannot be empty' });
// The row is untouched.
const row = testDb.prepare('SELECT username FROM users WHERE id = ?').get(user.id) as { username: string };
expect(row.username).toBe(user.username);
@@ -619,7 +620,7 @@ const mcpTokenCount = (id: number): number =>
(testDb.prepare('SELECT COUNT(*) AS n FROM mcp_tokens WHERE user_id = ?').get(id) as { n: number }).n;
describe('admin password reset revokes what an intruder already holds', () => {
it('ADMIN-SVC-080 — setting a password bumps password_version, so existing cookies stop working', () => {
it('ADMIN-SVC-080 — setting a password bumps password_version, so existing cookies stop working', async () => {
// An admin sets somebody else's password for one reason: the account is
// believed compromised. Without the bump, verifyJwtAndLoadUser keeps
// accepting every cookie the intruder holds, and the one action taken to
@@ -627,26 +628,26 @@ describe('admin password reset revokes what an intruder already holds', () => {
const { user } = createUser(testDb);
const before = pv(user.id);
updateUser(String(user.id), { password: 'ANewStrongPass123!' });
await updateUser(String(user.id), { password: 'ANewStrongPass123!' });
expect(pv(user.id)).toBe(before + 1);
});
it('ADMIN-SVC-081 — and clears the MCP tokens, which the version bump does not reach', () => {
it('ADMIN-SVC-081 — and clears the MCP tokens, which the version bump does not reach', async () => {
const { user } = createUser(testDb);
testDb.prepare("INSERT INTO mcp_tokens (user_id, token_hash, token_prefix, name) VALUES (?, 'hash', 'trek_ab', 'cli')").run(user.id);
updateUser(String(user.id), { password: 'ANewStrongPass123!' });
await updateUser(String(user.id), { password: 'ANewStrongPass123!' });
expect(mcpTokenCount(user.id)).toBe(0);
});
it('ADMIN-SVC-082 — renaming a user touches neither, so an ordinary edit stays ordinary', () => {
it('ADMIN-SVC-082 — renaming a user touches neither, so an ordinary edit stays ordinary', async () => {
const { user } = createUser(testDb);
const before = pv(user.id);
testDb.prepare("INSERT INTO mcp_tokens (user_id, token_hash, token_prefix, name) VALUES (?, 'hash', 'trek_ab', 'cli')").run(user.id);
updateUser(String(user.id), { username: 'renamed' });
await updateUser(String(user.id), { username: 'renamed' });
expect(pv(user.id)).toBe(before);
expect(mcpTokenCount(user.id)).toBe(1);
@@ -654,14 +655,14 @@ describe('admin password reset revokes what an intruder already holds', () => {
});
describe('resetUserMfa', () => {
it('ADMIN-SVC-083 — clears the three columns disableMfa clears, so both paths leave one state', () => {
it('ADMIN-SVC-083 — clears the three columns disableMfa clears, so both paths leave one state', async () => {
// The passkey half has existed since passkeys landed; TOTP never had an
// answer, which left "somebody on the trip lost their phone" with no way out
// short of an operator reaching into the database.
const admin = createAdmin(testDb);
const { user } = createUserWithMfa(testDb);
const result = svc.resetUserMfa(String(user.id), admin.user.id) as { success?: boolean; email?: string };
const result = (await svc.resetUserMfa(String(user.id), admin.user.id)) as { success?: boolean; email?: string };
expect(result.success).toBe(true);
expect(result.email).toBe(user.email);
@@ -673,22 +674,22 @@ describe('resetUserMfa', () => {
expect(row.mfa_backup_codes).toBeNull();
});
it('ADMIN-SVC-084 — refuses to strip the callers own second factor', () => {
it('ADMIN-SVC-084 — refuses to strip the callers own second factor', async () => {
// Reachable from a stolen admin session otherwise, and it would take the
// second factor off the very account that session came from. The
// self-service path in Settings asks for the current password.
const admin = createAdmin(testDb);
const result = svc.resetUserMfa(String(admin.user.id), admin.user.id) as { error?: string; status?: number };
const result = (await svc.resetUserMfa(String(admin.user.id), admin.user.id)) as { error?: string; status?: number };
expect(result.status).toBe(400);
expect(result.error).toMatch(/your own/i);
});
it('ADMIN-SVC-085 — 404 for a user that is not there', () => {
it('ADMIN-SVC-085 — 404 for a user that is not there', async () => {
const admin = createAdmin(testDb);
expect(svc.resetUserMfa('99999', admin.user.id) as { status?: number }).toMatchObject({ status: 404 });
expect((await svc.resetUserMfa('99999', admin.user.id)) as { status?: number }).toMatchObject({ status: 404 });
});
});
@@ -90,6 +90,7 @@ beforeAll(async () => {
await makeNotificationsService(dbs, realtime),
userCleanup,
realtime,
await createTestUnitOfWork(dbs.connection),
);
});
const checkAndNotifyVersion = () => svc.checkAndNotifyVersion();
@@ -67,8 +67,9 @@ import type { DocumentProviderRegistry } from '../../../../src/nest/doc-sync/doc
// 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';
import { createTestUnitOfWork } from '../../../helpers/test-uow';
const svc = new DocSyncConfigService(new DatabaseService(testDb), {} as DocumentProviderRegistry);
let svc: DocSyncConfigService;
const TOKEN = 'paperless-token-1234';
@@ -105,20 +106,21 @@ function linkInput(connectionId: number, over: Partial<DocsyncLinkInput> = {}):
};
}
function link(connectionId: number, over: Partial<DocsyncLinkInput> = {}): LinkRow {
const result = svc.createLink(TRIP, OWNER, linkInput(connectionId, over));
async function link(connectionId: number, over: Partial<DocsyncLinkInput> = {}): Promise<LinkRow> {
const result = await 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;
async function storedSecret(connectionId: number): Promise<string | undefined> {
const row = (await svc.getConnection(connectionId)) as ConnectionRow;
return svc.toRef(row).secrets.api_token;
}
beforeAll(() => {
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
svc = new DocSyncConfigService(new DatabaseService(testDb), {} as DocumentProviderRegistry, await createTestUnitOfWork(testDb));
});
beforeEach(() => {
@@ -142,7 +144,7 @@ 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);
expect(await storedSecret(created.id)).toBe(TOKEN);
});
it('keeps it when the form posts back the mask it was shown', async () => {
@@ -150,19 +152,19 @@ describe('upsertConnection secrets', () => {
// 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);
expect(await 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);
expect(await 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');
expect(await storedSecret(created.id)).toBe('rotated-token');
});
it('updates the trip\'s connection in place rather than adding a second one', async () => {
@@ -194,10 +196,10 @@ describe('upsertConnection secrets', () => {
expect(docFailed(result)).toBe(true);
expect(docFailed(result) && result.error.code).toBe('unauthorized');
const row = svc.getConnection(created.id) as ConnectionRow;
const row = await svc.getConnection(created.id) as ConnectionRow;
expect(row.base_url).toBe('https://paperless.example.com');
expect(row.owner_user_id).toBe(OWNER);
expect(storedSecret(created.id)).toBe(TOKEN);
expect(await storedSecret(created.id)).toBe(TOKEN);
});
it('refuses the mask as well, since the mask is not the credential', async () => {
@@ -214,22 +216,22 @@ describe('upsertConnection secrets', () => {
const moved = await connect({ baseUrl: 'https://paperless.example.net', credentials: { api_token: 'new-token' } });
expect(moved.id).toBe(created.id);
expect(moved.base_url).toBe('https://paperless.example.net');
expect(storedSecret(created.id)).toBe('new-token');
expect(await storedSecret(created.id)).toBe('new-token');
});
it('drops a secret the provider earned for the old address, even when the form is complete', async () => {
const conn = await connect({ providerId: 'synologydrive', baseUrl: 'https://nas.example.com:5001', credentials: { username: 'anna', password: 'nas-pw' } });
svc.saveEarnedSecret(conn.id, 'device_token', 'a1b2c3:DEVICE-7');
await svc.saveEarnedSecret(conn.id, 'device_token', 'a1b2c3:DEVICE-7');
await connect({ providerId: 'synologydrive', baseUrl: 'https://nas.example.net:5001', credentials: { username: 'anna', password: 'nas-pw' } });
expect(svc.toRef(svc.getConnection(conn.id) as ConnectionRow).secrets).toEqual({ password: 'nas-pw' });
expect(svc.toRef((await svc.getConnection(conn.id)) as ConnectionRow).secrets).toEqual({ password: 'nas-pw' });
});
it('reads a path or a trailing slash on the same server as the same address', async () => {
const created = await connect();
await connect({ baseUrl: 'https://paperless.example.com/paperless/', credentials: {} });
expect(storedSecret(created.id)).toBe(TOKEN);
expect(await storedSecret(created.id)).toBe(TOKEN);
});
it('reads another port or scheme as another server', async () => {
@@ -251,13 +253,13 @@ describe('upsertConnection secrets', () => {
it('stays with the person whose secret is stored when somebody else saves the form blank', async () => {
const created = await connect();
await connect({ credentials: {} }, MEMBER);
expect((svc.getConnection(created.id) as ConnectionRow).owner_user_id).toBe(OWNER);
expect((await svc.getConnection(created.id) as ConnectionRow).owner_user_id).toBe(OWNER);
});
it('moves to the person who typed a new secret in', async () => {
const created = await connect();
await connect({ credentials: { api_token: 'members-own-token' } }, MEMBER);
expect((svc.getConnection(created.id) as ConnectionRow).owner_user_id).toBe(MEMBER);
expect((await svc.getConnection(created.id) as ConnectionRow).owner_user_id).toBe(MEMBER);
});
it('stays put when only an optional secret is typed, since that runs against the stored password', async () => {
@@ -265,7 +267,7 @@ describe('upsertConnection secrets', () => {
const created = await connect({ ...nas, credentials: { username: 'anna', password: 'nas-pw' } });
await connect({ ...nas, credentials: { username: 'anna', otp_code: '123456' } }, MEMBER);
const row = svc.getConnection(created.id) as ConnectionRow;
const row = await svc.getConnection(created.id) as ConnectionRow;
expect(row.owner_user_id).toBe(OWNER);
expect(svc.toRef(row).secrets).toEqual({ password: 'nas-pw', otp_code: '123456' });
});
@@ -286,7 +288,7 @@ describe('upsertConnection secrets', () => {
credentials: { login_name: 'anna' },
allowInsecureTls: false,
});
const row = svc.listConnections(TRIP).find((c) => c.provider_id === 'nextcloud') as ConnectionRow;
const row = (await 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');
});
@@ -295,7 +297,7 @@ describe('upsertConnection secrets', () => {
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);
const view = await svc.publicConnection((await svc.getConnection(created.id)) as ConnectionRow);
expect(view.secrets).toEqual({ api_token: DOCSYNC_SECRET_MASK });
expect(JSON.stringify(view)).not.toContain(TOKEN);
});
@@ -310,14 +312,14 @@ describe('publicConnection', () => {
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 });
const row = (await svc.listConnections(TRIP)).find((c) => c.provider_id === 'synologydrive') as ConnectionRow;
expect((await 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);
const view = await svc.publicConnection((await svc.getConnection(created.id)) as ConnectionRow);
expect(view.capabilities).toBeNull();
});
});
@@ -330,22 +332,22 @@ describe('a secret the provider earned itself', () => {
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;
async function secretsOf(connectionId: number): Promise<Readonly<Record<string, string>>> {
return svc.toRef((await 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);
await 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');
expect(await secretsOf(conn.id)).toEqual({ password: 'nas-pw', otp_code: '123456', device_token: EARNED });
expect((await 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);
await svc.saveEarnedSecret(conn.id, 'device_token', EARNED);
const view = await svc.publicConnection((await 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');
@@ -354,48 +356,48 @@ describe('a secret the provider earned itself', () => {
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 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 });
expect(await 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();
expect((await secretsOf(conn.id)).device_token).toBeUndefined();
svc.saveEarnedSecret(conn.id, 'device_token', EARNED);
await 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');
expect((await secretsOf(conn.id)).device_token).toBe(EARNED);
expect(svc.toRef((await 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);
await ref.saveSecret!('device_token', EARNED);
expect(secretsOf(conn.id)).toMatchObject({ password: 'rotated', device_token: EARNED });
expect(await 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);
await svc.saveEarnedSecret(conn.id, 'device_token', EARNED);
await svc.saveEarnedSecret(conn.id, 'device_token', null);
expect(secretsOf(conn.id)).toEqual({ password: 'nas-pw', otp_code: '123456' });
expect(await 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);
await svc.deleteConnection(conn.id);
ref.saveSecret!('device_token', EARNED);
expect(svc.getConnection(conn.id)).toBeUndefined();
await ref.saveSecret!('device_token', EARNED);
expect(await svc.getConnection(conn.id)).toBeUndefined();
});
});
@@ -414,7 +416,7 @@ describe('validateBaseUrl', () => {
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);
expect(await svc.listConnections(TRIP)).toHaveLength(0);
});
it('strips trailing slashes so the adapter can append its own path', async () => {
@@ -434,7 +436,7 @@ describe('upsertConnection required fields', () => {
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);
expect(await svc.listConnections(TRIP)).toHaveLength(0);
});
it('refuses a missing required field that is not a secret either', async () => {
@@ -462,12 +464,12 @@ describe('upsertConnection required fields', () => {
});
describe('enabledProviderIds', () => {
it('names only the providers an admin switched on, in the order the shelf shows them', () => {
it('names only the providers an admin switched on, in the order the shelf shows them', async () => {
// 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([]);
expect(await svc.enabledProviderIds()).toEqual([]);
testDb.prepare("UPDATE document_providers SET enabled = 1 WHERE id IN ('nextcloud', 'paperless')").run();
expect(svc.enabledProviderIds()).toEqual(['paperless', 'nextcloud']);
expect(await svc.enabledProviderIds()).toEqual(['paperless', 'nextcloud']);
});
});
@@ -477,10 +479,10 @@ describe('recordProbe', () => {
// 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);
await svc.recordProbe(conn.id, 'ok', null, { push: 'multipart' });
await svc.recordProbe(conn.id, 'failed', '401 Unauthorized', null);
const view = svc.publicConnection(svc.getConnection(conn.id) as ConnectionRow);
const view = await svc.publicConnection((await svc.getConnection(conn.id)) as ConnectionRow);
expect(view).toMatchObject({
lastProbeState: 'failed',
lastProbeError: '401 Unauthorized',
@@ -497,16 +499,16 @@ describe('deleteConnection', () => {
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' });
const doomedLink = await link(doomed.id, { scopeKey: 'tag:1' });
const keptLink = await 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);
await svc.deleteConnection(doomed.id);
expect(svc.getConnection(doomed.id)).toBeUndefined();
expect(svc.listLinks(TRIP).map((l) => l.id)).toEqual([keptLink.id]);
expect(await svc.getConnection(doomed.id)).toBeUndefined();
expect((await 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 });
});
});
@@ -515,7 +517,7 @@ 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);
const before = svc.toRef(await 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.
@@ -532,8 +534,8 @@ describe('toRef', () => {
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 });
const created = await link(conn.id, { direction: 'both', conflictPolicy: 'manual' });
const patched = await svc.updateLink(created.id, { direction: 'pull', syncEnabled: false });
expect(patched).toMatchObject({
direction: 'pull',
sync_enabled: 0,
@@ -544,8 +546,8 @@ describe('updateLink', () => {
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);
const created = await link(conn.id);
expect(await svc.updateLink(created.id, {})).toEqual(created);
});
});
@@ -554,7 +556,7 @@ describe('toScopeRef', () => {
// 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(
const created = await svc.createLink(
TRIP,
OWNER,
linkInput(conn.id, { scopeKey: 'fileid:437', remoteRootId: '437', remoteRootPath: '/TREK/japan' }),
@@ -563,7 +565,7 @@ describe('toScopeRef', () => {
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({
expect(svc.toScopeRef(await svc.getLink(row.id) as LinkRow)).toEqual({
linkId: row.id,
tripId: TRIP,
scopeKey: 'fileid:437',
@@ -577,37 +579,37 @@ describe('toScopeRef', () => {
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' }));
const first = await link(conn.id);
const again = await svc.createLink(TRIP, MEMBER, linkInput(conn.id, { remoteLabel: 'renamed' }));
expect(again.success && again.data.id).toBe(first.id);
expect(svc.listLinks(TRIP)).toHaveLength(1);
expect(await 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' });
const first = await link(conn.id, { scopeKey: 'tag:1' });
const second = await link(conn.id, { scopeKey: 'tag:2' });
expect(second.id).not.toBe(first.id);
expect(svc.listLinks(TRIP)).toHaveLength(2);
expect(await 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));
const result = await 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);
expect(await 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));
const result = await 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(
const result = await svc.createLink(
TRIP,
OWNER,
linkInput(conn.id, { remoteRootId: '17', remoteRootPath: '/TREK/japan', remoteLabel: 'Japan 2026' }),
@@ -623,7 +625,7 @@ describe('createLink', () => {
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));
const result = await svc.createLink(TRIP, OWNER, linkInput(conn.id));
expect(result.success && result.data).toMatchObject({ remote_root_id: null, remote_root_path: null });
});
@@ -631,15 +633,15 @@ describe('createLink', () => {
// 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' });
const first = await link(conn.id, { scopeKey: 'tag:1' });
const second = await 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);
expect((await 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');
const view = await svc.publicLink(first, 'https://trek.example.com');
expect(view.webhookSecret).toBe(DOCSYNC_SECRET_MASK);
expect(JSON.stringify(view)).not.toContain(secret);
});
@@ -650,24 +652,24 @@ describe('publicLink', () => {
// 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);
const bound = await 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' });
expect(await 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');
const bound = await link(conn.id);
expect((await 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 doomed = await link(conn.id, { scopeKey: 'tag:1' });
const kept = await link(conn.id, { scopeKey: 'tag:2' });
const insert = testDb.prepare(
'INSERT INTO document_sync_items (link_id, trip_id, trek_doc_uid) VALUES (?, ?, ?)',
);
@@ -675,18 +677,18 @@ describe('deleteLink', () => {
insert.run(doomed.id, TRIP, 'uid-b');
insert.run(kept.id, TRIP, 'uid-c');
svc.deleteLink(doomed.id);
await svc.deleteLink(doomed.id);
expect(svc.getLink(doomed.id)).toBeUndefined();
expect(svc.getLink(kept.id)).toBeDefined();
expect(await svc.getLink(doomed.id)).toBeUndefined();
expect(await 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();
await svc.deleteLink((await link(conn.id)).id);
expect(await svc.getConnection(conn.id)).toBeDefined();
});
});
@@ -695,15 +697,15 @@ describe('markOrphanedLinks', () => {
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}` });
return await 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 });
expect(await svc.markOrphanedLinks()).toBe(1);
expect(await 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 () => {
@@ -711,8 +713,8 @@ describe('markOrphanedLinks', () => {
// 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 });
expect(await svc.markOrphanedLinks()).toBe(0);
expect(await 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 () => {
@@ -720,25 +722,25 @@ describe('markOrphanedLinks', () => {
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 });
expect(await svc.markOrphanedLinks()).toBe(1);
expect((await svc.getLink(orphan.id))?.last_sync_state).toBe('orphaned');
expect(await 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);
expect(await svc.markOrphanedLinks()).toBe(1);
expect(await 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 });
await 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');
expect(await svc.markOrphanedLinks()).toBe(0);
expect((await svc.getLink(paused.id))?.last_sync_state).toBe('never');
});
});
@@ -749,39 +751,39 @@ describe('isOrphaned', () => {
it('answers yes for a paused binding whose owner left, which the sweep never marks', async () => {
const paused = await bind(MEMBER);
svc.updateLink(paused.id, { syncEnabled: false });
await 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.isOrphaned(svc.getLink(paused.id)!)).toBe(true);
expect(await svc.markOrphanedLinks()).toBe(0);
expect(await svc.isOrphaned((await svc.getLink(paused.id))!)).toBe(true);
});
it('answers yes for a marked binding, and no while the owner is on the trip', async () => {
const kept = await bind(OWNER);
expect(svc.isOrphaned(kept)).toBe(false);
expect(await svc.isOrphaned(kept)).toBe(false);
testDb.prepare("UPDATE trip_document_links SET last_sync_state = 'orphaned' WHERE id = ?").run(kept.id);
expect(svc.isOrphaned(svc.getLink(kept.id)!)).toBe(true);
expect(await svc.isOrphaned((await svc.getLink(kept.id))!)).toBe(true);
});
it('leaves a connection that is gone to the run, which reports it as not found', async () => {
const bound = await bind(OWNER);
expect(svc.isOrphaned({ ...bound, connection_id: 999999 })).toBe(false);
expect(await svc.isOrphaned({ ...bound, connection_id: 999999 })).toBe(false);
});
});
describe('switching an orphaned binding back on', () => {
async function orphan(): Promise<LinkRow> {
const bound = link((await connect({}, MEMBER)).id);
const bound = await link((await connect({}, MEMBER)).id);
testDb.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(TRIP, MEMBER);
svc.markOrphanedLinks();
await svc.markOrphanedLinks();
return bound;
}
it('keeps it off while its owner is still gone, and changes the rest of the patch', async () => {
const bound = await orphan();
const res = svc.updateLink(bound.id, { syncEnabled: true, direction: 'pull' });
const res = await svc.updateLink(bound.id, { syncEnabled: true, direction: 'pull' });
expect(res).toMatchObject({ sync_enabled: 0, last_sync_state: 'orphaned', direction: 'pull' });
});
@@ -790,9 +792,9 @@ describe('switching an orphaned binding back on', () => {
const bound = await orphan();
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(TRIP, MEMBER);
const res = svc.updateLink(bound.id, { syncEnabled: true });
const res = await svc.updateLink(bound.id, { syncEnabled: true });
expect(res).toMatchObject({ sync_enabled: 1, last_sync_state: 'never' });
expect(svc.isOrphaned(res!)).toBe(false);
expect(await svc.isOrphaned(res!)).toBe(false);
});
});
@@ -78,6 +78,7 @@ import type {
DocsyncLinkDto,
} from '../../../../src/nest/doc-sync/doc-sync.dto';
import type { User } from '../../../../src/types';
import { createTestUnitOfWork } from '../../../helpers/test-uow';
const CAPS = {
push: 'webhook-self-registered' as const,
@@ -124,9 +125,11 @@ const sync = {
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);
// Built in beforeAll: DocSyncConfigService now takes a UnitOfWork, and
// createTestUnitOfWork is async — module-scope construction cannot await it.
let config: DocSyncConfigService;
let controller: DocSyncController;
/** Only what publicOrigin reads: header lookup plus the connection's own scheme. */
function makeReq(headers: Record<string, string> = {}, protocol = 'http'): Request {
@@ -178,7 +181,9 @@ let admin: User;
let tripId: number;
let otherTripId: number;
beforeAll(() => {
beforeAll(async () => {
config = new DocSyncConfigService(dbs, registry, await createTestUnitOfWork(testDb));
controller = new DocSyncController(config, sync as unknown as DocSyncService, registry, dbs, realtime as unknown as RealtimeService);
createTables(testDb);
runMigrations(testDb);
const o = createUser(testDb, { username: 'owner', email: 'owner@test.local' }).user;
@@ -233,8 +238,8 @@ describe('who may change a trip binding', () => {
});
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 }>;
it('reports an enabled provider with no registered adapter as unavailable instead of hiding it', async () => {
const rows = (await 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);
@@ -242,8 +247,8 @@ describe('providers', () => {
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 }> }>;
it('hands the form flags to the client as booleans rather than the 0/1 the column stores', async () => {
const rows = (await 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);
@@ -262,7 +267,7 @@ describe('storing a connection', () => {
expect(res.secrets.api_token).not.toContain('super-secret');
const listed = controller.listConnections(String(tripId)) as Array<{ id: number; secrets: Record<string, string> }>;
const listed = (await 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
@@ -273,7 +278,7 @@ describe('storing a connection', () => {
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);
expect(await config.listConnections(tripId)).toHaveLength(0);
});
it('refuses to point the stored secret at another server when the form leaves it blank', async () => {
@@ -285,8 +290,8 @@ describe('storing a connection', () => {
controller.upsertConnection(String(tripId), admin, connBody({ baseUrl: 'https://elsewhere.example', credentials: {} })),
);
expect(err.getStatus()).toBe(400);
expect(config.getConnection(conn.id)!.base_url).toBe('https://paperless.example.com');
expect(config.getConnection(conn.id)!.owner_user_id).toBe(Number(owner.id));
expect((await config.getConnection(conn.id))!.base_url).toBe('https://paperless.example.com');
expect((await config.getConnection(conn.id))!.owner_user_id).toBe(Number(owner.id));
});
it('refuses a provider the instance admin has not switched on, and names it', async () => {
@@ -372,14 +377,14 @@ describe('probing form values', () => {
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)!;
const row = (await 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(await config.listConnections(tripId)).toHaveLength(0);
expect(paperless.probe.mock.calls[0][0]).toMatchObject({ connectionId: 0, secrets: { api_token: 'first-try' } });
});
});
@@ -395,9 +400,9 @@ describe('a secret the adapter earned itself', () => {
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);
await config.saveEarnedSecret(created.id, 'device_token', EARNED);
const listed = JSON.stringify(controller.listConnections(String(tripId)));
const listed = JSON.stringify(await controller.listConnections(String(tripId)));
const edited = JSON.stringify(
await controller.upsertConnection(String(tripId), owner, { ...nas, credentials: { username: 'anna', password: 'rotated' } }),
);
@@ -405,12 +410,12 @@ describe('a secret the adapter earned itself', () => {
expect(payload).not.toContain('DEVICE-SECRET');
expect(payload).not.toContain('device_token');
}
expect(config.toRef(config.getConnection(created.id)!).secrets.device_token).toBe(EARNED);
expect(config.toRef((await 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);
await 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];
@@ -446,7 +451,7 @@ describe('removing a connection', () => {
);
await expect(controller.deleteConnection(String(tripId), String(conn.id), owner)).resolves.toEqual({ success: true });
expect(config.getConnection(conn.id)).toBeUndefined();
expect(await config.getConnection(conn.id)).toBeUndefined();
expect(testDb.prepare('SELECT id FROM trip_files WHERE id = ?').get(fileId)).toBeTruthy();
});
@@ -469,8 +474,8 @@ describe('removing a connection', () => {
expect(paperless.unregisterWebhook.mock.calls.map((c) => c[1]).sort()).toEqual(['sub-7', 'sub-8']);
expect(paperless.unregisterWebhook.mock.calls[0][0]).toMatchObject({ connectionId: conn.id, secrets: { api_token: 'stored-token' } });
expect(config.getConnection(conn.id)).toBeUndefined();
expect(config.getLink(first.id)).toBeUndefined();
expect(await config.getConnection(conn.id)).toBeUndefined();
expect(await config.getLink(first.id)).toBeUndefined();
});
it('still unbinds when the provider refuses to take a subscription down', async () => {
@@ -479,14 +484,14 @@ describe('removing a connection', () => {
paperless.unregisterWebhook.mockResolvedValueOnce({ success: false, error: { code: 'unreachable' } } as never);
await expect(controller.deleteConnection(String(tripId), String(conn.id), owner)).resolves.toEqual({ success: true });
expect(config.getConnection(conn.id)).toBeUndefined();
expect(await config.getConnection(conn.id)).toBeUndefined();
});
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(await config.getConnection(conn.id)).toBeTruthy();
expect(realtime.broadcast).not.toHaveBeenCalled();
});
@@ -498,14 +503,14 @@ describe('removing a connection', () => {
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 }));
const bind = async (connectionId: number, scopeKey: string) => {
const res = await 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');
const first = await bind(conn.id, 'tag:1');
const second = await bind(conn.id, 'tag:2');
await bind(cloud.data.id, 'folder:1');
await controller.deleteConnection(String(tripId), String(conn.id), owner);
@@ -593,7 +598,7 @@ describe('creating a binding', () => {
makeReq({ 'x-forwarded-proto': 'https', 'x-forwarded-host': 'trek.example' }),
)) as { id: number };
const row = config.getLink(link.id)!;
const row = (await 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.
@@ -611,7 +616,7 @@ describe('creating a binding', () => {
makeReq({ 'x-forwarded-host': 'trek.example' }),
)) as { id: number; syncEnabled: boolean };
const row = config.getLink(link.id)!;
const row = (await config.getLink(link.id))!;
expect(row.webhook_subscription_id).toBeNull();
expect(row.sync_enabled).toBe(1);
});
@@ -675,7 +680,7 @@ describe('changing a binding', () => {
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 {
const res = (await controller.updateLink(String(tripId), String(created.id), owner, { syncEnabled: false }, makeReq())) as {
syncEnabled: boolean;
direction: string;
remoteLabel: string;
@@ -691,7 +696,7 @@ describe('changing a binding', () => {
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);
expect((await config.getLink(created.id))!.sync_enabled).toBe(1);
});
});
@@ -775,14 +780,14 @@ describe('the document list', () => {
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 }>;
const rows = (await 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 }>;
const rows = (await controller.items(String(tripId), 'conflict')) as Array<{ trek_doc_uid: string }>;
expect(rows.map((r) => r.trek_doc_uid)).toEqual(['uid-2']);
});
});
@@ -817,7 +822,7 @@ describe('removing a binding', () => {
expect(res).toEqual({ success: true, documentsKept: true });
expect(paperless.unregisterWebhook.mock.calls[0][1]).toBe('sub-7');
expect(config.getLink(created.id)).toBeUndefined();
expect(await config.getLink(created.id)).toBeUndefined();
expect(testDb.prepare('SELECT id FROM trip_files WHERE id = ?').get(fileId)).toBeTruthy();
});
@@ -839,7 +844,7 @@ describe('removing a binding', () => {
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(await config.getLink(created.id)).toBeTruthy();
expect(realtime.broadcast).not.toHaveBeenCalled();
});
});
@@ -848,30 +853,30 @@ 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)!;
return (await 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 }>;
const [link] = (await 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 }>;
const [link] = (await 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 }>;
const [link] = (await 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 }>;
const [link] = (await controller.listLinks(String(tripId), makeReq())) as Array<{ webhookUrl: string | null }>;
expect(link.webhookUrl).toBeNull();
});
@@ -879,15 +884,15 @@ describe('the callback origin a provider is given', () => {
// Synology takes no webhook. Showing the address with "paste this into
// your provider" next to it promised something there was nowhere to do.
const row = await linkedTrip();
config.recordProbe(row.connection_id, 'ok', null, { ...CAPS, push: 'none' });
const [link] = controller.listLinks(String(tripId), makeReq({ host: 'trek.example' })) as Array<{ webhookUrl: string | null }>;
await config.recordProbe(row.connection_id, 'ok', null, { ...CAPS, push: 'none' });
const [link] = (await controller.listLinks(String(tripId), makeReq({ host: 'trek.example' }))) as Array<{ webhookUrl: string | null }>;
expect(link.webhookUrl).toBeNull();
});
it('keeps offering it for a store the probe found able to take one', async () => {
const row = await linkedTrip();
config.recordProbe(row.connection_id, 'ok', null, { ...CAPS, push: 'webhook-manual' });
const [link] = controller.listLinks(String(tripId), makeReq({ host: 'trek.example' })) as Array<{ webhookUrl: string | null }>;
await config.recordProbe(row.connection_id, 'ok', null, { ...CAPS, push: 'webhook-manual' });
const [link] = (await controller.listLinks(String(tripId), makeReq({ host: 'trek.example' }))) as Array<{ webhookUrl: string | null }>;
expect(link.webhookUrl).toBe(`http://trek.example/api/docsync/webhook/${row.webhook_token}`);
});
});
@@ -106,48 +106,48 @@ function makeJob(over: Partial<Setup> = {}) {
beforeEach(() => vi.clearAllMocks());
describe('DocSyncJob bootstrap', () => {
it('schedules nothing, reads nothing and logs nothing while the registrar is off', () => {
it('schedules nothing, reads nothing and logs nothing while the registrar is off', async () => {
// 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();
await 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', () => {
it('registers one cron under a name of its own, on the minute', async () => {
// 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();
await 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', () => {
it('reads the interval from its own app_settings key', async () => {
const { job, db } = makeJob({ interval: '600' });
job.onApplicationBootstrap();
await 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();
await 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', () => {
it('does not decide at bootstrap whether the addon is on', async () => {
// 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();
await job.onApplicationBootstrap();
expect(addons.isAddonEnabled).not.toHaveBeenCalled();
});
});
@@ -421,9 +421,10 @@ describe('DocSyncJob and a provider switched off in the admin panel', () => {
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);
// Built in beforeAll: DocSyncService now takes a UnitOfWork, and
// createTestUnitOfWork is async — module-scope construction cannot await it.
// Built in beforeAll: DocSyncConfigService and DocSyncService now take a
// UnitOfWork, and createTestUnitOfWork is async — module-scope construction
// cannot await it.
let config: DocSyncConfigService;
let service: DocSyncService;
const registrar = { isEnabled: () => false } as unknown as CronRegistrarService;
/** A job of its own per pass, so the interval never decides whether a tick runs. */
@@ -434,6 +435,7 @@ describe('DocSyncJob and a provider switched off in the admin panel', () => {
const linkRow = (id: number) => testDb.prepare('SELECT * FROM trip_document_links WHERE id = ?').get(id);
beforeAll(async () => {
config = new DocSyncConfigService(dbs, registry, await createTestUnitOfWork(testDb));
service = new DocSyncService(
dbs, config, registry,
{} as StorageService, {} as FilesService, new AllowedFileTypesService(dbs),
File diff suppressed because it is too large Load Diff
@@ -470,7 +470,7 @@ describe('SynologyDriveDocumentProvider: device tokens', () => {
function saved(store: Record<string, string>, overrides: Partial<DocumentConnectionRef> = {}): DocumentConnectionRef {
return connection({
secrets: { ...store },
saveSecret: (key, value) => {
saveSecret: async (key, value) => {
writes.push([key, value]);
if (value === null) delete store[key];
else store[key] = value;
+2 -2
View File
@@ -143,7 +143,7 @@ beforeAll(async () => {
daysSvc,
new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)),
budgetSvc,
new VacayService(dbs(), new RealtimeService(), notificationsStub()),
new VacayService(dbs(), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection)),
new RealtimeService(),
undefined as never, // unsplash — not exercised here
coversFx.storage,
@@ -1210,7 +1210,7 @@ describe('quirk fixes', () => {
daysSvc,
new PermissionsService(dbs(), await createTestUnitOfWork(dbs().connection)),
budgetSvc,
new VacayService(dbs(), new RealtimeService(), notificationsStub()),
new VacayService(dbs(), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(dbs().connection)),
new RealtimeService(),
undefined as never,
coversFx.storage,
+41 -41
View File
@@ -25,9 +25,9 @@ async function thrown(fn: () => unknown): Promise<{ status: number; body: unknow
const planBase = { getActivePlanId: vi.fn().mockReturnValue(10), getActivePlan: vi.fn().mockReturnValue({ id: 10 }) };
describe('VacayController (parity with the legacy /api/addons/vacay route)', () => {
it('GET /plan delegates getPlanData', () => {
it('GET /plan delegates getPlanData', async () => {
const getPlanData = vi.fn().mockReturnValue({ plan: { id: 10 } });
expect(makeController({ getPlanData }).getPlan(user)).toEqual({ plan: { id: 10 } });
expect(await makeController({ getPlanData }).getPlan(user)).toEqual({ plan: { id: 10 } });
});
it('PUT /plan forwards the socket id', async () => {
@@ -39,9 +39,9 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
describe('holiday calendars', () => {
// A missing region now 400s in the global ZodValidationPipe (the schema
// requires it), so the bespoke 'region required' guard is gone.
it('creates a calendar', () => {
it('creates a calendar', async () => {
const addHolidayCalendar = vi.fn().mockReturnValue({ id: 1, region: 'DE-BY' });
const res = makeController({ ...planBase, addHolidayCalendar }).addHolidayCalendar(user, { region: 'DE-BY', label: 'Bayern' }, 'sock');
const res = await makeController({ ...planBase, addHolidayCalendar }).addHolidayCalendar(user, { region: 'DE-BY', label: 'Bayern' }, 'sock');
expect(res).toEqual({ calendar: { id: 1, region: 'DE-BY' } });
expect(addHolidayCalendar).toHaveBeenCalledWith(10, 'DE-BY', 'Bayern', undefined, undefined, 'sock', undefined);
});
@@ -66,10 +66,10 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
expect(r).toEqual({ status: 403, body: { error: 'User not in plan' } }));
});
it('sets the colour for an in-plan user', () => {
it('sets the colour for an in-plan user', async () => {
const getPlanUsers = vi.fn().mockReturnValue([{ id: 1 }]);
const setUserColor = vi.fn();
expect(makeController({ ...planBase, getPlanUsers, setUserColor }).setColor(user, { color: '#fff' }, 'sock')).toEqual({ success: true });
expect(await makeController({ ...planBase, getPlanUsers, setUserColor }).setColor(user, { color: '#fff' }, 'sock')).toEqual({ success: true });
expect(setUserColor).toHaveBeenCalledWith(1, 10, '#fff', 'sock');
});
});
@@ -88,9 +88,9 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
expect(r).toEqual({ status: 409, body: { error: 'Already in a plan' } }));
});
it('sends an invite', () => {
it('sends an invite', async () => {
const sendInvite = vi.fn().mockReturnValue({});
expect(makeController({ ...planBase, sendInvite }).invite(user, { user_id: 2 })).toEqual({ success: true });
expect(await makeController({ ...planBase, sendInvite }).invite(user, { user_id: 2 })).toEqual({ success: true });
expect(sendInvite).toHaveBeenCalledWith(10, 1, 'u', 'u@example.test', 2);
});
@@ -100,11 +100,11 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
expect(r).toEqual({ status: 404, body: { error: 'Invite not found' } }));
});
it('decline / cancel / dissolve return success', () => {
it('decline / cancel / dissolve return success', async () => {
const declineInvite = vi.fn(); const cancelInvite = vi.fn(); const dissolvePlan = vi.fn();
expect(makeController({ declineInvite }).declineInvite(user, { plan_id: 5 })).toEqual({ success: true });
expect(makeController({ ...planBase, cancelInvite }).cancelInvite(user, { user_id: 2 })).toEqual({ success: true });
expect(makeController({ dissolvePlan }).dissolve(user)).toEqual({ success: true });
expect(await makeController({ declineInvite }).declineInvite(user, { plan_id: 5 })).toEqual({ success: true });
expect(await makeController({ ...planBase, cancelInvite }).cancelInvite(user, { user_id: 2 })).toEqual({ success: true });
expect(await makeController({ dissolvePlan }).dissolve(user)).toEqual({ success: true });
});
});
@@ -116,10 +116,10 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
expect(r).toEqual({ status: 400, body: { error: 'Year required' } }));
});
it('adds and deletes years', () => {
it('adds and deletes years', async () => {
const addYear = vi.fn().mockReturnValue([2026]); const deleteYear = vi.fn().mockReturnValue([]);
expect(makeController({ ...planBase, addYear }).addYear(user, { year: 2026 }, 'sock')).toEqual({ years: [2026] });
expect(makeController({ ...planBase, deleteYear }).deleteYear(user, '2026', 'sock')).toEqual({ years: [] });
expect(await makeController({ ...planBase, addYear }).addYear(user, { year: 2026 }, 'sock')).toEqual({ years: [2026] });
expect(await makeController({ ...planBase, deleteYear }).deleteYear(user, '2026', 'sock')).toEqual({ years: [] });
});
});
@@ -132,15 +132,15 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
expect(r).toEqual({ status: 403, body: { error: 'User not in plan' } }));
});
it('toggles for the caller', () => {
it('toggles for the caller', async () => {
const toggleEntry = vi.fn().mockReturnValue({ action: 'added' });
expect(makeController({ ...planBase, toggleEntry }).toggleEntry(user, { date: '2026-07-01' }, 'sock')).toEqual({ action: 'added' });
expect(await makeController({ ...planBase, toggleEntry }).toggleEntry(user, { date: '2026-07-01' }, 'sock')).toEqual({ action: 'added' });
expect(toggleEntry).toHaveBeenCalledWith(1, 10, '2026-07-01', undefined, undefined, 'sock');
});
it('forwards the half-day fraction (#552)', () => {
it('forwards the half-day fraction (#552)', async () => {
const toggleEntry = vi.fn().mockReturnValue({ action: 'added', fraction: 0.5 });
makeController({ ...planBase, toggleEntry }).toggleEntry(user, { date: '2026-07-01', fraction: 0.5 }, 'sock');
await makeController({ ...planBase, toggleEntry }).toggleEntry(user, { date: '2026-07-01', fraction: 0.5 }, 'sock');
expect(toggleEntry).toHaveBeenCalledWith(1, 10, '2026-07-01', 0.5, undefined, 'sock');
});
@@ -150,30 +150,30 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
expect(r).toEqual({ status: 400, body: { error: 'Weekend days are blocked on this plan' } }));
});
it('forwards the comp/flex leave type (#1074)', () => {
it('forwards the comp/flex leave type (#1074)', async () => {
const toggleEntry = vi.fn().mockReturnValue({ action: 'added', kind: 'comp' });
makeController({ ...planBase, toggleEntry }).toggleEntry(user, { date: '2026-07-01', kind: 'comp' }, 'sock');
await makeController({ ...planBase, toggleEntry }).toggleEntry(user, { date: '2026-07-01', kind: 'comp' }, 'sock');
expect(toggleEntry).toHaveBeenCalledWith(1, 10, '2026-07-01', undefined, 'comp', 'sock');
});
it('GET reads entries over the caller window (#737)', () => {
it('GET reads entries over the caller window (#737)', async () => {
const getEntries = vi.fn().mockReturnValue({ entries: [], companyHolidays: [] });
makeController({ ...planBase, getEntries }).entries(user, '2026');
await makeController({ ...planBase, getEntries }).entries(user, '2026');
expect(getEntries).toHaveBeenCalledWith(10, '2026', 1);
});
});
describe('year settings (#737)', () => {
it('GET wraps the caller settings', () => {
it('GET wraps the caller settings', async () => {
const getYearSettings = vi.fn().mockReturnValue({ year_type: 'calendar' });
expect(makeController({ getYearSettings }).yearSettings(user)).toEqual({ settings: { year_type: 'calendar' } });
expect(await makeController({ getYearSettings }).yearSettings(user)).toEqual({ settings: { year_type: 'calendar' } });
expect(getYearSettings).toHaveBeenCalledWith(1);
});
it('PUT saves for the caller and returns the stored settings', () => {
it('PUT saves for the caller and returns the stored settings', async () => {
const updateYearSettings = vi.fn().mockReturnValue({ year_type: 'fiscal', year_start_month: 7, year_start_day: 1 });
const body = { year_type: 'fiscal' as const, year_start_month: 7, year_start_day: 1 };
expect(makeController({ updateYearSettings }).updateYearSettings(user, body)).toEqual({
expect(await makeController({ updateYearSettings }).updateYearSettings(user, body)).toEqual({
settings: { year_type: 'fiscal', year_start_month: 7, year_start_day: 1 },
});
expect(updateYearSettings).toHaveBeenCalledWith(1, body);
@@ -181,9 +181,9 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
});
describe('stats', () => {
it('GET wraps stats', () => {
it('GET wraps stats', async () => {
const getStats = vi.fn().mockReturnValue({ used: 5 });
expect(makeController({ ...planBase, getStats }).stats(user, '2026')).toEqual({ stats: { used: 5 } });
expect(await makeController({ ...planBase, getStats }).stats(user, '2026')).toEqual({ stats: { used: 5 } });
});
it('403 on updateStats for a user not in the plan', () => {
@@ -213,9 +213,9 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
});
describe('read-only shares', () => {
it('GET /shares delegates listShares', () => {
it('GET /shares delegates listShares', async () => {
const listShares = vi.fn().mockReturnValue({ outgoing: [{ id: 1 }], incoming: [] });
expect(makeController({ listShares }).shares(user)).toEqual({ outgoing: [{ id: 1 }], incoming: [] });
expect(await makeController({ listShares }).shares(user)).toEqual({ outgoing: [{ id: 1 }], incoming: [] });
expect(listShares).toHaveBeenCalledWith(1);
});
@@ -230,27 +230,27 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
expect(r).toEqual({ status: 400, body: { error: 'Already shared' } }));
});
it('shares a calendar (user_id coerced to a number, socket id forwarded)', () => {
it('shares a calendar (user_id coerced to a number, socket id forwarded)', async () => {
const shareCalendar = vi.fn().mockReturnValue({});
expect(makeController({ shareCalendar }).share(user, { user_id: '2' }, 'sock-1')).toEqual({ success: true });
expect(await makeController({ shareCalendar }).share(user, { user_id: '2' }, 'sock-1')).toEqual({ success: true });
expect(shareCalendar).toHaveBeenCalledWith(1, 'u@example.test', 2, 'sock-1');
});
it('GET /shares/available-users wraps the user list', () => {
it('GET /shares/available-users wraps the user list', async () => {
const getShareAvailableUsers = vi.fn().mockReturnValue([{ id: 3 }]);
expect(makeController({ getShareAvailableUsers }).shareAvailableUsers(user)).toEqual({ users: [{ id: 3 }] });
expect(await makeController({ getShareAvailableUsers }).shareAvailableUsers(user)).toEqual({ users: [{ id: 3 }] });
expect(getShareAvailableUsers).toHaveBeenCalledWith(1);
});
it('GET /shares/calendars/:year wraps the calendars', () => {
it('GET /shares/calendars/:year wraps the calendars', async () => {
const getSharedCalendars = vi.fn().mockReturnValue([{ share_id: 4 }]);
expect(makeController({ getSharedCalendars }).sharedCalendars(user, '2026')).toEqual({ calendars: [{ share_id: 4 }] });
expect(await makeController({ getSharedCalendars }).sharedCalendars(user, '2026')).toEqual({ calendars: [{ share_id: 4 }] });
expect(getSharedCalendars).toHaveBeenCalledWith(1, '2026');
});
it('PUT /shares/:id forwards the socket id and the hidden flag', () => {
it('PUT /shares/:id forwards the socket id and the hidden flag', async () => {
const setShareHidden = vi.fn().mockReturnValue(true);
expect(makeController({ setShareHidden }).updateShare(user, '7', { hidden: true }, 'sock-1')).toEqual({ success: true });
expect(await makeController({ setShareHidden }).updateShare(user, '7', { hidden: true }, 'sock-1')).toEqual({ success: true });
expect(setShareHidden).toHaveBeenCalledWith(7, 1, true, 'sock-1');
});
@@ -260,9 +260,9 @@ describe('VacayController (parity with the legacy /api/addons/vacay route)', ()
expect(r).toEqual({ status: 404, body: { error: 'Share not found' } }));
});
it('DELETE /shares/:id forwards the socket id', () => {
it('DELETE /shares/:id forwards the socket id', async () => {
const removeShare = vi.fn().mockReturnValue(true);
expect(makeController({ removeShare }).deleteShare(user, '7', 'sock-1')).toEqual({ success: true });
expect(await makeController({ removeShare }).deleteShare(user, '7', 'sock-1')).toEqual({ success: true });
expect(removeShare).toHaveBeenCalledWith(7, 1, 'sock-1');
});
File diff suppressed because it is too large Load Diff