A local-first personal finance app
Bank Sync Provider per budget file [2/3] - Sync server - Pluggy.ai use per-budget credentials when available (#8317)
lelemm744dd1eaff26
diff --git a/packages/loot-core/src/server/accounts/app.ts b/packages/loot-core/src/server/accounts/app.tsindex e531c2317a..95265a5779 100644--- a/packages/loot-core/src/server/accounts/app.ts+++ b/packages/loot-core/src/server/accounts/app.ts@@ -14,7 +14,7 @@ import {} from '#server/errors';import { app as mainApp } from '#server/main-app';import { mutator } from '#server/mutators';-import { get, post } from '#server/post';+import { del, get, post } from '#server/post';import { getServer } from '#server/server-config';import { batchMessages } from '#server/sync';import { undoable, withUndo } from '#server/undo';@@ -711,9 +711,11 @@ async function moveAccount({async function setSecret({name,value,+ fileId = null,}: {name: string;value: string | null;+ fileId?: string | null;}) {const userToken = await asyncStorage.getItem('user-token');@@ -726,16 +728,27 @@ async function setSecret({throw new Error('Failed to get server config.');}+ const headers = {+ 'X-ACTUAL-TOKEN': userToken,+ ...(fileId ? { 'X-Actual-File-Id': fileId } : {}),+ };+try {+ if (value === null) {+ return await del(+ serverConfig.BASE_SERVER + '/secret/' + name,+ {},+ headers,+ );+ }+return await post(serverConfig.BASE_SERVER + '/secret',{name,value,},- {- 'X-ACTUAL-TOKEN': userToken,- },+ headers,);} catch (error) {return {diff --git a/packages/sync-server/src/app-pluggyai/app-pluggyai.js b/packages/sync-server/src/app-pluggyai/app-pluggyai.jsindex b1df0bb263..4a8c3edad9 100644--- a/packages/sync-server/src/app-pluggyai/app-pluggyai.js+++ b/packages/sync-server/src/app-pluggyai/app-pluggyai.js@@ -1,11 +1,14 @@import express from 'express';+import { isAdmin } from '#account-db';import { handleError } from '#app-gocardless/util/handle-error';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 { pluggyaiService } from './pluggyai-service';@@ -15,16 +18,41 @@ app.use(requestLoggerMiddleware);app.use(express.json());app.use(validateSessionMiddleware);+function canAccessFile(fileId, userId) {+ return isAdmin(userId) || UserService.countUserAccess(fileId, userId) > 0;+}+app.post('/status',handleError(async (req, res) => {- const clientId = secretsService.get(SecretName.pluggyai_clientId);- const configured = clientId != null;+ const fileId = req.get('X-Actual-File-Id');+ if (!!fileId) {+ if (!isValidFileId(fileId)) {+ res.status(400).send({+ status: 'error',+ reason: 'invalid-file-id',+ details: 'invalid fileId',+ });+ return;+ }++ if (!canAccessFile(fileId, res.locals.user_id)) {+ res.status(403).send({+ status: 'error',+ reason: 'file-access-denied',+ details: "You don't have permissions over this file",+ });+ return;+ }+ }++ const source = pluggyaiService.getCredentialSource(fileId);res.send({status: 'ok',data: {- configured,+ configured: !!source,+ source,},});}),@@ -33,16 +61,50 @@ app.post(app.post('/accounts',handleError(async (req, res) => {+ const fileId = req.get('X-Actual-File-Id');+ if (!!fileId) {+ if (!isValidFileId(fileId)) {+ res.status(400).send({+ status: 'error',+ reason: 'invalid-file-id',+ details: 'invalid fileId',+ });+ return;+ }++ if (!canAccessFile(fileId, res.locals.user_id)) {+ res.status(403).send({+ status: 'error',+ reason: 'file-access-denied',+ details: "You don't have permissions over this file",+ });+ return;+ }+ }+try {- const itemIds = secretsService- .get(SecretName.pluggyai_itemIds)+ const source = pluggyaiService.getCredentialSource(fileId);+ if (!source) {+ res.status(400).send({+ status: 'error',+ reason: 'not-configured',+ details: 'Pluggy credentials are not configured',+ });+ return;+ }++ const credentialFileId = source === 'per-budget-file' ? fileId : null;+ const itemIds = (+ secretsService.get(SecretName.pluggyai_itemIds, credentialFileId) ?? ''+ ).split(',')- .map(item => item.trim());+ .map(item => item.trim())+ .filter(Boolean);let accounts = [];for (const item of itemIds) {- const partial = await pluggyaiService.getAccountsByItemId(item);+ const partial = await pluggyaiService.getAccountsByItemId(item, fileId);accounts = accounts.concat(partial.results);}@@ -67,14 +129,45 @@ app.post('/transactions',handleError(async (req, res) => {const { accountId, startDate } = req.body || {};+ const fileId = req.get('X-Actual-File-Id');+ if (!!fileId) {+ if (!isValidFileId(fileId)) {+ res.status(400).send({+ status: 'error',+ reason: 'invalid-file-id',+ details: 'invalid fileId',+ });+ return;+ }++ if (!canAccessFile(fileId, res.locals.user_id)) {+ res.status(403).send({+ status: 'error',+ reason: 'file-access-denied',+ details: "You don't have permissions over this file",+ });+ return;+ }+ }try {+ const source = pluggyaiService.getCredentialSource(fileId);+ if (!source) {+ res.status(400).send({+ status: 'error',+ reason: 'not-configured',+ details: 'Pluggy credentials are not configured',+ });+ return;+ }+const transactions = await pluggyaiService.getTransactionsByAccountId(accountId,startDate,+ fileId,);- const account = await pluggyaiService.getAccountById(accountId);+ const account = await pluggyaiService.getAccountById(accountId, fileId);let startingBalance = parseInt(Math.round(account.balance * 100).toString(),diff --git a/packages/sync-server/src/app-pluggyai/pluggyai-service.js b/packages/sync-server/src/app-pluggyai/pluggyai-service.jsindex f63ddb303f..270661de5b 100644--- a/packages/sync-server/src/app-pluggyai/pluggyai-service.js+++ b/packages/sync-server/src/app-pluggyai/pluggyai-service.js@@ -2,34 +2,79 @@ import { PluggyClient } from 'pluggy-sdk';import { SecretName, secretsService } from '#services/secrets-service';-let pluggyClient = null;+const pluggyClients = new Map();-function getPluggyClient() {- if (!pluggyClient) {- const clientId = secretsService.get(SecretName.pluggyai_clientId);- const clientSecret = secretsService.get(SecretName.pluggyai_clientSecret);+function hasCredentials(fileId = null) {+ return !!(+ secretsService.get(SecretName.pluggyai_clientId, fileId) &&+ secretsService.get(SecretName.pluggyai_clientSecret, fileId) &&+ secretsService.get(SecretName.pluggyai_itemIds, fileId)+ );+}++function getCredentialSource(fileId) {+ if (!!fileId && hasCredentials(fileId)) {+ return 'per-budget-file';+ }++ if (hasCredentials()) {+ return 'global';+ }++ return null;+}+function getCredentialsCacheEntry(credentialFileId) {+ const clientId = secretsService.get(+ SecretName.pluggyai_clientId,+ credentialFileId,+ );+ const clientSecret = secretsService.get(+ SecretName.pluggyai_clientSecret,+ credentialFileId,+ );++ return {+ cacheKey: JSON.stringify({+ fileId: credentialFileId,+ [SecretName.pluggyai_clientId]: clientId,+ [SecretName.pluggyai_clientSecret]: clientSecret,+ }),+ clientId,+ clientSecret,+ };+}++function getPluggyClient(fileId) {+ const credentialSource = getCredentialSource(fileId);+ if (!credentialSource) {+ throw new Error('Pluggy credentials are not configured');+ }++ const credentialFileId =+ credentialSource === 'per-budget-file' ? fileId : null;+ const { cacheKey, clientId, clientSecret } =+ getCredentialsCacheEntry(credentialFileId);+ let pluggyClient = pluggyClients.get(cacheKey);+ if (!pluggyClient) {pluggyClient = new PluggyClient({clientId,clientSecret,});+ pluggyClients.set(cacheKey, pluggyClient);}return pluggyClient;}export const pluggyaiService = {- isConfigured: () => {- return !!(- secretsService.get(SecretName.pluggyai_clientId) &&- secretsService.get(SecretName.pluggyai_clientSecret) &&- secretsService.get(SecretName.pluggyai_itemIds)- );- },+ isConfigured: fileId => getCredentialSource(fileId) != null,++ getCredentialSource,- getAccountsByItemId: async itemId => {+ getAccountsByItemId: async (itemId, fileId) => {try {- const client = getPluggyClient();+ const client = getPluggyClient(fileId);const { results, total, ...rest } = await client.fetchAccounts(itemId);return {results,@@ -43,9 +88,9 @@ export const pluggyaiService = {throw error;}},- getAccountById: async accountId => {+ getAccountById: async (accountId, fileId) => {try {- const client = getPluggyClient();+ const client = getPluggyClient(fileId);const account = await client.fetchAccount(accountId);return {...account,@@ -58,11 +103,11 @@ export const pluggyaiService = {}},- getTransactionsByAccountId: async (accountId, startDate) => {+ getTransactionsByAccountId: async (accountId, startDate, fileId) => {try {- const client = getPluggyClient();+ const client = getPluggyClient(fileId);- const account = await pluggyaiService.getAccountById(accountId);+ const account = await pluggyaiService.getAccountById(accountId, fileId);// the sandbox data doesn't move the dates automatically so the// transactions are often older than 90 days. The owner on one of thediff --git a/upcoming-release-notes/pluggy-per-budget-credentials.md b/upcoming-release-notes/pluggy-per-budget-credentials.mdnew file mode 100644index 0000000000..cd3cd25c92--- /dev/null+++ b/upcoming-release-notes/pluggy-per-budget-credentials.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [lelemm]+---++Use per-budget-file credentials for Pluggy.ai bank sync.