Skip to content

A local-first personal finance app

Merge commit from fork

Julian Dominguez-Schatz42e9d79d4aab
diff --git a/packages/api/index.browser.ts b/packages/api/index.browser.ts
index feeb7c8a71..bcb6c78500 100644
--- a/packages/api/index.browser.ts
+++ b/packages/api/index.browser.ts
@@ -8,6 +8,7 @@ export * from './methods';
export * as utils from './utils';
let worker: Worker | null = null;
+let ownsSession = false;
export async function init(
config: InitConfig = {},
@@ -16,6 +17,7 @@ export async function init(
try {
await startBackendWorker(worker, config);
+ ownsSession = Boolean(config.serverURL && config.password);
} catch (error) {
worker.terminate();
worker = null;
@@ -35,8 +37,15 @@ export async function shutdown() {
try {
await send('close-budget');
} finally {
- worker.terminate();
- worker = null;
+ try {
+ if (ownsSession) {
+ await send('subscribe-sign-out');
+ }
+ } finally {
+ ownsSession = false;
+ worker.terminate();
+ worker = null;
+ }
}
}
}
diff --git a/packages/api/index.ts b/packages/api/index.ts
index fed097eda1..b7124bc5b2 100644
--- a/packages/api/index.ts
+++ b/packages/api/index.ts
@@ -9,10 +9,13 @@ export * as utils from './utils';
/** @deprecated Please use return value of `init` instead */
export let internal: typeof lib | null = null;
+let ownsSession = false;
+
export async function init(config: InitConfig = {}) {
validateNodeVersion();
internal = await initLootCore(config);
+ ownsSession = Boolean(config.serverURL && config.password);
return internal;
}
@@ -24,7 +27,17 @@ export async function shutdown() {
// most likely that no budget is loaded, so the sync failed
}
- await internal.send('close-budget');
- internal = null;
+ try {
+ await internal.send('close-budget');
+ } finally {
+ try {
+ if (ownsSession) {
+ await internal.send('subscribe-sign-out');
+ }
+ } finally {
+ ownsSession = false;
+ internal = null;
+ }
+ }
}
}
diff --git a/packages/api/session.test.ts b/packages/api/session.test.ts
new file mode 100644
index 0000000000..6f4406cb0b
--- /dev/null
+++ b/packages/api/session.test.ts
@@ -0,0 +1,94 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { createServer } from 'node:http';
+import type { Server } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+import * as api from './index';
+
+let server: Server;
+let serverURL: string;
+let dataDir: string;
+let logouts: unknown[];
+
+beforeEach(async () => {
+ global.IS_TESTING = true;
+ dataDir = await mkdtemp(join(tmpdir(), 'actual-session-'));
+ logouts = [];
+ server = createServer(async (req, res) => {
+ let body = '';
+ for await (const chunk of req) body += chunk;
+ if (req.url === '/account/logout') logouts.push(JSON.parse(body));
+ res.setHeader('Content-Type', 'application/json');
+ res.end(
+ JSON.stringify({
+ status: 'ok',
+ data: req.url === '/account/login' ? { token: 'owned-session' } : {},
+ }),
+ );
+ });
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') {
+ throw new Error('No test server address');
+ }
+ serverURL = `http://127.0.0.1:${address.port}`;
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await api.shutdown();
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ await rm(dataDir, { recursive: true, force: true });
+});
+
+it.each([false, true])(
+ 'revokes the API-created session on shutdown (close failure: %s)',
+ async failClose => {
+ const instance = await api.init({
+ dataDir,
+ serverURL,
+ password: 'password',
+ });
+ if (failClose) {
+ const send = instance.send;
+ vi.spyOn(instance, 'send').mockImplementation((name, args) => {
+ if (name === 'close-budget') {
+ return Promise.reject(new Error('close failed'));
+ }
+ return send(name, args);
+ });
+ await expect(api.shutdown()).rejects.toThrow('close failed');
+ } else {
+ await api.shutdown();
+ }
+ await api.shutdown();
+ expect(logouts).toEqual([{ token: 'owned-session' }]);
+ },
+);
+
+it('does not revoke a caller-supplied token', async () => {
+ await api.init({ dataDir, serverURL, sessionToken: 'borrowed-session' });
+ await api.shutdown();
+ expect(logouts).toEqual([]);
+});
+
+it('revokes the current token on explicit sign-out', async () => {
+ const instance = await api.init({
+ dataDir,
+ serverURL,
+ sessionToken: 'borrowed-session',
+ });
+ await instance.send('subscribe-sign-out');
+ expect(logouts).toEqual([{ token: 'borrowed-session' }]);
+ expect(await instance.send('subscribe-get-user')).toBeNull();
+});
+
+it('clears local credentials when the server is offline', async () => {
+ const instance = await api.init({ dataDir, serverURL, password: 'password' });
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ await expect(instance.send('subscribe-sign-out')).resolves.toBe('ok');
+ expect(await instance.send('subscribe-get-user')).toBeNull();
+});
diff --git a/packages/cli/src/output.test.ts b/packages/cli/src/output.test.ts
index d8d7f77895..30144bfed0 100644
--- a/packages/cli/src/output.test.ts
+++ b/packages/cli/src/output.test.ts
@@ -236,3 +236,34 @@ describe('printOutput', () => {
expect(writeSpy).toHaveBeenCalledWith('\n');
});
});
+
+describe('BOM-prefixed CSV formulas', () => {
+ it.each(['=1+1', '+1+1', '-2+3', '@SUM(1+1)', '\ttext', '\rtext'])(
+ 'neutralizes %j after repeated BOMs in values, headers and scalars',
+ formula => {
+ for (const prefix of ['\uFEFF', '\uFEFF\uFEFF']) {
+ const text = prefix + formula;
+ const expected = formula.includes('\r') ? `"'${text}"` : `'${text}`;
+ expect(formatOutput([{ value: text }], 'csv')).toBe(
+ `value\n${expected}`,
+ );
+ expect(formatOutput({ [text]: 'ordinary' }, 'csv')).toBe(
+ `${expected}\nordinary`,
+ );
+ expect(formatOutput([{ [text]: 'ordinary' }], 'csv')).toBe(
+ `${expected}\nordinary`,
+ );
+ expect(formatOutput(text, 'csv')).toBe(expected);
+ }
+ },
+ );
+
+ it('preserves quoting and Unicode text', () => {
+ expect(formatOutput('\uFEFF=CONCAT("é","日")', 'csv')).toBe(
+ '"\'\uFEFF=CONCAT(""é"",""日"")"',
+ );
+ expect(formatOutput('\uFEFFQuébec', 'csv')).toBe('\uFEFFQuébec');
+ expect(formatOutput(-25, 'csv')).toBe('-25');
+ expect(formatOutput([{ amount: -2500 }], 'csv')).toBe('amount\n-25.00');
+ });
+});
diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts
index 312c5058d7..b478952b96 100644
--- a/packages/cli/src/output.ts
+++ b/packages/cli/src/output.ts
@@ -72,11 +72,11 @@ function formatCsv(data: unknown): string {
if (!Array.isArray(data)) {
if (data && typeof data === 'object') {
const entries = Object.entries(data);
- const header = entries.map(([k]) => escapeCsv(k)).join(',');
+ const header = entries.map(([k]) => formatCsvCell('', k)).join(',');
const values = entries.map(([k, v]) => formatCsvCell(k, v)).join(',');
return header + '\n' + values;
}
- return String(data);
+ return typeof data === 'string' ? formatCsvCell('', data) : String(data);
}
if (data.length === 0) {
@@ -84,7 +84,7 @@ function formatCsv(data: unknown): string {
}
const keys = Object.keys(data[0] as Record<string, unknown>);
- const header = keys.map(k => escapeCsv(k)).join(',');
+ const header = keys.map(k => formatCsvCell('', k)).join(',');
const rows = data.map(row => {
const r = row as Record<string, unknown>;
return keys.map(k => formatCsvCell(k, r[k])).join(',');
@@ -93,7 +93,7 @@ function formatCsv(data: unknown): string {
return [header, ...rows].join('\n');
}
-const FORMULA_TRIGGERS = /^[=+\-@\t\r]/;
+const FORMULA_TRIGGERS = /^\uFEFF*[=+\-@\t\r]/;
function formatCsvCell(key: string, value: unknown): string {
let formatted = formatCellValue(key, value);
diff --git a/packages/desktop-client/src/budgetfiles/budgetfilesSlice.ts b/packages/desktop-client/src/budgetfiles/budgetfilesSlice.ts
index 15ea6c4628..91f0faa737 100644
--- a/packages/desktop-client/src/budgetfiles/budgetfilesSlice.ts
+++ b/packages/desktop-client/src/budgetfiles/budgetfilesSlice.ts
@@ -286,25 +286,30 @@ export const closeAndLoadBudget = createAppAsyncThunk(
type CloseAndDownloadBudgetPayload = {
cloudFileId: string;
+ localId?: string;
};
export const closeAndDownloadBudget = createAppAsyncThunk(
`${sliceName}/closeAndDownloadBudget`,
- async ({ cloudFileId }: CloseAndDownloadBudgetPayload, { dispatch }) => {
+ async (
+ { cloudFileId, localId }: CloseAndDownloadBudgetPayload,
+ { dispatch },
+ ) => {
await dispatch(closeBudget());
- await dispatch(downloadBudget({ cloudFileId, replace: true }));
+ await dispatch(downloadBudget({ cloudFileId, localId, replace: true }));
},
);
type DownloadBudgetPayload = {
cloudFileId: string;
+ localId?: string;
replace?: boolean;
};
export const downloadBudget = createAppAsyncThunk(
`${sliceName}/downloadBudget`,
async (
- { cloudFileId, replace = false }: DownloadBudgetPayload,
+ { cloudFileId, localId, replace = false }: DownloadBudgetPayload,
{ dispatch },
): Promise<string | null> => {
dispatch(
@@ -315,6 +320,7 @@ export const downloadBudget = createAppAsyncThunk(
const { id, error } = await send('download-budget', {
cloudFileId,
+ localId,
});
if (error) {
@@ -328,7 +334,7 @@ export const downloadBudget = createAppAsyncThunk(
),
cloudFileId,
onSuccess: () => {
- void dispatch(downloadBudget({ cloudFileId, replace }));
+ void dispatch(downloadBudget({ cloudFileId, localId, replace }));
},
};
@@ -358,7 +364,7 @@ export const downloadBudget = createAppAsyncThunk(
);
return await dispatch(
- downloadBudget({ cloudFileId, replace: true }),
+ downloadBudget({ cloudFileId, localId, replace: true }),
).unwrap();
} else {
dispatch(setAppState({ loadingText: null }));
diff --git a/packages/desktop-client/src/components/manager/subscribe/ChangePassword.tsx b/packages/desktop-client/src/components/manager/subscribe/ChangePassword.tsx
index 37c78221e3..80120bf70f 100644
--- a/packages/desktop-client/src/components/manager/subscribe/ChangePassword.tsx
+++ b/packages/desktop-client/src/components/manager/subscribe/ChangePassword.tsx
@@ -3,6 +3,7 @@ import React, { useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Button } from '@actual-app/components/button';
+import { BigInput } from '@actual-app/components/input';
import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
@@ -19,9 +20,18 @@ export function ChangePassword() {
const navigate = useNavigate();
const [error, setError] = useState(null);
const [msg, setMessage] = useState(null);
+ const [currentPassword, setCurrentPassword] = useState('');
function getErrorMessage(error) {
switch (error) {
+ case 'invalid-current-password':
+ return t('The current password is incorrect');
+ case 'too-many-requests':
+ return t('Too many attempts. Please try again later.');
+ case 'sign-in-failed':
+ return t(
+ 'Your password was changed, but signing in failed. Please sign in again.',
+ );
case 'invalid-password':
return t('Password cannot be empty');
case 'password-match':
@@ -35,13 +45,22 @@ export function ChangePassword() {
async function onSetPassword(password) {
setError(null);
- const { error } = await send('subscribe-change-password', { password });
+ const { error } = await send('subscribe-change-password', {
+ password,
+ currentPassword,
+ });
if (error) {
setError(error);
} else {
setMessage(t('Password successfully changed'));
- await send('subscribe-sign-in', { password });
+ setCurrentPassword('');
+ const result = await send('subscribe-sign-in', { password });
+ if (result.error) {
+ setMessage(null);
+ setError('sign-in-failed');
+ return;
+ }
void navigate('/');
}
}
@@ -58,7 +77,7 @@ export function ChangePassword() {
>
<Trans>
This will change the password for this server instance. All existing
- sessions will stay logged in.
+ sessions will be signed out.
</Trans>
</Text>
@@ -88,6 +107,16 @@ export function ChangePassword() {
</Text>
)}
+ <BigInput
+ aria-label={t('Current password')}
+ placeholder={t('Current password')}
+ type="password"
+ autoComplete="current-password"
+ value={currentPassword}
+ onChangeValue={setCurrentPassword}
+ style={{ marginTop: 20 }}
+ />
+
<ConfirmPasswordForm
buttons={
<Button
diff --git a/packages/desktop-client/src/components/modals/EnableBankingInitialiseModal.tsx b/packages/desktop-client/src/components/modals/EnableBankingInitialiseModal.tsx
index 8388a39d47..09b0c58fde 100644
--- a/packages/desktop-client/src/components/modals/EnableBankingInitialiseModal.tsx
+++ b/packages/desktop-client/src/components/modals/EnableBankingInitialiseModal.tsx
@@ -11,6 +11,8 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { send } from '@actual-app/core/platform/client/connection';
+import { useAuth } from '#auth/AuthProvider';
+import { Permissions } from '#auth/types';
import { Error as ErrorAlert } from '#components/alerts';
import { Link } from '#components/common/Link';
import {
@@ -32,6 +34,8 @@ export function EnableBankingInitialiseModal({
onSuccess,
}: EnableBankingInitialiseProps) {
const { t } = useTranslation();
+ const { hasPermission } = useAuth();
+ const isAdmin = hasPermission(Permissions.ADMINISTRATOR);
const [applicationId, setApplicationId] = useState('');
const [secretKey, setSecretKey] = useState('');
const [isValid, setIsValid] = useState(true);
@@ -59,6 +63,7 @@ export function EnableBankingInitialiseModal({
}
async function onSubmit(close: () => void) {
+ if (!isAdmin) return;
if (!applicationId || !secretKey) {
setIsValid(false);
setError(
@@ -121,6 +126,13 @@ export function EnableBankingInitialiseModal({
rightContent={<ModalCloseButton onPress={() => state.close()} />}
/>
<View style={{ display: 'flex', gap: 10 }}>
+ {!isAdmin && (
+ <ErrorAlert>
+ <Trans>
+ Only an administrator can configure Enable Banking.
+ </Trans>
+ </ErrorAlert>
+ )}
<Text>
<Trans>
In order to enable bank sync via Enable Banking (for EU banks)
@@ -161,6 +173,7 @@ export function EnableBankingInitialiseModal({
/>
<InitialFocus>
<Input
+ disabled={!isAdmin}
id="application-id-field"
type="text"
value={applicationId}
@@ -178,6 +191,7 @@ export function EnableBankingInitialiseModal({
htmlFor="secret-key-field"
/>
<input
+ disabled={!isAdmin}
id="secret-key-field"
type="file"
accept=".pem,.key"
@@ -209,6 +223,7 @@ export function EnableBankingInitialiseModal({
<ButtonWithLoading
variant="primary"
isLoading={isLoading}
+ isDisabled={!isAdmin}
onPress={() => {
void onSubmit(() => state.close());
}}
diff --git a/packages/desktop-client/src/sync-events.ts b/packages/desktop-client/src/sync-events.ts
index aafe5ed557..e8182ae38c 100644
--- a/packages/desktop-client/src/sync-events.ts
+++ b/packages/desktop-client/src/sync-events.ts
@@ -301,7 +301,7 @@ export function listenForSyncEvent(store: AppStore, queryClient: QueryClient) {
// the server does not match the local one. This can mean a
// few things depending on the state, and we try to show an
// appropriate message and call to action to fix it.
- const { cloudFileId } = store.getState().prefs.local;
+ const { cloudFileId, id: localId } = store.getState().prefs.local;
if (!cloudFileId) {
console.error(
'Received file-has-reset or file-has-new-key error but no cloudFileId in prefs',
@@ -325,7 +325,9 @@ export function listenForSyncEvent(store: AppStore, queryClient: QueryClient) {
button: {
title: t('Revert'),
action: () => {
- void store.dispatch(closeAndDownloadBudget({ cloudFileId }));
+ void store.dispatch(
+ closeAndDownloadBudget({ cloudFileId, localId }),
+ );
},
},
};
diff --git a/packages/desktop-client/src/util/error.ts b/packages/desktop-client/src/util/error.ts
index e09ef1e5b1..3549b4decc 100644
--- a/packages/desktop-client/src/util/error.ts
+++ b/packages/desktop-client/src/util/error.ts
@@ -118,6 +118,10 @@ export function getDownloadError({
return t(
'Downloaded file is invalid, sorry! Visit https://actualbudget.org/contact/ for support.',
);
+ case 'mismatched-cloud-file':
+ return t(
+ 'The selected local budget does not match this cloud file. It has not been replaced.',
+ );
case 'zip-too-large': {
const zipMeta = getUnsafeZipMeta(meta);
if (zipMeta) {
diff --git a/packages/desktop-electron/e2e/navigation-security.test.ts b/packages/desktop-electron/e2e/navigation-security.test.ts
new file mode 100644
index 0000000000..0c7c6ce268
--- /dev/null
+++ b/packages/desktop-electron/e2e/navigation-security.test.ts
@@ -0,0 +1,104 @@
+import { createServer } from 'node:http';
+
+import { expect } from '@playwright/test';
+
+import { test } from './fixtures';
+
+for (const target of ['', '_blank', 'ipc']) {
+ for (const url of [
+ 'https://example.invalid/help',
+ 'http://example.invalid/?next=app://actual',
+ 'https://example.invalid/?next=localhost:3001',
+ ]) {
+ test(`opens ${url} externally via ${target || 'ordinary click'}`, async ({
+ electronApp,
+ electronPage,
+ }) => {
+ const opened = await electronApp.evaluateHandle(({ shell }) => {
+ const urls: string[] = [];
+ // Capture browser handoffs without launching real OS handlers.
+ shell.openExternal = async url => {
+ urls.push(url);
+ };
+ return urls;
+ });
+ await expect(electronPage).toHaveURL('app://actual/config-server');
+ const appUrl = electronPage.url();
+ if (target === 'ipc') {
+ await electronPage.evaluate(
+ url => window.Actual.openURLInBrowser(url),
+ url,
+ );
+ } else {
+ await electronPage.evaluate(
+ ({ url, target }) => {
+ const link = document.createElement('a');
+ link.id = 'external-link';
+ link.href = url;
+ link.target = target;
+ link.textContent = 'Open link';
+ document.body.append(link);
+ },
+ { url, target },
+ );
+ await electronPage
+ .locator('#external-link')
+ .click({ noWaitAfter: true });
+ }
+ await expect.poll(() => opened.jsonValue()).toEqual([url]);
+ expect(electronPage.url()).toBe(appUrl);
+ });
+ }
+}
+
+test('redirects cannot replace the app with an external page', async ({
+ electronApp,
+ electronPage,
+}) => {
+ await expect(electronPage).toHaveURL('app://actual/config-server');
+ const appUrl = electronPage.url();
+ const server = createServer((_req, res) => {
+ res.writeHead(302, { Location: 'https://example.invalid/redirected' });
+ res.end();
+ });
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const address = server.address();
+ if (!address || typeof address === 'string') {
+ throw new Error('Missing port');
+ }
+ // Main-process loadURL bypasses will-navigate, exercising the redirect guard.
+ await electronApp.evaluate(async ({ BrowserWindow }, port) => {
+ try {
+ await BrowserWindow.getAllWindows()[0].loadURL(
+ `http://127.0.0.1:${port}/`,
+ );
+ return null;
+ } catch (error) {
+ return String(error);
+ }
+ }, address.port);
+ expect(electronPage.url()).toBe(appUrl);
+ } finally {
+ await new Promise<void>((resolve, reject) =>
+ server.close(error => (error ? reject(error) : resolve())),
+ );
+ }
+});
+
+test('forwards queued startup logs to the app DevTools console', async ({
+ electronPage,
+}) => {
+ await expect(electronPage).toHaveURL('app://actual/config-server');
+ const messages: string[] = [];
+ const session = await electronPage.context().newCDPSession(electronPage);
+ session.on('Runtime.consoleAPICalled', event => {
+ messages.push(event.args.map(arg => arg.value).join(' '));
+ });
+ // Runtime.enable also reports console messages emitted before attachment.
+ await session.send('Runtime.enable');
+ await expect
+ .poll(() => messages.join('\n'))
+ .toContain('Could not load global state');
+ await session.detach();
+});
diff --git a/packages/desktop-electron/external-links.ts b/packages/desktop-electron/external-links.ts
new file mode 100644
index 0000000000..c195e7c03e
--- /dev/null
+++ b/packages/desktop-electron/external-links.ts
@@ -0,0 +1,37 @@
+import { isAbsolute } from 'node:path';
+
+export async function openExternalUrl(
+ value: unknown,
+ open: (url: string) => Promise<void>,
+): Promise<boolean> {
+ if (typeof value !== 'string') {
+ return false;
+ }
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return false;
+ }
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+ return false;
+ }
+ await open(url.href);
+ return true;
+}
+
+export function revealLocalFile(
+ value: unknown,
+ reveal: (path: string) => void,
+ isAbsolutePath: (path: string) => boolean = isAbsolute,
+): boolean {
+ if (
+ typeof value !== 'string' ||
+ !isAbsolutePath(value) ||
+ value.replace(/\\/g, '/').startsWith('//')
+ ) {
+ return false;
+ }
+ reveal(value);
+ return true;
+}
diff --git a/packages/desktop-electron/index.ts b/packages/desktop-electron/index.ts
index 731d528f63..c402c015fe 100644
--- a/packages/desktop-electron/index.ts
+++ b/packages/desktop-electron/index.ts
@@ -33,9 +33,11 @@ import type {
UtilityProcess,
} from 'electron';
+import { openExternalUrl, revealLocalFile } from './external-links';
import { getMenu } from './menu';
import { retry as promiseRetry } from './retry';
import type { AppInitFailurePayload } from './server';
+import { isInternalUrl } from './trusted-url';
import {
get as getWindowState,
listen as listenToWindowState,
@@ -93,7 +95,7 @@ const logMessage = (loglevel: 'info' | 'error', message: string) => {
const trimmedMessage = JSON.stringify(message.trim()); // ensure line endings are removed
console[loglevel](trimmedMessage);
- if (!clientWin) {
+ if (!clientWin || !isInternalUrl(clientWin.webContents.getURL(), isDev)) {
// queue up the logs until the client window is ready
queuedClientWinLogs.push(`console.${loglevel}(${trimmedMessage})`);
} else {
@@ -572,7 +574,7 @@ async function createWindow() {
win.on('focus', async () => {
if (clientWin) {
const url = clientWin.webContents.getURL();
- if (url.includes('app://') || url.includes('localhost:')) {
+ if (isInternalUrl(url, isDev)) {
void clientWin.webContents.executeJavaScript(
'window.__actionsForMenu.appFocused()',
);
@@ -583,8 +585,8 @@ async function createWindow() {
// hit when middle-clicking buttons or <a href/> with a target set to _blank
// always deny, optionally redirect to browser
win.webContents.setWindowOpenHandler(({ url }) => {
- if (isExternalUrl(url)) {
- void shell.openExternal(url);
+ if (!isInternalUrl(url, isDev)) {
+ void openExternalUrl(url, target => shell.openExternal(target));
}
return { action: 'deny' };
@@ -593,9 +595,8 @@ async function createWindow() {
// hit when clicking <a href/> with no target
// optionally redirect to browser
win.webContents.on('will-navigate', (event, url) => {
- if (isExternalUrl(url)) {
- void shell.openExternal(url);
- event.preventDefault();
+ if (!isInternalUrl(url, isDev)) {
+ void openExternalUrl(url, target => shell.openExternal(target));
}
});
@@ -603,18 +604,17 @@ async function createWindow() {
clientWin = win;
- // Execute queued logs - displaying them in the client window
- void Promise.all(
- queuedClientWinLogs.map((log: string) =>
- win.webContents.executeJavaScript(log),
- ),
- );
-
- queuedClientWinLogs = [];
-}
-
-function isExternalUrl(url: string) {
- return !url.includes('localhost:') && !url.includes('app://');
+ // Wait for an internal page before forwarding queued logs to DevTools.
+ win.webContents.on('did-finish-load', () => {
+ if (!isInternalUrl(win.webContents.getURL(), isDev)) {
+ return;
+ }
+ const logs = queuedClientWinLogs;
+ queuedClientWinLogs = [];
+ for (const log of logs) {
+ void win.webContents.executeJavaScript(log);
+ }
+ });
}
app.setAppUserModelId('com.actualbudget.actual');
@@ -833,11 +833,11 @@ ipcMain.handle(
);
ipcMain.handle('open-external-url', (event, url) => {
- void shell.openExternal(url);
+ void openExternalUrl(url, target => shell.openExternal(target));
});
ipcMain.handle('open-in-file-manager', (event, filepath) => {
- shell.showItemInFolder(filepath);
+ revealLocalFile(filepath, target => shell.showItemInFolder(target));
});
ipcMain.on('message', (_event, msg) => {
diff --git a/packages/desktop-electron/package.json b/packages/desktop-electron/package.json
index 2470805ac1..b9d189da22 100644
--- a/packages/desktop-electron/package.json
+++ b/packages/desktop-electron/package.json
@@ -9,6 +9,7 @@
"update-client": "bin/update-client",
"build": "yarn build:dist && electron-builder",
"build:dist": "tsgo && yarn copy-static-assets",
+ "test": "vitest --run",
"typecheck": "tsgo -b && tsc-strict",
"copy-static-assets": "copyfiles --exclude 'build/**/*' **/*.html icons/**/* build/desktop-electron",
"watch": "yarn build:dist && cross-env ACTUAL_DOCUMENT_DIR=\"../../data\" ACTUAL_DATA_DIR=\"../../data\" electron .",
@@ -29,12 +30,14 @@
"cross-env": "^10.1.0",
"electron": "43.5.0",
"electron-builder": "26.8.1",
- "typescript-strict-plugin": "^2.4.4"
+ "typescript-strict-plugin": "^2.4.4",
+ "vitest": "^5.0.0"
},
"build": {
"appId": "com.actualbudget.actual",
"files": [
"build",
+ "!build/desktop-electron/{tests,vitest.config.*}",
"!node_modules/@actual-app/web",
"node_modules/@actual-app/web/build",
"node_modules/@actual-app/web/package.json",
diff --git a/packages/desktop-electron/security.ts b/packages/desktop-electron/security.ts
index 6bc3e2006e..12019a3ff1 100644
--- a/packages/desktop-electron/security.ts
+++ b/packages/desktop-electron/security.ts
@@ -13,9 +13,8 @@ app.on('web-contents-created', function (event, contents) {
event.preventDefault();
});
- contents.on('will-navigate', event => {
- event.preventDefault();
- });
+ contents.on('will-navigate', event => event.preventDefault());
+ contents.on('will-redirect', event => event.preventDefault());
});
app.on('ready', function () {
diff --git a/packages/desktop-electron/tests/external-links.test.ts b/packages/desktop-electron/tests/external-links.test.ts
new file mode 100644
index 0000000000..92d06fe951
--- /dev/null
+++ b/packages/desktop-electron/tests/external-links.test.ts
@@ -0,0 +1,96 @@
+import assert from 'node:assert/strict';
+import { resolve, win32 } from 'node:path';
+
+import { test } from 'vitest';
+
+import { openExternalUrl, revealLocalFile } from '../external-links';
+
+test('does not invoke OS handlers for unsupported links', async () => {
+ for (const url of [
+ 'custom://handler',
+ 'file:///etc/passwd',
+ ['javascript', 'alert(1)'].join(':'),
+ 'data:text/html,hello',
+ 'mailto:[email protected]',
+ 'ms-msdt:/id',
+ 'not a URL',
+ null,
+ ]) {
+ assert.equal(
+ await openExternalUrl(url, async () =>
+ assert.fail('OS handler must not be invoked'),
+ ),
+ false,
+ );
+ }
+});
+
+test('opens parsed HTTP and HTTPS URLs, including mixed-case schemes', async () => {
+ const opened: string[] = [];
+ for (const url of [
+ 'https://example.com/path?q=one',
+ 'HTTP://example.com/path',
+ 'hTtPs://example.com',
+ ]) {
+ assert.equal(
+ await openExternalUrl(url, async value => {
+ opened.push(value);
+ }),
+ true,
+ );
+ }
+ assert.deepEqual(opened, [
+ 'https://example.com/path?q=one',
+ 'http://example.com/path',
+ 'https://example.com/',
+ ]);
+});
+
+test('rejects network and UNC paths in the separate file-manager action', () => {
+ for (const path of [
+ '//server/share/file',
+ '\\\\server\\share\\file',
+ 'file://server/share/file',
+ 'https://example.com/file',
+ 'relative/file',
+ '/\\server/share/file',
+ String.raw`\\?\UNC\server\share\file`,
+ ]) {
+ assert.equal(
+ revealLocalFile(path, () =>
+ assert.fail('File manager must not be invoked'),
+ ),
+ false,
+ );
+ }
+});
+
+test('preserves local file reveal for native absolute paths', () => {
+ const path = resolve('local-budget', 'metadata.json');
+ const revealed: string[] = [];
+ assert.equal(
+ revealLocalFile(path, value => revealed.push(value)),
+ true,
+ );
+ assert.deepEqual(revealed, [path]);
+});
+
+test('uses Windows path semantics to reject network paths and reveal drive paths', () => {
+ const revealed: string[] = [];
+ for (const path of [
+ String.raw`\\server\share\file`,
+ '//server/share/file',
+ String.raw`\\?\UNC\server\share\file`,
+ ]) {
+ assert.equal(
+ revealLocalFile(path, value => revealed.push(value), win32.isAbsolute),
+ false,
+ );
+ }
+ const local = String.raw`C:\Users\me\receipt.pdf`;
+ assert.equal(
+ revealLocalFile(local, value => revealed.push(value), win32.isAbsolute),
+ true,
+ );
+ assert.deepEqual(revealed, [local]);
+});
diff --git a/packages/desktop-electron/tests/trusted-url.test.ts b/packages/desktop-electron/tests/trusted-url.test.ts
new file mode 100644
index 0000000000..acea8c1c55
--- /dev/null
+++ b/packages/desktop-electron/tests/trusted-url.test.ts
@@ -0,0 +1,30 @@
+import assert from 'node:assert/strict';
+
+import { test } from 'vitest';
+
+import { isInternalUrl } from '../trusted-url';
+
+test('rejects misleading URLs in production and development', () => {
+ for (const url of [
+ 'https://evil.example/?next=app://actual',
+ 'https://evil.example/?next=localhost:3001',
+ 'http://localhost.evil.example:3001',
+ 'http://localhost:3002',
+ 'https://localhost:3001',
+ 'app://evil',
+ 'app://actual.evil',
+ 'app://actual:3001',
+ 'app://user@actual',
+ 'file:///tmp/app.html',
+ 'invalid',
+ ]) {
+ assert.equal(isInternalUrl(url, false), false, url);
+ assert.equal(isInternalUrl(url, true), false, url);
+ }
+});
+
+test('accepts only the app origin and the exact development origin', () => {
+ assert.equal(isInternalUrl('app://actual/budget?tab=one', false), true);
+ assert.equal(isInternalUrl('http://localhost:3001/budget', false), false);
+ assert.equal(isInternalUrl('http://localhost:3001/budget', true), true);
+});
diff --git a/packages/desktop-electron/trusted-url.ts b/packages/desktop-electron/trusted-url.ts
new file mode 100644
index 0000000000..6fa444f751
--- /dev/null
+++ b/packages/desktop-electron/trusted-url.ts
@@ -0,0 +1,14 @@
+export function isInternalUrl(value: string, isDev: boolean): boolean {
+ try {
+ const url = new URL(value);
+ if (url.username || url.password) {
+ return false;
+ }
+ return (
+ (url.protocol === 'app:' && url.hostname === 'actual' && !url.port) ||
+ (isDev && url.origin === 'http://localhost:3001')
+ );
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/desktop-electron/vitest.config.ts b/packages/desktop-electron/vitest.config.ts
new file mode 100644
index 0000000000..dbb45fdcd9
--- /dev/null
+++ b/packages/desktop-electron/vitest.config.ts
@@ -0,0 +1,20 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ include: ['tests/**/*.test.ts'],
+ environment: 'node',
+ reporters: process.env.CI
+ ? [
+ 'default',
+ [
+ 'junit',
+ {
+ outputFile: './test-results/junit.xml',
+ suiteName: 'desktop-electron',
+ },
+ ],
+ ]
+ : ['default'],
+ },
+});
diff --git a/packages/docs/docs/api/reference.md b/packages/docs/docs/api/reference.md
index 5c71c1d127..64c1ab8ee0 100644
--- a/packages/docs/docs/api/reference.md
+++ b/packages/docs/docs/api/reference.md
@@ -856,7 +856,9 @@ Returns a list of all budget files either locally cached or on the remote server
<Method name="loadBudget" args={[{ properties: [{ name: 'syncId', type: 'string' }] }]} returns="Promise<void>" />
-Load a locally cached budget file.
+Load a locally cached budget file using its local `id` from `getBudgets()`. Downloaded budgets receive a local ID that can differ between devices; do not use the Budget ID from another device.
+
+To download and open a budget using its Sync ID, use `downloadBudget()`.
#### `downloadBudget`
diff --git a/packages/docs/docs/troubleshooting/server.md b/packages/docs/docs/troubleshooting/server.md
index 0d3980ec9f..8930d73150 100644
--- a/packages/docs/docs/troubleshooting/server.md
+++ b/packages/docs/docs/troubleshooting/server.md
@@ -5,3 +5,30 @@ Actual uses the standard Node.js `debug` module to optionally log helpful debugg
If your configuration options (set either in the config file or as environment variables) are not being applied, you can enable debug logging by adding an environment variable named `DEBUG` with the value `actual:config`. If you're seeing issues with your HTTPS configuration, you can instead set the value to `actual:config,actual-sensitive:config` to log the actual values of the HTTPS secrets (which are obscured by default so they don't get leaked unintentionally).
It may be useful to compare your configuration file with the configuration schema. The schema can be found at [/packages/sync-server/src/load-config.js](https://github.com/actualbudget/actual/blob/45530638feaacf74c28fddb846ae91170a99d94e/packages/sync-server/src/load-config.js#L43)
+
+## Troubleshooting Sign-In and Bank Connections
+
+Ordinary logs include request paths, response statuses, and short error summaries. Provider messages and full error details are available through the existing sensitive debug logging option when needed for support.
+
+:::caution
+Sensitive logs may contain credentials, bank information, or other private data. They appear in your existing server console or container logs, not in a separate file. Do not post them in public issues or Discord channels. If a maintainer requests them, arrange a private exchange, such as a Discord direct message.
+:::
+
+1. Add the appropriate value below to your server's `DEBUG` environment variable. If `DEBUG` already has a value, append the new value after a comma.
+
+ | Problem | `DEBUG` Value |
+ | --------------------------------- | ------------------------------------------------------------ |
+ | OpenID sign-in | `actual-sensitive:openid` |
+ | Enable Banking connection | `actual-sensitive:enable-banking,actual-sensitive:bank-sync` |
+ | Akahu connection | `actual-sensitive:bank-sync` |
+ | SimpleFIN connection | `actual-sensitive:simplefin,actual-sensitive:bank-sync` |
+ | GoCardless connection | `actual-sensitive:gocardless,actual-sensitive:bank-sync` |
+ | Pluggy connection | `actual-sensitive:pluggy,actual-sensitive:bank-sync` |
+ | Other server errors | `actual-sensitive:server` |
+ | Plugin download through the proxy | `actual-sensitive:cors-proxy` |
+
+2. Restart the server, then repeat the action that failed.
+3. Save the relevant log output for the maintainer helping you.
+4. Restore your previous `DEBUG` setting and restart the server to stop collecting sensitive diagnostics. Turning logging off does not remove the output already collected.
+
+Use the specific namespace needed for the problem. `DEBUG=actual:*` enables ordinary debugging without these sensitive namespaces. Broad patterns such as `DEBUG=*` or `DEBUG=actual*` also enable sensitive output, including the existing configuration-secret logging.
diff --git a/packages/loot-core/src/server/api.ts b/packages/loot-core/src/server/api.ts
index dd819a00a3..00215737ec 100644
--- a/packages/loot-core/src/server/api.ts
+++ b/packages/loot-core/src/server/api.ts
@@ -252,6 +252,7 @@ handlers['api/download-budget'] = async function ({ syncId, password }) {
// Download the remote file (no need to perform a sync as the file will already be up-to-date)
const result = await handlers['download-budget']({
cloudFileId: remoteBudget.fileId,
+ localId: budgets.find(b => b.cloudFileId === remoteBudget.fileId)?.id,
});
if (result.error) {
logger.log('Full error details', result.error);
diff --git a/packages/loot-core/src/server/auth/app.ts b/packages/loot-core/src/server/auth/app.ts
index 28850655ac..1e9f9c75a6 100644
--- a/packages/loot-core/src/server/auth/app.ts
+++ b/packages/loot-core/src/server/auth/app.ts
@@ -204,7 +204,13 @@ async function getUser() {
}
}
-async function changePassword({ password }: { password: string }) {
+async function changePassword({
+ password,
+ currentPassword,
+}: {
+ password: string;
+ currentPassword: string;
+}) {
const userToken = await asyncStorage.getItem('user-token');
if (!userToken) {
return { error: 'not-logged-in' };
@@ -218,6 +224,7 @@ async function changePassword({ password }: { password: string }) {
await post(serverConfig.SIGNUP_SERVER + '/change-password', {
token: userToken,
password,
+ currentPassword,
});
} catch (err) {
if (err instanceof PostError) {
@@ -283,6 +290,17 @@ async function signIn(
}
async function signOut() {
+ const token = await asyncStorage.getItem('user-token');
+ const server = getServer();
+ if (token && server) {
+ try {
+ await post(server.SIGNUP_SERVER + '/logout', { token }, {}, 5000);
+ } catch {
+ // Local sign-out must still work offline or with an older server.
+ logger.log('Could not revoke the server session; signing out locally.');
+ }
+ }
+
encryption.unloadAllKeys();
await asyncStorage.multiRemove([
'user-token',
diff --git a/packages/loot-core/src/server/budgetfiles/app.ts b/packages/loot-core/src/server/budgetfiles/app.ts
index 0acd745ecc..fb68209e42 100644
--- a/packages/loot-core/src/server/budgetfiles/app.ts
+++ b/packages/loot-core/src/server/budgetfiles/app.ts
@@ -183,12 +183,17 @@ async function uploadBudget({ id }: { id?: Budget['id'] } = {}): Promise<{
async function downloadBudget({
cloudFileId,
+ localId,
}: {
cloudFileId: Budget['cloudFileId'];
+ localId?: Budget['id'];
}): Promise<{ id?: Budget['id']; error?: { reason: string; meta?: unknown } }> {
let result;
try {
- result = await cloudStorage.download(cloudFileId);
+ if (localId) {
+ await closeBudget();
+ }
+ result = await cloudStorage.download(cloudFileId, localId);
} catch (e) {
if (e.type === 'FileDownloadError') {
if (e.reason === 'file-exists' && e.meta.id) {
diff --git a/packages/loot-core/src/server/cloud-import.test.ts b/packages/loot-core/src/server/cloud-import.test.ts
new file mode 100644
index 0000000000..c4ffb044ec
--- /dev/null
+++ b/packages/loot-core/src/server/cloud-import.test.ts
@@ -0,0 +1,234 @@
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import * as fs from '#platform/server/fs';
+import * as sqlite from '#platform/server/sqlite';
+import type { ServerHandlers } from '#types/server-handlers';
+
+import { installAPI } from './api';
+import { app as budgetFilesApp } from './budgetfiles/app';
+import { download, importBuffer } from './cloud-storage';
+import * as prefs from './prefs';
+import { safeZip } from './util/zip';
+
+// Install only the handlers used here rather than bootstrapping the whole app.
+vi.mock('#server/main', () => ({ handlers: {} }));
+
+let directory: string;
+let databaseBytes: Buffer;
+
+beforeEach(async () => {
+ vi.spyOn(Date, 'now').mockReturnValue(Date.UTC(2026, 8, 27));
+ directory = mkdtempSync(join(tmpdir(), 'actual-import-'));
+ fs._setDocumentDir(directory);
+ const filename = join(directory, 'source.sqlite');
+ const database = await sqlite.openDatabase(filename);
+ sqlite.execQuery(
+ database,
+ "CREATE TABLE accounts (id TEXT PRIMARY KEY, name TEXT); INSERT INTO accounts VALUES ('account', 'Incoming account')",
+ );
+ sqlite.closeDatabase(database);
+ databaseBytes = readFileSync(filename);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ rmSync(directory, { recursive: true, force: true });
+});
+
+function archive(id: string, prefix = '') {
+ return safeZip({
+ [`${prefix}db.sqlite`]: databaseBytes,
+ [`${prefix}metadata.json`]: Buffer.from(
+ JSON.stringify({ id, budgetName: 'Incoming' }),
+ ),
+ });
+}
+
+async function createLocal(id = 'victim', cloudFileId = 'original-cloud') {
+ const dir = fs.getBudgetDir(id);
+ await fs.mkdir(dir);
+ await fs.writeFile(join(dir, 'db.sqlite'), databaseBytes);
+ const database = await sqlite.openDatabase(join(dir, 'db.sqlite'));
+ sqlite.execQuery(database, "UPDATE accounts SET name = 'Original account'");
+ sqlite.closeDatabase(database);
+ await fs.writeFile(
+ join(dir, 'metadata.json'),
+ JSON.stringify({
+ id,
+ budgetName: 'Original',
+ cloudFileId,
+ groupId: 'old-group',
+ }),
+ );
+ return dir;
+}
+
+it.each(['', 'nested/budget/'])(
+ 'imports cloud archives to fresh IDs and preserves colliding local files (%s)',
+ async prefix => {
+ const victim = await createLocal();
+ const original = readFileSync(join(victim, 'metadata.json'));
+ const originalDb = readFileSync(join(victim, 'db.sqlite'));
+ const { id } = await importBuffer(
+ { fileId: 'incoming-cloud', groupId: 'group' },
+ archive('victim', prefix),
+ );
+ expect(id).not.toBe('victim');
+ expect(readFileSync(join(victim, 'metadata.json'))).toEqual(original);
+ expect(readFileSync(join(victim, 'db.sqlite'))).toEqual(originalDb);
+ expect(
+ JSON.parse(
+ readFileSync(join(fs.getBudgetDir(id), 'metadata.json'), 'utf8'),
+ ),
+ ).toMatchObject({ id, cloudFileId: 'incoming-cloud' });
+ },
+);
+
+it('ignores IDs from local archive imports, including path-like IDs', async () => {
+ const { id } = await importBuffer(
+ { fileId: null, groupId: null },
+ archive('../../outside'),
+ );
+ expect(id).not.toBe('../../outside');
+ expect(
+ JSON.parse(
+ readFileSync(join(fs.getBudgetDir(id), 'metadata.json'), 'utf8'),
+ ),
+ ).toMatchObject({ id, cloudFileId: null });
+});
+
+it('rejects replacement of a budget associated with another cloud file', async () => {
+ const victim = await createLocal();
+ const original = readFileSync(join(victim, 'metadata.json'));
+ const originalDb = readFileSync(join(victim, 'db.sqlite'));
+ await expect(
+ importBuffer({ fileId: 'incoming-cloud' }, archive('victim'), 'victim'),
+ ).rejects.toMatchObject({ reason: 'mismatched-cloud-file' });
+ expect(readFileSync(join(victim, 'metadata.json'))).toEqual(original);
+ expect(readFileSync(join(victim, 'db.sqlite'))).toEqual(originalDb);
+});
+
+it('replaces the selected budget after a sync ID reset and retains existing backups', async () => {
+ const dir = await createLocal('selected', 'incoming-cloud');
+ await fs.mkdir(join(dir, 'backups'));
+ await fs.writeFile(join(dir, 'backups', 'existing.zip'), 'existing backup');
+ expect(
+ await importBuffer(
+ { fileId: 'incoming-cloud', groupId: 'new-group' },
+ archive('untrusted-archive-id'),
+ 'selected',
+ ),
+ ).toEqual({ id: 'selected' });
+ expect(
+ JSON.parse(readFileSync(join(dir, 'metadata.json'), 'utf8')),
+ ).toMatchObject({
+ id: 'selected',
+ budgetName: 'Incoming',
+ cloudFileId: 'incoming-cloud',
+ groupId: 'new-group',
+ });
+ expect(readFileSync(join(dir, 'db.sqlite'))).toEqual(databaseBytes);
+ expect(readFileSync(join(dir, 'backups', 'existing.zip'), 'utf8')).toBe(
+ 'existing backup',
+ );
+});
+
+it('does not combine files from different archive directories', async () => {
+ const buffer = safeZip({
+ 'one/db.sqlite': databaseBytes,
+ 'two/metadata.json': Buffer.from(
+ JSON.stringify({ id: 'victim', budgetName: 'Invalid' }),
+ ),
+ });
+ await expect(importBuffer({ fileId: 'cloud' }, buffer)).rejects.toMatchObject(
+ { reason: 'invalid-zip-file' },
+ );
+});
+
+it('rejects cloud metadata describing a different file than the one requested', async () => {
+ const before = await fs.listDir(directory);
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async url =>
+ String(url).endsWith('/get-user-file-info')
+ ? new Response(
+ JSON.stringify({ status: 'ok', data: { fileId: 'other-file' } }),
+ )
+ : new Response(new Uint8Array(archive('victim'))),
+ ),
+ );
+ await expect(download('requested-file')).rejects.toMatchObject({
+ reason: 'mismatched-cloud-file',
+ });
+ expect(await fs.listDir(directory)).toEqual(before);
+});
+
+it.each([
+ {},
+ {
+ id: 'victim',
+ cloudFileId: 'obsolete-cloud',
+ groupId: 'obsolete-group',
+ encryptKeyId: 'obsolete-key',
+ },
+])(
+ 'imports a recovery archive with missing optional metadata or obsolete IDs (%j)',
+ async metadata => {
+ const victim = await createLocal();
+ const original = readFileSync(join(victim, 'metadata.json'));
+ const originalDb = readFileSync(join(victim, 'db.sqlite'));
+ const buffer = safeZip({
+ 'db.sqlite': databaseBytes,
+ 'metadata.json': Buffer.from(JSON.stringify(metadata)),
+ });
+ // Use the same detached import context as the local .actual importer.
+ const { id } = await importBuffer(
+ { cloudFileId: null, groupId: null },
+ buffer,
+ );
+ expect(id).not.toBe('victim');
+ expect(readFileSync(join(victim, 'metadata.json'))).toEqual(original);
+ expect(readFileSync(join(victim, 'db.sqlite'))).toEqual(originalDb);
+ expect(readFileSync(join(fs.getBudgetDir(id), 'db.sqlite'))).toEqual(
+ databaseBytes,
+ );
+ const imported = JSON.parse(
+ readFileSync(join(fs.getBudgetDir(id), 'metadata.json'), 'utf8'),
+ );
+ expect(imported).toMatchObject({ id, groupId: null, encryptKeyId: null });
+ expect(imported.cloudFileId).toBeUndefined();
+ },
+);
+
+it.each(['original-cloud', 'different-cloud'])(
+ 'API downloads after a sync reset replace only a matching cloud file (%s)',
+ async fileId => {
+ prefs.unloadPrefs();
+ await createLocal();
+ const remote = { fileId, groupId: 'new-group' };
+ const loadBudget = vi.fn().mockResolvedValue({});
+ const handlers = Object.assign(installAPI({} as ServerHandlers), {
+ ...budgetFilesApp.handlers,
+ 'get-remote-files': async () => [remote],
+ 'download-budget': async ({ localId }: { localId?: string }) =>
+ importBuffer(remote, archive('victim'), localId),
+ 'load-budget': loadBudget,
+ });
+
+ await handlers['api/download-budget']({ syncId: 'new-group' });
+
+ const budgets = await budgetFilesApp.handlers['get-budgets']();
+ const downloaded = budgets.find(b => b.groupId === 'new-group');
+ expect(downloaded?.cloudFileId).toBe(fileId);
+ expect(budgets).toHaveLength(fileId === 'original-cloud' ? 1 : 2);
+ if (fileId === 'original-cloud') {
+ expect(downloaded?.id).toBe('victim');
+ } else {
+ expect(downloaded?.id).not.toBe('victim');
+ }
+ expect(loadBudget).toHaveBeenCalledWith({ id: downloaded?.id });
+ },
+);
diff --git a/packages/loot-core/src/server/cloud-storage.ts b/packages/loot-core/src/server/cloud-storage.ts
index 0e1c375742..f6c6dde516 100644
--- a/packages/loot-core/src/server/cloud-storage.ts
+++ b/packages/loot-core/src/server/cloud-storage.ts
@@ -209,7 +209,7 @@ export async function exportBuffer() {
return { data: Buffer.from(zipped), warnings };
}
-export async function importBuffer(fileData, buffer) {
+export async function importBuffer(fileData, buffer, localId?: string) {
let entries;
try {
entries = safeUnzip(buffer);
@@ -253,18 +253,27 @@ export async function importBuffer(fileData, buffer) {
throw FileDownloadError('invalid-meta-file');
}
- // Update the metadata. The stored file on the server might be
- // out-of-date with a few keys
+ // Only local selection can authorize replacement. Archive IDs are never
+ // used as destinations, including for archives imported from disk.
+ const id = localId || uuidv4();
+ if (localId) {
+ const localMeta = JSON.parse(
+ await fs.readFile(fs.join(fs.getBudgetDir(id), 'metadata.json')),
+ );
+ if (!fileData.fileId || localMeta.cloudFileId !== fileData.fileId) {
+ throw FileDownloadError('mismatched-cloud-file');
+ }
+ }
+
meta = {
...meta,
+ id,
cloudFileId: fileData.fileId,
groupId: fileData.groupId,
lastUploaded: monthUtils.currentDay(),
encryptKeyId: fileData.encryptMeta ? fileData.encryptMeta.keyId : null,
};
-
- const budgetDir = fs.getBudgetDir(meta.id);
-
+ const budgetDir = fs.getBudgetDir(id);
if (await fs.exists(budgetDir)) {
// Don't remove the directory so that backups are retained
const dbFile = fs.join(budgetDir, 'db.sqlite');
@@ -441,7 +450,7 @@ export async function listRemoteFiles(): Promise<RemoteFile[]> {
.filter(Boolean);
}
-export async function download(cloudFileId) {
+export async function download(cloudFileId, localId?: string) {
const userToken = await asyncStorage.getItem('user-token');
const syncServer = getServer().SYNC_SERVER;
@@ -487,6 +496,9 @@ export async function download(cloudFileId) {
}
const fileData = userFileInfoRes.data;
+ if (fileData.fileId !== cloudFileId) {
+ throw FileDownloadError('mismatched-cloud-file');
+ }
let buffer = userFileRes;
// The download process checks if the server gave us decrypt
@@ -502,5 +514,5 @@ export async function download(cloudFileId) {
}
}
- return importBuffer(fileData, buffer);
+ return importBuffer(fileData, buffer, localId);
}
diff --git a/packages/loot-core/src/shared/errors.ts b/packages/loot-core/src/shared/errors.ts
index 7e9d45f0eb..219365c182 100644
--- a/packages/loot-core/src/shared/errors.ts
+++ b/packages/loot-core/src/shared/errors.ts
@@ -108,6 +108,8 @@ export function getDownloadError({
case 'invalid-zip-file':
case 'invalid-meta-file':
return 'Downloaded file is invalid, sorry! Visit https://actualbudget.org/contact/ for support.';
+ case 'mismatched-cloud-file':
+ return 'The selected local budget does not match this cloud file. It has not been replaced.';
case 'zip-too-large': {
const zipMeta = getUnsafeZipMeta(meta);
if (zipMeta) {
diff --git a/packages/sync-server/src/accounts/openid.test.ts b/packages/sync-server/src/accounts/openid.test.ts
new file mode 100644
index 0000000000..62588df11e
--- /dev/null
+++ b/packages/sync-server/src/accounts/openid.test.ts
@@ -0,0 +1,93 @@
+import { format } from 'node:util';
+
+import createDebug from 'debug';
+import type * as OpenIdClient from 'openid-client';
+
+import { getAccountDb } from '#account-db';
+
+import { loginWithOpenIdFinalize, loginWithOpenIdSetup } from './openid';
+
+const provider = vi.hoisted(() => ({
+ callback: vi.fn(),
+ userinfo: vi.fn(),
+}));
+
+vi.mock('openid-client', async importOriginal => {
+ const actual = await importOriginal<typeof OpenIdClient>();
+ class Client {
+ redirect_uris = ['https://actual.example/openid/callback'];
+ callback = provider.callback;
+ userinfo = provider.userinfo;
+ authorizationUrl(params: Record<string, string>) {
+ return `https://identity.example/authorize?${new URLSearchParams(params).toString()}`;
+ }
+ }
+ return { ...actual, Issuer: { discover: async () => ({ Client }) } };
+});
+
+beforeEach(() => {
+ getAccountDb().mutate("DELETE FROM sessions WHERE auth_method = 'openid'");
+ getAccountDb().mutate(
+ 'INSERT INTO auth (method, active, extra_data) VALUES (?, 1, ?)',
+ [
+ 'openid',
+ JSON.stringify({
+ issuer: 'https://identity.example',
+ client_id: 'client',
+ client_secret: 'secret',
+ server_hostname: 'https://actual.example',
+ }),
+ ],
+ );
+ provider.callback.mockReset().mockResolvedValue({
+ access_token: 'provider-token',
+ claims: () => ({ iss: 'https://identity.example', sub: 'fixed-id' }),
+ });
+ provider.userinfo.mockReset().mockResolvedValue({
+ sub: 'fixed-id',
+ preferred_username: 'renamed-admin',
+ });
+});
+
+afterEach(() => {
+ const db = getAccountDb();
+ db.mutate("DELETE FROM auth WHERE method = 'openid'");
+ db.mutate('DELETE FROM pending_openid_requests');
+ db.mutate("DELETE FROM sessions WHERE auth_method = 'openid'");
+});
+
+it.each(['', 'actual:*', 'actual-sensitive:openid'])(
+ 'keeps provider details behind the sensitive namespace (%s)',
+ async namespaces => {
+ const previous = createDebug.disable();
+ createDebug.enable(namespaces);
+ const debugLog = vi
+ .spyOn(createDebug, 'log')
+ .mockImplementation(() => undefined);
+ const secret = 'private-provider-code-and-token';
+ const start = await loginWithOpenIdSetup('https://actual.example');
+ const state = new URL(start.url ?? '').searchParams.get('state');
+ provider.callback.mockRejectedValue(new Error(secret));
+ const log = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ try {
+ const result = await loginWithOpenIdFinalize({ code: secret, state });
+ expect(result.error).toBeTruthy();
+ expect(log).toHaveBeenCalled();
+ expect(JSON.stringify(log.mock.calls)).not.toContain(secret);
+ const details = debugLog.mock.calls
+ .map(args => format(...args))
+ .join('\n');
+ expect(details.includes(secret)).toBe(
+ namespaces === 'actual-sensitive:openid',
+ );
+ if (namespaces === 'actual-sensitive:openid') {
+ expect(details).toContain('Error:');
+ expect(details).toContain('openid.test.ts:');
+ }
+ } finally {
+ log.mockRestore();
+ debugLog.mockRestore();
+ createDebug.enable(previous);
+ }
+ },
+);
diff --git a/packages/sync-server/src/accounts/openid.ts b/packages/sync-server/src/accounts/openid.ts
index 3d26e82bef..14a0ecc597 100644
--- a/packages/sync-server/src/accounts/openid.ts
+++ b/packages/sync-server/src/accounts/openid.ts
@@ -1,4 +1,5 @@
// @ts-strict-ignore
+import createDebug from 'debug';
import { custom, generators, Issuer } from 'openid-client';
import { v4 as uuidv4 } from 'uuid';
@@ -24,6 +25,8 @@ export type ConfigParameter = {
server_hostname?: string;
};
+const debugSensitive = createDebug('actual-sensitive:openid');
+
export async function bootstrapOpenId(configParameter: ConfigParameter) {
if (!('issuer' in configParameter) && !('discoveryURL' in configParameter)) {
return { error: 'missing-issuer-or-discoveryURL' };
@@ -51,8 +54,9 @@ export async function bootstrapOpenId(configParameter: ConfigParameter) {
}
await setupOpenIdClient(configParameter);
- } catch (err) {
- console.error('Error setting up OpenID client:', err);
+ } catch (error) {
+ console.error('Error setting up OpenID client');
+ debugSensitive('Error setting up OpenID client: %O', error);
return { error: 'configuration-error' };
}
@@ -66,8 +70,9 @@ export async function bootstrapOpenId(configParameter: ConfigParameter) {
[JSON.stringify(configParameter)],
);
});
- } catch (err) {
- console.error('Error updating auth table:', err);
+ } catch (error) {
+ console.error('Error updating auth table');
+ debugSensitive('Error updating auth table: %O', error);
return { error: 'database-error' };
}
@@ -135,16 +140,18 @@ export async function loginWithOpenIdSetup(
try {
config = JSON.parse(config['extra_data']);
- } catch (err) {
- console.error('Error parsing OpenID configuration:', err);
+ } catch (error) {
+ console.error('Error parsing OpenID configuration');
+ debugSensitive('Error parsing OpenID configuration: %O', error);
return { error: 'openid-setup-failed' };
}
let client;
try {
client = await setupOpenIdClient(config);
- } catch (err) {
- console.error('Error setting up OpenID client:', err);
+ } catch (error) {
+ console.error('Error setting up OpenID client');
+ debugSensitive('Error setting up OpenID client: %O', error);
return { error: 'openid-setup-failed' };
}
@@ -192,15 +199,17 @@ export async function loginWithOpenIdFinalize(body) {
}
try {
configFromDb = JSON.parse(configFromDb['extra_data']);
- } catch (err) {
- console.error('Error parsing OpenID configuration:', err);
+ } catch (error) {
+ console.error('Error parsing OpenID configuration');
+ debugSensitive('Error parsing OpenID configuration: %O', error);
return { error: 'openid-setup-failed' };
}
let client;
try {
client = await setupOpenIdClient(configFromDb);
- } catch (err) {
- console.error('Error setting up OpenID client:', err);
+ } catch (error) {
+ console.error('Error setting up OpenID client');
+ debugSensitive('Error setting up OpenID client: %O', error);
return { error: 'openid-setup-failed' };
}
@@ -334,8 +343,9 @@ export async function loginWithOpenIdFinalize(body) {
clearExpiredSessions();
return { url: `${return_url}/openid-cb?token=${token}` };
- } catch (err) {
- console.error('OpenID grant failed:', err);
+ } catch (error) {
+ console.error('OpenID grant failed');
+ debugSensitive('OpenID grant failed: %O', error);
return { error: 'openid-grant-failed' };
}
}
@@ -350,7 +360,8 @@ export function getServerHostname() {
const openIdConfig = JSON.parse(auth.extra_data);
return openIdConfig.server_hostname;
} catch (error) {
- console.error('Error parsing OpenID configuration:', error);
+ console.error('Error parsing OpenID configuration');
+ debugSensitive('Error parsing OpenID configuration: %O', error);
}
}
return null;
diff --git a/packages/sync-server/src/accounts/password.js b/packages/sync-server/src/accounts/password.js
index 9c3573cf8d..ea66a77554 100644
--- a/packages/sync-server/src/accounts/password.js
+++ b/packages/sync-server/src/accounts/password.js
@@ -15,15 +15,18 @@ const ARGON2_OPTIONS = {
};
export function isValidPassword(password) {
- return password != null && password !== '';
+ return typeof password === 'string' && password.length > 0;
}
export function hashPassword(password) {
+ if (!isValidPassword(password)) {
+ throw new TypeError('invalid-password');
+ }
return argon2.hash(password, ARGON2_OPTIONS);
}
export async function verifyPassword(password, hash) {
- if (typeof hash !== 'string') return false;
+ if (!isValidPassword(password) || typeof hash !== 'string') return false;
if (hash.startsWith('$argon2')) {
try {
@@ -88,87 +91,106 @@ export async function loginWithPassword(password) {
return { error: 'invalid-password' };
}
- if (isLegacyHash(passwordHash)) {
- const rehashed = await hashPassword(password);
- accountDb.mutate(
- "UPDATE auth SET extra_data = ? WHERE method = 'password' AND extra_data = ?",
- [rehashed, passwordHash],
- );
- }
-
- const sessionRow = accountDb.first(
- 'SELECT * FROM sessions WHERE auth_method = ?',
- ['password'],
- );
-
- const token = sessionRow ? sessionRow.token : uuidv4();
+ const rehashed = isLegacyHash(passwordHash)
+ ? await hashPassword(password)
+ : null;
- const { totalOfUsers } = accountDb.first(
- 'SELECT count(*) as totalOfUsers FROM users',
- );
- let userId = null;
- if (totalOfUsers === 0) {
- userId = uuidv4();
- accountDb.mutate(
- 'INSERT INTO users (id, user_name, display_name, enabled, owner, role) VALUES (?, ?, ?, 1, 1, ?)',
- [userId, '', '', 'ADMIN'],
+ return accountDb.transaction(() => {
+ // Password verification yields to other requests. A reset must also
+ // invalidate logins that were still verifying the previous password.
+ const currentAuth = accountDb.first(
+ "SELECT extra_data FROM auth WHERE method = 'password'",
);
- } else {
- const { id: userIdFromDb } = accountDb.first(
- 'SELECT id FROM users WHERE user_name = ?',
- [''],
- );
-
- userId = userIdFromDb;
-
- if (!userId) {
- return { error: 'user-not-found' };
+ if (currentAuth?.extra_data !== passwordHash) {
+ return { error: 'invalid-password' };
+ }
+ if (rehashed) {
+ accountDb.mutate(
+ "UPDATE auth SET extra_data = ? WHERE method = 'password'",
+ [rehashed],
+ );
}
- }
- let expiration = TOKEN_EXPIRATION_NEVER;
- if (
- config.get('token_expiration') !== 'never' &&
- config.get('token_expiration') !== 'openid-provider' &&
- typeof config.get('token_expiration') === 'number'
- ) {
- expiration =
- Math.floor(Date.now() / 1000) + config.get('token_expiration') * 60;
- }
+ const { totalOfUsers } = accountDb.first(
+ 'SELECT count(*) as totalOfUsers FROM users',
+ );
+ let userId = null;
+ if (totalOfUsers === 0) {
+ userId = uuidv4();
+ accountDb.mutate(
+ 'INSERT INTO users (id, user_name, display_name, enabled, owner, role) VALUES (?, ?, ?, 1, 1, ?)',
+ [userId, '', '', 'ADMIN'],
+ );
+ } else {
+ const { id: userIdFromDb } = accountDb.first(
+ 'SELECT id FROM users WHERE user_name = ?',
+ [''],
+ );
+
+ userId = userIdFromDb;
+
+ if (!userId) {
+ return { error: 'user-not-found' };
+ }
+ }
- if (!sessionRow) {
+ let expiration = TOKEN_EXPIRATION_NEVER;
+ if (
+ config.get('token_expiration') !== 'never' &&
+ config.get('token_expiration') !== 'openid-provider' &&
+ typeof config.get('token_expiration') === 'number'
+ ) {
+ expiration =
+ Math.floor(Date.now() / 1000) + config.get('token_expiration') * 60;
+ }
+ const token = uuidv4();
accountDb.mutate(
'INSERT INTO sessions (token, expires_at, user_id, auth_method) VALUES (?, ?, ?, ?)',
[token, expiration, userId, 'password'],
);
- } else {
- accountDb.mutate(
- 'UPDATE sessions SET user_id = ?, expires_at = ? WHERE token = ?',
- [userId, expiration, token],
- );
- }
-
- clearExpiredSessions();
-
- return { token };
+ clearExpiredSessions();
+ return { token };
+ });
}
-export async function changePassword(newPassword) {
+export async function changePassword(newPassword, currentPassword) {
const accountDb = getAccountDb();
if (!isValidPassword(newPassword)) {
return { error: 'invalid-password' };
}
- const hashed = await hashPassword(newPassword);
- const result = accountDb.mutate(
- "UPDATE auth SET extra_data = ? WHERE method = 'password'",
- [hashed],
+ const auth = accountDb.first(
+ "SELECT extra_data FROM auth WHERE method = 'password'",
);
- if (result.changes === 0) {
+ if (!auth) {
return { error: 'no-password-method' };
}
- return {};
+ if (
+ currentPassword !== undefined &&
+ !(await verifyPassword(currentPassword, auth.extra_data))
+ ) {
+ return { error: 'invalid-current-password' };
+ }
+ const hashed = await hashPassword(newPassword);
+ return accountDb.transaction(() => {
+ if (
+ currentPassword !== undefined &&
+ accountDb.first("SELECT extra_data FROM auth WHERE method = 'password'")
+ ?.extra_data !== auth.extra_data
+ ) {
+ return { error: 'invalid-current-password' };
+ }
+ const result = accountDb.mutate(
+ "UPDATE auth SET extra_data = ? WHERE method = 'password'",
+ [hashed],
+ );
+ if (result.changes === 0) {
+ return { error: 'no-password-method' };
+ }
+ accountDb.mutate("DELETE FROM sessions WHERE auth_method = 'password'");
+ return {};
+ });
}
export async function checkPassword(password) {
diff --git a/packages/sync-server/src/accounts/password.test.js b/packages/sync-server/src/accounts/password.test.js
index 4c895c4e6b..d61ad903be 100644
--- a/packages/sync-server/src/accounts/password.test.js
+++ b/packages/sync-server/src/accounts/password.test.js
@@ -1,6 +1,7 @@
+import * as argon2 from 'argon2';
import * as bcrypt from 'bcrypt';
-import { getAccountDb } from '#account-db';
+import { bootstrap, getAccountDb } from '#account-db';
import {
bootstrapPassword,
@@ -13,6 +14,8 @@ import {
verifyPassword,
} from './password';
+vi.mock('argon2', { spy: true });
+
const FALLBACK_OWNER_ID = 'password-test-owner';
function getStoredPasswordHash() {
@@ -59,6 +62,48 @@ afterEach(() => {
});
describe('isValidPassword', () => {
+ it.each(
+ [null, undefined, '', {}, { length: 1000000000 }, [], 123, true].map(
+ value => [value],
+ ),
+ )(
+ 'rejects invalid input without passing it to a password hasher: %j',
+ async password => {
+ const hash = vi.spyOn(argon2, 'hash');
+ const verify = vi.spyOn(argon2, 'verify');
+ try {
+ expect(isValidPassword(password)).toBe(false);
+ expect(() => hashPassword(password)).toThrow('invalid-password');
+ expect(await verifyPassword(password, '$argon2id$test')).toBe(false);
+ expect(await bootstrap({ password })).toEqual({
+ error: 'invalid-password',
+ });
+ expect(hash).not.toHaveBeenCalled();
+ expect(verify).not.toHaveBeenCalled();
+ } finally {
+ hash.mockRestore();
+ verify.mockRestore();
+ }
+ },
+ );
+
+ it('rejects invalid passwords without hashing on a configured server', async () => {
+ await bootstrapPassword('existing password');
+ const hash = vi.spyOn(argon2, 'hash');
+ hash.mockClear();
+ try {
+ for (const password of [{}, { length: 1000000000 }, [], 123, null, '']) {
+ expect(await bootstrap({ password })).toEqual({
+ error: 'invalid-password',
+ });
+ }
+ expect(hash).not.toHaveBeenCalled();
+ expect(await checkPassword('existing password')).toBe(true);
+ } finally {
+ hash.mockRestore();
+ }
+ });
+
it('rejects null, undefined and empty passwords', () => {
expect(isValidPassword(null)).toBe(false);
expect(isValidPassword(undefined)).toBe(false);
@@ -200,3 +245,73 @@ describe('checkPassword', () => {
expect(await checkPassword('anything')).toBe(false);
});
});
+
+describe('password session revocation', () => {
+ it('issues distinct sessions and revokes both when the password changes', async () => {
+ await bootstrapPassword('old password');
+ const first = await loginWithPassword('old password');
+ const second = await loginWithPassword('old password');
+ expect(first.token).not.toBe(second.token);
+ expect(first.token).toBeTruthy();
+ expect(second.token).toBeTruthy();
+
+ await changePassword('new password');
+ for (const token of [first.token, second.token]) {
+ expect(
+ getAccountDb().first('SELECT token FROM sessions WHERE token = ?', [
+ token,
+ ]),
+ ).toBeNull();
+ }
+ expect(await loginWithPassword('old password')).toEqual({
+ error: 'invalid-password',
+ });
+ const fresh = await loginWithPassword('new password');
+ expect(fresh.token).toBeTruthy();
+ expect([first.token, second.token]).not.toContain(fresh.token);
+ });
+
+ it('rolls back the password update if session revocation fails', async () => {
+ await bootstrapPassword('old password');
+ const { token } = await loginWithPassword('old password');
+ const db = getAccountDb();
+ db.exec(
+ "CREATE TEMP TRIGGER fail_password_revocation BEFORE DELETE ON sessions WHEN OLD.auth_method = 'password' BEGIN SELECT RAISE(ABORT, 'revocation failed'); END",
+ );
+ try {
+ await expect(changePassword('new password')).rejects.toThrow(
+ 'revocation failed',
+ );
+ expect(await checkPassword('old password')).toBe(true);
+ expect(
+ db.first('SELECT token FROM sessions WHERE token = ?', [token]),
+ ).not.toBeNull();
+ } finally {
+ db.exec('DROP TRIGGER fail_password_revocation');
+ }
+ });
+
+ it('does not issue a session if the password changes during verification', async () => {
+ await bootstrapPassword('old password');
+ let finishVerification;
+ const verify = vi.spyOn(argon2, 'verify').mockImplementationOnce(
+ () =>
+ new Promise(resolve => {
+ finishVerification = resolve;
+ }),
+ );
+ try {
+ const pendingLogin = loginWithPassword('old password');
+ await changePassword('new password');
+ finishVerification(true);
+ expect(await pendingLogin).toEqual({ error: 'invalid-password' });
+ expect(
+ getAccountDb().all(
+ "SELECT token FROM sessions WHERE auth_method = 'password'",
+ ),
+ ).toEqual([]);
+ } finally {
+ verify.mockRestore();
+ }
+ });
+});
diff --git a/packages/sync-server/src/app-account.js b/packages/sync-server/src/app-account.js
index 34b00d6637..00591781b7 100644
--- a/packages/sync-server/src/app-account.js
+++ b/packages/sync-server/src/app-account.js
@@ -3,6 +3,7 @@ import rateLimit from 'express-rate-limit';
import {
bootstrap,
+ getAccountDb,
getActiveLoginMethod,
getLoginMethod,
getServerPrefs,
@@ -13,7 +14,11 @@ import {
setServerPrefs,
} from './account-db';
import { isValidRedirectUrl, loginWithOpenIdSetup } from './accounts/openid';
-import { changePassword, loginWithPassword } from './accounts/password';
+import {
+ changePassword,
+ isValidPassword,
+ loginWithPassword,
+} from './accounts/password';
import { errorMiddleware, requestLoggerMiddleware } from './util/middlewares';
import { validateAuthHeader, validateSession } from './util/validate-user';
@@ -128,7 +133,17 @@ app.post('/login', authRateLimiter, async (req, res) => {
res.send({ status: 'ok', data: { token } });
});
-app.post('/change-password', async (req, res) => {
+app.post('/logout', (req, res) => {
+ const token = req.body?.token;
+ if (typeof token !== 'string' || !token) {
+ res.status(400).send({ status: 'error', reason: 'invalid-token' });
+ return;
+ }
+ getAccountDb().mutate('DELETE FROM sessions WHERE token = ?', [token]);
+ res.send({ status: 'ok', data: {} });
+});
+
+app.post('/change-password', authRateLimiter, async (req, res) => {
const session = validateSession(req, res);
if (!session) return;
@@ -150,7 +165,17 @@ app.post('/change-password', async (req, res) => {
return;
}
- const { error } = await changePassword(req.body.password);
+ if (!isValidPassword(req.body.currentPassword)) {
+ res
+ .status(400)
+ .send({ status: 'error', reason: 'invalid-current-password' });
+ return;
+ }
+
+ const { error } = await changePassword(
+ req.body.password,
+ req.body.currentPassword,
+ );
if (error) {
res.status(400).send({ status: 'error', reason: error });
diff --git a/packages/sync-server/src/app-account.test.js b/packages/sync-server/src/app-account.test.js
index ac22d7f5f5..625779e62d 100644
--- a/packages/sync-server/src/app-account.test.js
+++ b/packages/sync-server/src/app-account.test.js
@@ -2,7 +2,7 @@ import request from 'supertest';
import { v4 as uuidv4 } from 'uuid';
import { getAccountDb, getLoginMethod, getServerPrefs } from './account-db';
-import { bootstrapPassword } from './accounts/password';
+import { bootstrapPassword, checkPassword } from './accounts/password';
import { handlers as app, authRateLimiter } from './app-account';
const ADMIN_ROLE = 'ADMIN';
@@ -132,7 +132,7 @@ describe('/change-password', () => {
const res = await request(app)
.post('/change-password')
.set('x-actual-token', basicPasswordToken)
- .send({ password: 'newpassword' });
+ .send({ password: 'newpassword', currentPassword: 'oldpassword' });
expect(res.statusCode).toEqual(403);
expect(res.body).toEqual({
@@ -148,7 +148,7 @@ describe('/change-password', () => {
const res = await request(app)
.post('/change-password')
.set('x-actual-token', adminOpenidToken)
- .send({ password: 'newpassword' });
+ .send({ password: 'newpassword', currentPassword: 'oldpassword' });
expect(res.statusCode).toEqual(403);
expect(res.body).toEqual({
@@ -164,7 +164,7 @@ describe('/change-password', () => {
const res = await request(app)
.post('/change-password')
.set('x-actual-token', adminPasswordToken)
- .send({ password: '' });
+ .send({ password: '', currentPassword: 'oldpassword' });
expect(res.statusCode).toEqual(400);
expect(res.body).toEqual({ status: 'error', reason: 'invalid-password' });
@@ -176,11 +176,45 @@ describe('/change-password', () => {
const res = await request(app)
.post('/change-password')
.set('x-actual-token', adminPasswordToken)
- .send({ password: 'newpassword' });
+ .send({ password: 'newpassword', currentPassword: 'oldpassword' });
expect(res.statusCode).toEqual(200);
expect(res.body).toEqual({ status: 'ok', data: {} });
});
+ it.each([undefined, '', 'wrong', null, {}])(
+ 'rejects a stolen token without the current password: %j',
+ async currentPassword => {
+ await bootstrapPassword('oldpassword');
+ const res = await request(app)
+ .post('/change-password')
+ .set('x-actual-token', adminPasswordToken)
+ .send({ password: 'attacker password', currentPassword });
+ expect(res.statusCode).toBe(400);
+ expect(res.body.reason).toBe('invalid-current-password');
+ expect(await checkPassword('oldpassword')).toBe(true);
+ expect(
+ getAccountDb().first('SELECT token FROM sessions WHERE token = ?', [
+ adminPasswordToken,
+ ]),
+ ).not.toBeNull();
+ },
+ );
+
+ it('rate limits incorrect current passwords', async () => {
+ await bootstrapPassword('oldpassword');
+ for (let i = 0; i < 5; i++) {
+ await request(app)
+ .post('/change-password')
+ .set('x-actual-token', adminPasswordToken)
+ .send({ password: 'newpassword', currentPassword: 'wrong' });
+ }
+ const res = await request(app)
+ .post('/change-password')
+ .set('x-actual-token', adminPasswordToken)
+ .send({ password: 'newpassword', currentPassword: 'oldpassword' });
+ expect(res.statusCode).toBe(429);
+ expect(await checkPassword('oldpassword')).toBe(true);
+ });
});
describe('getLoginMethod()', () => {
@@ -416,3 +450,43 @@ describe('/server-prefs', () => {
});
});
});
+
+describe('logout', () => {
+ it('revokes only the supplied token and allows repeated logout', async () => {
+ const userId = uuidv4();
+ const token = generateSessionToken();
+ const otherToken = generateSessionToken();
+ createUser(userId, userId, BASIC_ROLE);
+ createSession(userId, token, 'password');
+ createSession(userId, otherToken, 'password');
+ try {
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const res = await request(app).post('/logout').send({ token });
+ expect(res.status).toBe(200);
+ }
+ expect(
+ getAccountDb().first('SELECT token FROM sessions WHERE token = ?', [
+ token,
+ ]),
+ ).toBeNull();
+ expect(
+ getAccountDb().first('SELECT token FROM sessions WHERE token = ?', [
+ otherToken,
+ ]),
+ ).toEqual({ token: otherToken });
+ for (const token of [undefined, '', null, [], {}]) {
+ expect(
+ (await request(app).post('/logout').send({ token })).status,
+ ).toBe(400);
+ }
+ expect(
+ getAccountDb().first('SELECT token FROM sessions WHERE token = ?', [
+ otherToken,
+ ]),
+ ).toEqual({ token: otherToken });
+ } finally {
+ getAccountDb().mutate('DELETE FROM sessions WHERE user_id = ?', [userId]);
+ deleteUser(userId);
+ }
+ });
+});
diff --git a/packages/sync-server/src/app-cors-proxy.js b/packages/sync-server/src/app-cors-proxy.js
index 9a7de0bf5c..fdcab8a70d 100644
--- a/packages/sync-server/src/app-cors-proxy.js
+++ b/packages/sync-server/src/app-cors-proxy.js
@@ -1,3 +1,4 @@
+import createDebug from 'debug';
import express from 'express';
import rateLimit from 'express-rate-limit';
@@ -6,6 +7,8 @@ import { requestLoggerMiddleware } from './util/middlewares';
import { isBlockedIp } from './util/ssrf';
import { validateSession } from './util/validate-user';
+const debugSensitive = createDebug('actual-sensitive:cors-proxy');
+
const app = express();
app.use(express.json());
@@ -111,7 +114,8 @@ function isUrlAllowed(targetUrl) {
return false;
} catch (e) {
- console.warn('Invalid target URL:', targetUrl, e.message);
+ console.warn('Invalid target URL');
+ debugSensitive('Invalid target URL %s: %O', targetUrl, e);
return false;
}
}
@@ -158,7 +162,8 @@ app.use('/', async (req, res) => {
// Check if the URL is allowed
if (!isUrlAllowed(url.href)) {
- console.warn('Blocked request to unauthorized URL:', url.href);
+ console.warn('Blocked request to unauthorized URL');
+ debugSensitive('Blocked request to unauthorized URL: %s', url.href);
return res.status(403).json({
error: 'URL not allowed',
message:
diff --git a/packages/sync-server/src/app-cors-proxy.test.js b/packages/sync-server/src/app-cors-proxy.test.js
index 5fd4e9fb9b..462c38e9f2 100644
--- a/packages/sync-server/src/app-cors-proxy.test.js
+++ b/packages/sync-server/src/app-cors-proxy.test.js
@@ -1,3 +1,6 @@
+import { format } from 'node:util';
+
+import createDebug from 'debug';
import request from 'supertest';
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -280,8 +283,7 @@ describe('app-cors-proxy', () => {
expect(res.statusCode).toBe(403);
expect(res.body.error).toBe('URL not allowed');
expect(console.warn).toHaveBeenCalledWith(
- 'Blocked request to unauthorized URL:',
- 'https://api.github.com/repos/user/repo1-private/contents/.env',
+ 'Blocked request to unauthorized URL',
);
});
@@ -301,18 +303,37 @@ describe('app-cors-proxy', () => {
expect(res.statusCode).toBe(200);
});
- it('should block non-allowlisted URLs', async () => {
- const res = await request(app)
- .get('/')
- .query({ url: 'https://malicious.com/evil' });
-
- expect(res.statusCode).toBe(403);
- expect(res.body.error).toBe('URL not allowed');
- expect(console.warn).toHaveBeenCalledWith(
- 'Blocked request to unauthorized URL:',
- 'https://malicious.com/evil',
- );
- });
+ it.each(['', 'actual:*', 'actual-sensitive:cors-proxy'])(
+ 'keeps rejected URL details behind sensitive debugging (%s)',
+ async namespaces => {
+ const previous = createDebug.disable();
+ createDebug.enable(namespaces);
+ const log = vi
+ .spyOn(createDebug, 'log')
+ .mockImplementation(() => undefined);
+ const secret = 'private-download-token';
+ try {
+ const res = await request(app)
+ .get('/')
+ .query({
+ url: `https://malicious.com/evil?token=${secret}`,
+ });
+ expect(res.statusCode).toBe(403);
+ expect(res.body.error).toBe('URL not allowed');
+ expect(console.warn).toHaveBeenCalledWith(
+ 'Blocked request to unauthorized URL',
+ );
+ expect(JSON.stringify(console.warn.mock.calls)).not.toContain(secret);
+ const output = log.mock.calls.map(args => format(...args)).join('\n');
+ expect(output.includes(secret)).toBe(
+ namespaces === 'actual-sensitive:cors-proxy',
+ );
+ } finally {
+ log.mockRestore();
+ createDebug.enable(previous);
+ }
+ },
+ );
});
describe('Allowlist fetching and caching', () => {
@@ -617,8 +638,7 @@ describe('app-cors-proxy', () => {
expect(res.statusCode).toBe(403);
expect(console.warn).toHaveBeenCalledWith(
- 'Blocked request to unauthorized URL:',
- 'https://example.com/',
+ 'Blocked request to unauthorized URL',
);
});
});
diff --git a/packages/sync-server/src/app-enablebanking/app-enablebanking.ts b/packages/sync-server/src/app-enablebanking/app-enablebanking.ts
index 3ae791f42c..676a842de7 100644
--- a/packages/sync-server/src/app-enablebanking/app-enablebanking.ts
+++ b/packages/sync-server/src/app-enablebanking/app-enablebanking.ts
@@ -3,6 +3,7 @@ import type { Request, Response } from 'express';
import express from 'express';
import { v4 as uuidv4 } from 'uuid';
+import { isAdmin } from '#account-db';
import { handleError } from '#app-gocardless/util/handle-error';
import { SecretName, secretsService } from '#services/secrets-service';
import {
@@ -24,6 +25,8 @@ import {
} from './services/enablebanking-service';
import { EnableBankingError } from './utils/errors';
+const debugSensitive = createDebug('actual-sensitive:enable-banking');
+
const debug = createDebug('actual:enable-banking:app');
const app = express();
@@ -89,7 +92,12 @@ async function buildSessionResult(
);
balances = balanceResult.balances.map(normalizeBalance);
} catch (err) {
- debug('Failed to fetch balances for account %s: %s', account.uid, err);
+ debug('Failed to fetch account balances');
+ debugSensitive(
+ 'Failed to fetch balances for account %s: %O',
+ account.uid,
+ err,
+ );
}
const preferredBalance =
@@ -137,11 +145,8 @@ app.get('/auth_callback', async (req: Request, res: Response) => {
try {
const session = await enableBankingService.createSession(code);
- debug(
- 'Callback session created: %s with %d accounts',
- session.session_id,
- session.accounts.length,
- );
+ debug('Callback session created with %d accounts', session.accounts.length);
+ debugSensitive('Callback session created: %s', session.session_id);
const result = await buildSessionResult(session, extractPsuHeaders(req));
@@ -173,7 +178,8 @@ app.get('/auth_callback', async (req: Request, res: Response) => {
cleanupPendingAuth(state);
}
- debug('Callback auth error: %s', error);
+ debug('Callback authentication failed');
+ debugSensitive('Callback authentication failed: %O', error);
res
.status(500)
.send(
@@ -230,6 +236,15 @@ app.post(
app.post(
'/configure',
handleError(async (req: Request, res: Response) => {
+ if (!isAdmin(res.locals.user_id)) {
+ res.status(403).send({
+ status: 'error',
+ reason: 'forbidden',
+ details: 'permission-not-found',
+ });
+ return;
+ }
+
const { applicationId, secretKey } = req.body || {};
if (!applicationId || !secretKey) {
@@ -250,9 +265,14 @@ app.post(
applicationId,
secretKey,
);
- debug('Enable Banking application validated: %o', appInfo);
+ debug('Enable Banking application validated');
+ debugSensitive('Enable Banking application validated: %O', appInfo);
} catch (error) {
- debug('Enable Banking configuration validation failed: %s', error);
+ debug('Enable Banking configuration validation failed');
+ debugSensitive(
+ 'Enable Banking configuration validation failed: %O',
+ error,
+ );
res.send({
status: 'ok',
data: {
@@ -363,11 +383,8 @@ app.post(
try {
const session = await enableBankingService.createSession(code);
- debug(
- 'Session created: %s with %d accounts',
- session.session_id,
- session.accounts.length,
- );
+ debug('Session created with %d accounts', session.accounts.length);
+ debugSensitive('Session created: %s', session.session_id);
const result = await buildSessionResult(session, extractPsuHeaders(req));
@@ -566,7 +583,7 @@ app.post(
// non-numeric amount) — one of them would otherwise abort the entire
// account sync. Pending transactions that carry a date are unaffected.
if (!isImportableTransaction(normalized)) {
- debug(
+ debugSensitive(
'Skipping unimportable transaction id=%s date=%s amount=%s',
normalized.transactionId,
normalized.date,
@@ -596,7 +613,8 @@ app.post(
},
});
} catch (error) {
- debug('Error fetching transactions: %s', error);
+ debug('Error fetching transactions');
+ debugSensitive('Error fetching transactions: %O', error);
// Return structured error codes so the client can show
// appropriate UI (e.g. re-auth prompt for expired sessions)
diff --git a/packages/sync-server/src/app-enablebanking/services/enablebanking-service.ts b/packages/sync-server/src/app-enablebanking/services/enablebanking-service.ts
index 85c7353f17..c5c722969a 100644
--- a/packages/sync-server/src/app-enablebanking/services/enablebanking-service.ts
+++ b/packages/sync-server/src/app-enablebanking/services/enablebanking-service.ts
@@ -7,6 +7,8 @@ import {
import { getJWT } from '#app-enablebanking/utils/jwt';
import { SecretName, secretsService } from '#services/secrets-service';
+const debugSensitive = createDebug('actual-sensitive:enable-banking');
+
const debug = createDebug('actual:enable-banking:service');
const BASE_URL = 'https://api.enablebanking.com';
@@ -128,7 +130,8 @@ async function request<T>(
psuHeaders?: PsuHeaders,
): Promise<T> {
const url = `${BASE_URL}${path}`;
- debug('%s %s', method, url);
+ debug('%s request', method);
+ debugSensitive('%s %s', method, url);
const headers: Record<string, string> = {
Authorization: authHeaderOverride ?? getAuthorizationHeader(),
diff --git a/packages/sync-server/src/app-enablebanking/tests/callback-logging.test.ts b/packages/sync-server/src/app-enablebanking/tests/callback-logging.test.ts
new file mode 100644
index 0000000000..b028fc3e5d
--- /dev/null
+++ b/packages/sync-server/src/app-enablebanking/tests/callback-logging.test.ts
@@ -0,0 +1,47 @@
+import { format } from 'node:util';
+
+import createDebug from 'debug';
+import request from 'supertest';
+
+import { handlers } from '#app-enablebanking/app-enablebanking';
+import { enableBankingService } from '#app-enablebanking/services/enablebanking-service';
+
+it.each(['', 'actual:*', 'actual-sensitive:enable-banking'])(
+ 'keeps callback credentials and provider details behind the sensitive namespace (%s)',
+ async namespaces => {
+ const previous = createDebug.disable();
+ createDebug.enable(namespaces);
+ const log = vi
+ .spyOn(createDebug, 'log')
+ .mockImplementation(() => undefined);
+ const provider = vi.spyOn(enableBankingService, 'createSession');
+ const secret = 'private-callback-credential';
+ try {
+ provider.mockResolvedValueOnce({
+ session_id: secret,
+ accounts: [],
+ });
+ await request(handlers)
+ .get('/auth_callback')
+ .query({ code: secret, state: secret })
+ .expect(200);
+ provider.mockRejectedValueOnce(new Error(secret));
+ await request(handlers)
+ .get('/auth_callback')
+ .query({ code: secret, state: secret })
+ .expect(500);
+ const output = log.mock.calls.map(args => format(...args)).join('\n');
+ expect(output.includes(secret)).toBe(
+ namespaces === 'actual-sensitive:enable-banking',
+ );
+ if (namespaces === 'actual-sensitive:enable-banking') {
+ expect(output).toContain('Error:');
+ expect(output).toContain('callback-logging.test.ts:');
+ }
+ } finally {
+ provider.mockRestore();
+ log.mockRestore();
+ createDebug.enable(previous);
+ }
+ },
+);
diff --git a/packages/sync-server/src/app-enablebanking/tests/configure-permissions.test.ts b/packages/sync-server/src/app-enablebanking/tests/configure-permissions.test.ts
new file mode 100644
index 0000000000..3cb5f6c206
--- /dev/null
+++ b/packages/sync-server/src/app-enablebanking/tests/configure-permissions.test.ts
@@ -0,0 +1,55 @@
+import request from 'supertest';
+
+import { handlers } from '#app-enablebanking/app-enablebanking';
+import { enableBankingService } from '#app-enablebanking/services/enablebanking-service';
+import { SecretName, secretsService } from '#services/secrets-service';
+
+const application = SecretName.enablebanking_applicationId;
+const key = SecretName.enablebanking_secretKey;
+
+afterEach(() => {
+ secretsService.reset(application);
+ secretsService.reset(key);
+ vi.restoreAllMocks();
+});
+
+it.each([false, true])(
+ 'requires an admin with existing configuration: %s',
+ async configured => {
+ if (configured) {
+ secretsService.set(application, 'original-id');
+ secretsService.set(key, 'original-key');
+ }
+ const validate = vi
+ .spyOn(enableBankingService, 'validateCredentials')
+ .mockResolvedValue({ name: 'Test app' });
+ for (const [token, status] of [
+ ['invalid-token', 401],
+ ['valid-token-user', 403],
+ ] as const) {
+ for (const body of [
+ {},
+ { applicationId: 'replacement-id', secretKey: 'replacement-key' },
+ ]) {
+ await request(handlers)
+ .post('/configure')
+ .set('x-actual-token', token)
+ .send(body)
+ .expect(status);
+ }
+ expect(secretsService.get(application)).toBe(
+ configured ? 'original-id' : null,
+ );
+ expect(secretsService.get(key)).toBe(configured ? 'original-key' : null);
+ }
+ expect(validate).not.toHaveBeenCalled();
+ await request(handlers)
+ .post('/configure')
+ .set('x-actual-token', 'valid-token-admin')
+ .send({ applicationId: 'replacement-id', secretKey: 'replacement-key' })
+ .expect(200);
+ expect(validate).toHaveBeenCalledWith('replacement-id', 'replacement-key');
+ expect(secretsService.get(application)).toBe('replacement-id');
+ expect(secretsService.get(key)).toBe('replacement-key');
+ },
+);
diff --git a/packages/sync-server/src/app-enablebanking/tests/poll-auth.spec.ts b/packages/sync-server/src/app-enablebanking/tests/poll-auth.spec.ts
index cb8c909b3b..1958a39d10 100644
--- a/packages/sync-server/src/app-enablebanking/tests/poll-auth.spec.ts
+++ b/packages/sync-server/src/app-enablebanking/tests/poll-auth.spec.ts
@@ -21,8 +21,14 @@ vi.mock('../utils/jwt', () => ({
vi.mock('../../util/middlewares', () => ({
requestLoggerMiddleware: (_req: unknown, _res: unknown, next: () => void) =>
next(),
- validateSessionMiddleware: (_req: unknown, _res: unknown, next: () => void) =>
- next(),
+ validateSessionMiddleware: (
+ _req: unknown,
+ res: { locals: { user_id?: string } },
+ next: () => void,
+ ) => {
+ res.locals.user_id = 'genericAdmin';
+ next();
+ },
}));
vi.mock('../../app-gocardless/util/handle-error', () => ({
diff --git a/packages/sync-server/src/app-enablebanking/utils/errors.ts b/packages/sync-server/src/app-enablebanking/utils/errors.ts
index 88eabc0dc1..25e30cb557 100644
--- a/packages/sync-server/src/app-enablebanking/utils/errors.ts
+++ b/packages/sync-server/src/app-enablebanking/utils/errors.ts
@@ -1,5 +1,7 @@
import createDebug from 'debug';
+const debugSensitive = createDebug('actual-sensitive:enable-banking');
+
const debug = createDebug('actual:enable-banking:errors');
export class EnableBankingError extends Error {
@@ -20,7 +22,12 @@ export function handleEnableBankingError(
): EnableBankingError {
const bodyStr =
typeof body === 'string' ? body : JSON.stringify(body ?? 'unknown');
- debug('Enable Banking API error: status=%d body=%s', statusCode, bodyStr);
+ debug('Enable Banking API error: status=%d', statusCode);
+ debugSensitive(
+ 'Enable Banking API error: status=%d body=%s',
+ statusCode,
+ bodyStr,
+ );
const parsed: Record<string, unknown> =
typeof body === 'object' && body !== null
diff --git a/packages/sync-server/src/app-gocardless/app-gocardless.ts b/packages/sync-server/src/app-gocardless/app-gocardless.ts
index 1f0e1bfae0..a22c1bd62f 100644
--- a/packages/sync-server/src/app-gocardless/app-gocardless.ts
+++ b/packages/sync-server/src/app-gocardless/app-gocardless.ts
@@ -1,3 +1,4 @@
+import createDebug from 'debug';
import express from 'express';
import type { Request, Response } from 'express';
@@ -27,6 +28,8 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
+const debugSensitive = createDebug('actual-sensitive:gocardless');
+
const ELECTRON_APP_ORIGIN = 'app://actual';
function validateOrigin(origin: string | undefined) {
@@ -350,14 +353,16 @@ app.post(
});
break;
case error instanceof GenericGoCardlessError:
- console.log('Something went wrong', errorMessage);
+ console.log('GoCardless synchronization failed');
+ debugSensitive('GoCardless synchronization failed: %s', errorMessage);
sendErrorResponse({
error_type: 'SYNC_ERROR',
error_code: 'NORDIGEN_ERROR',
});
break;
default:
- console.log('Something went wrong', errorMessage);
+ console.log('GoCardless synchronization failed');
+ debugSensitive('GoCardless synchronization failed: %s', errorMessage);
sendErrorResponse({
error_type: 'UNKNOWN',
error_code: 'UNKNOWN',
diff --git a/packages/sync-server/src/app-gocardless/banks/commerzbank_cobadeff.ts b/packages/sync-server/src/app-gocardless/banks/commerzbank_cobadeff.ts
index 9a01e535f8..cb296d9211 100644
--- a/packages/sync-server/src/app-gocardless/banks/commerzbank_cobadeff.ts
+++ b/packages/sync-server/src/app-gocardless/banks/commerzbank_cobadeff.ts
@@ -41,15 +41,25 @@ export default {
// Clean up remittanceInformation, deduplicate payee (removing slashes ...
// ... that are added to the remittanceInformation field), and ...
// ... remove clutter like "End-to-End-Ref.: NOTPROVIDED"
- const payee = escapeRegExp(
- transaction.creditorName || transaction.debtorName || '',
+ const payeeTokens = (
+ transaction.creditorName ||
+ transaction.debtorName ||
+ ''
+ )
+ .split(/[\s/]+/)
+ .filter(Boolean)
+ .map(escapeRegExp);
+ let notes = editedTrans.remittanceInformationUnstructured.replace(
+ /\s*(,)?\s+/g,
+ '$1 ',
);
- editedTrans.remittanceInformationUnstructured =
- editedTrans.remittanceInformationUnstructured
- .replace(/\s*(,)?\s+/g, '$1 ')
- .replace(RegExp(payee.split(' ').join('(/*| )'), 'gi'), ' ')
- .replace(', End-to-End-Ref.: NOTPROVIDED', '')
- .trim();
+ if (payeeTokens.length > 0) {
+ // Separators consume at least one character and cannot overlap tokens.
+ notes = notes.replace(new RegExp(payeeTokens.join('[\\s/]+'), 'gi'), ' ');
+ }
+ editedTrans.remittanceInformationUnstructured = notes
+ .replace(', End-to-End-Ref.: NOTPROVIDED', '')
+ .trim();
return Fallback.normalizeTransaction(transaction, booked, editedTrans);
},
diff --git a/packages/sync-server/src/app-gocardless/banks/tests/commerzbank_cobadeff.spec.ts b/packages/sync-server/src/app-gocardless/banks/tests/commerzbank_cobadeff.spec.ts
index f1c7a65e7a..b356d3908a 100644
--- a/packages/sync-server/src/app-gocardless/banks/tests/commerzbank_cobadeff.spec.ts
+++ b/packages/sync-server/src/app-gocardless/banks/tests/commerzbank_cobadeff.spec.ts
@@ -131,3 +131,41 @@ describe('CommerzbankCobadeff', () => {
});
});
});
+
+describe('hostile payee names', () => {
+ it('handles the reported multi-word payload and slash-heavy near misses within a hard process deadline', async () => {
+ const { execFileSync } = await import('node:child_process');
+ const { fileURLToPath } = await import('node:url');
+ const cases = [
+ { name: ' '.repeat(100), notes: 'Ordinary note' },
+ { name: 'A' + ' '.repeat(24) + 'B', notes: 'A' + '/'.repeat(48) + 'C' },
+ { name: 'A / B', notes: 'A' + '/'.repeat(10000) + 'C' },
+ { name: 'A (B)', notes: 'A///(B) reference' },
+ ];
+ const input = cases.map(({ name, notes }) => ({
+ creditorName: name,
+ transactionAmount: { amount: '-1', currency: 'EUR' },
+ bookingDate: '2026-09-27',
+ remittanceInformationUnstructuredArray: [notes],
+ }));
+ const output = execFileSync(
+ process.execPath,
+ [
+ fileURLToPath(
+ new URL('./fixtures/commerzbank-hostile.mjs', import.meta.url),
+ ),
+ ],
+ {
+ input: JSON.stringify(input),
+ timeout: 20000,
+ encoding: 'utf8',
+ },
+ );
+ expect(JSON.parse(output)).toEqual([
+ cases[0].notes,
+ cases[1].notes,
+ cases[2].notes,
+ 'reference',
+ ]);
+ }, 30000);
+});
diff --git a/packages/sync-server/src/app-gocardless/banks/tests/fixtures/commerzbank-hostile.mjs b/packages/sync-server/src/app-gocardless/banks/tests/fixtures/commerzbank-hostile.mjs
new file mode 100644
index 0000000000..0f2c04ff7d
--- /dev/null
+++ b/packages/sync-server/src/app-gocardless/banks/tests/fixtures/commerzbank-hostile.mjs
@@ -0,0 +1,23 @@
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+import { createServer } from 'vite';
+
+const server = await createServer({
+ configFile: false,
+ server: { middlewareMode: true },
+ logLevel: 'silent',
+});
+try {
+ const { default: bank } = await server.ssrLoadModule(
+ fileURLToPath(new URL('../../commerzbank_cobadeff.ts', import.meta.url)),
+ );
+ const inputs = JSON.parse(readFileSync(0, 'utf8'));
+ process.stdout.write(
+ JSON.stringify(
+ inputs.map(input => bank.normalizeTransaction(input, false)?.notes),
+ ),
+ );
+} finally {
+ await server.close();
+}
diff --git a/packages/sync-server/src/app-gocardless/services/gocardless-api.ts b/packages/sync-server/src/app-gocardless/services/gocardless-api.ts
index 9a1bf91d0f..5cd02473fc 100644
--- a/packages/sync-server/src/app-gocardless/services/gocardless-api.ts
+++ b/packages/sync-server/src/app-gocardless/services/gocardless-api.ts
@@ -1,3 +1,5 @@
+import createDebug from 'debug';
+
import type {
GoCardlessAccountDetails,
GoCardlessAccountId,
@@ -13,6 +15,8 @@ import type {
GetTransactionsResponse,
} from '#app-gocardless/gocardless.types';
+const debugSensitive = createDebug('actual-sensitive:gocardless');
+
const BASE_URL = 'https://bankaccountdata.gocardless.com/api/v2';
const ALLOWED_ORIGIN = new URL(BASE_URL).origin;
@@ -145,7 +149,8 @@ export class GoCardlessApi {
try {
error.response.data = await response.json();
} catch {}
- console.log(
+ console.log(`GoCardless request failed: ${response.status}`);
+ debugSensitive(
`GoCardless ${method} ${endpoint} ${response.status}`,
error.response.data ? JSON.stringify(error.response.data) : '(no body)',
);
diff --git a/packages/sync-server/src/app-gocardless/services/gocardless-service.ts b/packages/sync-server/src/app-gocardless/services/gocardless-service.ts
index 0ff5fb5979..2d01235ac9 100644
--- a/packages/sync-server/src/app-gocardless/services/gocardless-service.ts
+++ b/packages/sync-server/src/app-gocardless/services/gocardless-service.ts
@@ -1,3 +1,4 @@
+import createDebug from 'debug';
import { v4 as uuidv4 } from 'uuid';
import { BankFactory } from '#app-gocardless/bank-factory';
@@ -41,6 +42,8 @@ import { SecretName, secretsService } from '#services/secrets-service';
import type { AccountDetailsResponse, TokenResponse } from './gocardless-api';
import { GoCardlessApi, GoCardlessApiError } from './gocardless-api';
+const debugSensitive = createDebug('actual-sensitive:gocardless');
+
const clients = new Map<string, GoCardlessApi>();
const getGocardlessClient = (): GoCardlessApi => {
@@ -339,8 +342,7 @@ export const goCardlessService = {
});
const response = await client.initSession(body).catch(async () => {
- console.log('Failed to link using:');
- console.log(body);
+ debugSensitive('Failed to link using: %O', body);
console.log(
'Falling back to accessValidForDays = 90 ' +
'and maxHistoricalDays = 89',
diff --git a/packages/sync-server/src/app-gocardless/util/handle-error.ts b/packages/sync-server/src/app-gocardless/util/handle-error.ts
index 4cc90d3988..c1c7efb05e 100644
--- a/packages/sync-server/src/app-gocardless/util/handle-error.ts
+++ b/packages/sync-server/src/app-gocardless/util/handle-error.ts
@@ -1,11 +1,20 @@
+import createDebug from 'debug';
import type { Request, Response } from 'express';
+const debugSensitive = createDebug('actual-sensitive:bank-sync');
+
export function handleError(
func: (req: Request, res: Response) => Promise<unknown>,
) {
return (req: Request, res: Response) => {
func(req, res).catch(err => {
- console.log('Error', req.originalUrl, err.message || String(err));
+ console.log('Error', req.method, req.baseUrl + req.path);
+ debugSensitive(
+ 'Error on %s %s: %O',
+ req.method,
+ req.baseUrl + req.path,
+ err,
+ );
res.send({
status: 'ok',
data: {
diff --git a/packages/sync-server/src/app-pluggyai/pluggyai-service.js b/packages/sync-server/src/app-pluggyai/pluggyai-service.js
index 270661de5b..015272a1c1 100644
--- a/packages/sync-server/src/app-pluggyai/pluggyai-service.js
+++ b/packages/sync-server/src/app-pluggyai/pluggyai-service.js
@@ -1,7 +1,10 @@
+import createDebug from 'debug';
import { PluggyClient } from 'pluggy-sdk';
import { SecretName, secretsService } from '#services/secrets-service';
+const debugSensitive = createDebug('actual-sensitive:pluggy');
+
const pluggyClients = new Map();
function hasCredentials(fileId = null) {
@@ -84,7 +87,8 @@ export const pluggyaiService = {
errors: {},
};
} catch (error) {
- console.error(`Error fetching accounts: ${error.message}`);
+ console.error('Error fetching accounts');
+ debugSensitive('Error fetching accounts: %O', error);
throw error;
}
},
@@ -98,7 +102,8 @@ export const pluggyaiService = {
errors: {},
};
} catch (error) {
- console.error(`Error fetching account: ${error.message}`);
+ console.error('Error fetching account');
+ debugSensitive('Error fetching account: %O', error);
throw error;
}
},
@@ -134,7 +139,8 @@ export const pluggyaiService = {
errors: {},
};
} catch (error) {
- console.error(`Error fetching transactions: ${error.message}`);
+ console.error('Error fetching transactions');
+ debugSensitive('Error fetching transactions: %O', error);
throw error;
}
},
diff --git a/packages/sync-server/src/app-simplefin/app-simplefin.js b/packages/sync-server/src/app-simplefin/app-simplefin.js
index 3846370b87..286150c96c 100644
--- a/packages/sync-server/src/app-simplefin/app-simplefin.js
+++ b/packages/sync-server/src/app-simplefin/app-simplefin.js
@@ -1,3 +1,4 @@
+import createDebug from 'debug';
import express from 'express';
import { handleError } from '#app-gocardless/util/handle-error';
@@ -8,6 +9,8 @@ import {
} from '#util/middlewares';
import { assertUrlAllowed } from '#util/ssrf';
+const debugSensitive = createDebug('actual-sensitive:simplefin');
+
const app = express();
export { app as handlers };
app.use(requestLoggerMiddleware);
@@ -59,10 +62,10 @@ app.post(
}
if (isInvalidAccessKey(accessKey)) {
- console.log(
- `SimpleFIN rejected the setup token claim: ${
- accessKey.slice(0, 200) || '(empty response)'
- }`,
+ console.log('SimpleFIN rejected the setup token claim');
+ debugSensitive(
+ 'SimpleFIN rejected the setup token claim: %s',
+ accessKey.slice(0, 200) || '(empty response)',
);
invalidToken(res);
return;
@@ -296,7 +299,8 @@ function invalidToken(res) {
}
function serverDown(e, res) {
- console.log(e);
+ console.log('Error communicating with SimpleFIN');
+ debugSensitive('Error communicating with SimpleFIN: %O', e);
res.send({
status: 'ok',
data: {
@@ -477,7 +481,8 @@ async function getAccounts(
results.errors = {};
return results;
} catch (e) {
- console.log(`Error parsing JSON response: ${text}`);
+ console.log('Error parsing SimpleFIN response');
+ debugSensitive('Error parsing SimpleFIN response: %s', text);
throw e;
}
}
diff --git a/packages/sync-server/src/app-simplefin/app-simplefin.test.js b/packages/sync-server/src/app-simplefin/app-simplefin.test.js
index 00ee0729e9..2eeff4a945 100644
--- a/packages/sync-server/src/app-simplefin/app-simplefin.test.js
+++ b/packages/sync-server/src/app-simplefin/app-simplefin.test.js
@@ -1,3 +1,6 @@
+import { format } from 'node:util';
+
+import createDebug from 'debug';
import request from 'supertest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -48,6 +51,28 @@ describe('app-simplefin', () => {
vi.restoreAllMocks();
});
+ it('preserves format sequences in sensitive provider diagnostics', async () => {
+ const previous = createDebug.disable();
+ createDebug.enable('actual-sensitive:simplefin');
+ const log = vi
+ .spyOn(createDebug, 'log')
+ .mockImplementation(() => undefined);
+ const response = 'Rejected: %O %s %%';
+ mockFetch({ claim: okResponse(response) });
+ secretsService.set(SecretName.simplefin_token, SETUP_TOKEN);
+ try {
+ await post('/accounts');
+ expect(log.mock.calls.map(args => format(...args)).join('\n')).toContain(
+ response,
+ );
+ expect(JSON.stringify(vi.mocked(console.log).mock.calls)).not.toContain(
+ response,
+ );
+ } finally {
+ createDebug.enable(previous);
+ }
+ });
+
describe('/status', () => {
it('reports configured when a real token is stored', async () => {
secretsService.set(SecretName.simplefin_token, SETUP_TOKEN);
diff --git a/packages/sync-server/src/app-simplefin/ssrf.test.ts b/packages/sync-server/src/app-simplefin/ssrf.test.ts
new file mode 100644
index 0000000000..abfc8bd9c7
--- /dev/null
+++ b/packages/sync-server/src/app-simplefin/ssrf.test.ts
@@ -0,0 +1,70 @@
+import dns from 'dns';
+
+import request from 'supertest';
+
+import { SecretName, secretsService } from '#services/secrets-service';
+
+import { handlers } from './app-simplefin';
+
+vi.mock('dns', () => ({ default: { lookup: vi.fn() } }));
+
+beforeEach(() => {
+ secretsService.reset(SecretName.simplefin_token);
+ secretsService.reset(SecretName.simplefin_accessKey);
+ vi.stubGlobal('fetch', vi.fn());
+});
+
+afterEach(() => {
+ secretsService.reset(SecretName.simplefin_token);
+ secretsService.reset(SecretName.simplefin_accessKey);
+ vi.unstubAllGlobals();
+ vi.resetAllMocks();
+});
+
+it('does not fetch a claim URL using a transition address', async () => {
+ secretsService.set(
+ SecretName.simplefin_token,
+ Buffer.from('http://[64:ff9b::a9fe:a9fe]/claim').toString('base64'),
+ );
+ const response = await request(handlers)
+ .post('/accounts')
+ .set('x-actual-token', 'valid-token');
+ expect(response.body.data.error_code).toBe('SERVER_DOWN');
+ expect(fetch).not.toHaveBeenCalled();
+});
+
+it('does not fetch accounts on a host resolving to a transition address', async () => {
+ vi.mocked(dns.lookup).mockImplementation((...args: unknown[]) => {
+ const callback = args[args.length - 1];
+ if (typeof callback === 'function') {
+ callback(null, [{ address: '2002:a9fe:a9fe::', family: 6 }]);
+ }
+ });
+ secretsService.set(
+ SecretName.simplefin_accessKey,
+ 'https://user:[email protected]',
+ );
+ const response = await request(handlers)
+ .post('/accounts')
+ .set('x-actual-token', 'valid-token');
+ expect(response.body.data.error_code).toBe('SERVER_DOWN');
+ expect(fetch).not.toHaveBeenCalled();
+});
+
+it('rejects an unsafe redirect before fetching the next hop', async () => {
+ secretsService.set(
+ SecretName.simplefin_accessKey,
+ 'https://user:[email protected]',
+ );
+ vi.mocked(fetch).mockResolvedValue(
+ new Response(null, {
+ status: 302,
+ headers: { Location: 'http://[ff02::1]/accounts' },
+ }),
+ );
+ const response = await request(handlers)
+ .post('/accounts')
+ .set('x-actual-token', 'valid-token');
+ expect(response.body.data.error_code).toBe('SERVER_DOWN');
+ expect(fetch).toHaveBeenCalledTimes(1);
+});
diff --git a/packages/sync-server/src/app.ts b/packages/sync-server/src/app.ts
index 276059e591..189a6b3fe1 100644
--- a/packages/sync-server/src/app.ts
+++ b/packages/sync-server/src/app.ts
@@ -3,6 +3,7 @@ import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import cors from 'cors';
+import createDebug from 'debug';
import express from 'express';
import rateLimit from 'express-rate-limit';
@@ -20,10 +21,13 @@ import * as simpleFinApp from './app-simplefin/app-simplefin';
import * as syncApp from './app-sync';
import { config } from './load-config';
+const debugSensitive = createDebug('actual-sensitive:server');
+
const app = express();
process.on('unhandledRejection', reason => {
- console.log('Rejection:', reason);
+ console.log('Unhandled rejection');
+ debugSensitive('Unhandled rejection: %O', reason);
});
app.disable('x-powered-by');
diff --git a/packages/sync-server/src/services/secrets-service.js b/packages/sync-server/src/services/secrets-service.js
index a7f0484b81..025dad7e55 100644
--- a/packages/sync-server/src/services/secrets-service.js
+++ b/packages/sync-server/src/services/secrets-service.js
@@ -41,7 +41,7 @@ class SecretsDb {
}
const secretKey = getSecretKey(name, fileId);
- this.debug(`setting secret '${name}' to '${value}'`);
+ this.debug(`setting secret '${name}'`);
return this.db.mutate(
`INSERT OR REPLACE INTO secrets (name, value) VALUES (?, ?)`,
[secretKey, value],
diff --git a/packages/sync-server/src/util/middlewares.test.ts b/packages/sync-server/src/util/middlewares.test.ts
new file mode 100644
index 0000000000..20030f01c5
--- /dev/null
+++ b/packages/sync-server/src/util/middlewares.test.ts
@@ -0,0 +1,117 @@
+import { format } from 'node:util';
+
+import createDebug from 'debug';
+import express from 'express';
+import request from 'supertest';
+import * as winston from 'winston';
+
+import { errorMiddleware, requestLoggerMiddleware } from './middlewares';
+
+it.each(['/openid/callback', '/enablebanking/auth_callback'])(
+ 'excludes secrets from serialized request and error logs for %s',
+ async path => {
+ const records: string[] = [];
+ const transport = vi
+ .spyOn(winston.transports.Console.prototype, 'log')
+ .mockImplementation((info, callback) => {
+ records.push(JSON.stringify(info));
+ if (typeof info === 'object' && info !== null) {
+ records.push(String(Reflect.get(info, Symbol.for('message'))));
+ }
+ if (typeof callback === 'function') callback();
+ });
+ const consoleLog = vi
+ .spyOn(console, 'log')
+ .mockImplementation((...args) => {
+ records.push(JSON.stringify(args));
+ });
+ const secrets = {
+ code: 'secret-authorization-code',
+ state: 'secret-client-state',
+ token: 'secret-session-token',
+ verifier: 'secret-exchange-verifier',
+ };
+ const app = express();
+ app.use(requestLoggerMiddleware);
+ app.get(path, (req, res) => {
+ if (req.query.fail) {
+ throw new Error(JSON.stringify(secrets));
+ }
+ res.status(200).send(secrets);
+ });
+ app.use(errorMiddleware);
+ try {
+ await request(app).get(path).query(secrets).expect(200);
+ await request(app)
+ .get(path)
+ .query({ ...secrets, fail: 'yes' })
+ .expect(500);
+ const logged = records.join('\n');
+ for (const secret of Object.values(secrets)) {
+ expect(logged).not.toContain(secret);
+ }
+ expect(logged).toContain(path);
+ expect(logged).toContain('GET');
+ expect(logged).toContain('200');
+ expect(logged).toContain('500');
+ } finally {
+ transport.mockRestore();
+ consoleLog.mockRestore();
+ }
+ },
+);
+
+it.each(['', 'actual:*', 'actual-sensitive:server'])(
+ 'retains full server errors only with sensitive debugging (%s)',
+ async namespaces => {
+ const previous = createDebug.disable();
+ createDebug.enable(namespaces);
+ const debugLog = vi
+ .spyOn(createDebug, 'log')
+ .mockImplementation(() => undefined);
+ const ordinaryLog = vi
+ .spyOn(console, 'log')
+ .mockImplementation(() => undefined);
+ const secret = 'private-error-detail';
+ const original = new Error(
+ `Provider rejected ${secret}: redirect mismatch`,
+ );
+ let forwarded: Error | undefined;
+ const app = express();
+ app.get('/stream', (_req, res, next) => {
+ res.write('started');
+ next(original);
+ });
+ app.use(errorMiddleware);
+ app.use(
+ (
+ error: Error,
+ _req: express.Request,
+ res: express.Response,
+ _next: express.NextFunction,
+ ) => {
+ forwarded = error;
+ res.end();
+ },
+ );
+ try {
+ await request(app).get('/stream').expect(200);
+ expect(forwarded?.message).not.toContain(secret);
+ expect(JSON.stringify(ordinaryLog.mock.calls)).not.toContain(secret);
+ const output = debugLog.mock.calls
+ .map(args => format(...args))
+ .join('\n');
+ expect(output.includes(secret)).toBe(
+ namespaces === 'actual-sensitive:server',
+ );
+ if (namespaces === 'actual-sensitive:server') {
+ expect(output).toContain('redirect mismatch');
+ expect(output).toContain('middlewares.test.ts:');
+ }
+ } finally {
+ debugLog.mockRestore();
+ ordinaryLog.mockRestore();
+ createDebug.enable(previous);
+ }
+ },
+);
diff --git a/packages/sync-server/src/util/middlewares.ts b/packages/sync-server/src/util/middlewares.ts
index 347a0f4be5..3d18444ac6 100644
--- a/packages/sync-server/src/util/middlewares.ts
+++ b/packages/sync-server/src/util/middlewares.ts
@@ -1,3 +1,4 @@
+import createDebug from 'debug';
import type { NextFunction, Request, Response } from 'express';
import * as expressWinston from 'express-winston';
import * as winston from 'winston';
@@ -10,6 +11,8 @@ async function errorMiddleware(
res: Response,
next: NextFunction,
) {
+ debugSensitive('Error on %s %s: %O', req.method, req.baseUrl + req.path, err);
+
if (res.headersSent) {
// If you call next() with an error after you have started writing the response
// (for example, if you encounter an error while streaming the response
@@ -20,16 +23,19 @@ async function errorMiddleware(
// to the default Express error handler, when the headers
// have already been sent to the client
// Source: https://expressjs.com/en/guide/error-handling.html
- return next(err);
+ return next(new Error('Request failed after response headers were sent'));
}
console.log(`Error on endpoint %s`, {
- requestUrl: req.url,
- stacktrace: err.stack,
+ method: req.method,
+ path: req.baseUrl + req.path,
+ statusCode: 500,
});
res.status(500).send({ status: 'error', reason: 'internal-error' });
}
+const debugSensitive = createDebug('actual-sensitive:server');
+
const validateSessionMiddleware = async (
req: Request,
res: Response,
@@ -46,6 +52,11 @@ const validateSessionMiddleware = async (
const requestLoggerMiddleware = expressWinston.logger({
transports: [new winston.transports.Console()],
+ msg: 'HTTP request',
+ requestWhitelist: ['method', 'path'],
+ responseWhitelist: ['statusCode'],
+ requestFilter: (req, key) =>
+ key === 'path' ? req.baseUrl + req.path : req.method,
format: winston.format.combine(
...(Object.prototype.hasOwnProperty.call(process.env, 'NO_COLOR')
? []
@@ -55,7 +66,7 @@ const requestLoggerMiddleware = expressWinston.logger({
const { timestamp, level, meta } = args;
const { res, req } = meta as { res: Response; req: Request };
- return `${String(timestamp)} ${String(level)}: ${req.method} ${res.statusCode} ${req.url}`;
+ return `${String(timestamp)} ${String(level)}: ${req.method} ${res.statusCode} ${req.path}`;
}),
),
});
diff --git a/packages/sync-server/src/util/sensitive-logging.test.ts b/packages/sync-server/src/util/sensitive-logging.test.ts
new file mode 100644
index 0000000000..0178d70f6d
--- /dev/null
+++ b/packages/sync-server/src/util/sensitive-logging.test.ts
@@ -0,0 +1,106 @@
+import { format } from 'node:util';
+
+import createDebug from 'debug';
+import express from 'express';
+import request from 'supertest';
+
+import { enableBankingService } from '#app-enablebanking/services/enablebanking-service';
+import { handleEnableBankingError } from '#app-enablebanking/utils/errors';
+import { handleError } from '#app-gocardless/util/handle-error';
+import { SecretName, secretsService } from '#services/secrets-service';
+
+vi.mock('#app-enablebanking/utils/jwt', () => ({
+ getJWT: () => 'provider-jwt',
+}));
+
+it.each(['', 'actual:*', 'actual-sensitive:enable-banking'])(
+ 'protects provider response bodies and session URLs (%s)',
+ async namespaces => {
+ const previous = createDebug.disable();
+ createDebug.enable(namespaces);
+ const log = vi
+ .spyOn(createDebug, 'log')
+ .mockImplementation(() => undefined);
+ const secret = 'private-provider-session';
+ secretsService.set(
+ SecretName.enablebanking_applicationId,
+ 'test-application',
+ );
+ secretsService.set(SecretName.enablebanking_secretKey, 'test-key');
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}')));
+ try {
+ const error = handleEnableBankingError(400, {
+ message: `Invalid redirect for ${secret}`,
+ });
+ expect(error.message).toContain('Invalid redirect');
+ await enableBankingService.getSession(secret);
+ const output = log.mock.calls.map(args => format(...args)).join('\n');
+ expect(output.includes(secret)).toBe(
+ namespaces === 'actual-sensitive:enable-banking',
+ );
+ if (namespaces === 'actual-sensitive:enable-banking') {
+ expect(output).toContain('Invalid redirect');
+ expect(output).toContain(`/sessions/${secret}`);
+ }
+ } finally {
+ secretsService.reset(SecretName.enablebanking_applicationId);
+ secretsService.reset(SecretName.enablebanking_secretKey);
+ vi.unstubAllGlobals();
+ log.mockRestore();
+ createDebug.enable(previous);
+ }
+ },
+);
+
+it.each(['', 'actual:*', 'actual-sensitive:bank-sync'])(
+ 'protects query strings and errors in the shared bank handler (%s)',
+ async namespaces => {
+ const previous = createDebug.disable();
+ createDebug.enable(namespaces);
+ const log = vi
+ .spyOn(createDebug, 'log')
+ .mockImplementation(() => undefined);
+ const ordinary = vi
+ .spyOn(console, 'log')
+ .mockImplementation(() => undefined);
+ const secret = 'private-bank-code';
+ const app = express();
+ app.get(
+ '/callback',
+ handleError(async () => {
+ throw new Error(`Provider rejected ${secret}`);
+ }),
+ );
+ try {
+ await request(app).get('/callback').query({ code: secret }).expect(200);
+ expect(JSON.stringify(ordinary.mock.calls)).not.toContain(secret);
+ expect(JSON.stringify(ordinary.mock.calls)).toContain('/callback');
+ const output = log.mock.calls.map(args => format(...args)).join('\n');
+ expect(output.includes(secret)).toBe(
+ namespaces === 'actual-sensitive:bank-sync',
+ );
+ } finally {
+ log.mockRestore();
+ ordinary.mockRestore();
+ createDebug.enable(previous);
+ }
+ },
+);
+
+it('does not log stored secret values even with all debugging enabled', () => {
+ const previous = createDebug.disable();
+ createDebug.enable('*');
+ const log = vi.spyOn(createDebug, 'log').mockImplementation(() => undefined);
+ const secret = 'private-stored-token';
+ try {
+ secretsService.set(SecretName.simplefin_token, secret);
+ expect(secretsService.get(SecretName.simplefin_token)).toBe(secret);
+ const output = log.mock.calls.map(args => format(...args)).join('\n');
+ expect(output).toContain('setting secret');
+ expect(output).not.toContain(secret);
+ } finally {
+ secretsService.reset(SecretName.simplefin_token);
+ log.mockRestore();
+ createDebug.enable(previous);
+ }
+});
diff --git a/packages/sync-server/src/util/ssrf.test.ts b/packages/sync-server/src/util/ssrf.test.ts
index d0ccdeeb61..a186803634 100644
--- a/packages/sync-server/src/util/ssrf.test.ts
+++ b/packages/sync-server/src/util/ssrf.test.ts
@@ -160,3 +160,80 @@ describe('assertUrlAllowed', () => {
await expect(assertUrlAllowed('not a url')).rejects.toThrow(/Invalid URL/);
});
});
+
+const unsafeAddresses = [
+ '64:ff9b::c0a8:101', // NAT64 private IPv4
+ '64:ff9b::7f00:1', // NAT64 loopback
+ '64:ff9b::a9fe:a9fe', // NAT64 well-known prefix
+ '64:ff9b:1::a9fe:a9fe', // NAT64 local-use prefix
+ '2002:a9fe:a9fe::', // 6to4
+ '2001:0:4136:e378:8000:63bf:3fff:fdd2', // Teredo
+ '::ffff:0:169.254.169.254', // RFC 6145 translation
+ 'ff02::1', // multicast
+ 'fe80::1', // link-local
+ '2001:db8::1', // documentation/reserved
+ '224.0.0.1', // IPv4 multicast
+];
+
+it.each(unsafeAddresses)(
+ 'blocks %s as a literal and DNS answer in both modes',
+ async address => {
+ for (const allowPrivateNetwork of [false, true]) {
+ const host = address.includes(':') ? `[${address}]` : address;
+ await expect(
+ assertUrlAllowed(`https://${host}/`, { allowPrivateNetwork }),
+ ).rejects.toThrow();
+ mockDnsLookup(['8.8.8.8', address]);
+ await expect(
+ assertUrlAllowed('https://bridge.example/', { allowPrivateNetwork }),
+ ).rejects.toThrow();
+ }
+ },
+);
+
+it.each(['2606:4700:4700::1111', '::ffff:8.8.8.8'])(
+ 'allows public unicast %s',
+ async address => {
+ await expect(
+ assertUrlAllowed(`https://[${address}]/`),
+ ).resolves.toBeUndefined();
+ },
+);
+
+it.each(['::1', 'fd00::1', '::ffff:192.168.1.1'])(
+ 'permits private %s only when explicitly enabled',
+ async address => {
+ await expect(assertUrlAllowed(`http://[${address}]/`)).rejects.toThrow();
+ await expect(
+ assertUrlAllowed(`http://[${address}]/`, { allowPrivateNetwork: true }),
+ ).resolves.toBeUndefined();
+ },
+);
+
+it.each(['100.64.0.1', '100.127.255.254', '::ffff:100.64.0.1'])(
+ 'permits CGNAT %s as a literal and DNS answer only when explicitly enabled',
+ async address => {
+ const host = address.includes(':') ? `[${address}]` : address;
+ mockDnsLookup(['8.8.8.8', address]);
+
+ for (const url of [`https://${host}/`, 'https://bridge.example/']) {
+ await expect(assertUrlAllowed(url)).rejects.toThrow();
+ await expect(
+ assertUrlAllowed(url, { allowPrivateNetwork: true }),
+ ).resolves.toBeUndefined();
+ }
+ },
+);
+
+it.each([false, true])(
+ 'allows public NAT64 literals and DNS answers (private mode: %s)',
+ async allowPrivateNetwork => {
+ await expect(
+ assertUrlAllowed('https://[64:ff9b::808:808]/', { allowPrivateNetwork }),
+ ).resolves.toBeUndefined();
+ mockDnsLookup(['64:ff9b::808:808']);
+ await expect(
+ assertUrlAllowed('https://bridge.example/', { allowPrivateNetwork }),
+ ).resolves.toBeUndefined();
+ },
+);
diff --git a/packages/sync-server/src/util/ssrf.ts b/packages/sync-server/src/util/ssrf.ts
index 1f02fd3679..6f61b1cfef 100644
--- a/packages/sync-server/src/util/ssrf.ts
+++ b/packages/sync-server/src/util/ssrf.ts
@@ -4,30 +4,21 @@ import { promisify } from 'util';
import ipaddr from 'ipaddr.js';
const dnsLookup = promisify(dns.lookup);
-
-// IP ranges (as classified by ipaddr.js) that are never a legitimate
-// destination and are the highest-risk SSRF targets, so they are blocked
-// unconditionally. linkLocal covers the cloud metadata endpoint
-// (169.254.169.254) — the credential-theft vector this protection primarily
-// guards against — and no real service is hosted on the reserved, broadcast or
-// unspecified ranges.
-const ALWAYS_BLOCKED_IP_RANGES = [
- 'linkLocal',
- 'unspecified',
- 'reserved',
- 'broadcast',
+const NAT64_PREFIX = ipaddr.IPv6.parseCIDR('64:ff9b::/96');
+
+// Only public unicast is allowed by default. Private-network mode additionally
+// permits these classes. Except for public IPv4 via the well-known NAT64 prefix,
+// neither mode permits transition, multicast, link-local,
+// or reserved addresses.
+const PRIVATE_IP_RANGES = [
+ 'private',
+ 'loopback',
+ 'uniqueLocal',
+ 'carrierGradeNat',
];
-// Private-network ranges (LAN, loopback, IPv6 unique-local). These are blocked
-// by default, but self-hosters legitimately run services such as their own
-// SimpleFIN bridge on them, so callers that expect to reach private
-// infrastructure can opt in with { allowPrivateNetwork: true }. Trusting the
-// local network by default keeps self-hosting working out of the box; the
-// always-blocked ranges above still close the worst-case (metadata) attack.
-const PRIVATE_IP_RANGES = ['private', 'loopback', 'uniqueLocal'];
-
type SsrfOptions = {
- // Allow requests to private/loopback/unique-local addresses. Defaults to
+ // Allow requests to private/loopback/unique-local/CGNAT addresses. Defaults to
// false (strict). Set by callers like the SimpleFIN integration whose
// upstream may be a self-hosted server on the local network.
allowPrivateNetwork?: boolean;
@@ -49,13 +40,19 @@ export function isBlockedIp(
// process() normalizes IPv4-mapped IPv6 addresses (e.g. ::ffff:127.0.0.1)
// back to their IPv4 form so their range is classified correctly.
- const range = ipaddr.process(address).range();
-
- if (ALWAYS_BLOCKED_IP_RANGES.includes(range)) {
- return true;
+ const parsed = ipaddr.process(address);
+ if (parsed instanceof ipaddr.IPv6 && parsed.match(NAT64_PREFIX)) {
+ // The well-known NAT64 prefix is only for globally routable IPv4.
+ return (
+ ipaddr.fromByteArray(parsed.toByteArray().slice(12)).range() !== 'unicast'
+ );
}
+ const range = parsed.range();
- return !allowPrivateNetwork && PRIVATE_IP_RANGES.includes(range);
+ return (
+ range !== 'unicast' &&
+ !(allowPrivateNetwork && PRIVATE_IP_RANGES.includes(range))
+ );
}
/**
@@ -66,7 +63,7 @@ export function isBlockedIp(
*
* Pass { allowPrivateNetwork: true } for callers (e.g. SimpleFIN) whose
* upstream may legitimately be a self-hosted server on the local network; the
- * always-blocked ranges (cloud metadata, reserved, broadcast) remain blocked
+ * other address classes (including transition, multicast and link-local) remain blocked
* regardless.
*/
export async function assertUrlAllowed(
diff --git a/upcoming-release-notes/avoid-commerzbank-import-stalls.md b/upcoming-release-notes/avoid-commerzbank-import-stalls.md
new file mode 100644
index 0000000000..a97bb16f7d
--- /dev/null
+++ b/upcoming-release-notes/avoid-commerzbank-import-stalls.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Prevent certain Commerzbank payee names from stalling transaction imports.
diff --git a/upcoming-release-notes/exclude-callback-secrets-from-logs.md b/upcoming-release-notes/exclude-callback-secrets-from-logs.md
new file mode 100644
index 0000000000..572a1c5d7f
--- /dev/null
+++ b/upcoming-release-notes/exclude-callback-secrets-from-logs.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Keep sign-in and bank connection credentials out of server request logs.
diff --git a/upcoming-release-notes/protect-csv-formulas-after-bom.md b/upcoming-release-notes/protect-csv-formulas-after-bom.md
new file mode 100644
index 0000000000..cc1dcdc1a9
--- /dev/null
+++ b/upcoming-release-notes/protect-csv-formulas-after-bom.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Prevent CSV text beginning with invisible byte-order marks from being interpreted as spreadsheet formulas.
diff --git a/upcoming-release-notes/protect-local-import-destinations.md b/upcoming-release-notes/protect-local-import-destinations.md
new file mode 100644
index 0000000000..ab3ea6f869
--- /dev/null
+++ b/upcoming-release-notes/protect-local-import-destinations.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Prevent downloaded and imported budgets from replacing unrelated local budgets.
diff --git a/upcoming-release-notes/require-admin-enablebanking-configuration.md b/upcoming-release-notes/require-admin-enablebanking-configuration.md
new file mode 100644
index 0000000000..937e396c77
--- /dev/null
+++ b/upcoming-release-notes/require-admin-enablebanking-configuration.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Require administrator permission to configure Enable Banking.
diff --git a/upcoming-release-notes/restrict-desktop-navigation.md b/upcoming-release-notes/restrict-desktop-navigation.md
new file mode 100644
index 0000000000..0095dd660a
--- /dev/null
+++ b/upcoming-release-notes/restrict-desktop-navigation.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Prevent misleading web addresses from being treated as trusted desktop app pages.
diff --git a/upcoming-release-notes/restrict-external-links.md b/upcoming-release-notes/restrict-external-links.md
new file mode 100644
index 0000000000..b1a598df8c
--- /dev/null
+++ b/upcoming-release-notes/restrict-external-links.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Allow desktop links to open only web pages, and prevent network paths from opening through the file-manager action.
diff --git a/upcoming-release-notes/restrict-ssrf-address-ranges.md b/upcoming-release-notes/restrict-ssrf-address-ranges.md
new file mode 100644
index 0000000000..3db41f1f58
--- /dev/null
+++ b/upcoming-release-notes/restrict-ssrf-address-ranges.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Block unsafe network address ranges when connecting to banking services, including when private-network access is enabled.
diff --git a/upcoming-release-notes/revoke-sessions-on-password-change.md b/upcoming-release-notes/revoke-sessions-on-password-change.md
new file mode 100644
index 0000000000..43d7cb06db
--- /dev/null
+++ b/upcoming-release-notes/revoke-sessions-on-password-change.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Sign out existing sessions when the server password changes.
diff --git a/upcoming-release-notes/revoke-sessions-on-sign-out.md b/upcoming-release-notes/revoke-sessions-on-sign-out.md
new file mode 100644
index 0000000000..79db46b149
--- /dev/null
+++ b/upcoming-release-notes/revoke-sessions-on-sign-out.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+End server sessions when signing out or shutting down a password-authenticated API client
diff --git a/upcoming-release-notes/validate-server-password-input.md b/upcoming-release-notes/validate-server-password-input.md
new file mode 100644
index 0000000000..61aabf8b98
--- /dev/null
+++ b/upcoming-release-notes/validate-server-password-input.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Reject invalid password requests before processing them.
diff --git a/upcoming-release-notes/verify-current-server-password.md b/upcoming-release-notes/verify-current-server-password.md
new file mode 100644
index 0000000000..bee1320be3
--- /dev/null
+++ b/upcoming-release-notes/verify-current-server-password.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Require the current server password before changing it in settings.
diff --git a/yarn.lock b/yarn.lock
index be812904bb..8b10ca3c76 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -13537,6 +13537,7 @@ __metadata:
electron: "npm:43.5.0"
electron-builder: "npm:26.8.1"
typescript-strict-plugin: "npm:^2.4.4"
+ vitest: "npm:^5.0.0"
languageName: unknown
linkType: soft