Skip to content

A local-first personal finance app

fix electron GoCardless linking (#8510)

Matt Fiddamana31cfe751458
diff --git a/packages/desktop-client/src/gocardless.ts b/packages/desktop-client/src/gocardless.ts
index 7a2b9d1483..9d077b4126 100644
--- a/packages/desktop-client/src/gocardless.ts
+++ b/packages/desktop-client/src/gocardless.ts
@@ -29,6 +29,9 @@ function _authorize(
});
if ('error' in resp) return resp;
+ if ('error_code' in resp) {
+ return { error: 'unknown', message: resp.error_type };
+ }
const { link, requisitionId } = resp;
window.Actual.openURLInBrowser(link);
diff --git a/packages/loot-core/src/platform/server/fetch/index.test.ts b/packages/loot-core/src/platform/server/fetch/index.test.ts
new file mode 100644
index 0000000000..3535f074c2
--- /dev/null
+++ b/packages/loot-core/src/platform/server/fetch/index.test.ts
@@ -0,0 +1,32 @@
+import { fetch } from '#platform/server/fetch';
+
+describe('electron fetch', () => {
+ const globalFetch = vi.fn();
+
+ beforeEach(() => {
+ globalFetch.mockReset();
+ globalFetch.mockResolvedValue(new Response('ok'));
+ vi.stubGlobal('fetch', globalFetch);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('sends the app://actual origin', async () => {
+ await fetch('https://sync.example.com/gocardless/create-web-token', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ });
+
+ expect(globalFetch).toHaveBeenCalledWith(
+ 'https://sync.example.com/gocardless/create-web-token',
+ expect.objectContaining({
+ headers: {
+ 'Content-Type': 'application/json',
+ origin: 'app://actual',
+ },
+ }),
+ );
+ });
+});
diff --git a/packages/sync-server/src/app-gocardless/app-gocardless.test.ts b/packages/sync-server/src/app-gocardless/app-gocardless.test.ts
new file mode 100644
index 0000000000..9289d6c096
--- /dev/null
+++ b/packages/sync-server/src/app-gocardless/app-gocardless.test.ts
@@ -0,0 +1,117 @@
+import express from 'express';
+import request from 'supertest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { GoCardlessRequisitionId } from './gocardless-node.types';
+
+vi.mock('#util/middlewares', () => ({
+ requestLoggerMiddleware: (_req: unknown, _res: unknown, next: () => void) =>
+ next(),
+ validateSessionMiddleware: (_req: unknown, _res: unknown, next: () => void) =>
+ next(),
+}));
+
+vi.mock('./services/gocardless-service', () => ({
+ goCardlessService: {
+ createRequisition: vi.fn(),
+ },
+}));
+
+const { goCardlessService } = await import('./services/gocardless-service');
+const { handlers } = await import('./app-gocardless');
+
+const app = express();
+app.use('/', handlers);
+
+describe('/create-web-token', () => {
+ const createRequisition = vi.mocked(goCardlessService.createRequisition);
+
+ beforeEach(() => {
+ createRequisition.mockReset();
+ createRequisition.mockResolvedValue({
+ link: 'https://gocardless.example/start',
+ requisitionId: 'req-1' as GoCardlessRequisitionId,
+ });
+ });
+
+ it('passes an http(s) origin through as the redirect host', async () => {
+ const res = await request(app)
+ .post('/create-web-token')
+ .set('Origin', 'https://budget.example.com')
+ .send({ institutionId: 'SANDBOXFINANCE_SFIN0000' });
+
+ expect(res.body).toEqual({
+ status: 'ok',
+ data: {
+ link: 'https://gocardless.example/start',
+ requisitionId: 'req-1',
+ },
+ });
+ expect(createRequisition).toHaveBeenCalledWith({
+ institutionId: 'SANDBOXFINANCE_SFIN0000',
+ host: 'https://budget.example.com',
+ });
+ });
+
+ it('redirects the electron app origin to the server itself', async () => {
+ const res = await request(app)
+ .post('/create-web-token')
+ .set('Origin', 'app://actual')
+ .send({ institutionId: 'SANDBOXFINANCE_SFIN0000' });
+
+ expect(res.body.status).toBe('ok');
+ expect(res.body.data.link).toBe('https://gocardless.example/start');
+ expect(createRequisition).toHaveBeenCalledWith({
+ institutionId: 'SANDBOXFINANCE_SFIN0000',
+ host: expect.stringMatching(/^http:\/\/127\.0\.0\.1:\d+$/),
+ });
+ });
+
+ it('rejects a missing Origin header', async () => {
+ const res = await request(app)
+ .post('/create-web-token')
+ .send({ institutionId: 'SANDBOXFINANCE_SFIN0000' });
+
+ expect(res.body.data).toEqual({
+ error_code: 'INTERNAL_ERROR',
+ error_type: 'Invalid Origin header',
+ });
+ expect(createRequisition).not.toHaveBeenCalled();
+ });
+
+ it('rejects non-http(s) origins', async () => {
+ const res = await request(app)
+ .post('/create-web-token')
+ .set('Origin', 'file://actual')
+ .send({ institutionId: 'SANDBOXFINANCE_SFIN0000' });
+
+ expect(res.body.data).toEqual({
+ error_code: 'INTERNAL_ERROR',
+ error_type: 'Invalid Origin header',
+ });
+ expect(createRequisition).not.toHaveBeenCalled();
+ });
+
+ it('rejects a missing institutionId', async () => {
+ const res = await request(app)
+ .post('/create-web-token')
+ .set('Origin', 'https://budget.example.com')
+ .send({});
+
+ expect(res.body.data).toEqual({
+ error_code: 'INTERNAL_ERROR',
+ error_type: 'Invalid GoCardless identifier: undefined',
+ });
+ expect(createRequisition).not.toHaveBeenCalled();
+ });
+});
+
+describe('/link', () => {
+ it('serves the completion page', async () => {
+ const res = await request(app).get('/link');
+
+ expect(res.status).toBe(200);
+ expect(res.headers['content-type']).toMatch(/text\/html/);
+ expect(res.text).toContain('window.close()');
+ });
+});
diff --git a/packages/sync-server/src/app-gocardless/app-gocardless.ts b/packages/sync-server/src/app-gocardless/app-gocardless.ts
index 15da0b7fc0..85c29d7106 100644
--- a/packages/sync-server/src/app-gocardless/app-gocardless.ts
+++ b/packages/sync-server/src/app-gocardless/app-gocardless.ts
@@ -1,6 +1,5 @@
-import path from 'path';
-
import express from 'express';
+import type { Request } from 'express';
import { sha256String } from '#util/hash';
import {
@@ -28,6 +27,8 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
+const ELECTRON_APP_ORIGIN = 'app://actual';
+
function validateOrigin(origin: string | undefined) {
let url;
try {
@@ -41,6 +42,15 @@ function validateOrigin(origin: string | undefined) {
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)) {
@@ -49,11 +59,30 @@ function sanitizeId<T extends string = string>(id: unknown): T {
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.sendFile('link.html', { root: path.resolve('./src/app-gocardless') });
+ res.send(LINK_PAGE_HTML);
});
export { app as handlers };
@@ -74,7 +103,7 @@ app.post(
handleError(async (req, res) => {
const { institutionId: rawInstitutionId } = req.body || {};
const institutionId = sanitizeId<GoCardlessInstitutionId>(rawInstitutionId);
- const host = validateOrigin(req.headers.origin);
+ const host = resolveRedirectHost(req);
const { link, requisitionId } = await goCardlessService.createRequisition({
institutionId,
diff --git a/packages/sync-server/src/app-gocardless/link.html b/packages/sync-server/src/app-gocardless/link.html
deleted file mode 100644
index 4ddffd1cf8..0000000000
--- a/packages/sync-server/src/app-gocardless/link.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!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>
diff --git a/upcoming-release-notes/fix-desktop-gocardless-linking.md b/upcoming-release-notes/fix-desktop-gocardless-linking.md
new file mode 100644
index 0000000000..cfb01d3c11
--- /dev/null
+++ b/upcoming-release-notes/fix-desktop-gocardless-linking.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [matt-fidd]
+---
+
+Fix GoCardless account linking in the desktop app