Skip to content

A local-first personal finance app

better simplefin errors (#8568)

Matt Fiddamancefd52e9c33e
diff --git a/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts b/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts
index ee038f258c..d0b645c767 100644
--- a/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts
+++ b/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts
@@ -403,8 +403,12 @@ export function useBuiltInBankSyncProviders({
try {
const results = await send('simplefin-accounts');
+ if (results.error_code === 'INVALID_ACCESS_TOKEN') {
+ onSimpleFinInit();
+ return;
+ }
if (results.error_code) {
- throw new Error(results.reason);
+ throw new Error(results.reason || results.error_code);
}
if ('error' in results && results.error) {
throw new Error(results.reason || results.error);
@@ -433,8 +437,17 @@ export function useBuiltInBankSyncProviders({
},
}),
);
- } catch {
- onSimpleFinInit();
+ } catch (error) {
+ dispatch(
+ addNotification({
+ notification: {
+ type: 'error',
+ title: t('Error when trying to contact SimpleFIN'),
+ message: error instanceof Error ? error.message : String(error),
+ timeout: 5000,
+ },
+ }),
+ );
} finally {
setLoadingSimpleFinAccounts(false);
}
@@ -443,6 +456,7 @@ export function useBuiltInBankSyncProviders({
isSimpleFinSetupComplete,
loadingSimpleFinAccounts,
onSimpleFinInit,
+ t,
upgradingAccountId,
]);
diff --git a/packages/sync-server/src/app-simplefin/app-simplefin.js b/packages/sync-server/src/app-simplefin/app-simplefin.js
index b99d9b5e94..3846370b87 100644
--- a/packages/sync-server/src/app-simplefin/app-simplefin.js
+++ b/packages/sync-server/src/app-simplefin/app-simplefin.js
@@ -34,22 +34,41 @@ app.post(
handleError(async (req, res) => {
let accessKey = secretsService.get(SecretName.simplefin_accessKey);
- try {
+ if (isInvalidAccessKey(accessKey)) {
+ const token = secretsService.get(SecretName.simplefin_token);
+ if (token == null || isForbidden(token)) {
+ invalidToken(res);
+ return;
+ }
+
+ const claimUrl = decodeClaimUrl(token);
+ if (claimUrl == null) {
+ console.log(
+ 'SimpleFIN setup token does not decode to a claim URL - re-enter the token',
+ );
+ invalidToken(res);
+ return;
+ }
+
+ try {
+ accessKey = await claimAccessKey(claimUrl);
+ } catch (e) {
+ console.log('Failed to claim the SimpleFIN setup token:');
+ serverDown(e, res);
+ return;
+ }
+
if (isInvalidAccessKey(accessKey)) {
- const token = secretsService.get(SecretName.simplefin_token);
- if (token == null || isForbidden(token)) {
- throw new Error('No token');
- } else {
- accessKey = await getAccessKey(token);
- if (isInvalidAccessKey(accessKey)) {
- throw new Error('No access key');
- }
- secretsService.set(SecretName.simplefin_accessKey, accessKey);
- }
+ console.log(
+ `SimpleFIN rejected the setup token claim: ${
+ accessKey.slice(0, 200) || '(empty response)'
+ }`,
+ );
+ invalidToken(res);
+ return;
}
- } catch {
- invalidToken(res);
- return;
+
+ secretsService.set(SecretName.simplefin_accessKey, accessKey);
}
try {
@@ -289,6 +308,8 @@ function serverDown(e, res) {
});
}
+const ACCESS_KEY_FORMAT = /^.*\/\/.*:.*@.*$/;
+
function parseAccessKey(accessKey) {
let scheme = null;
let rest = null;
@@ -296,7 +317,7 @@ function parseAccessKey(accessKey) {
let username = null;
let password = null;
let baseUrl = null;
- if (!accessKey || !accessKey.match(/^.*\/\/.*:.*@.*$/)) {
+ if (!accessKey || !ACCESS_KEY_FORMAT.test(accessKey)) {
console.log('Invalid SimpleFIN access key');
throw new Error(`Invalid access key`);
}
@@ -311,15 +332,39 @@ function parseAccessKey(accessKey) {
};
}
-async function getAccessKey(base64Token) {
- const token = Buffer.from(base64Token, 'base64').toString();
+function decodeClaimUrl(base64Token) {
+ const decoded = Buffer.from(base64Token, 'base64').toString();
+
+ let url;
+ try {
+ url = new URL(decoded);
+ } catch {
+ return null;
+ }
+
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
+ return null;
+ }
+
+ return decoded;
+}
+
+async function claimAccessKey(claimUrl) {
// Self-hosters may run their own SimpleFIN bridge on the local network, so
// private addresses are allowed here; cloud metadata and other always-blocked
// ranges are still rejected.
- await assertUrlAllowed(token, { allowPrivateNetwork: true });
+ await assertUrlAllowed(claimUrl, { allowPrivateNetwork: true });
// don't auto-follow redirects for SSRF safety
- const response = await fetch(token, { method: 'POST', redirect: 'manual' });
+ const response = await fetch(claimUrl, {
+ method: 'POST',
+ redirect: 'manual',
+ });
+
+ if (!response.ok && response.status !== 403) {
+ throw new Error(`SimpleFIN claim failed with HTTP ${response.status}`);
+ }
+
return (await response.text()).trim();
}
@@ -330,8 +375,8 @@ function isForbidden(value) {
function isInvalidAccessKey(accessKey) {
return (
typeof accessKey !== 'string' ||
- accessKey.trim() === '' ||
- isForbidden(accessKey)
+ isForbidden(accessKey) ||
+ !ACCESS_KEY_FORMAT.test(accessKey)
);
}
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 d61ea35f48..00ee0729e9 100644
--- a/packages/sync-server/src/app-simplefin/app-simplefin.test.js
+++ b/packages/sync-server/src/app-simplefin/app-simplefin.test.js
@@ -2,6 +2,7 @@ import request from 'supertest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { SecretName, secretsService } from '#services/secrets-service';
+import { assertUrlAllowed } from '#util/ssrf';
import { handlers as app } from './app-simplefin';
@@ -14,12 +15,15 @@ const SETUP_TOKEN = Buffer.from(
'https://bridge.example.com/claim/abc',
).toString('base64');
-const okResponse = body => ({
- status: 200,
+const statusResponse = (status, body = '') => ({
+ ok: status >= 200 && status < 300,
+ status,
headers: { get: () => null },
text: () => Promise.resolve(body),
});
+const okResponse = body => statusResponse(200, body);
+
// The claim is a POST to the bridge; listing accounts is a GET. Route the mock
// by method so a test can stub one or both.
function mockFetch({ claim, accounts }) {
@@ -141,5 +145,125 @@ describe('app-simplefin', () => {
VALID_ACCESS_KEY,
);
});
+
+ it('re-claims when a stale non-URL access key is cached', async () => {
+ secretsService.set(SecretName.simplefin_token, SETUP_TOKEN);
+ secretsService.set(
+ SecretName.simplefin_accessKey,
+ '<html>Bad Gateway</html>',
+ );
+ mockFetch({
+ claim: okResponse(VALID_ACCESS_KEY),
+ accounts: okResponse(
+ JSON.stringify({ accounts: [{ id: 'account-1' }] }),
+ ),
+ });
+
+ const res = await post('/accounts');
+
+ expect(res.body.data.accounts).toEqual([{ id: 'account-1' }]);
+ expect(secretsService.get(SecretName.simplefin_accessKey)).toBe(
+ VALID_ACCESS_KEY,
+ );
+ });
+
+ it('treats a claim response that is not an access URL as invalid and does not persist it', async () => {
+ secretsService.set(SecretName.simplefin_token, SETUP_TOKEN);
+ mockFetch({ claim: okResponse('<html>Service unavailable</html>') });
+
+ const res = await post('/accounts');
+
+ expect(res.body.data.error_code).toBe('INVALID_ACCESS_TOKEN');
+ expect(secretsService.get(SecretName.simplefin_accessKey)).toBeNull();
+ });
+
+ it('rejects a token that does not decode to a claim URL without contacting SimpleFIN', async () => {
+ secretsService.set(
+ SecretName.simplefin_token,
+ Buffer.from('not a claim url').toString('base64'),
+ );
+ global.fetch = vi.fn();
+
+ const res = await post('/accounts');
+
+ expect(res.body.data.error_code).toBe('INVALID_ACCESS_TOKEN');
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+
+ it('treats a 403 Forbidden claim as an invalid token and does not persist it', async () => {
+ secretsService.set(SecretName.simplefin_token, SETUP_TOKEN);
+ mockFetch({
+ claim: statusResponse(403, 'Forbidden (was it already claimed?)'),
+ });
+
+ const res = await post('/accounts');
+
+ expect(res.body.data.error_code).toBe('INVALID_ACCESS_TOKEN');
+ expect(secretsService.get(SecretName.simplefin_accessKey)).toBeNull();
+ });
+
+ it('reports SERVER_DOWN when the claim response is a redirect', async () => {
+ secretsService.set(SecretName.simplefin_token, SETUP_TOKEN);
+ mockFetch({ claim: statusResponse(302) });
+
+ const res = await post('/accounts');
+
+ expect(res.body.data.error_code).toBe('SERVER_DOWN');
+ expect(secretsService.get(SecretName.simplefin_accessKey)).toBeNull();
+ });
+
+ it('reports SERVER_DOWN when the claim fails with a server error', async () => {
+ secretsService.set(SecretName.simplefin_token, SETUP_TOKEN);
+ mockFetch({
+ claim: statusResponse(502, '<html>Bad Gateway</html>'),
+ });
+
+ const res = await post('/accounts');
+
+ expect(res.body.data.error_code).toBe('SERVER_DOWN');
+ expect(secretsService.get(SecretName.simplefin_accessKey)).toBeNull();
+ });
+
+ it('reports SERVER_DOWN when the claim request fails at the network level', async () => {
+ secretsService.set(SecretName.simplefin_token, SETUP_TOKEN);
+ global.fetch = vi.fn().mockRejectedValue(new TypeError('fetch failed'));
+
+ const res = await post('/accounts');
+
+ expect(res.body.data.error_code).toBe('SERVER_DOWN');
+ expect(secretsService.get(SecretName.simplefin_accessKey)).toBeNull();
+ });
+
+ it('reports SERVER_DOWN when the claim URL fails the SSRF preflight', async () => {
+ secretsService.set(SecretName.simplefin_token, SETUP_TOKEN);
+ assertUrlAllowed.mockRejectedValueOnce(
+ new Error('Unable to resolve host: bridge.example.com'),
+ );
+ global.fetch = vi.fn();
+
+ const res = await post('/accounts');
+
+ expect(res.body.data.error_code).toBe('SERVER_DOWN');
+ expect(global.fetch).not.toHaveBeenCalled();
+ expect(secretsService.get(SecretName.simplefin_accessKey)).toBeNull();
+ });
+ });
+
+ describe('/transactions', () => {
+ it('reports an invalid token when the cached access key is not an access URL', async () => {
+ secretsService.set(
+ SecretName.simplefin_accessKey,
+ '<html>Bad Gateway</html>',
+ );
+ global.fetch = vi.fn();
+
+ const res = await post('/transactions').send({
+ accountId: 'account-1',
+ startDate: '2026-07-01',
+ });
+
+ expect(res.body.data.error_code).toBe('INVALID_ACCESS_TOKEN');
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
});
});
diff --git a/upcoming-release-notes/fix-simplefin-claim-error-reporting.md b/upcoming-release-notes/fix-simplefin-claim-error-reporting.md
new file mode 100644
index 0000000000..3865de4911
--- /dev/null
+++ b/upcoming-release-notes/fix-simplefin-claim-error-reporting.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [matt-fidd]
+---
+
+Show a clearer error when SimpleFIN can't be reached while linking accounts, instead of wrongly reporting the token as invalid