Skip to content

A local-first personal finance app

replace nordigen-node with our own GoCardless implementation (#7352)

Matt Fiddaman8511687da4a6
diff --git a/package.json b/package.json
index c651bfbba5..0117061e82 100644
--- a/package.json
+++ b/package.json
@@ -89,7 +89,6 @@
},
"resolutions": {
"adm-zip": "patch:adm-zip@npm%3A0.5.16#~/.yarn/patches/adm-zip-npm-0.5.16-4556fea098.patch",
- "axios": "1.14.0",
"[email protected]": "10.2.5",
"[email protected]": "3.1.5",
"minimatch@>=10.0.0 <11.0.0": "10.2.5",
diff --git a/packages/sync-server/package.json b/packages/sync-server/package.json
index fd24cacaeb..8c0b2fa4c2 100644
--- a/packages/sync-server/package.json
+++ b/packages/sync-server/package.json
@@ -41,9 +41,7 @@
"express-rate-limit": "^8.3.0",
"express-winston": "^4.2.0",
"ipaddr.js": "^2.3.0",
- "jws": "^4.0.1",
"migrate": "^2.1.0",
- "nordigen-node": "^1.4.1",
"openid-client": "^5.7.1",
"pluggy-sdk": "^0.83.0",
"uuid": "^13.0.0",
diff --git a/packages/sync-server/src/app-gocardless/app-gocardless.js b/packages/sync-server/src/app-gocardless/app-gocardless.js
index cf5ed7c87b..b6f8edf905 100644
--- a/packages/sync-server/src/app-gocardless/app-gocardless.js
+++ b/packages/sync-server/src/app-gocardless/app-gocardless.js
@@ -1,6 +1,5 @@
import path from 'path';
-import { isAxiosError } from 'axios';
import express from 'express';
import { sha256String } from '../util/hash';
@@ -18,6 +17,27 @@ import {
import { goCardlessService } from './services/gocardless-service';
import { handleError } from './util/handle-error';
+function validateOrigin(origin) {
+ 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;
+}
+
+const SAFE_ID = /^[a-zA-Z0-9_-]+$/;
+function sanitizeId(id) {
+ if (typeof id !== 'string' || !SAFE_ID.test(id)) {
+ throw new Error(`Invalid GoCardless identifier: ${String(id)}`);
+ }
+ return id;
+}
+
const app = express();
app.use(requestLoggerMiddleware);
@@ -41,12 +61,13 @@ app.post('/status', async (req, res) => {
app.post(
'/create-web-token',
handleError(async (req, res) => {
- const { institutionId } = req.body || {};
- const { origin } = req.headers;
+ const { institutionId: rawInstitutionId } = req.body || {};
+ const institutionId = sanitizeId(rawInstitutionId);
+ const host = validateOrigin(req.headers.origin);
const { link, requisitionId } = await goCardlessService.createRequisition({
institutionId,
- host: origin,
+ host,
});
res.send({
@@ -62,7 +83,7 @@ app.post(
app.post(
'/get-accounts',
handleError(async (req, res) => {
- const { requisitionId } = req.body || {};
+ const requisitionId = sanitizeId((req.body || {}).requisitionId);
try {
const { requisition, accounts } =
@@ -97,7 +118,8 @@ app.post(
app.post(
'/get-banks',
handleError(async (req, res) => {
- const { country, showDemo = false } = req.body || {};
+ const { country: rawCountry, showDemo = false } = req.body || {};
+ const country = sanitizeId(rawCountry);
await goCardlessService.setToken();
const data = await goCardlessService.getInstitutions(country);
@@ -120,7 +142,7 @@ app.post(
app.post(
'/remove-account',
handleError(async (req, res) => {
- const { requisitionId } = req.body || {};
+ const requisitionId = sanitizeId((req.body || {}).requisitionId);
const data = await goCardlessService.deleteRequisition(requisitionId);
if (data.summary === 'Requisition deleted') {
@@ -144,12 +166,14 @@ app.post(
'/transactions',
handleError(async (req, res) => {
const {
- requisitionId,
+ requisitionId: rawRequisitionId,
startDate,
endDate,
- accountId,
+ accountId: rawAccountId,
includeBalance = true,
} = req.body || {};
+ const requisitionId = sanitizeId(rawRequisitionId);
+ const accountId = sanitizeId(rawAccountId);
try {
if (includeBalance) {
@@ -206,7 +230,7 @@ app.post(
const rateLimitHeaders = Object.fromEntries(
Object.entries(headers).filter(([key]) =>
- key.startsWith('http_x_ratelimit'),
+ key.startsWith('x-ratelimit-'),
),
);
@@ -249,17 +273,6 @@ app.post(
error_code: 'NORDIGEN_ERROR',
});
break;
- case isAxiosError(error):
- console.log(
- 'Something went wrong',
- error.message,
- error.response?.data?.summary || error.response?.data?.detail || '',
- );
- sendErrorResponse({
- error_type: 'SYNC_ERROR',
- error_code: 'NORDIGEN_ERROR',
- });
- break;
default:
console.log('Something went wrong', error.message || String(error));
sendErrorResponse({
diff --git a/packages/sync-server/src/app-gocardless/errors.js b/packages/sync-server/src/app-gocardless/errors.ts
similarity index 67%
rename from packages/sync-server/src/app-gocardless/errors.js
rename to packages/sync-server/src/app-gocardless/errors.ts
index 3a77360bfa..f374959818 100644
--- a/packages/sync-server/src/app-gocardless/errors.js
+++ b/packages/sync-server/src/app-gocardless/errors.ts
@@ -1,60 +1,70 @@
+import type { GoCardlessRequisitionId } from './gocardless-node.types';
+
export class RequisitionNotLinked extends Error {
- constructor(params = {}) {
+ details: unknown;
+
+ constructor(params: unknown = {}) {
super('Requisition not linked yet');
this.details = params;
}
}
export class AccountNotLinkedToRequisition extends Error {
- constructor(accountId, requisitionId) {
+ details: {
+ accountId: string;
+ requisitionId: GoCardlessRequisitionId;
+ };
+
+ constructor(accountId: string, requisitionId: GoCardlessRequisitionId) {
super('Provided account id is not linked to given requisition');
- this.details = {
- accountId,
- requisitionId,
- };
+ this.details = { accountId, requisitionId };
}
}
export class GenericGoCardlessError extends Error {
- constructor(data = {}) {
+ details: unknown;
+
+ constructor(data: unknown = {}) {
super('GoCardless returned error');
this.details = data;
}
}
export class GoCardlessClientError extends Error {
- constructor(message, details) {
+ details: unknown;
+
+ constructor(message: string, details: unknown) {
super(message);
this.details = details;
}
}
export class InvalidInputDataError extends GoCardlessClientError {
- constructor(response) {
+ constructor(response: unknown) {
super('Invalid provided parameters', response);
}
}
export class InvalidGoCardlessTokenError extends GoCardlessClientError {
- constructor(response) {
+ constructor(response: unknown) {
super('Token is invalid or expired', response);
}
}
export class AccessDeniedError extends GoCardlessClientError {
- constructor(response) {
+ constructor(response: unknown) {
super('IP address access denied', response);
}
}
export class NotFoundError extends GoCardlessClientError {
- constructor(response) {
+ constructor(response: unknown) {
super('Resource not found', response);
}
}
export class ResourceSuspended extends GoCardlessClientError {
- constructor(response) {
+ constructor(response: unknown) {
super(
'Resource was suspended due to numerous errors that occurred while accessing it',
response,
@@ -63,7 +73,7 @@ export class ResourceSuspended extends GoCardlessClientError {
}
export class RateLimitError extends GoCardlessClientError {
- constructor(response) {
+ constructor(response: unknown) {
super(
'Daily request limit set by the Institution has been exceeded',
response,
@@ -72,13 +82,13 @@ export class RateLimitError extends GoCardlessClientError {
}
export class UnknownError extends GoCardlessClientError {
- constructor(response) {
+ constructor(response: unknown) {
super('Request to Institution returned an error', response);
}
}
export class ServiceError extends GoCardlessClientError {
- constructor(response) {
+ constructor(response: unknown) {
super('Institution service unavailable', response);
}
}
diff --git a/packages/sync-server/src/app-gocardless/gocardless-node.types.ts b/packages/sync-server/src/app-gocardless/gocardless-node.types.ts
index c7d3809b93..528dfcaf40 100644
--- a/packages/sync-server/src/app-gocardless/gocardless-node.types.ts
+++ b/packages/sync-server/src/app-gocardless/gocardless-node.types.ts
@@ -1,3 +1,10 @@
+import type { BrandedId } from '../util/types';
+
+export type GoCardlessAccountId = BrandedId<'gocardless-account'>;
+export type GoCardlessRequisitionId = BrandedId<'gocardless-requisition'>;
+export type GoCardlessInstitutionId = BrandedId<'gocardless-institution'>;
+export type GoCardlessAgreementId = BrandedId<'gocardless-agreement'>;
+
type RequisitionStatus =
| 'CR'
| 'ID'
@@ -20,12 +27,12 @@ export type Requisition = {
/**
* array of account IDs retrieved within a scope of this requisition
*/
- accounts: string[];
+ accounts: GoCardlessAccountId[];
/**
* EUA associated with this requisition
*/
- agreement: string;
+ agreement: GoCardlessAgreementId;
/**
* The date & time at which the requisition was created.
@@ -35,12 +42,12 @@ export type Requisition = {
/**
* The unique ID of the requisition
*/
- id: string;
+ id: GoCardlessRequisitionId;
/**
* an Institution ID for this Requisition
*/
- institution_id: string;
+ institution_id: GoCardlessInstitutionId;
/**
* link to initiate authorization with Institution
@@ -180,7 +187,7 @@ export type GoCardlessAccountMetadata = {
/**
* ID of the GoCardless account metadata
*/
- id: string;
+ id: GoCardlessAccountId;
/**
* Date when the GoCardless account metadata was created
*/
@@ -196,7 +203,7 @@ export type GoCardlessAccountMetadata = {
/**
* ID of the institution associated with the GoCardless account metadata
*/
- institution_id: string;
+ institution_id: GoCardlessInstitutionId;
/**
* Status of the GoCardless account
* DISCOVERED: User has successfully authenticated and account is discovered
@@ -226,7 +233,7 @@ export type Institution = {
/**
* The id of the institution, for example "N26_NTSBDEB1"
*/
- id: string;
+ id: GoCardlessInstitutionId;
/**
* The name of the institution, for example "N26 Bank"
diff --git a/packages/sync-server/src/app-gocardless/gocardless.types.ts b/packages/sync-server/src/app-gocardless/gocardless.types.ts
index b06860eb62..dfb669a525 100644
--- a/packages/sync-server/src/app-gocardless/gocardless.types.ts
+++ b/packages/sync-server/src/app-gocardless/gocardless.types.ts
@@ -1,7 +1,9 @@
import type {
Balance,
GoCardlessAccountDetails,
+ GoCardlessAccountId,
GoCardlessAccountMetadata,
+ GoCardlessInstitutionId,
Institution,
Transaction,
Transactions,
@@ -10,7 +12,7 @@ import type {
export type DetailedAccount = Omit<GoCardlessAccountDetails, 'status'> &
GoCardlessAccountMetadata;
export type DetailedAccountWithInstitution = DetailedAccount & {
- institution: Institution;
+ institution: Institution | null;
};
export type TransactionWithBookedStatus = Transaction & { booked: boolean };
@@ -18,12 +20,12 @@ export type NormalizedAccountDetails = {
/**
* Id of the account
*/
- account_id: string;
+ account_id: GoCardlessAccountId;
/**
* Institution of account
*/
- institution: Institution;
+ institution: Institution | null;
/**
* last 4 digits from the account iban
@@ -55,12 +57,12 @@ export type GetTransactionsParams = {
/**
* Id of the institution from GoCardless
*/
- institutionId: string;
+ institutionId: GoCardlessInstitutionId;
/**
* Id of account from the GoCardless app
*/
- accountId: string;
+ accountId: GoCardlessAccountId;
/**
* Begin date of the period from which we want to download transactions
@@ -80,7 +82,7 @@ export type GetTransactionsResponse = {
};
export type CreateRequisitionParams = {
- institutionId: string;
+ institutionId: GoCardlessInstitutionId;
/**
* Host of your frontend app - on this host you will be redirected after linking with bank
diff --git a/packages/sync-server/src/app-gocardless/services/gocardless-api.ts b/packages/sync-server/src/app-gocardless/services/gocardless-api.ts
new file mode 100644
index 0000000000..485ade0693
--- /dev/null
+++ b/packages/sync-server/src/app-gocardless/services/gocardless-api.ts
@@ -0,0 +1,327 @@
+import type {
+ GoCardlessAccountDetails,
+ GoCardlessAccountId,
+ GoCardlessAccountMetadata,
+ GoCardlessAgreementId,
+ GoCardlessInstitutionId,
+ GoCardlessRequisitionId,
+ Institution,
+ Requisition,
+} from '../gocardless-node.types';
+import type { GetBalances, GetTransactionsResponse } from '../gocardless.types';
+
+const BASE_URL = 'https://bankaccountdata.gocardless.com/api/v2';
+const ALLOWED_ORIGIN = new URL(BASE_URL).origin;
+
+export type TokenResponse = {
+ access: string;
+ refresh: string;
+ access_expires: number;
+ refresh_expires: number;
+};
+
+type AgreementResponse = {
+ id: GoCardlessAgreementId;
+ created: string;
+ max_historical_days: number;
+ access_valid_for_days: number;
+ access_scope: string[];
+ accepted: string | null;
+ institution_id: GoCardlessInstitutionId;
+};
+
+export type AccountDetailsResponse = {
+ account: GoCardlessAccountDetails;
+};
+
+export class GoCardlessApiError extends Error {
+ response: {
+ status: number;
+ headers: Record<string, string>;
+ data?: unknown;
+ };
+
+ constructor(
+ message: string,
+ status: number,
+ headers: Record<string, string>,
+ ) {
+ super(message);
+ this.response = { status, headers };
+ }
+}
+
+export class GoCardlessApi {
+ #secretId: string | null;
+ #secretKey: string | null;
+ #token: string | null = null;
+
+ constructor({
+ secretId,
+ secretKey,
+ }: {
+ secretId: string | null;
+ secretKey: string | null;
+ }) {
+ this.#secretId = secretId;
+ this.#secretKey = secretKey;
+ }
+
+ get secretId(): string | null {
+ return this.#secretId;
+ }
+
+ get secretKey(): string | null {
+ return this.#secretKey;
+ }
+
+ get token(): string | null {
+ return this.#token;
+ }
+
+ set token(value: string | null) {
+ this.#token = value;
+ }
+
+ async #request<T>(
+ endpoint: string,
+ {
+ method = 'GET',
+ body,
+ }: {
+ method?: 'GET' | 'POST' | 'DELETE';
+ body?: Record<string, unknown>;
+ } = {},
+ ): Promise<T> {
+ const headers: Record<string, string> = {
+ accept: 'application/json',
+ 'Content-Type': 'application/json',
+ };
+
+ if (this.#token) {
+ headers.Authorization = `Bearer ${this.#token}`;
+ }
+
+ const url = new URL(`${BASE_URL}${endpoint}`);
+ if (url.origin !== ALLOWED_ORIGIN || !url.pathname.startsWith('/api/v2/')) {
+ throw new Error(`Invalid GoCardless API endpoint: ${endpoint}`);
+ }
+
+ const response = await fetch(url, {
+ method,
+ headers,
+ signal: AbortSignal.timeout(20000),
+ ...(body
+ ? {
+ body: JSON.stringify(
+ Object.fromEntries(
+ Object.entries(body).filter(([, v]) => v != null),
+ ),
+ ),
+ }
+ : {}),
+ });
+
+ if (!response.ok) {
+ const error = new GoCardlessApiError(
+ `GoCardless API error: ${response.status}`,
+ response.status,
+ Object.fromEntries(response.headers.entries()),
+ );
+ try {
+ error.response.data = await response.json();
+ } catch {}
+ console.log(
+ `GoCardless ${method} ${endpoint} ${response.status}`,
+ error.response.data ? JSON.stringify(error.response.data) : '(no body)',
+ );
+ throw error;
+ }
+
+ return response.json() as Promise<T>;
+ }
+
+ async generateToken(): Promise<TokenResponse> {
+ const data = await this.#request<TokenResponse>('/token/new/', {
+ method: 'POST',
+ body: {
+ secret_id: this.#secretId,
+ secret_key: this.#secretKey,
+ },
+ });
+ this.#token = data.access;
+ return data;
+ }
+
+ async exchangeToken({
+ refreshToken,
+ }: {
+ refreshToken: string;
+ }): Promise<TokenResponse> {
+ const data = await this.#request<TokenResponse>('/token/refresh/', {
+ method: 'POST',
+ body: { refresh: refreshToken },
+ });
+ this.#token = data.access;
+ return data;
+ }
+
+ async getInstitutions({
+ country,
+ }: {
+ country: string;
+ }): Promise<Institution[]> {
+ return this.#request<Institution[]>(`/institutions/?country=${country}`);
+ }
+
+ async getInstitutionById(id: GoCardlessInstitutionId): Promise<Institution> {
+ return this.#request<Institution>(`/institutions/${id}/`);
+ }
+
+ async createRequisition({
+ redirectUrl,
+ institutionId,
+ agreement,
+ userLanguage,
+ reference,
+ ssn,
+ redirectImmediate,
+ accountSelection,
+ }: {
+ redirectUrl: string;
+ institutionId: GoCardlessInstitutionId;
+ agreement: GoCardlessAgreementId;
+ userLanguage: string;
+ reference: string | null;
+ ssn: string | null;
+ redirectImmediate: boolean;
+ accountSelection: boolean;
+ }): Promise<Requisition> {
+ return this.#request<Requisition>('/requisitions/', {
+ method: 'POST',
+ body: {
+ redirect: redirectUrl,
+ institution_id: institutionId,
+ agreement,
+ user_language: userLanguage,
+ reference,
+ ssn,
+ redirect_immediate: redirectImmediate,
+ account_selection: accountSelection,
+ },
+ });
+ }
+
+ async getRequisitionById(
+ requisitionId: GoCardlessRequisitionId,
+ ): Promise<Requisition> {
+ return this.#request<Requisition>(`/requisitions/${requisitionId}/`);
+ }
+
+ async deleteRequisition(
+ requisitionId: GoCardlessRequisitionId,
+ ): Promise<{ summary: string; detail: string }> {
+ return this.#request(`/requisitions/${requisitionId}/`, {
+ method: 'DELETE',
+ });
+ }
+
+ async createAgreement({
+ institutionId,
+ maxHistoricalDays = 90,
+ accessValidForDays = 90,
+ accessScope = ['balances', 'details', 'transactions'],
+ }: {
+ institutionId: GoCardlessInstitutionId;
+ maxHistoricalDays?: number;
+ accessValidForDays?: number;
+ accessScope?: string[];
+ }): Promise<AgreementResponse> {
+ return this.#request<AgreementResponse>('/agreements/enduser/', {
+ method: 'POST',
+ body: {
+ institution_id: institutionId,
+ max_historical_days: maxHistoricalDays,
+ access_valid_for_days: accessValidForDays,
+ access_scope: accessScope,
+ },
+ });
+ }
+
+ async getAccountMetadata(
+ accountId: GoCardlessAccountId,
+ ): Promise<GoCardlessAccountMetadata> {
+ return this.#request<GoCardlessAccountMetadata>(`/accounts/${accountId}/`);
+ }
+
+ async getAccountDetails(
+ accountId: GoCardlessAccountId,
+ ): Promise<AccountDetailsResponse> {
+ return this.#request<AccountDetailsResponse>(
+ `/accounts/${accountId}/details/`,
+ );
+ }
+
+ async getAccountBalances(
+ accountId: GoCardlessAccountId,
+ ): Promise<GetBalances> {
+ return this.#request<GetBalances>(`/accounts/${accountId}/balances/`);
+ }
+
+ async getAccountTransactions({
+ accountId,
+ dateFrom,
+ dateTo,
+ }: {
+ accountId: GoCardlessAccountId;
+ dateFrom?: string;
+ dateTo?: string;
+ }): Promise<GetTransactionsResponse> {
+ const params = new URLSearchParams();
+ if (dateFrom) params.set('date_from', dateFrom);
+ if (dateTo) params.set('date_to', dateTo);
+ const query = params.toString();
+ return this.#request<GetTransactionsResponse>(
+ `/accounts/${accountId}/transactions/${query ? `?${query}` : ''}`,
+ );
+ }
+
+ async initSession({
+ redirectUrl,
+ institutionId,
+ maxHistoricalDays = 90,
+ accessValidForDays = 90,
+ userLanguage = 'en',
+ referenceId = null,
+ ssn = null,
+ redirectImmediate = false,
+ accountSelection = false,
+ }: {
+ redirectUrl: string;
+ institutionId: GoCardlessInstitutionId;
+ maxHistoricalDays?: number | string;
+ accessValidForDays?: number | string;
+ userLanguage?: string;
+ referenceId?: string | null;
+ ssn?: string | null;
+ redirectImmediate?: boolean;
+ accountSelection?: boolean;
+ }): Promise<Requisition> {
+ const agreement = await this.createAgreement({
+ institutionId,
+ maxHistoricalDays: Number(maxHistoricalDays),
+ accessValidForDays: Number(accessValidForDays),
+ });
+
+ return this.createRequisition({
+ redirectUrl,
+ institutionId,
+ agreement: agreement.id,
+ userLanguage,
+ reference: referenceId,
+ ssn,
+ redirectImmediate,
+ accountSelection,
+ });
+ }
+}
diff --git a/packages/sync-server/src/app-gocardless/services/gocardless-service.js b/packages/sync-server/src/app-gocardless/services/gocardless-service.js
deleted file mode 100644
index 8da4220179..0000000000
--- a/packages/sync-server/src/app-gocardless/services/gocardless-service.js
+++ /dev/null
@@ -1,650 +0,0 @@
-import jwt from 'jws';
-import * as nordigenNode from 'nordigen-node';
-import { v4 as uuidv4 } from 'uuid';
-
-import { SecretName, secretsService } from '../../services/secrets-service';
-import { BankFactory, isSpecialContinuousAccessBank } from '../bank-factory';
-import {
- AccessDeniedError,
- AccountNotLinkedToRequisition,
- GenericGoCardlessError,
- InvalidGoCardlessTokenError,
- InvalidInputDataError,
- NotFoundError,
- RateLimitError,
- RequisitionNotLinked,
- ResourceSuspended,
- ServiceError,
- UnknownError,
-} from '../errors';
-
-const GoCardlessClient = nordigenNode.default;
-
-const clients = new Map();
-
-const getGocardlessClient = () => {
- const secrets = {
- secretId: secretsService.get(SecretName.gocardless_secretId),
- secretKey: secretsService.get(SecretName.gocardless_secretKey),
- };
-
- const hash = JSON.stringify(secrets);
-
- if (!clients.has(hash)) {
- clients.set(hash, new GoCardlessClient(secrets));
- }
-
- return clients.get(hash);
-};
-
-export const handleGoCardlessError = error => {
- const status = error?.response?.status;
-
- switch (status) {
- case 400:
- throw new InvalidInputDataError(error);
- case 401:
- throw new InvalidGoCardlessTokenError(error);
- case 403:
- throw new AccessDeniedError(error);
- case 404:
- throw new NotFoundError(error);
- case 409:
- throw new ResourceSuspended(error);
- case 429:
- throw new RateLimitError(error);
- case 500:
- throw new UnknownError(error);
- case 503:
- throw new ServiceError(error);
- default:
- throw new GenericGoCardlessError(error);
- }
-};
-
-export const goCardlessService = {
- /**
- * Check if the GoCardless service is configured to be used.
- * @returns {boolean}
- */
- isConfigured: () => {
- return !!(
- getGocardlessClient().secretId && getGocardlessClient().secretKey
- );
- },
-
- /**
- *
- * @returns {Promise<void>}
- */
- setToken: async () => {
- const isExpiredJwtToken = token => {
- const decodedToken = jwt.decode(token);
- if (!decodedToken) {
- return true;
- }
- const payload = decodedToken.payload;
- const clockTimestamp = Math.floor(Date.now() / 1000);
- return clockTimestamp >= payload.exp;
- };
-
- if (isExpiredJwtToken(getGocardlessClient().token)) {
- // Generate new access token. Token is valid for 24 hours
- // Note: access_token is automatically injected to other requests after you successfully obtain it
- try {
- await client.generateToken();
- } catch (error) {
- handleGoCardlessError(error);
- }
- }
- },
-
- /**
- *
- * @param requisitionId
- * @throws {RequisitionNotLinked} Will throw an error if requisition is not in Linked
- * @throws {InvalidInputDataError}
- * @throws {InvalidGoCardlessTokenError}
- * @throws {AccessDeniedError}
- * @throws {NotFoundError}
- * @throws {ResourceSuspended}
- * @throws {RateLimitError}
- * @throws {UnknownError}
- * @throws {ServiceError}
- * @returns {Promise<import('../gocardless-node.types').Requisition>}
- */
- getLinkedRequisition: async requisitionId => {
- const requisition = await goCardlessService.getRequisition(requisitionId);
-
- const { status } = requisition;
-
- // Continue only if status of requisition is "LN" what does
- // mean that account has been successfully linked to requisition
- if (status !== 'LN') {
- throw new RequisitionNotLinked({ requisitionStatus: status });
- }
-
- return requisition;
- },
-
- /**
- * Returns requisition and all linked accounts in their Bank format.
- * Each account object is extended about details of the institution
- * @param requisitionId
- * @throws {RequisitionNotLinked} Will throw an error if requisition is not in Linked
- * @throws {InvalidInputDataError}
- * @throws {InvalidGoCardlessTokenError}
- * @throws {AccessDeniedError}
- * @throws {NotFoundError}
- * @throws {ResourceSuspended}
- * @throws {RateLimitError}
- * @throws {UnknownError}
- * @throws {ServiceError}
- * @returns {Promise<{requisition: import('../gocardless-node.types').Requisition, accounts: Array<import('../gocardless.types').NormalizedAccountDetails>}>}
- */
- getRequisitionWithAccounts: async requisitionId => {
- const requisition =
- await goCardlessService.getLinkedRequisition(requisitionId);
-
- const institutionIdSet = new Set();
- const detailedAccounts = await Promise.all(
- requisition.accounts.map(async accountId => {
- const account = await goCardlessService.getDetailedAccount(accountId);
- institutionIdSet.add(account.institution_id);
- return account;
- }),
- );
-
- const institutions = await Promise.all(
- Array.from(institutionIdSet).map(async institutionId => {
- return await goCardlessService.getInstitution(institutionId);
- }),
- );
-
- const extendedAccounts =
- await goCardlessService.extendAccountsAboutInstitutions({
- accounts: detailedAccounts,
- institutions,
- });
-
- const normalizedAccounts = extendedAccounts.map(account => {
- const bankAccount = BankFactory(account.institution_id);
- return bankAccount.normalizeAccount(account);
- });
-
- return { requisition, accounts: normalizedAccounts };
- },
-
- /**
- *
- * @param requisitionId
- * @param accountId
- * @param startDate
- * @param endDate
- * @throws {AccountNotLinkedToRequisition} Will throw an error if requisition not includes provided account id
- * @throws {RequisitionNotLinked} Will throw an error if requisition is not in Linked
- * @throws {InvalidInputDataError}
- * @throws {InvalidGoCardlessTokenError}
- * @throws {AccessDeniedError}
- * @throws {NotFoundError}
- * @throws {ResourceSuspended}
- * @throws {RateLimitError}
- * @throws {UnknownError}
- * @throws {ServiceError}
- * @returns {Promise<{balances: Array<import('../gocardless-node.types').Balance>, institutionId: string, transactions: {booked: Array<import('../gocardless-node.types').Transaction>, pending: Array<import('../gocardless-node.types').Transaction>, all: Array<import('../gocardless.types').TransactionWithBookedStatus>}, startingBalance: number}>}
- */
- getTransactionsWithBalance: async (
- requisitionId,
- accountId,
- startDate,
- endDate,
- ) => {
- const { institution_id, accounts: accountIds } =
- await goCardlessService.getLinkedRequisition(requisitionId);
-
- if (!accountIds.includes(accountId)) {
- throw new AccountNotLinkedToRequisition(accountId, requisitionId);
- }
-
- const [normalizedTransactions, accountBalance] = await Promise.all([
- goCardlessService.getNormalizedTransactions(
- requisitionId,
- accountId,
- startDate,
- endDate,
- ),
- goCardlessService.getBalances(accountId),
- ]);
-
- const transactions = normalizedTransactions.transactions;
-
- const bank = BankFactory(institution_id);
-
- const startingBalance = bank.calculateStartingBalance(
- transactions.booked,
- accountBalance.balances,
- );
-
- return {
- balances: accountBalance.balances,
- institutionId: institution_id,
- startingBalance,
- transactions,
- };
- },
-
- /**
- *
- * @param requisitionId
- * @param accountId
- * @param startDate
- * @param endDate
- * @throws {AccountNotLinkedToRequisition} Will throw an error if requisition not includes provided account id
- * @throws {RequisitionNotLinked} Will throw an error if requisition is not in Linked
- * @throws {InvalidInputDataError}
- * @throws {InvalidGoCardlessTokenError}
- * @throws {AccessDeniedError}
- * @throws {NotFoundError}
- * @throws {ResourceSuspended}
- * @throws {RateLimitError}
- * @throws {UnknownError}
- * @throws {ServiceError}
- * @returns {Promise<{institutionId: string, transactions: {booked: Array<import('../gocardless-node.types').Transaction>, pending: Array<import('../gocardless-node.types').Transaction>, all: Array<import('../gocardless.types').TransactionWithBookedStatus>}}>}
- */
- getNormalizedTransactions: async (
- requisitionId,
- accountId,
- startDate,
- endDate,
- ) => {
- const { institution_id, accounts: accountIds } =
- await goCardlessService.getLinkedRequisition(requisitionId);
-
- if (!accountIds.includes(accountId)) {
- throw new AccountNotLinkedToRequisition(accountId, requisitionId);
- }
-
- const transactions = await goCardlessService.getTransactions({
- institutionId: institution_id,
- accountId,
- startDate,
- endDate,
- });
-
- const bank = BankFactory(institution_id);
- const sortedBookedTransactions = bank.sortTransactions(
- transactions.transactions?.booked,
- );
- const sortedPendingTransactions = bank.sortTransactions(
- transactions.transactions?.pending,
- );
- const allTransactions = sortedBookedTransactions.map(t => {
- return { ...t, booked: true };
- });
- sortedPendingTransactions.forEach(t =>
- allTransactions.push({ ...t, booked: false }),
- );
- const sortedAllTransactions = bank.sortTransactions(allTransactions);
-
- return {
- institutionId: institution_id,
- transactions: {
- booked: sortedBookedTransactions,
- pending: sortedPendingTransactions,
- all: sortedAllTransactions,
- },
- };
- },
-
- /**
- *
- * @param {import('../gocardless.types').CreateRequisitionParams} params
- * @throws {InvalidInputDataError}
- * @throws {InvalidGoCardlessTokenError}
- * @throws {AccessDeniedError}
- * @throws {NotFoundError}
- * @throws {ResourceSuspended}
- * @throws {RateLimitError}
- * @throws {UnknownError}
- * @throws {ServiceError}
- * @returns {Promise<{requisitionId, link}>}
- */
- createRequisition: async ({ institutionId, host }) => {
- await goCardlessService.setToken();
-
- const institution = await goCardlessService.getInstitution(institutionId);
- const accountSelection =
- institution.supported_features?.includes('account_selection') ?? false;
-
- let response;
- const body = {
- redirectUrl: host + '/gocardless/link',
- institutionId,
- referenceId: uuidv4(),
- accessValidForDays: institution.max_access_valid_for_days,
- maxHistoricalDays: isSpecialContinuousAccessBank(institutionId)
- ? 90
- : institution.transaction_total_days,
- userLanguage: 'en',
- ssn: null,
- redirectImmediate: false,
- accountSelection,
- };
- try {
- response = await client.initSession(body);
- } catch {
- try {
- console.log('Failed to link using:');
- console.log(body);
- console.log(
- 'Falling back to accessValidForDays = 90 ' +
- 'and maxHistoricalDays = 89',
- );
-
- response = await client.initSession({
- ...body,
- accessValidForDays: 90,
- maxHistoricalDays: 89,
- });
- } catch (error) {
- handleGoCardlessError(error);
- }
- }
-
- const { link, id: requisitionId } = response;
-
- return {
- link,
- requisitionId,
- };
- },
-
- /**
- * Deletes requisition by provided ID
- * @param requisitionId
- * @throws {InvalidInputDataError}
- * @throws {InvalidGoCardlessTokenError}
- * @throws {AccessDeniedError}
- * @throws {NotFoundError}
- * @throws {ResourceSuspended}
- * @throws {RateLimitError}
- * @throws {UnknownError}
- * @throws {ServiceError}
- * @returns {Promise<{summary: string, detail: string}>}
- */
- deleteRequisition: async requisitionId => {
- await goCardlessService.getRequisition(requisitionId);
-
- let response;
- try {
- response = client.deleteRequisition(requisitionId);
- } catch (error) {
- handleGoCardlessError(error);
- }
-
- return response;
- },
-
- /**
- * Retrieve a requisition by ID
- * https://nordigen.com/en/docs/account-information/integration/parameters-and-responses/#/requisitions/requisition%20by%20id
- * @param { string } requisitionId
- * @throws {InvalidInputDataError}
- * @throws {InvalidGoCardlessTokenError}
- * @throws {AccessDeniedError}
- * @throws {NotFoundError}
- * @throws {ResourceSuspended}
- * @throws {RateLimitError}
- * @throws {UnknownError}
- * @throws {ServiceError}
- * @returns { Promise<import('../gocardless-node.types').Requisition> }
- */
- getRequisition: async requisitionId => {
- await goCardlessService.setToken();
-
- let response;
- try {
- response = client.getRequisitionById(requisitionId);
- } catch (error) {
- handleGoCardlessError(error);
- }
-
- return response;
- },
-
- /**
- * Retrieve an detailed account by account id
- * @param accountId
- * @returns {Promise<import('../gocardless.types').DetailedAccount>}
- */
- getDetailedAccount: async accountId => {
- let detailedAccount, metadataAccount;
- try {
- [detailedAccount, metadataAccount] = await Promise.all([
- client.getDetails(accountId),
- client.getMetadata(accountId),
- ]);
- } catch (error) {
- handleGoCardlessError(error);
- }
-
- // Handle cases where either response is null/undefined
- const accountDetails = detailedAccount?.account || {};
- const metadata = metadataAccount || {};
-
- // Some banks provide additional data in both fields, but can do yucky things like have an empty
- // string in one place but not the other. We'll fix this by merging the two objects, but preferring truthy values
- // from the metadata object over the details object.
- const mergedAccount = {};
- const uniqueKeys = new Set([
- ...Object.keys(accountDetails),
- ...Object.keys(metadata),
- ]);
-
- for (const key of uniqueKeys) {
- mergedAccount[key] = metadata[key] || accountDetails[key];
- }
-
- return mergedAccount;
- },
-
- /**
- * Retrieve account metadata by account id
- *
- * Unlike getDetailedAccount, this method is not affected by institution rate-limits.
- *
- * @param accountId
- * @returns {Promise<import('../gocardless-node.types').GoCardlessAccountMetadata>}
- */
- getAccountMetadata: async accountId => {
- let response;
- try {
- response = await client.getMetadata(accountId);
- } catch (error) {
- handleGoCardlessError(error);
- }
-
- return response;
- },
-
- /**
- * Retrieve details about all Institutions in a specific country
- * @param country
- * @throws {InvalidInputDataError}
- * @throws {InvalidGoCardlessTokenError}
- * @throws {AccessDeniedError}
- * @throws {NotFoundError}
- * @throws {ResourceSuspended}
- * @throws {RateLimitError}
- * @throws {UnknownError}
- * @throws {ServiceError}
- * @returns {Promise<Array<import('../gocardless-node.types').Institution>>}
- */
- getInstitutions: async country => {
- let response;
- try {
- response = await client.getInstitutions(country);
- } catch (error) {
- handleGoCardlessError(error);
- }
-
- return response;
- },
-
- /**
- * Retrieve details about a specific Institution
- * @param institutionId
- * @throws {InvalidInputDataError}
- * @throws {InvalidGoCardlessTokenError}
- * @throws {AccessDeniedError}
- * @throws {NotFoundError}
- * @throws {ResourceSuspended}
- * @throws {RateLimitError}
- * @throws {UnknownError}
- * @throws {ServiceError}
- * @returns {Promise<import('../gocardless-node.types').Institution>}
- */
- getInstitution: async institutionId => {
- let response;
- try {
- response = await client.getInstitutionById(institutionId);
- } catch (error) {
- handleGoCardlessError(error);
- }
-
- return response;
- },
-
- /**
- * Extends provided accounts about details of their institution
- * @param {{accounts: Array<import('../gocardless.types').DetailedAccount>, institutions: Array<import('../gocardless-node.types').Institution>}} params
- * @returns {Promise<Array<import('../gocardless.types').DetailedAccount&{institution: import('../gocardless-node.types').Institution}>>}
- */
- extendAccountsAboutInstitutions: async ({ accounts, institutions }) => {
- const institutionsById = institutions.reduce((acc, institution) => {
- acc[institution.id] = institution;
- return acc;
- }, {});
-
- return accounts.map(account => {
- const institution = institutionsById[account.institution_id] || null;
- return {
- ...account,
- institution,
- };
- });
- },
-
- /**
- * Returns account transaction in provided dates
- * @param {import('../gocardless.types').GetTransactionsParams} params
- * @throws {InvalidInputDataError}
- * @throws {InvalidGoCardlessTokenError}
- * @throws {AccessDeniedError}
- * @throws {NotFoundError}
- * @throws {ResourceSuspended}
- * @throws {RateLimitError}
- * @throws {UnknownError}
- * @throws {ServiceError}
- * @returns {Promise<import('../gocardless.types').GetTransactionsResponse>}
- */
- getTransactions: async ({ institutionId, accountId, startDate, endDate }) => {
- let response;
- try {
- response = await client.getTransactions({
- accountId,
- dateFrom: startDate,
- dateTo: endDate,
- });
- } catch (error) {
- handleGoCardlessError(error);
- }
-
- const bank = BankFactory(institutionId);
- response.transactions.booked = response.transactions.booked
- .map(transaction => bank.normalizeTransaction(transaction, true))
- .filter(transaction => transaction);
- response.transactions.pending = response.transactions.pending
- .map(transaction => bank.normalizeTransaction(transaction, false))
- .filter(transaction => transaction);
-
- return response;
- },
-
- /**
- * Returns account available balances
- * @param accountId
- * @throws {InvalidInputDataError}
- * @throws {InvalidGoCardlessTokenError}
- * @throws {AccessDeniedError}
- * @throws {NotFoundError}
- * @throws {ResourceSuspended}
- * @throws {RateLimitError}
- * @throws {UnknownError}
- * @throws {ServiceError}
- * @returns {Promise<import('../gocardless.types').GetBalances>}
- */
- getBalances: async accountId => {
- let response;
- try {
- response = await client.getBalances(accountId);
- } catch (error) {
- handleGoCardlessError(error);
- }
-
- return response;
- },
-};
-
-/**
- * All executions of goCardlessClient should be here for testing purposes,
- * as the nordigen-node library is not written in a way that is conducive to testing.
- * In that way we can mock the `client` const instead of nordigen library
- */
-export const client = {
- getBalances: async accountId =>
- await getGocardlessClient().account(accountId).getBalances(),
- getTransactions: async ({ accountId, dateFrom, dateTo }) =>
- await getGocardlessClient().account(accountId).getTransactions({
- dateFrom,
- dateTo,
- country: undefined,
- }),
- getInstitutions: async country =>
- await getGocardlessClient().institution.getInstitutions({ country }),
- getInstitutionById: async institutionId =>
- await getGocardlessClient().institution.getInstitutionById(institutionId),
- getDetails: async accountId =>
- await getGocardlessClient().account(accountId).getDetails(),
- getMetadata: async accountId =>
- await getGocardlessClient().account(accountId).getMetadata(),
- getRequisitionById: async requisitionId =>
- await getGocardlessClient().requisition.getRequisitionById(requisitionId),
- deleteRequisition: async requisitionId =>
- await getGocardlessClient().requisition.deleteRequisition(requisitionId),
- initSession: async ({
- redirectUrl,
- institutionId,
- referenceId,
- accessValidForDays,
- maxHistoricalDays,
- userLanguage,
- ssn,
- redirectImmediate,
- accountSelection,
- }) =>
- await getGocardlessClient().initSession({
- redirectUrl,
- institutionId,
- referenceId,
- accessValidForDays,
- maxHistoricalDays,
- userLanguage,
- ssn,
- redirectImmediate,
- accountSelection,
- }),
- generateToken: async () => await getGocardlessClient().generateToken(),
- exchangeToken: async ({ refreshToken }) =>
- await getGocardlessClient().exchangeToken({ refreshToken }),
-};
diff --git a/packages/sync-server/src/app-gocardless/services/gocardless-service.ts b/packages/sync-server/src/app-gocardless/services/gocardless-service.ts
new file mode 100644
index 0000000000..2c4b26b42f
--- /dev/null
+++ b/packages/sync-server/src/app-gocardless/services/gocardless-service.ts
@@ -0,0 +1,510 @@
+import { v4 as uuidv4 } from 'uuid';
+
+import { SecretName, secretsService } from '../../services/secrets-service';
+import { BankFactory, isSpecialContinuousAccessBank } from '../bank-factory';
+import type { IBank } from '../banks/bank.interface';
+import {
+ AccessDeniedError,
+ AccountNotLinkedToRequisition,
+ GenericGoCardlessError,
+ InvalidGoCardlessTokenError,
+ InvalidInputDataError,
+ NotFoundError,
+ RateLimitError,
+ RequisitionNotLinked,
+ ResourceSuspended,
+ ServiceError,
+ UnknownError,
+} from '../errors';
+import type {
+ Balance,
+ GoCardlessAccountId,
+ GoCardlessAccountMetadata,
+ GoCardlessInstitutionId,
+ GoCardlessRequisitionId,
+ Institution,
+ Requisition,
+ Transaction,
+} from '../gocardless-node.types';
+import type {
+ CreateRequisitionParams,
+ DetailedAccount,
+ DetailedAccountWithInstitution,
+ GetBalances,
+ GetTransactionsParams,
+ GetTransactionsResponse,
+ NormalizedAccountDetails,
+ TransactionWithBookedStatus,
+} from '../gocardless.types';
+
+import type { AccountDetailsResponse, TokenResponse } from './gocardless-api';
+import { GoCardlessApi, GoCardlessApiError } from './gocardless-api';
+
+const clients = new Map<string, GoCardlessApi>();
+
+const getGocardlessClient = (): GoCardlessApi => {
+ const secrets = {
+ secretId: secretsService.get(SecretName.gocardless_secretId),
+ secretKey: secretsService.get(SecretName.gocardless_secretKey),
+ };
+
+ const hash = JSON.stringify(secrets);
+
+ let client = clients.get(hash);
+ if (!client) {
+ client = new GoCardlessApi(secrets);
+ clients.set(hash, client);
+ }
+
+ return client;
+};
+
+export const handleGoCardlessError = (error: unknown): never => {
+ const status =
+ error instanceof GoCardlessApiError ? error.response.status : undefined;
+
+ switch (status) {
+ case 400:
+ throw new InvalidInputDataError(error);
+ case 401:
+ throw new InvalidGoCardlessTokenError(error);
+ case 403:
+ throw new AccessDeniedError(error);
+ case 404:
+ throw new NotFoundError(error);
+ case 409:
+ throw new ResourceSuspended(error);
+ case 429:
+ throw new RateLimitError(error);
+ case 500:
+ throw new UnknownError(error);
+ case 503:
+ throw new ServiceError(error);
+ default:
+ throw new GenericGoCardlessError(error);
+ }
+};
+
+export const goCardlessService = {
+ isConfigured: (): boolean => {
+ return !!(
+ getGocardlessClient().secretId && getGocardlessClient().secretKey
+ );
+ },
+
+ setToken: async (): Promise<void> => {
+ const isExpiredJwtToken = (token: string | null): boolean => {
+ if (!token) return true;
+ try {
+ const payload = JSON.parse(
+ Buffer.from(token.split('.')[1], 'base64url').toString(),
+ );
+ const clockTimestamp = Math.floor(Date.now() / 1000);
+ return clockTimestamp >= payload.exp;
+ } catch {
+ return true;
+ }
+ };
+
+ if (isExpiredJwtToken(getGocardlessClient().token)) {
+ await client.generateToken().catch(handleGoCardlessError);
+ }
+ },
+
+ getLinkedRequisition: async (
+ requisitionId: GoCardlessRequisitionId,
+ ): Promise<Requisition> => {
+ const requisition = await goCardlessService.getRequisition(requisitionId);
+
+ const { status } = requisition;
+
+ // Continue only if status of requisition is "LN" which
+ // means the account has been successfully linked to the requisition
+ if (status !== 'LN') {
+ throw new RequisitionNotLinked({ requisitionStatus: status });
+ }
+
+ return requisition;
+ },
+
+ getRequisitionWithAccounts: async (
+ requisitionId: GoCardlessRequisitionId,
+ ): Promise<{
+ requisition: Requisition;
+ accounts: NormalizedAccountDetails[];
+ }> => {
+ const requisition =
+ await goCardlessService.getLinkedRequisition(requisitionId);
+
+ const institutionIdSet = new Set<GoCardlessInstitutionId>();
+ const detailedAccounts = await Promise.all(
+ requisition.accounts.map(async (accountId: GoCardlessAccountId) => {
+ const account = await goCardlessService.getDetailedAccount(accountId);
+ institutionIdSet.add(account.institution_id);
+ return account;
+ }),
+ );
+
+ const institutions = await Promise.all(
+ Array.from(institutionIdSet).map(
+ async (institutionId: GoCardlessInstitutionId) => {
+ return await goCardlessService.getInstitution(institutionId);
+ },
+ ),
+ );
+
+ const extendedAccounts =
+ await goCardlessService.extendAccountsAboutInstitutions({
+ accounts: detailedAccounts,
+ institutions,
+ });
+
+ const normalizedAccounts = extendedAccounts.map(account => {
+ const bank: IBank = BankFactory(account.institution_id);
+ return bank.normalizeAccount(account);
+ });
+
+ return { requisition, accounts: normalizedAccounts };
+ },
+
+ getTransactionsWithBalance: async (
+ requisitionId: GoCardlessRequisitionId,
+ accountId: GoCardlessAccountId,
+ startDate: string,
+ endDate: string,
+ ): Promise<{
+ balances: Balance[];
+ institutionId: GoCardlessInstitutionId;
+ startingBalance: number;
+ transactions: {
+ booked: Transaction[];
+ pending: Transaction[];
+ all: TransactionWithBookedStatus[];
+ };
+ }> => {
+ const { institution_id, accounts: accountIds } =
+ await goCardlessService.getLinkedRequisition(requisitionId);
+
+ if (!accountIds.includes(accountId)) {
+ throw new AccountNotLinkedToRequisition(accountId, requisitionId);
+ }
+
+ const [normalizedTransactions, accountBalance] = await Promise.all([
+ goCardlessService.getNormalizedTransactions(
+ requisitionId,
+ accountId,
+ startDate,
+ endDate,
+ ),
+ goCardlessService.getBalances(accountId),
+ ]);
+
+ const transactions = normalizedTransactions.transactions;
+
+ const bank: IBank = BankFactory(institution_id);
+
+ const startingBalance = bank.calculateStartingBalance(
+ transactions.booked,
+ accountBalance.balances,
+ );
+
+ return {
+ balances: accountBalance.balances,
+ institutionId: institution_id,
+ startingBalance,
+ transactions,
+ };
+ },
+
+ getNormalizedTransactions: async (
+ requisitionId: GoCardlessRequisitionId,
+ accountId: GoCardlessAccountId,
+ startDate: string,
+ endDate: string,
+ ): Promise<{
+ institutionId: GoCardlessInstitutionId;
+ transactions: {
+ booked: Transaction[];
+ pending: Transaction[];
+ all: TransactionWithBookedStatus[];
+ };
+ }> => {
+ const { institution_id, accounts: accountIds } =
+ await goCardlessService.getLinkedRequisition(requisitionId);
+
+ if (!accountIds.includes(accountId)) {
+ throw new AccountNotLinkedToRequisition(accountId, requisitionId);
+ }
+
+ const transactions = await goCardlessService.getTransactions({
+ institutionId: institution_id,
+ accountId,
+ startDate,
+ endDate,
+ });
+
+ const bank: IBank = BankFactory(institution_id);
+ const sortedBookedTransactions = bank.sortTransactions(
+ transactions.transactions?.booked,
+ );
+ const sortedPendingTransactions = bank.sortTransactions(
+ transactions.transactions?.pending,
+ );
+ const allTransactions: TransactionWithBookedStatus[] =
+ sortedBookedTransactions.map(t => ({
+ ...t,
+ booked: true,
+ }));
+ sortedPendingTransactions.forEach(t =>
+ allTransactions.push({ ...t, booked: false }),
+ );
+ const sortedAllTransactions = bank.sortTransactions(allTransactions);
+
+ return {
+ institutionId: institution_id,
+ transactions: {
+ booked: sortedBookedTransactions,
+ pending: sortedPendingTransactions,
+ all: sortedAllTransactions,
+ },
+ };
+ },
+
+ createRequisition: async ({
+ institutionId,
+ host,
+ }: CreateRequisitionParams): Promise<{
+ link: string;
+ requisitionId: GoCardlessRequisitionId;
+ }> => {
+ await goCardlessService.setToken();
+
+ const institution = await goCardlessService.getInstitution(institutionId);
+ const accountSelection =
+ institution.supported_features?.includes('account_selection') ?? false;
+
+ const body = {
+ redirectUrl: host + '/gocardless/link',
+ institutionId,
+ referenceId: uuidv4(),
+ accessValidForDays: institution.max_access_valid_for_days,
+ maxHistoricalDays: isSpecialContinuousAccessBank(institutionId)
+ ? 90
+ : institution.transaction_total_days,
+ userLanguage: 'en',
+ ssn: null,
+ redirectImmediate: false,
+ accountSelection,
+ };
+
+ const response = await client.initSession(body).catch(async () => {
+ console.log('Failed to link using:');
+ console.log(body);
+ console.log(
+ 'Falling back to accessValidForDays = 90 ' +
+ 'and maxHistoricalDays = 89',
+ );
+
+ return await client
+ .initSession({
+ ...body,
+ accessValidForDays: 90,
+ maxHistoricalDays: 89,
+ })
+ .catch(handleGoCardlessError);
+ });
+
+ const { link, id: requisitionId } = response;
+
+ return {
+ link,
+ requisitionId,
+ };
+ },
+
+ deleteRequisition: async (
+ requisitionId: GoCardlessRequisitionId,
+ ): Promise<{ summary: string; detail: string }> => {
+ await goCardlessService.getRequisition(requisitionId);
+ return client.deleteRequisition(requisitionId).catch(handleGoCardlessError);
+ },
+
+ getRequisition: async (
+ requisitionId: GoCardlessRequisitionId,
+ ): Promise<Requisition> => {
+ await goCardlessService.setToken();
+ return client
+ .getRequisitionById(requisitionId)
+ .catch(handleGoCardlessError);
+ },
+
+ getDetailedAccount: async (
+ accountId: GoCardlessAccountId,
+ ): Promise<DetailedAccount> => {
+ const [detailedAccount, metadataAccount] = await Promise.all([
+ client.getDetails(accountId),
+ client.getMetadata(accountId),
+ ]).catch(handleGoCardlessError);
+
+ const accountDetails = detailedAccount.account ?? {};
+ const metadata = metadataAccount ?? {};
+
+ // Some banks provide additional data in both fields, but can do yucky things like have an empty
+ // string in one place but not the other. We'll fix this by merging the two objects, but preferring truthy values
+ // from the metadata object over the details object.
+ const truthyMetadata = Object.fromEntries(
+ Object.entries(metadata).filter(([, v]) => v),
+ );
+ return {
+ ...accountDetails,
+ ...truthyMetadata,
+ } as unknown as DetailedAccount;
+ },
+
+ getAccountMetadata: async (
+ accountId: GoCardlessAccountId,
+ ): Promise<GoCardlessAccountMetadata> =>
+ client.getMetadata(accountId).catch(handleGoCardlessError),
+
+ getInstitutions: async (country: string): Promise<Institution[]> =>
+ client.getInstitutions(country).catch(handleGoCardlessError),
+
+ getInstitution: async (
+ institutionId: GoCardlessInstitutionId,
+ ): Promise<Institution> =>
+ client.getInstitutionById(institutionId).catch(handleGoCardlessError),
+
+ extendAccountsAboutInstitutions: async ({
+ accounts,
+ institutions,
+ }: {
+ accounts: DetailedAccount[];
+ institutions: Institution[];
+ }): Promise<DetailedAccountWithInstitution[]> => {
+ const institutionsById = institutions.reduce<Record<string, Institution>>(
+ (acc, institution) => {
+ acc[institution.id] = institution;
+ return acc;
+ },
+ {},
+ );
+
+ return accounts.map(account => {
+ const institution = institutionsById[account.institution_id] ?? null;
+ return {
+ ...account,
+ institution,
+ };
+ });
+ },
+
+ getTransactions: async ({
+ institutionId,
+ accountId,
+ startDate,
+ endDate,
+ }: GetTransactionsParams): Promise<GetTransactionsResponse> => {
+ const response = await client
+ .getTransactions({
+ accountId,
+ dateFrom: startDate,
+ dateTo: endDate,
+ })
+ .catch(handleGoCardlessError);
+
+ const bank: IBank = BankFactory(institutionId);
+ response.transactions.booked = response.transactions.booked
+ .map(transaction => bank.normalizeTransaction(transaction, true))
+ .filter((t): t is Transaction => t != null);
+ response.transactions.pending = response.transactions.pending
+ .map(transaction => bank.normalizeTransaction(transaction, false))
+ .filter((t): t is Transaction => t != null);
+
+ return response;
+ },
+
+ getBalances: async (accountId: GoCardlessAccountId): Promise<GetBalances> =>
+ client.getBalances(accountId).catch(handleGoCardlessError),
+};
+
+// All GoCardless API calls go through this object so tests can mock it easily.
+export const client = {
+ getBalances: async (accountId: GoCardlessAccountId): Promise<GetBalances> =>
+ await getGocardlessClient().getAccountBalances(accountId),
+ getTransactions: async ({
+ accountId,
+ dateFrom,
+ dateTo,
+ }: {
+ accountId: GoCardlessAccountId;
+ dateFrom?: string;
+ dateTo?: string;
+ }): Promise<GetTransactionsResponse> =>
+ await getGocardlessClient().getAccountTransactions({
+ accountId,
+ dateFrom,
+ dateTo,
+ }),
+ getInstitutions: async (country: string): Promise<Institution[]> =>
+ await getGocardlessClient().getInstitutions({ country }),
+ getInstitutionById: async (
+ institutionId: GoCardlessInstitutionId,
+ ): Promise<Institution> =>
+ await getGocardlessClient().getInstitutionById(institutionId),
+ getDetails: async (
+ accountId: GoCardlessAccountId,
+ ): Promise<AccountDetailsResponse> =>
+ await getGocardlessClient().getAccountDetails(accountId),
+ getMetadata: async (
+ accountId: GoCardlessAccountId,
+ ): Promise<GoCardlessAccountMetadata> =>
+ await getGocardlessClient().getAccountMetadata(accountId),
+ getRequisitionById: async (
+ requisitionId: GoCardlessRequisitionId,
+ ): Promise<Requisition> =>
+ await getGocardlessClient().getRequisitionById(requisitionId),
+ deleteRequisition: async (
+ requisitionId: GoCardlessRequisitionId,
+ ): Promise<{ summary: string; detail: string }> =>
+ await getGocardlessClient().deleteRequisition(requisitionId),
+ initSession: async ({
+ redirectUrl,
+ institutionId,
+ referenceId,
+ accessValidForDays,
+ maxHistoricalDays,
+ userLanguage,
+ ssn,
+ redirectImmediate,
+ accountSelection,
+ }: {
+ redirectUrl: string;
+ institutionId: GoCardlessInstitutionId;
+ referenceId: string | null;
+ accessValidForDays: number | string;
+ maxHistoricalDays: number | string;
+ userLanguage: string;
+ ssn: string | null;
+ redirectImmediate: boolean;
+ accountSelection: boolean;
+ }): Promise<Requisition> =>
+ await getGocardlessClient().initSession({
+ redirectUrl,
+ institutionId,
+ referenceId,
+ accessValidForDays,
+ maxHistoricalDays,
+ userLanguage,
+ ssn,
+ redirectImmediate,
+ accountSelection,
+ }),
+ generateToken: async (): Promise<TokenResponse> =>
+ await getGocardlessClient().generateToken(),
+ exchangeToken: async ({
+ refreshToken,
+ }: {
+ refreshToken: string;
+ }): Promise<TokenResponse> =>
+ await getGocardlessClient().exchangeToken({ refreshToken }),
+};
diff --git a/packages/sync-server/src/app-gocardless/services/tests/gocardless-service.spec.js b/packages/sync-server/src/app-gocardless/services/tests/gocardless-service.spec.js
index a2c81bd1ff..220060ebbe 100644
--- a/packages/sync-server/src/app-gocardless/services/tests/gocardless-service.spec.js
+++ b/packages/sync-server/src/app-gocardless/services/tests/gocardless-service.spec.js
@@ -11,6 +11,7 @@ import {
ServiceError,
UnknownError,
} from '../../errors';
+import { GoCardlessApiError } from '../gocardless-api';
import {
client,
goCardlessService,
@@ -505,53 +506,57 @@ describe('goCardlessService', () => {
});
describe('#handleGoCardlessError', () => {
+ const apiError = status =>
+ new GoCardlessApiError(`error: ${status}`, status, {});
+
it('throws InvalidInputDataError for status code 400', () => {
- const response = { response: { status: 400 } };
- expect(() => handleGoCardlessError(response)).toThrow(
+ expect(() => handleGoCardlessError(apiError(400))).toThrow(
InvalidInputDataError,
);
});
it('throws InvalidGoCardlessTokenError for status code 401', () => {
- const response = { response: { status: 401 } };
- expect(() => handleGoCardlessError(response)).toThrow(
+ expect(() => handleGoCardlessError(apiError(401))).toThrow(
InvalidGoCardlessTokenError,
);
});
it('throws AccessDeniedError for status code 403', () => {
- const response = { response: { status: 403 } };
- expect(() => handleGoCardlessError(response)).toThrow(AccessDeniedError);
+ expect(() => handleGoCardlessError(apiError(403))).toThrow(
+ AccessDeniedError,
+ );
});
it('throws NotFoundError for status code 404', () => {
- const response = { response: { status: 404 } };
- expect(() => handleGoCardlessError(response)).toThrow(NotFoundError);
+ expect(() => handleGoCardlessError(apiError(404))).toThrow(NotFoundError);
});
it('throws ResourceSuspended for status code 409', () => {
- const response = { response: { status: 409 } };
- expect(() => handleGoCardlessError(response)).toThrow(ResourceSuspended);
+ expect(() => handleGoCardlessError(apiError(409))).toThrow(
+ ResourceSuspended,
+ );
});
it('throws RateLimitError for status code 429', () => {
- const response = { response: { status: 429 } };
- expect(() => handleGoCardlessError(response)).toThrow(RateLimitError);
+ expect(() => handleGoCardlessError(apiError(429))).toThrow(RateLimitError);
});
it('throws UnknownError for status code 500', () => {
- const response = { response: { status: 500 } };
- expect(() => handleGoCardlessError(response)).toThrow(UnknownError);
+ expect(() => handleGoCardlessError(apiError(500))).toThrow(UnknownError);
});
it('throws ServiceError for status code 503', () => {
- const response = { response: { status: 503 } };
- expect(() => handleGoCardlessError(response)).toThrow(ServiceError);
+ expect(() => handleGoCardlessError(apiError(503))).toThrow(ServiceError);
+ });
+
+ it('throws GenericGoCardlessError for unrecognised status codes', () => {
+ expect(() => handleGoCardlessError(apiError(0))).toThrow(
+ GenericGoCardlessError,
+ );
});
- it('throws a generic error when the status code is not recognised', () => {
- const response = { response: { status: 0 } };
- expect(() => handleGoCardlessError(response)).toThrow(
+ it('throws GenericGoCardlessError for non-API errors', () => {
+ expect(() => handleGoCardlessError(new Error('network down'))).toThrow(
GenericGoCardlessError,
);
});
diff --git a/upcoming-release-notes/7352.md b/upcoming-release-notes/7352.md
new file mode 100644
index 0000000000..802eee1a2b
--- /dev/null
+++ b/upcoming-release-notes/7352.md
@@ -0,0 +1,6 @@
+---
+category: Maintenance
+authors: [matt-fidd]
+---
+
+Replace nordigen-node with our own GoCardless implementation
diff --git a/yarn.lock b/yarn.lock
index b2a882e6a1..16bf9b2c9e 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -210,10 +210,8 @@ __metadata:
express-winston: "npm:^4.2.0"
http-proxy-middleware: "npm:^3.0.5"
ipaddr.js: "npm:^2.3.0"
- jws: "npm:^4.0.1"
migrate: "npm:^2.1.0"
nodemon: "npm:^3.1.14"
- nordigen-node: "npm:^1.4.1"
openid-client: "npm:^5.7.1"
pluggy-sdk: "npm:^0.83.0"
supertest: "npm:^7.2.2"
@@ -12095,17 +12093,6 @@ __metadata:
languageName: node
linkType: hard
-"axios@npm:1.14.0":
- version: 1.14.0
- resolution: "axios@npm:1.14.0"
- dependencies:
- follow-redirects: "npm:^1.15.11"
- form-data: "npm:^4.0.5"
- proxy-from-env: "npm:^2.1.0"
- checksum: 10/c3444e9e3da1714916e4ddd7cda05bb41a5d5d80e3e27b099a116439684c63f2280c88503d1acd65841698b63af0b542b4d5780454e28fd0aed2d783ef90943e
- languageName: node
- linkType: hard
-
"b4a@npm:^1.6.4":
version: 1.7.3
resolution: "b4a@npm:1.7.3"
@@ -15504,13 +15491,6 @@ __metadata:
languageName: node
linkType: hard
-"dotenv@npm:^10.0.0":
- version: 10.0.0
- resolution: "dotenv@npm:10.0.0"
- checksum: 10/55f701ae213e3afe3f4232fae5edfb6e0c49f061a363ff9f1c5a0c2bf3fb990a6e49aeada11b2a116efb5fdc3bc3f1ef55ab330be43033410b267f7c0809a9dc
- languageName: node
- linkType: hard
-
"dotenv@npm:^16.0.0, dotenv@npm:^16.4.5":
version: 16.6.1
resolution: "dotenv@npm:16.6.1"
@@ -17115,7 +17095,7 @@ __metadata:
languageName: node
linkType: hard
-"follow-redirects@npm:^1.0.0, follow-redirects@npm:^1.15.11":
+"follow-redirects@npm:^1.0.0":
version: 1.15.11
resolution: "follow-redirects@npm:1.15.11"
peerDependenciesMeta:
@@ -19846,17 +19826,6 @@ __metadata:
languageName: node
linkType: hard
-"jwa@npm:^2.0.1":
- version: 2.0.1
- resolution: "jwa@npm:2.0.1"
- dependencies:
- buffer-equal-constant-time: "npm:^1.0.1"
- ecdsa-sig-formatter: "npm:1.0.11"
- safe-buffer: "npm:^5.0.1"
- checksum: 10/b04312a1de85f912b96aa3a7211717b8336945fab5b4f7cbc7800f4c80934060c0a3111576fad8d76e41ad62887d6da4b21fd4c47e45c174197f8be7dc0c1694
- languageName: node
- linkType: hard
-
"jws@npm:^3.2.2":
version: 3.2.2
resolution: "jws@npm:3.2.2"
@@ -19867,16 +19836,6 @@ __metadata:
languageName: node
linkType: hard
-"jws@npm:^4.0.1":
- version: 4.0.1
- resolution: "jws@npm:4.0.1"
- dependencies:
- jwa: "npm:^2.0.1"
- safe-buffer: "npm:^5.0.1"
- checksum: 10/75d7b157489fa9a72023712c58a7a7706c7e2b10eec27fabd3bb9cae0c9e492251ab72527d20a8a5f5726196f0508c320c643fddff7076657f6bca16d0ceeeeb
- languageName: node
- linkType: hard
-
"katex@npm:^0.16.22":
version: 0.16.25
resolution: "katex@npm:0.16.25"
@@ -22228,16 +22187,6 @@ __metadata:
languageName: node
linkType: hard
-"nordigen-node@npm:^1.4.1":
- version: 1.4.1
- resolution: "nordigen-node@npm:1.4.1"
- dependencies:
- axios: "npm:^1.2.1"
- dotenv: "npm:^10.0.0"
- checksum: 10/b8b856adc6231db01bd0f23b2dea157f1888dd6b86c8ff5290887857def680c2de76ce4b3fc06559ff75474b9fb4355f400a167bc2bf793e4d0743fa641b0297
- languageName: node
- linkType: hard
-
"normalize-package-data@npm:^2.3.2":
version: 2.5.0
resolution: "normalize-package-data@npm:2.5.0"
@@ -24434,13 +24383,6 @@ __metadata:
languageName: node
linkType: hard
-"proxy-from-env@npm:^2.1.0":
- version: 2.1.0
- resolution: "proxy-from-env@npm:2.1.0"
- checksum: 10/fbbaf4dab2a6231dc9e394903a5f66f20475e36b734335790b46feb9da07c37d6b32e2c02e3e2ea4d4b23774c53d8562e5b7cc73282cb43f4a597b7eacaee2ee
- languageName: node
- linkType: hard
-
"pstree.remy@npm:^1.1.8":
version: 1.1.8
resolution: "pstree.remy@npm:1.1.8"