From dda91d2b7052449c44dba43eb4d723db3e09666e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Thu, 9 Nov 2023 10:32:52 +0100 Subject: [PATCH] fix: change CORS to allow origin `app://-` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The origin of the Electron app depends on how we run the app. - via `npm start` -> origin is http://localhost:3000 - packaged -> origin is app://- In this commit, I am changing our CORS header to be either `http://localhost:3000` or `app://-`, depending on what the client sends in the request header "Origin". Signed-off-by: Miroslav Bajtoš --- bin/station-wallet-screening.js | 2 +- index.js | 23 +++++++++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/bin/station-wallet-screening.js b/bin/station-wallet-screening.js index 5dd03ca..888d338 100644 --- a/bin/station-wallet-screening.js +++ b/bin/station-wallet-screening.js @@ -26,7 +26,7 @@ Sentry.init({ tracesSampleRate: 0.1 }) -assert(CHAINALYSIS_API_KEY) +assert(CHAINALYSIS_API_KEY, 'CHAINALYSIS_API_KEY must be set via env vars') const server = http.createServer(createHandler({ apiKey: CHAINALYSIS_API_KEY diff --git a/index.js b/index.js index 1e8c565..f64b518 100644 --- a/index.js +++ b/index.js @@ -2,9 +2,28 @@ import { STATUS_CODES } from 'node:http' import assert from 'node:assert' import Sentry from '@sentry/node' +/** + * + * @param {import('node:http').IncomingMessage} req + * @param {import('node:http').ServerResponse} res + * @param {string} apiKey + * @param {typeof fetch} fetch + */ const handler = async (req, res, apiKey, fetch) => { - // The origin is the electron app, which always has this address. - res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000') + // The origin is the electron app. The origin depends on how we run the app. + // - via `npm start` -> origin is http://localhost:3000 + // - packaged -> origin is app://- + // Unfortunately, Access-Control-Allow-Origin supports only a single value (single origin) + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin + // > Only a single origin can be specified. If the server supports clients from multiple origins, + // > it must return the origin for the specific client making the request. + console.log('origin:', req.headers.origin) + if (req.headers.origin === 'http://localhost:3000') { + res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000') + } else { + res.setHeader('Access-Control-Allow-Origin', 'app://-') + } + const address = req.url.split('/')[1].trim() const fetchRes = await fetch( `https://public.chainalysis.com/api/v1/address/${address}`,