A local-first personal finance app
import createDebug from 'debug';
import express from 'express';
import type { Request, Response } from 'express';
import { sha256String } from '#util/hash';
import {
requestLoggerMiddleware,
validateSessionMiddleware,
} from '#util/middlewares';
import {
AccountNotLinkedToRequisition,
EndUserAgreementExpiredError,
GenericGoCardlessError,
GoCardlessClientError,
RateLimitError,
RequisitionNotLinked,
} from './errors';
import type {
GoCardlessAccountId,
GoCardlessInstitutionId,
GoCardlessRequisitionId,
} from './gocardless-node.types';
import { goCardlessService } from './services/gocardless-service';
import { handleError } from './util/handle-error';
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) {
let url;
try {
url = new URL(origin ?? '');
} catch {
throw new Error('Invalid Origin header');
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new Error('Invalid Origin header');
}
return url.origin;
}
function resolveRedirectHost(req: Request) {
const { origin } = req.headers;
const host = req.get('host');
if (origin === ELECTRON_APP_ORIGIN && host) {
return `${req.protocol}://${host}`;
}
return validateOrigin(origin);
}
const SAFE_ID = /^[a-zA-Z0-9_-]+$/;
function sanitizeId<T extends string = string>(id: unknown): T {
if (typeof id !== 'string' || !SAFE_ID.test(id)) {
throw new Error(`Invalid GoCardless identifier: ${String(id)}`);
}
return id as T;
}
const LINK_PAGE_HTML = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Actual</title>
</head>
<body>
<script>
window.close();
</script>
<p>Please wait...</p>
<p>
The window should close automatically. If nothing happened you can close
this window or tab.
</p>
</body>
</html>`;
const app = express();
app.use(requestLoggerMiddleware);
app.get('/link', function (req, res) {
res.send(LINK_PAGE_HTML);
});
export { app as handlers };
app.use(express.json());
app.use(validateSessionMiddleware);
app.post('/status', async (req, res) => {
res.send({
status: 'ok',
data: {
configured: goCardlessService.isConfigured(),
},
});
});
const ensureConfigured = (
_req: Request,
res: Response,
next: express.NextFunction,
) => {
if (!goCardlessService.isConfigured()) {
res.send({
status: 'ok',
data: {
error_type: 'GOCARDLESS_NOT_CONFIGURED',
error_code: 'GOCARDLESS_NOT_CONFIGURED',
reason: 'GoCardless credentials are missing',
},
});
return;
}
next();
};
app.post(
'/create-web-token',
handleError(async (req, res) => {
const { institutionId: rawInstitutionId } = req.body || {};
const institutionId = sanitizeId<GoCardlessInstitutionId>(rawInstitutionId);
const host = resolveRedirectHost(req);
const { link, requisitionId } = await goCardlessService.createRequisition({
institutionId,
host,
});
res.send({
status: 'ok',
data: {
link,
requisitionId,
},
});
}),
);
app.post(
'/get-accounts',
handleError(async (req, res) => {
const requisitionId = sanitizeId<GoCardlessRequisitionId>(
(req.body || {}).requisitionId,
);
try {
const { requisition, accounts } =
await goCardlessService.getRequisitionWithAccounts(requisitionId);
res.send({
status: 'ok',
data: {
...requisition,
accounts: await Promise.all(
accounts.map(async account =>
account?.iban
? { ...account, iban: sha256String(account.iban) }
: account,
),
),
},
});
} catch (error) {
if (error instanceof RequisitionNotLinked) {
res.send({
status: 'ok',
requisitionStatus: isRecord(error.details)
? error.details.requisitionStatus
: undefined,
});
} else {
throw error;
}
}
}),
);
app.post(
'/get-banks',
handleError(async (req, res) => {
const { country: rawCountry, showDemo = false } = req.body || {};
const country = sanitizeId(rawCountry);
await goCardlessService.setToken();
const data = await goCardlessService.getInstitutions(country);
res.send({
status: 'ok',
data: showDemo
? [
{
id: 'SANDBOXFINANCE_SFIN0000',
name: 'DEMO bank (used for testing bank-sync)',
},
...data,
]
: data,
});
}),
);
app.post(
'/remove-account',
handleError(async (req, res) => {
const requisitionId = sanitizeId<GoCardlessRequisitionId>(
(req.body || {}).requisitionId,
);
const data = await goCardlessService.deleteRequisition(requisitionId);
if (data.summary === 'Requisition deleted') {
res.send({
status: 'ok',
data,
});
} else {
res.send({
status: 'error',
data: {
data,
reason: 'Can not delete requisition',
},
});
}
}),
);
app.post(
'/transactions',
ensureConfigured,
handleError(async (req, res) => {
const {
requisitionId: rawRequisitionId,
startDate,
endDate,
accountId: rawAccountId,
includeBalance = true,
} = req.body || {};
const requisitionId = sanitizeId<GoCardlessRequisitionId>(rawRequisitionId);
const accountId = sanitizeId<GoCardlessAccountId>(rawAccountId);
try {
if (includeBalance) {
const {
balances,
institutionId,
startingBalance,
transactions: { booked, pending, all },
} = await goCardlessService.getTransactionsWithBalance(
requisitionId,
accountId,
startDate,
endDate,
);
res.send({
status: 'ok',
data: {
balances,
institutionId,
startingBalance,
transactions: {
booked,
pending,
all,
},
},
});
} else {
const {
institutionId,
transactions: { booked, pending, all },
} = await goCardlessService.getNormalizedTransactions(
requisitionId,
accountId,
startDate,
endDate,
);
res.send({
status: 'ok',
data: {
institutionId,
transactions: {
booked,
pending,
all,
},
},
});
}
} catch (error) {
const errorDetails =
error instanceof RequisitionNotLinked ||
error instanceof GenericGoCardlessError ||
error instanceof GoCardlessClientError ||
error instanceof AccountNotLinkedToRequisition
? error.details
: undefined;
const responseHeaders =
isRecord(errorDetails) && isRecord(errorDetails.response)
? errorDetails.response.headers
: undefined;
const rateLimitHeaders = isRecord(responseHeaders)
? Object.fromEntries(
Object.entries(responseHeaders).filter(([key]) =>
key.startsWith('x-ratelimit-'),
),
)
: {};
const errorMessage =
error instanceof Error && error.message ? error.message : String(error);
const sendErrorResponse = (data: Record<string, unknown>) =>
res.send({
status: 'ok',
data: { ...data, details: errorDetails, rateLimitHeaders },
});
switch (true) {
case error instanceof RequisitionNotLinked:
case error instanceof EndUserAgreementExpiredError:
sendErrorResponse({
error_type: 'ITEM_ERROR',
error_code: 'ITEM_LOGIN_REQUIRED',
status: 'expired',
reason:
'Access to account has expired as set in End User Agreement',
});
break;
case error instanceof AccountNotLinkedToRequisition:
sendErrorResponse({
error_type: 'INVALID_INPUT',
error_code: 'INVALID_ACCESS_TOKEN',
status: 'rejected',
reason: 'Account not linked with this requisition',
});
break;
case error instanceof RateLimitError:
sendErrorResponse({
error_type: 'RATE_LIMIT_EXCEEDED',
error_code: 'NORDIGEN_ERROR',
status: 'rejected',
reason: 'Rate limit exceeded',
});
break;
case error instanceof GenericGoCardlessError:
console.log('GoCardless synchronization failed');
debugSensitive('GoCardless synchronization failed: %s', errorMessage);
sendErrorResponse({
error_type: 'SYNC_ERROR',
error_code: 'NORDIGEN_ERROR',
});
break;
default:
console.log('GoCardless synchronization failed');
debugSensitive('GoCardless synchronization failed: %s', errorMessage);
sendErrorResponse({
error_type: 'UNKNOWN',
error_code: 'UNKNOWN',
reason: 'Something went wrong',
});
break;
}
}
}),
);