A local-first personal finance app
[AI] Add per-budget SimpleFIN credentials (#9214)
Julian Dominguez-Schatz97a7ca50f310
diff --git a/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts b/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.tsindex bcf539158f..80da4f7a42 100644--- a/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts+++ b/packages/desktop-client/src/components/banksync/useBuiltInBankSyncProviders.ts@@ -120,7 +120,7 @@ export function useBuiltInBankSyncProviders({const enableBankingEnabled = useFeatureFlag('enableBanking');const akahuEnabled = useFeatureFlag('akahuBankSync');const { configuredGoCardless } = useGoCardlessStatus();- const { configuredSimpleFin } = useSimpleFinStatus();+ const { simpleFinStatus, setSimpleFinStatus } = useSimpleFinStatus();const { pluggyAiStatus, setPluggyAiStatus } = usePluggyAiStatus();const { configuredAkahu } = useAkahuStatus(akahuEnabled);const { configuredEnableBanking, isLoading: isEnableBankingLoading } =@@ -136,16 +136,6 @@ export function useBuiltInBankSyncProviders({setIsGoCardlessSetupComplete(configuredGoCardless);}- const [isSimpleFinSetupComplete, setIsSimpleFinSetupComplete] = useState<- boolean | null- >(configuredSimpleFin);- const [prevConfiguredSimpleFin, setPrevConfiguredSimpleFin] =- useState(configuredSimpleFin);- if (configuredSimpleFin !== prevConfiguredSimpleFin) {- setPrevConfiguredSimpleFin(configuredSimpleFin);- setIsSimpleFinSetupComplete(configuredSimpleFin);- }-const [isEnableBankingSetupComplete, setIsEnableBankingSetupComplete] =useState<boolean | null>(configuredEnableBanking);const [prevConfiguredEnableBanking, setPrevConfiguredEnableBanking] =@@ -184,12 +174,18 @@ export function useBuiltInBankSyncProviders({modal: {name: 'simplefin-init',options: {- onSuccess: () => setIsSimpleFinSetupComplete(true),+ onSuccess: perBudgetFile => {+ setSimpleFinStatus({+ configured: true,+ source: perBudgetFile ? 'per-budget-file' : 'global',+ });+ },+ credentialSource: simpleFinStatus.source ?? 'global',},},}),);- }, [dispatch]);+ }, [dispatch, simpleFinStatus.source, setSimpleFinStatus]);const onPluggyAiInit = useCallback(() => {dispatch(@@ -278,10 +274,16 @@ export function useBuiltInBankSyncProviders({const onSimpleFinReset = useCallback(async () => {try {+ const fileId =+ simpleFinStatus.source === 'per-budget-file' ? cloudFileId : null;+ if (simpleFinStatus.source === 'per-budget-file' && !fileId) {+ throw new Error(t('Budget file ID is required.'));+ }await ensureSuccessResponse(await send('secret-set', {name: 'simplefin_token',value: null,+ fileId,}),'Failed to clear SimpleFIN token',);@@ -289,14 +291,21 @@ export function useBuiltInBankSyncProviders({await send('secret-set', {name: 'simplefin_accessKey',value: null,+ fileId,}),'Failed to clear SimpleFIN access key',);- setIsSimpleFinSetupComplete(false);+ setSimpleFinStatus(await send('simplefin-status'));} catch (error) {notifyResetFailure('SimpleFIN', error);}- }, [notifyResetFailure]);+ }, [+ cloudFileId,+ notifyResetFailure,+ simpleFinStatus.source,+ setSimpleFinStatus,+ t,+ ]);const onPluggyAiReset = useCallback(async () => {try {@@ -402,7 +411,7 @@ export function useBuiltInBankSyncProviders({]);const onConnectSimpleFin = useCallback(async () => {- if (!isSimpleFinSetupComplete) {+ if (!simpleFinStatus.configured) {onSimpleFinInit();return;}@@ -465,7 +474,7 @@ export function useBuiltInBankSyncProviders({}}, [dispatch,- isSimpleFinSetupComplete,+ simpleFinStatus.configured,loadingSimpleFinAccounts,onSimpleFinInit,t,@@ -649,7 +658,7 @@ export function useBuiltInBankSyncProviders({const configuredProviders = {goCardless: Boolean(isGoCardlessSetupComplete),- simpleFin: Boolean(isSimpleFinSetupComplete),+ simpleFin: Boolean(simpleFinStatus.configured),pluggyai: Boolean(pluggyAiStatus.configured),enableBanking: Boolean(isEnableBankingSetupComplete),akahu: Boolean(isAkahuSetupComplete),@@ -683,9 +692,11 @@ export function useBuiltInBankSyncProviders({'Link a North American bank account to automatically download transactions.',),isConfigured: configuredProviders.simpleFin,- credentialSource: 'global',- supportsPerBudgetFile: false,- canConfigure: canConfigureProviders,+ credentialSource: simpleFinStatus.source ?? 'global',+ supportsPerBudgetFile: true,+ canConfigure:+ syncServerStatus === 'online' &&+ (isAdmin || (isFileOwner && simpleFinStatus.source !== 'global')),isLoading: loadingSimpleFinAccounts,onConfigure: onSimpleFinInit,onLink: onConnectSimpleFin,@@ -758,6 +769,7 @@ export function useBuiltInBankSyncProviders({configuredProviders.simpleFin,configuredProviders.akahu,pluggyAiStatus,+ simpleFinStatus,syncServerStatus,enableBankingEnabled,akahuEnabled,diff --git a/packages/desktop-client/src/components/modals/SimpleFinInitialiseModal.test.tsx b/packages/desktop-client/src/components/modals/SimpleFinInitialiseModal.test.tsxnew file mode 100644index 0000000000..4eb69e35ea--- /dev/null+++ b/packages/desktop-client/src/components/modals/SimpleFinInitialiseModal.test.tsx@@ -0,0 +1,77 @@+import { send } from '@actual-app/core/platform/client/connection';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { vi } from 'vitest';++import { TestProviders } from '#mocks';++import { SimpleFinInitialiseModal } from './SimpleFinInitialiseModal';++vi.mock('#hooks/useCurrentAccess', () => ({+ useCurrentAccess: () => ({ cloudFileId: 'budget-a', isAdmin: true }),+}));++vi.mock('@actual-app/core/platform/client/connection', () => ({+ send: vi.fn(),+ listen: vi.fn(),+ unlisten: vi.fn(),+}));++async function switchToGlobal() {+ const onSuccess = vi.fn();+ render(+ <TestProviders>+ <SimpleFinInitialiseModal+ credentialSource="per-budget-file"+ onSuccess={onSuccess}+ />+ </TestProviders>,+ );+ fireEvent.click(screen.getByLabelText('For this budget only'));+ fireEvent.change(screen.getByLabelText('Token:'), {+ target: { value: 'new-global-token' },+ });+ fireEvent.click(screen.getByRole('button', { name: 'Save and continue' }));+ return onSuccess;+}++beforeEach(() => {+ vi.mocked(send).mockReset();+});++it('removes both budget credentials before reporting a successful global switch', async () => {+ const onSuccess = await switchToGlobal();+ await waitFor(() => expect(onSuccess).toHaveBeenCalledWith(false));+ expect(vi.mocked(send).mock.calls).toEqual([+ [+ 'secret-set',+ { name: 'simplefin_token', value: 'new-global-token', fileId: null },+ ],+ ['secret-set', { name: 'simplefin_accessKey', value: null, fileId: null }],+ [+ 'secret-set',+ { name: 'simplefin_token', value: null, fileId: 'budget-a' },+ ],+ [+ 'secret-set',+ { name: 'simplefin_accessKey', value: null, fileId: 'budget-a' },+ ],+ ]);+});++it.each([3, 4])(+ 'does not report success when cleanup request %s fails',+ async failedCall => {+ for (let call = 1; call < failedCall; call++) {+ vi.mocked(send).mockResolvedValueOnce(undefined);+ }+ vi.mocked(send).mockResolvedValueOnce({ error: 'internal' });+ const onSuccess = await switchToGlobal();+ await waitFor(() =>+ expect(+ screen.getByRole('button', { name: 'Save and continue' }),+ ).toBeEnabled(),+ );+ expect(send).toHaveBeenCalledTimes(failedCall);+ expect(onSuccess).not.toHaveBeenCalled();+ },+);diff --git a/packages/desktop-client/src/components/modals/SimpleFinInitialiseModal.tsx b/packages/desktop-client/src/components/modals/SimpleFinInitialiseModal.tsxindex 5528628932..da28e56faa 100644--- a/packages/desktop-client/src/components/modals/SimpleFinInitialiseModal.tsx+++ b/packages/desktop-client/src/components/modals/SimpleFinInitialiseModal.tsx@@ -5,6 +5,7 @@ import { Trans, useTranslation } from 'react-i18next';import { ButtonWithLoading } from '@actual-app/components/button';import { Input } from '@actual-app/components/input';import { Text } from '@actual-app/components/text';+import { Toggle } from '@actual-app/components/toggle';import { View } from '@actual-app/components/view';import { send } from '@actual-app/core/platform/client/connection';@@ -17,6 +18,7 @@ import {ModalHeader,} from '#components/common/Modal';import { FormField, FormLabel } from '#components/forms';+import { useCurrentAccess } from '#hooks/useCurrentAccess';import type { Modal as ModalType } from '#modals/modalsSlice';import { getSecretsError } from '#util/error';@@ -27,8 +29,13 @@ type SimpleFinInitialiseModalProps = Extract<export const SimpleFinInitialiseModal = ({onSuccess,+ credentialSource,}: SimpleFinInitialiseModalProps) => {const { t } = useTranslation();+ const { cloudFileId, isAdmin } = useCurrentAccess();+ const [perBudgetFile, setPerBudgetFile] = useState(+ credentialSource === 'per-budget-file' || !isAdmin,+ );const [token, setToken] = useState('');const [isValid, setIsValid] = useState(true);const [isLoading, setIsLoading] = useState(false);@@ -40,25 +47,54 @@ export const SimpleFinInitialiseModal = ({return;}+ const fileId = perBudgetFile ? cloudFileId : null;+ if (perBudgetFile && !fileId) {+ setIsValid(false);+ setError(t('Budget file ID is required.'));+ return;+ }setIsLoading(true);- const { error, reason } =+ let { error, reason } =(await send('secret-set', {name: 'simplefin_token',value: token,+ fileId,})) || {};+ if (!error) {+ ({ error, reason } =+ (await send('secret-set', {+ name: 'simplefin_accessKey',+ value: null,+ fileId,+ })) || {});+ }+ if (+ !error &&+ !perBudgetFile &&+ credentialSource === 'per-budget-file' &&+ cloudFileId+ ) {+ for (const name of ['simplefin_token', 'simplefin_accessKey']) {+ ({ error, reason } =+ (await send('secret-set', {+ name,+ value: null,+ fileId: cloudFileId,+ })) || {});+ if (error) {+ break;+ }+ }+ }+ setIsLoading(false);if (error) {setIsValid(false);setError(getSecretsError(error, reason));- } else {- await send('secret-set', {- name: 'simplefin_accessKey',- value: null,- });- onSuccess();+ return;}- setIsLoading(false);+ onSuccess(perBudgetFile);close();};@@ -87,6 +123,26 @@ export const SimpleFinInitialiseModal = ({</Trans></Text>+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 12,+ }}+ >+ <Text>+ <Trans>For this budget only</Trans>+ </Text>+ <Toggle+ id="simplefin-per-budget-file"+ aria-label={t('For this budget only')}+ isOn={perBudgetFile}+ isDisabled={!isAdmin}+ onToggle={setPerBudgetFile}+ />+ </View>+<FormField><FormLabel title={t('Token:')} htmlFor="token-field" /><Inputdiff --git a/packages/desktop-client/src/hooks/useSimpleFinStatus.ts b/packages/desktop-client/src/hooks/useSimpleFinStatus.tsindex 31cc2c0b70..8a4a13533c 100644--- a/packages/desktop-client/src/hooks/useSimpleFinStatus.ts+++ b/packages/desktop-client/src/hooks/useSimpleFinStatus.ts@@ -1,13 +1,13 @@import { useEffect, useState } from 'react';import { send } from '@actual-app/core/platform/client/connection';+import type { BankSyncProviderStatus } from '@actual-app/core/types/models';import { useSyncServerStatus } from './useSyncServerStatus';export function useSimpleFinStatus() {- const [configuredSimpleFin, setConfiguredSimpleFin] = useState<- boolean | null- >(null);+ const [simpleFinStatus, setSimpleFinStatus] =+ useState<BankSyncProviderStatus>({});const [isLoading, setIsLoading] = useState(false);const status = useSyncServerStatus();@@ -17,17 +17,21 @@ export function useSimpleFinStatus() {const results = await send('simplefin-status');- setConfiguredSimpleFin(results.configured || false);+ setSimpleFinStatus(results);setIsLoading(false);}- if (status === 'online') {- void fetch();+ if (status !== 'online') {+ setSimpleFinStatus({});+ return;}++ void fetch();}, [status]);return {- configuredSimpleFin,+ simpleFinStatus,+ setSimpleFinStatus,isLoading,};}diff --git a/packages/desktop-client/src/modals/modalsSlice.ts b/packages/desktop-client/src/modals/modalsSlice.tsindex bad2b28ae9..d9763f6359 100644--- a/packages/desktop-client/src/modals/modalsSlice.ts+++ b/packages/desktop-client/src/modals/modalsSlice.ts@@ -128,7 +128,8 @@ export type Modal =| {name: 'simplefin-init';options: {- onSuccess: () => void;+ onSuccess: (perBudgetFile: boolean) => void;+ credentialSource: BankSyncCredentialSource;};}| {diff --git a/packages/docs/docs/advanced/bank-sync/simplefin.md b/packages/docs/docs/advanced/bank-sync/simplefin.mdindex 8cd2f1c395..9826acfde1 100644--- a/packages/docs/docs/advanced/bank-sync/simplefin.md+++ b/packages/docs/docs/advanced/bank-sync/simplefin.md@@ -47,6 +47,10 @@ Server Version 24.10.0 or higher are required for this feature.<img width="510" alt="The Set-up SimpleFIN dialog with an empty Token field" src="/img/advanced/bank-sync/[email protected]" />+To use separate SimpleFIN credentials for this budget, enable **For this budget only** during setup. The budget must be uploaded to your sync server first. Administrators can choose global or budget-specific credentials; other budget owners can configure budget-specific credentials when global credentials are not active.++Budget-specific credentials take precedence over global credentials. Resetting them affects only that budget, which will then use global credentials if available.+### Link Accounts with SimpleFIN1. Add the link to your accounts in actual (Existing or New).diff --git a/packages/loot-core/src/server/accounts/app.ts b/packages/loot-core/src/server/accounts/app.tsindex 276fb99e9f..c68f3d21c8 100644--- a/packages/loot-core/src/server/accounts/app.ts+++ b/packages/loot-core/src/server/accounts/app.ts@@ -303,6 +303,7 @@ async function linkSimpleFinAccount({bank.bank_id,startingDate,startingBalance,+ getPrefs()?.cloudFileId,);await handleSyncResponse(syncRes, id);@@ -894,7 +895,7 @@ async function goCardlessStatus() {);}-async function simpleFinStatus() {+async function simpleFinStatus(): Promise<BankSyncProviderStatus> {const userToken = await asyncStorage.getItem('user-token');if (!userToken) {@@ -906,11 +907,13 @@ async function simpleFinStatus() {throw new Error('Failed to get server config.');}+ const fileId = getPrefs()?.cloudFileId;return post(serverConfig.SIMPLEFIN_SERVER + '/status',{},{'X-ACTUAL-TOKEN': userToken,+ ...(fileId ? { 'X-Actual-File-Id': fileId } : {}),},);}@@ -971,12 +974,14 @@ async function simpleFinAccounts() {throw new Error('Failed to get server config.');}+ const fileId = getPrefs()?.cloudFileId;try {return await post(serverConfig.SIMPLEFIN_SERVER + '/accounts',{},{'X-ACTUAL-TOKEN': userToken,+ ...(fileId ? { 'X-Actual-File-Id': fileId } : {}),},60000,);@@ -1564,6 +1569,7 @@ async function simpleFinBatchSync({id: a.id,account_id: a.account_id || null,})),+ getPrefs()?.cloudFileId,);for (const syncResponse of syncResponses) {const account = accounts.find(a => a.id === syncResponse.accountId);diff --git a/packages/loot-core/src/server/accounts/sync.test.ts b/packages/loot-core/src/server/accounts/sync.test.tsindex 89efa09f71..83ba3d18c8 100644--- a/packages/loot-core/src/server/accounts/sync.test.ts+++ b/packages/loot-core/src/server/accounts/sync.test.ts@@ -3,6 +3,8 @@ import * as asyncStorage from '#platform/server/asyncStorage';import * as db from '#server/db';import { loadMappings } from '#server/db/mappings';import { post } from '#server/post';+import * as requests from '#server/post';+import { loadPrefs, savePrefs } from '#server/prefs';import { getServer } from '#server/server-config';import { setSyncingMode } from '#server/sync';import { handlers } from '#server/tests/mockSyncServer';@@ -1004,6 +1006,48 @@ describe('SimpleFin batch sync', () => {}});+ test.each(['individual', 'batch'])(+ 'sends the budget ID for %s sync',+ async mode => {+ await loadPrefs();+ await savePrefs({ cloudFileId: 'simplefin-budget' });+ vi.mocked(asyncStorage.multiGet).mockResolvedValue({});+ db.runQuery(+ 'INSERT INTO banks (id, bank_id, name, tombstone) VALUES (?, ?, ?, 0)',+ ['sf-bank', 'sf-bank', 'Bank'],+ );+ const id = await db.insertAccount({+ id: 'sf-account',+ bank: 'sf-bank',+ account_id: 'external-account',+ name: 'Checking',+ account_sync_source: 'simpleFin',+ });+ mockSimpleFinTransactions({+ error_type: 'INVALID_ACCESS_TOKEN',+ error_code: 'INVALID_ACCESS_TOKEN',+ });+ const request = vi.spyOn(requests, 'post');+ try {+ const handler =+ mode === 'batch' ? 'simplefin-batch-sync' : 'accounts-bank-sync';+ await accountsApp.handlers[handler]({ ids: [id] });+ expect(request).toHaveBeenCalledWith(+ getServer().SIMPLEFIN_SERVER + '/transactions',+ expect.objectContaining({+ accountId:+ mode === 'batch' ? ['external-account'] : 'external-account',+ }),+ expect.objectContaining({ 'X-Actual-File-Id': 'simplefin-budget' }),+ expect.any(Number),+ );+ } finally {+ request.mockRestore();+ await loadPrefs();+ }+ },+ );+test('does not emit transaction CRDT messages when provider category appears later', async () => {const providerAccountId = 'sf-account-1';const acctId = await db.insertAccount({diff --git a/packages/loot-core/src/server/accounts/sync.ts b/packages/loot-core/src/server/accounts/sync.tsindex a23781bd79..409775bf30 100644--- a/packages/loot-core/src/server/accounts/sync.ts+++ b/packages/loot-core/src/server/accounts/sync.ts@@ -189,6 +189,7 @@ async function downloadGoCardlessTransactions(async function downloadSimpleFinTransactions(acctId: AccountEntity['id'] | AccountEntity['id'][],since: string | string[],+ fileId?: string,) {const userToken = await asyncStorage.getItem('user-token');if (!userToken) return;@@ -207,6 +208,7 @@ async function downloadSimpleFinTransactions(},{'X-ACTUAL-TOKEN': userToken,+ ...(fileId ? { 'X-Actual-File-Id': fileId } : {}),},// 5 minute timeout for batch sync, one minute for individual accountsArray.isArray(acctId) ? 300000 : 60000,@@ -1256,7 +1258,11 @@ export async function syncAccount(let download;if (acctRow.account_sync_source === 'simpleFin') {- download = await downloadSimpleFinTransactions(acctId, syncStartDate);+ download = await downloadSimpleFinTransactions(+ acctId,+ syncStartDate,+ fileId,+ );} else if (acctRow.account_sync_source === 'pluggyai') {download = await downloadPluggyAiTransactions(acctId,@@ -1299,6 +1305,7 @@ export async function syncAccount(export async function simpleFinBatchSync(accounts: Array<Pick<AccountEntity, 'id' | 'account_id'>>,+ fileId?: string,) {const startDates = await Promise.all(accounts.map(async a => getAccountSyncStartDate(a.id)),@@ -1307,6 +1314,7 @@ export async function simpleFinBatchSync(const res = await downloadSimpleFinTransactions(accounts.map(a => a.account_id),startDates,+ fileId,);if (!res) {diff --git a/packages/sync-server/src/app-simplefin/app-simplefin.js b/packages/sync-server/src/app-simplefin/app-simplefin.jsindex 9e7f5ebc5b..40f6959016 100644--- a/packages/sync-server/src/app-simplefin/app-simplefin.js+++ b/packages/sync-server/src/app-simplefin/app-simplefin.js@@ -4,10 +4,12 @@ import express from 'express';import { handleError } from '#app-gocardless/util/handle-error';import { config } from '#load-config';import { SecretName, secretsService } from '#services/secrets-service';+import * as UserService from '#services/user-service';import {requestLoggerMiddleware,validateSessionMiddleware,} from '#util/middlewares';+import { isValidFileId } from '#util/paths';import { assertUrlAllowed, createSsrfDispatcher } from '#util/ssrf';const debugSensitive = createDebug('actual-sensitive:simplefin');@@ -22,16 +24,48 @@ app.use(requestLoggerMiddleware);app.use(express.json());app.use(validateSessionMiddleware);+app.use((req, res, next) => {+ const fileId = req.get('X-Actual-File-Id');+ if (fileId != null) {+ if (!isValidFileId(fileId)) {+ res.status(400).send({ status: 'error', reason: 'invalid-file-id' });+ return;+ }+ if (!UserService.canAccessActiveFile(fileId, res.locals.user_id)) {+ res.status(403).send({ status: 'error', reason: 'file-access-denied' });+ return;+ }+ }++ // Select the pair together, even if a budget's setup token is invalid.+ // Falling back in that case could expose global accounts unexpectedly.+ res.locals.credentialFileId =+ fileId != null &&+ (secretsService.exists(SecretName.simplefin_token, fileId) ||+ secretsService.exists(SecretName.simplefin_accessKey, fileId))+ ? fileId+ : null;+ next();+});+app.post('/status',handleError(async (req, res) => {- const token = secretsService.get(SecretName.simplefin_token);+ const token = secretsService.get(+ SecretName.simplefin_token,+ res.locals.credentialFileId,+ );const configured = token != null && !isForbidden(token);res.send({status: 'ok',data: {configured,+ source: res.locals.credentialFileId+ ? 'per-budget-file'+ : configured+ ? 'global'+ : null,},});}),@@ -40,10 +74,16 @@ app.post(app.post('/accounts',handleError(async (req, res) => {- let accessKey = secretsService.get(SecretName.simplefin_accessKey);+ let accessKey = secretsService.get(+ SecretName.simplefin_accessKey,+ res.locals.credentialFileId,+ );if (isInvalidAccessKey(accessKey)) {- const token = secretsService.get(SecretName.simplefin_token);+ const token = secretsService.get(+ SecretName.simplefin_token,+ res.locals.credentialFileId,+ );if (token == null || isForbidden(token)) {invalidToken(res);return;@@ -76,7 +116,11 @@ app.post(return;}- secretsService.set(SecretName.simplefin_accessKey, accessKey);+ secretsService.set(+ SecretName.simplefin_accessKey,+ accessKey,+ res.locals.credentialFileId,+ );}try {@@ -100,7 +144,10 @@ app.post(handleError(async (req, res) => {const { accountId, startDate } = req.body || {};- const accessKey = secretsService.get(SecretName.simplefin_accessKey);+ const accessKey = secretsService.get(+ SecretName.simplefin_accessKey,+ res.locals.credentialFileId,+ );if (isInvalidAccessKey(accessKey)) {invalidToken(res);diff --git a/packages/sync-server/src/app-simplefin/app-simplefin.test.js b/packages/sync-server/src/app-simplefin/app-simplefin.test.jsindex fa753c111e..43235c5c75 100644--- a/packages/sync-server/src/app-simplefin/app-simplefin.test.js+++ b/packages/sync-server/src/app-simplefin/app-simplefin.test.js@@ -4,6 +4,7 @@ import createDebug from 'debug';import request from 'supertest';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { getAccountDb } from '#account-db';import { SecretName, secretsService } from '#services/secrets-service';import { assertUrlAllowed } from '#util/ssrf';@@ -294,3 +295,195 @@ describe('app-simplefin', () => {});});});++describe('per-budget credentials', () => {+ const fileA = 'simplefin-budget-a';+ const fileB = 'simplefin-budget-b';+ const keyB = 'https://other:[email protected]/simplefin';+ const keyC = 'https://third:[email protected]/simplefin';++ beforeEach(() => {+ for (const fileId of [fileA, fileB]) {+ getAccountDb().mutate(+ 'INSERT INTO files (id, deleted, owner) VALUES (?, FALSE, ?)',+ [fileId, 'genericAdmin'],+ );+ }+ for (const fileId of [null, fileA, fileB]) {+ secretsService.reset(SecretName.simplefin_token, fileId);+ secretsService.reset(SecretName.simplefin_accessKey, fileId);+ }+ secretsService.set(SecretName.simplefin_token, SETUP_TOKEN);+ secretsService.set(SecretName.simplefin_accessKey, VALID_ACCESS_KEY);+ });++ afterEach(() => {+ for (const fileId of [fileA, fileB]) {+ getAccountDb().mutate('DELETE FROM files WHERE id = ?', [fileId]);+ }+ for (const fileId of [null, fileA, fileB]) {+ secretsService.reset(SecretName.simplefin_token, fileId);+ secretsService.reset(SecretName.simplefin_accessKey, fileId);+ }+ vi.restoreAllMocks();+ });++ it('claims and stores the budget key without using or replacing global credentials', async () => {+ secretsService.set(SecretName.simplefin_token, SETUP_TOKEN, fileA);+ secretsService.set(SecretName.simplefin_accessKey, keyC, fileB);+ mockFetch({+ claim: okResponse(keyB),+ accounts: okResponse(JSON.stringify({ accounts: [], errors: [] })),+ });++ await post('/accounts').set('X-Actual-File-Id', fileA).expect(200);++ expect(global.fetch).toHaveBeenCalledWith(+ 'https://bridge.example.com/claim/abc',+ expect.objectContaining({ method: 'POST' }),+ );+ expect(global.fetch).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({+ headers: {+ Authorization: `Basic ${Buffer.from('other:password').toString('base64')}`,+ },+ }),+ );+ expect(secretsService.get(SecretName.simplefin_accessKey, fileA)).toBe(+ keyB,+ );+ expect(secretsService.get(SecretName.simplefin_accessKey, fileB)).toBe(+ keyC,+ );+ expect(secretsService.get(SecretName.simplefin_accessKey)).toBe(+ VALID_ACCESS_KEY,+ );+ });++ it('uses the selected budget key for individual and batch transactions', async () => {+ secretsService.set(SecretName.simplefin_accessKey, VALID_ACCESS_KEY, fileA);+ secretsService.set(SecretName.simplefin_accessKey, keyB, fileB);+ mockFetch({+ accounts: okResponse(+ JSON.stringify({+ accounts: [+ {+ id: 'account',+ org: { name: 'Bank' },+ balance: '0.00',+ 'balance-date': 1704067200,+ transactions: [],+ },+ ],+ errors: [],+ }),+ ),+ });++ for (const [fileId, credentials] of [+ [fileA, 'user:pass'],+ [fileB, 'other:password'],+ ]) {+ for (const batch of [false, true]) {+ const res = await post('/transactions')+ .set('X-Actual-File-Id', fileId)+ .send({+ accountId: batch ? ['account'] : 'account',+ startDate: batch ? ['2024-01-01'] : '2024-01-01',+ });+ expect(res.body.data).not.toHaveProperty('error_code');+ expect(global.fetch).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({+ headers: {+ Authorization: `Basic ${Buffer.from(credentials).toString('base64')}`,+ },+ }),+ );+ }+ }+ });++ it('does not fall back to global credentials when a budget token is invalid', async () => {+ secretsService.set(SecretName.simplefin_token, 'Forbidden', fileA);+ const fetch = vi.spyOn(global, 'fetch');+ const status = await post('/status').set('X-Actual-File-Id', fileA);+ expect(status.body.data).toEqual({+ configured: false,+ source: 'per-budget-file',+ });+ for (const path of ['/accounts', '/transactions']) {+ const res = await post(path).set('X-Actual-File-Id', fileA);+ expect(res.body.data.error_code).toBe('INVALID_ACCESS_TOKEN');+ }+ expect(fetch).not.toHaveBeenCalled();+ });++ it('falls back to global credentials after clearing only the budget credentials', async () => {+ secretsService.set(SecretName.simplefin_token, SETUP_TOKEN, fileA);+ expect(+ (await post('/status').set('X-Actual-File-Id', fileA)).body.data.source,+ ).toBe('per-budget-file');+ secretsService.set(SecretName.simplefin_token, null, fileA);+ expect(+ (await post('/status').set('X-Actual-File-Id', fileA)).body.data.source,+ ).toBe('global');+ expect((await post('/status')).body.data.source).toBe('global');+ });++ it.each(['/status', '/accounts', '/transactions'])(+ 'rejects deleted budgets before %s even with retained credentials',+ async path => {+ secretsService.set(+ SecretName.simplefin_accessKey,+ VALID_ACCESS_KEY,+ fileA,+ );+ getAccountDb().mutate('UPDATE files SET deleted = 1 WHERE id = ?', [+ fileA,+ ]);+ const fetch = vi.spyOn(global, 'fetch');+ for (const token of ['valid-token', 'valid-token-user']) {+ for (const fileId of [fileA, 'missing-budget']) {+ await request(app)+ .post(path)+ .set('x-actual-token', token)+ .set('X-Actual-File-Id', fileId)+ .expect(403);+ }+ }+ expect(fetch).not.toHaveBeenCalled();+ },+ );++ it.each(['/status', '/accounts', '/transactions'])(+ 'checks budget access before %s',+ async path => {+ const fetch = vi.spyOn(global, 'fetch');+ await post(path).set('X-Actual-File-Id', '../invalid').expect(400);+ await request(app)+ .post(path)+ .set('x-actual-token', 'valid-token-user')+ .set('X-Actual-File-Id', fileA)+ .expect(403);+ expect(fetch).not.toHaveBeenCalled();++ getAccountDb().mutate(+ 'INSERT INTO user_access (file_id, user_id) VALUES (?, ?)',+ [fileA, 'genericUser'],+ );+ try {+ await request(app)+ .post('/status')+ .set('x-actual-token', 'valid-token-user')+ .set('X-Actual-File-Id', fileA)+ .expect(200);+ } finally {+ getAccountDb().mutate('DELETE FROM user_access WHERE file_id = ?', [+ fileA,+ ]);+ }+ },+ );+});diff --git a/upcoming-release-notes/simplefin-per-budget.md b/upcoming-release-notes/simplefin-per-budget.mdnew file mode 100644index 0000000000..1eb95d5b20--- /dev/null+++ b/upcoming-release-notes/simplefin-per-budget.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [jfdoming]+---++Allow separate SimpleFIN credentials for each budget.