Skip to content

A local-first personal finance app

Frontend plugins Support [1/10]: CORS proxy (#5780)

lelemm81160256bc3f
diff --git a/packages/sync-server/package.json b/packages/sync-server/package.json
index 29a6fdd3f3..2a0010e0d4 100644
--- a/packages/sync-server/package.json
+++ b/packages/sync-server/package.json
@@ -38,6 +38,7 @@
"express": "5.1.0",
"express-rate-limit": "^8.0.1",
"express-winston": "^4.2.0",
+ "ipaddr.js": "^2.2.0",
"jws": "^4.0.0",
"migrate": "^2.1.0",
"nordigen-node": "^1.4.1",
diff --git a/packages/sync-server/src/app-cors-proxy.js b/packages/sync-server/src/app-cors-proxy.js
new file mode 100644
index 0000000000..81439f0c7e
--- /dev/null
+++ b/packages/sync-server/src/app-cors-proxy.js
@@ -0,0 +1,279 @@
+import express from 'express';
+import rateLimit from 'express-rate-limit';
+import ipaddr from 'ipaddr.js';
+
+import { config } from './load-config.js';
+import { requestLoggerMiddleware } from './util/middlewares.js';
+import { validateSession } from './util/validate-user.js';
+
+const app = express();
+
+app.use(express.json());
+app.use(requestLoggerMiddleware);
+app.use(
+ rateLimit({
+ windowMs: 60 * 1000,
+ max: 25,
+ legacyHeaders: false,
+ standardHeaders: true,
+ }),
+);
+
+// Cache for the allowlist to avoid fetching it on every request
+let allowlistedRepos = [];
+let lastAllowlistFetch = 0;
+const ALLOWLIST_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
+
+// Export cache clearing function for testing
+export const clearAllowlistCache = () => {
+ allowlistedRepos = [];
+ lastAllowlistFetch = 0;
+};
+
+async function fetchAllowlist() {
+ const now = Date.now();
+ if (
+ now - lastAllowlistFetch < ALLOWLIST_CACHE_TTL &&
+ allowlistedRepos.length > 0
+ ) {
+ return allowlistedRepos;
+ }
+
+ try {
+ const response = await fetch(
+ 'https://raw.githubusercontent.com/actualbudget/plugin-store/refs/heads/main/plugins.json',
+ );
+ if (!response.ok) {
+ throw new Error(`Failed to fetch allowlist: ${response.status}`);
+ }
+ const plugins = await response.json();
+ allowlistedRepos = plugins.map(plugin => plugin.url);
+ lastAllowlistFetch = now;
+ console.log('Updated plugin allowlist:', allowlistedRepos);
+ return allowlistedRepos;
+ } catch (error) {
+ console.error('Failed to fetch plugin allowlist:', error);
+ // Return empty array if fetch fails to be safe
+ allowlistedRepos = [];
+ return allowlistedRepos;
+ }
+}
+
+/**
+ * Return true only if the URL is on an allowlist and not a local/private address.
+ */
+function isUrlAllowed(targetUrl) {
+ try {
+ const url = new URL(targetUrl);
+ const hostname = url.hostname;
+
+ // Block private/local IP addresses
+ if (ipaddr.isValid(hostname)) {
+ const ip = ipaddr.parse(hostname);
+ if (
+ [
+ 'private',
+ 'loopback',
+ 'linkLocal',
+ 'uniqueLocal',
+ 'unspecified',
+ ].includes(ip.range())
+ ) {
+ console.warn(`Blocked request to private/localhost IP: ${hostname}`);
+ return false;
+ }
+ }
+
+ // Always allow the specific plugin-store URL
+ if (
+ targetUrl ===
+ 'https://raw.githubusercontent.com/actualbudget/plugin-store/refs/heads/main/plugins.json'
+ ) {
+ return true;
+ }
+
+ // Check against allowlisted repositories
+ for (const repoUrl of allowlistedRepos) {
+ try {
+ const { pathname } = new URL(repoUrl);
+ const [, repoOwner, repoName] = pathname.split('/');
+
+ if (
+ targetUrl === repoUrl ||
+ targetUrl.startsWith(repoUrl + '/') ||
+ (hostname === 'api.github.com' &&
+ url.pathname.startsWith(`/repos/${repoOwner}/${repoName}`)) ||
+ (hostname === 'raw.githubusercontent.com' &&
+ url.pathname.startsWith(`/${repoOwner}/${repoName}/`)) ||
+ (hostname === 'github.com' &&
+ url.pathname.startsWith(`/${repoOwner}/${repoName}/releases/`))
+ ) {
+ return true;
+ }
+ } catch (e) {
+ console.warn(
+ 'Invalid repository URL in allowlist:',
+ repoUrl,
+ e.message,
+ );
+ }
+ }
+
+ return false;
+ } catch (e) {
+ console.warn('Invalid target URL:', targetUrl, e.message);
+ return false;
+ }
+}
+
+app.use('/', async (req, res) => {
+ // CORS preflight
+ if (req.method === 'OPTIONS') {
+ res.set('Access-Control-Allow-Origin', '*');
+ res.set('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS');
+ res.set('Access-Control-Allow-Headers', 'Content-Type, X-Actual-Token');
+ res.set('Access-Control-Max-Age', '600');
+ return res.status(204).end();
+ }
+
+ const targetUrlString = req.query.url;
+
+ if (!targetUrlString) {
+ return res.status(400).json({ error: 'Missing url parameter' });
+ }
+
+ // Validate session/token
+ const session = await validateSession(req, res);
+ if (!session) {
+ return; // validateSession already sent the response
+ }
+
+ let url;
+ try {
+ url = new URL(targetUrlString);
+ } catch (e) {
+ return res.status(400).json({ error: 'Invalid url parameter' });
+ }
+
+ // Fetch the latest allowlist
+ try {
+ await fetchAllowlist();
+ } catch (error) {
+ console.error('Failed to fetch allowlist:', error);
+ return res.status(403).json({
+ error: 'URL not allowed',
+ message: 'Unable to verify allowlist',
+ });
+ }
+
+ // Check if the URL is allowed
+ if (!isUrlAllowed(url.href)) {
+ console.warn('Blocked request to unauthorized URL:', url.href);
+ return res.status(403).json({
+ error: 'URL not allowed',
+ message:
+ 'Only allowlisted plugin repositories are allowed (localhost only in development)',
+ });
+ }
+
+ try {
+ // Extract method, body, and headers from the request body (sent by loot-core)
+ const {
+ method = 'GET',
+ body,
+ headers: customHeaders = {},
+ } = req.body || {};
+
+ const methodNormalized =
+ typeof method === 'string' ? method.toUpperCase() : 'GET';
+ if (!['GET', 'HEAD'].includes(methodNormalized)) {
+ return res.status(405).json({ error: 'Method not allowed' });
+ }
+
+ const requestHeaders = {
+ ...req.headers,
+ ...customHeaders,
+ host: url.host,
+ };
+
+ // Remove headers that shouldn't be forwarded
+ delete requestHeaders['x-actual-token'];
+ delete requestHeaders['content-length'];
+ delete requestHeaders['cookie'];
+ delete requestHeaders['cookie2'];
+
+ // Add GitHub authentication if token is configured and request is to GitHub
+ const githubToken = config.get('github.token');
+ if (
+ githubToken &&
+ (url.hostname === 'api.github.com' ||
+ url.hostname === 'raw.githubusercontent.com' ||
+ (url.hostname === 'github.com' && url.pathname.includes('/releases/')))
+ ) {
+ requestHeaders['Authorization'] = `Bearer ${githubToken}`;
+ requestHeaders['User-Agent'] = 'Actual-Budget-Plugin-System';
+ console.log(
+ `Using GitHub authentication for request to: ${url.hostname}`,
+ );
+ }
+
+ const response = await fetch(url.href, {
+ method,
+ headers: requestHeaders,
+ body: ['GET', 'HEAD'].includes(method)
+ ? undefined
+ : typeof body === 'string'
+ ? body
+ : JSON.stringify(body),
+ });
+
+ const contentType =
+ response.headers.get('content-type') || 'application/octet-stream';
+
+ res.set('Access-Control-Allow-Origin', '*');
+ res.status(response.status);
+
+ // Try to detect if this might be JSON content based on URL or content
+ const urlString = url.toString().toLowerCase();
+ const isLikelyJson =
+ contentType?.includes('application/json') ||
+ urlString.includes('.json') ||
+ urlString.includes('/manifest') ||
+ urlString.includes('manifest.json') ||
+ urlString.includes('package.json');
+
+ if (isLikelyJson) {
+ // For JSON responses, return the actual content
+ res.set('Content-Type', 'application/json');
+ const text = await response.text();
+ try {
+ res.json(JSON.parse(text));
+ } catch {
+ // If it's not valid JSON, treat as text
+ res.set('Content-Type', contentType || 'text/plain');
+ res.send(text);
+ }
+ } else if (contentType?.includes('text/')) {
+ // For text responses, return as plain text
+ res.set('Content-Type', contentType);
+ const text = await response.text();
+ res.send(text);
+ } else {
+ // For actual binary responses, return as JSON format
+ res.set('Content-Type', 'application/json');
+ const buffer = await response.arrayBuffer();
+ const binaryData = {
+ data: Array.from(new Uint8Array(buffer)),
+ contentType,
+ isBinary: true,
+ };
+ res.json(binaryData);
+ }
+ } catch (err) {
+ res
+ .status(500)
+ .json({ error: 'Error proxying request', details: err.message });
+ }
+});
+
+export { app as handlers };
diff --git a/packages/sync-server/src/app-cors-proxy.test.js b/packages/sync-server/src/app-cors-proxy.test.js
new file mode 100644
index 0000000000..a46b0fd703
--- /dev/null
+++ b/packages/sync-server/src/app-cors-proxy.test.js
@@ -0,0 +1,589 @@
+import ipaddr from 'ipaddr.js';
+import request from 'supertest';
+import { vi, describe, it, expect, beforeEach, beforeAll } from 'vitest';
+
+import { handlers as app, clearAllowlistCache } from './app-cors-proxy.js';
+import { config } from './load-config.js';
+import { validateSession } from './util/validate-user.js';
+
+vi.mock('./load-config.js', () => ({
+ config: {
+ get: vi.fn(),
+ },
+}));
+
+vi.mock('./util/middlewares.js', () => ({
+ requestLoggerMiddleware: (req, res, next) => next(),
+}));
+
+vi.mock('./util/validate-user.js', () => ({
+ validateSession: vi.fn(),
+}));
+
+vi.mock('express-rate-limit', () => ({
+ default: vi.fn(() => (req, res, next) => next()),
+}));
+
+vi.mock('ipaddr.js', () => ({
+ default: {
+ isValid: vi.fn().mockReturnValue(false),
+ parse: vi.fn(),
+ },
+}));
+
+global.fetch = vi.fn();
+
+describe('app-cors-proxy', () => {
+ const defaultAllowlistedRepos = [
+ 'https://github.com/user/repo1',
+ 'https://github.com/user/repo2',
+ ];
+
+ const createFetchMock = (options = {}) => {
+ const {
+ allowlistedRepos = defaultAllowlistedRepos,
+ allowlistFetchFails = false,
+ allowlistHttpError = false,
+ proxyResponses = {},
+ } = options;
+
+ return vi.fn().mockImplementation((url, _requestOptions) => {
+ if (
+ url ===
+ 'https://raw.githubusercontent.com/actualbudget/plugin-store/refs/heads/main/plugins.json'
+ ) {
+ if (allowlistFetchFails) {
+ return Promise.reject(new Error('Network error'));
+ }
+ if (allowlistHttpError) {
+ return Promise.resolve({
+ ok: false,
+ status: 404,
+ });
+ }
+ return Promise.resolve({
+ ok: true,
+ json: () =>
+ Promise.resolve(
+ allowlistedRepos.map(repoUrl => ({ url: repoUrl })),
+ ),
+ });
+ }
+
+ if (proxyResponses[url]) {
+ const response = proxyResponses[url];
+ if (response.error) {
+ return Promise.reject(response.error);
+ }
+ return Promise.resolve(response);
+ }
+
+ return Promise.resolve({
+ ok: true,
+ text: () => Promise.resolve('default response'),
+ headers: {
+ get: () => 'text/plain',
+ },
+ status: 200,
+ });
+ });
+ };
+
+ const comprehensiveProxyResponses = {
+ 'https://github.com/user/repo1': {
+ ok: true,
+ text: () => Promise.resolve('test content'),
+ headers: { get: () => 'text/plain' },
+ status: 200,
+ },
+ 'https://api.github.com/repos/user/repo1/releases': {
+ ok: true,
+ text: () => Promise.resolve('{"name": "test"}'),
+ headers: { get: () => 'application/json' },
+ status: 200,
+ },
+ 'https://api.github.com/repos/user/repo1': {
+ ok: true,
+ text: () => Promise.resolve('{"name": "repo1"}'),
+ headers: { get: () => 'application/json' },
+ status: 200,
+ },
+ 'https://raw.githubusercontent.com/user/repo1/main/file.txt': {
+ ok: true,
+ text: () => Promise.resolve('file content'),
+ headers: { get: () => 'text/plain' },
+ status: 200,
+ },
+ 'https://github.com/user/repo1/releases/download/v1.0.0/file.zip': {
+ ok: true,
+ arrayBuffer: () =>
+ Promise.resolve(new TextEncoder().encode('release content').buffer),
+ headers: { get: () => 'application/octet-stream' },
+ status: 200,
+ },
+ 'https://github.com/user/repo1/manifest.json': {
+ ok: true,
+ text: () =>
+ Promise.resolve(JSON.stringify({ name: 'test', version: '1.0.0' })),
+ headers: { get: () => 'application/json' },
+ status: 200,
+ },
+ 'https://github.com/user/repo1/package.json': {
+ ok: true,
+ text: () => Promise.resolve(JSON.stringify({ test: true })),
+ headers: { get: () => 'text/plain' },
+ status: 200,
+ },
+ 'https://github.com/user/repo1/readme.txt': {
+ ok: true,
+ text: () => Promise.resolve('Hello, world!'),
+ headers: { get: () => 'text/plain' },
+ status: 200,
+ },
+ 'https://github.com/user/repo1/file.bin': {
+ ok: true,
+ arrayBuffer: () =>
+ Promise.resolve(new Uint8Array([1, 2, 3, 4, 5]).buffer),
+ headers: { get: () => 'application/octet-stream' },
+ status: 200,
+ },
+ 'https://github.com/user/repo1/invalid.json': {
+ ok: true,
+ text: () => Promise.resolve('not valid json'),
+ headers: { get: () => 'text/plain' },
+ status: 200,
+ },
+ 'https://github.com/user/repo1/network-error': {
+ error: new Error('Network error'),
+ },
+ };
+
+ beforeAll(() => {
+ global.fetch = createFetchMock({
+ proxyResponses: comprehensiveProxyResponses,
+ });
+ });
+
+ beforeEach(() => {
+ validateSession.mockClear?.();
+ ipaddr.isValid.mockClear?.();
+ ipaddr.parse.mockClear?.();
+
+ validateSession.mockReturnValue({ userId: 'test-user' });
+
+ clearAllowlistCache();
+
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ describe('CORS preflight', () => {
+ it('should handle OPTIONS requests properly', async () => {
+ const res = await request(app)
+ .options('/')
+ .query({ url: 'https://example.com' });
+
+ expect(res.statusCode).toBe(204);
+ expect(res.headers['access-control-allow-origin']).toBe('*');
+ expect(res.headers['access-control-allow-methods']).toBe(
+ 'GET,HEAD,OPTIONS',
+ );
+ expect(res.headers['access-control-allow-headers']).toBe(
+ 'Content-Type, X-Actual-Token',
+ );
+ expect(res.headers['access-control-max-age']).toBe('600');
+ });
+ });
+
+ describe('URL parameter validation', () => {
+ it('should return 400 if url parameter is missing', async () => {
+ validateSession.mockReturnValue({ userId: 'test-user' });
+
+ const res = await request(app).get('/');
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body.error).toBe('Missing url parameter');
+ });
+
+ it('should return 400 if url parameter is invalid', async () => {
+ validateSession.mockReturnValue({ userId: 'test-user' });
+
+ const res = await request(app).get('/').query({ url: 'invalid-url' });
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body.error).toBe('Invalid url parameter');
+ });
+ });
+
+ describe('Session validation', () => {
+ it('should return early if validateSession fails', async () => {
+ validateSession.mockImplementation((req, res) => {
+ res.status(401).json({ error: 'Unauthorized' });
+ return null;
+ });
+
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://example.com' });
+
+ expect(res.statusCode).toBe(401);
+ expect(validateSession).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('URL allowlist validation', () => {
+ beforeEach(() => {
+ validateSession.mockReturnValue({ userId: 'test-user' });
+ });
+
+ it('should block private IP addresses', async () => {
+ ipaddr.isValid.mockReturnValueOnce(true);
+ ipaddr.parse.mockReturnValueOnce({
+ range: () => 'private',
+ });
+
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'http://192.168.1.1/test' });
+
+ expect(res.statusCode).toBe(403);
+ expect(res.body.error).toBe('URL not allowed');
+ expect(console.warn).toHaveBeenCalledWith(
+ 'Blocked request to private/localhost IP: 192.168.1.1',
+ );
+ });
+
+ it('should block loopback addresses', async () => {
+ ipaddr.isValid.mockReturnValueOnce(true);
+ ipaddr.parse.mockReturnValueOnce({
+ range: () => 'loopback',
+ });
+
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'http://127.0.0.1/test' });
+
+ expect(res.statusCode).toBe(403);
+ expect(res.body.error).toBe('URL not allowed');
+ });
+
+ it('should allow allowlisted repository URLs', async () => {
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://github.com/user/repo1' });
+
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('should allow GitHub API URLs for allowlisted repos', async () => {
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://api.github.com/repos/user/repo1/releases' });
+
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('should allow raw.githubusercontent.com URLs for allowlisted repos', async () => {
+ const res = await request(app).get('/').query({
+ url: 'https://raw.githubusercontent.com/user/repo1/main/file.txt',
+ });
+
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('should allow github.com release URLs for allowlisted repos', async () => {
+ const res = await request(app).get('/').query({
+ url: 'https://github.com/user/repo1/releases/download/v1.0.0/file.zip',
+ });
+
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('should block non-allowlisted URLs', async () => {
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://malicious.com/evil' });
+
+ expect(res.statusCode).toBe(403);
+ expect(res.body.error).toBe('URL not allowed');
+ expect(console.warn).toHaveBeenCalledWith(
+ 'Blocked request to unauthorized URL:',
+ 'https://malicious.com/evil',
+ );
+ });
+ });
+
+ describe('Allowlist fetching and caching', () => {
+ beforeEach(() => {
+ validateSession.mockReturnValue({ userId: 'test-user' });
+ });
+
+ it('should fetch allowlist on first request', async () => {
+ await request(app)
+ .get('/')
+ .query({ url: 'https://github.com/user/repo1' });
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ 'https://raw.githubusercontent.com/actualbudget/plugin-store/refs/heads/main/plugins.json',
+ );
+ });
+
+ it('should handle allowlist fetch failure gracefully', async () => {
+ global.fetch = createFetchMock({
+ allowlistFetchFails: true,
+ proxyResponses: comprehensiveProxyResponses,
+ });
+
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://github.com/user/repo1' });
+
+ expect(res.statusCode).toBe(403);
+ expect(console.error).toHaveBeenCalledWith(
+ 'Failed to fetch plugin allowlist:',
+ expect.any(Error),
+ );
+
+ global.fetch = createFetchMock({
+ proxyResponses: comprehensiveProxyResponses,
+ });
+ });
+
+ it('should handle allowlist fetch HTTP error', async () => {
+ global.fetch = createFetchMock({
+ allowlistHttpError: true,
+ proxyResponses: comprehensiveProxyResponses,
+ });
+
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://github.com/user/repo1' });
+
+ expect(res.statusCode).toBe(403);
+ expect(console.error).toHaveBeenCalledWith(
+ 'Failed to fetch plugin allowlist:',
+ expect.any(Error),
+ );
+
+ global.fetch = createFetchMock({
+ proxyResponses: comprehensiveProxyResponses,
+ });
+ });
+ });
+
+ describe('HTTP method validation', () => {
+ beforeEach(() => {
+ validateSession.mockReturnValue({ userId: 'test-user' });
+ });
+
+ it('should allow GET method', async () => {
+ const res = await request(app)
+ .get('/')
+ .send({ method: 'GET' })
+ .query({ url: 'https://github.com/user/repo1' });
+
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('should allow HEAD method', async () => {
+ const res = await request(app)
+ .get('/')
+ .send({ method: 'HEAD' })
+ .query({ url: 'https://github.com/user/repo1' });
+
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('should block POST method', async () => {
+ const res = await request(app)
+ .get('/')
+ .send({ method: 'POST' })
+ .query({ url: 'https://github.com/user/repo1' });
+
+ expect(res.statusCode).toBe(405);
+ expect(res.body.error).toBe('Method not allowed');
+ });
+
+ it('should block PUT method', async () => {
+ const res = await request(app)
+ .get('/')
+ .send({ method: 'PUT' })
+ .query({ url: 'https://github.com/user/repo1' });
+
+ expect(res.statusCode).toBe(405);
+ expect(res.body.error).toBe('Method not allowed');
+ });
+ });
+
+ describe('GitHub authentication', () => {
+ beforeEach(() => {
+ validateSession.mockReturnValue({ userId: 'test-user' });
+ });
+
+ it('should add GitHub authentication for api.github.com when token is configured', async () => {
+ config.get.mockReturnValue('test-github-token');
+
+ await request(app)
+ .get('/')
+ .query({ url: 'https://api.github.com/repos/user/repo1' });
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ 'https://api.github.com/repos/user/repo1',
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ Authorization: 'Bearer test-github-token',
+ 'User-Agent': 'Actual-Budget-Plugin-System',
+ }),
+ }),
+ );
+ });
+
+ it('should add GitHub authentication for raw.githubusercontent.com when token is configured', async () => {
+ config.get.mockReturnValue('test-github-token');
+
+ await request(app).get('/').query({
+ url: 'https://raw.githubusercontent.com/user/repo1/main/file.txt',
+ });
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ 'https://raw.githubusercontent.com/user/repo1/main/file.txt',
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ Authorization: 'Bearer test-github-token',
+ 'User-Agent': 'Actual-Budget-Plugin-System',
+ }),
+ }),
+ );
+ });
+
+ it('should not add GitHub authentication when token is not configured', async () => {
+ config.get.mockReturnValue(null);
+
+ await request(app)
+ .get('/')
+ .query({ url: 'https://api.github.com/repos/user/repo1' });
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ 'https://api.github.com/repos/user/repo1',
+ expect.objectContaining({
+ headers: expect.not.objectContaining({
+ Authorization: expect.any(String),
+ }),
+ }),
+ );
+ });
+ });
+
+ describe('Response handling', () => {
+ beforeEach(() => {
+ validateSession.mockReturnValue({ userId: 'test-user' });
+ });
+
+ it('should handle JSON responses', async () => {
+ const jsonData = { name: 'test', version: '1.0.0' };
+
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://github.com/user/repo1/manifest.json' });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.headers['content-type']).toContain('application/json');
+ expect(res.body).toEqual(jsonData);
+ });
+
+ it('should handle text responses', async () => {
+ const textContent = 'Hello, world!';
+
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://github.com/user/repo1/readme.txt' });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.headers['content-type']).toContain('text/plain');
+ expect(res.text).toBe(textContent);
+ });
+
+ it('should handle binary responses', async () => {
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://github.com/user/repo1/file.bin' });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.headers['content-type']).toContain('application/json');
+ expect(res.body).toEqual({
+ data: [1, 2, 3, 4, 5],
+ contentType: 'application/octet-stream',
+ isBinary: true,
+ });
+ });
+
+ it('should handle invalid JSON gracefully', async () => {
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://github.com/user/repo1/invalid.json' });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.text).toBe('not valid json');
+ });
+
+ it('should detect JSON from URL patterns', async () => {
+ const jsonData = { test: true };
+
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://github.com/user/repo1/package.json' });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.headers['content-type']).toContain('application/json');
+ expect(res.body).toEqual(jsonData);
+ });
+ });
+
+ describe('Error handling', () => {
+ beforeEach(() => {
+ validateSession.mockReturnValue({ userId: 'test-user' });
+ });
+
+ it('should handle fetch errors', async () => {
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://github.com/user/repo1/network-error' });
+
+ expect(res.statusCode).toBe(500);
+ expect(res.body.error).toBe('Error proxying request');
+ expect(res.body.details).toBe('Network error');
+ });
+
+ it('should handle invalid repository URLs in allowlist', async () => {
+ global.fetch.mockResolvedValueOnce({
+ ok: true,
+ json: () => Promise.resolve([{ url: 'invalid-url' }]),
+ });
+
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://example.com' });
+
+ expect(res.statusCode).toBe(403);
+ expect(console.warn).toHaveBeenCalledWith(
+ 'Blocked request to unauthorized URL:',
+ 'https://example.com/',
+ );
+ });
+ });
+
+ describe('CORS headers', () => {
+ beforeEach(() => {
+ validateSession.mockReturnValue({ userId: 'test-user' });
+ });
+
+ it('should set CORS headers on successful responses', async () => {
+ const res = await request(app)
+ .get('/')
+ .query({ url: 'https://github.com/user/repo1' });
+
+ expect(res.headers['access-control-allow-origin']).toBe('*');
+ });
+ });
+});
diff --git a/packages/sync-server/src/app.ts b/packages/sync-server/src/app.ts
index 522f39a305..d1dbc4d041 100644
--- a/packages/sync-server/src/app.ts
+++ b/packages/sync-server/src/app.ts
@@ -9,6 +9,7 @@ import rateLimit from 'express-rate-limit';
import { bootstrap } from './account-db.js';
import * as accountApp from './app-account.js';
import * as adminApp from './app-admin.js';
+import * as corsApp from './app-cors-proxy.js';
import * as goCardlessApp from './app-gocardless/app-gocardless.js';
import * as openidApp from './app-openid.js';
import * as pluggai from './app-pluggyai/app-pluggyai.js';
@@ -60,6 +61,10 @@ app.use('/simplefin', simpleFinApp.handlers);
app.use('/pluggyai', pluggai.handlers);
app.use('/secret', secretApp.handlers);
+if (config.get('corsProxy.enabled')) {
+ app.use('/cors-proxy', corsApp.handlers);
+}
+
app.use('/admin', adminApp.handlers);
app.use('/openid', openidApp.handlers);
diff --git a/packages/sync-server/src/load-config.js b/packages/sync-server/src/load-config.js
index d62bc684d9..4de7763172 100644
--- a/packages/sync-server/src/load-config.js
+++ b/packages/sync-server/src/load-config.js
@@ -257,6 +257,27 @@ const configSchema = convict({
default: 'manual',
env: 'ACTUAL_USER_CREATION_MODE',
},
+
+ github: {
+ doc: 'GitHub API configuration.',
+
+ token: {
+ doc: 'GitHub Personal Access Token for API authentication.',
+ format: String,
+ default: '',
+ env: 'ACTUAL_GITHUB_TOKEN',
+ },
+ },
+ corsProxy: {
+ doc: 'CORS proxy configuration for frontend plugins.',
+
+ enabled: {
+ doc: 'Enable the CORS proxy endpoint.',
+ format: Boolean,
+ default: false,
+ env: 'ACTUAL_CORS_PROXY_ENABLED',
+ },
+ },
});
let configPath = null;
@@ -293,6 +314,8 @@ debug(`User files: ${configSchema.get('userFiles')}`);
debug(`Web root: ${configSchema.get('webRoot')}`);
debug(`Login method: ${configSchema.get('loginMethod')}`);
debug(`Allowed methods: ${configSchema.get('allowedLoginMethods').join(', ')}`);
+const corsProxyEnabled = configSchema.get('corsProxy.enabled');
+debug(`CORS Proxy enabled: ${corsProxyEnabled}`);
const httpsKey = configSchema.get('https.key');
if (httpsKey) {
@@ -306,4 +329,10 @@ if (httpsCert) {
debugSensitive(`HTTPS Cert: ${httpsCert}`);
}
+const githubToken = configSchema.get('github.token');
+if (githubToken) {
+ debug(`GitHub Token: ${'*'.repeat(Math.min(githubToken.length, 20))}`);
+ debugSensitive(`GitHub Token: ${githubToken}`);
+}
+
export { configSchema as config };
diff --git a/upcoming-release-notes/5780.md b/upcoming-release-notes/5780.md
new file mode 100644
index 0000000000..e906f556cb
--- /dev/null
+++ b/upcoming-release-notes/5780.md
@@ -0,0 +1,7 @@
+---
+category: Features
+authors: [lelemm]
+---
+
+Add Express-based CORS proxy with rate limiting, logging, and GitHub token authentication support.
+
diff --git a/yarn.lock b/yarn.lock
index 8a60ef57d2..372c5795a2 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -114,6 +114,7 @@ __metadata:
express-rate-limit: "npm:^8.0.1"
express-winston: "npm:^4.2.0"
http-proxy-middleware: "npm:^3.0.5"
+ ipaddr.js: "npm:^2.2.0"
jws: "npm:^4.0.0"
migrate: "npm:^2.1.0"
nodemon: "npm:^3.1.10"
@@ -13133,6 +13134,13 @@ __metadata:
languageName: node
linkType: hard
+"ipaddr.js@npm:^2.2.0":
+ version: 2.2.0
+ resolution: "ipaddr.js@npm:2.2.0"
+ checksum: 10/9e1cdd9110b3bca5d910ab70d7fb1933e9c485d9b92cb14ef39f30c412ba3fe02a553921bf696efc7149cc653453c48ccf173adb996ec27d925f1f340f872986
+ languageName: node
+ linkType: hard
+
"is-absolute-url@npm:^4.0.0":
version: 4.0.1
resolution: "is-absolute-url@npm:4.0.1"