Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

fix(server): answer 403 instead of 500 for a malformed origin or allow-list entry (#899)

nimbly19e0f7c2d50c3
diff --git a/server/src/middleware/index.js b/server/src/middleware/index.js
index 365c0c404..1f292cae9 100644
--- a/server/src/middleware/index.js
+++ b/server/src/middleware/index.js
@@ -1,6 +1,7 @@
import supabaseAdmin from '../config/supabase.js';
import logger from '../lib/logger.js';
import { markTokenVerified } from './verified-tokens.js';
+import { isAllowedOrigin } from './origin-check.js';
class Middleware {
async decodeTokenForSocket(socket, next) {
@@ -73,14 +74,7 @@ class Middleware {
return res.status(403).json({ message: 'Forbidden' });
}
- const url = new URL(domain);
-
- const isAllowed = allowedOrigins.some((origin) => {
- const allowed = new URL(origin);
- return url.hostname === allowed.hostname;
- });
-
- if (isAllowed) {
+ if (isAllowedOrigin(domain, allowedOrigins)) {
return next();
}
@@ -108,14 +102,7 @@ class Middleware {
return next(new Error('Forbidden Socket'));
}
- const url = new URL(domain);
-
- const isAllowed = allowedOrigins.some((origin) => {
- const allowed = new URL(origin);
- return url.hostname === allowed.hostname;
- });
-
- if (isAllowed) {
+ if (isAllowedOrigin(domain, allowedOrigins)) {
return next();
}
diff --git a/server/src/middleware/index.test.js b/server/src/middleware/index.test.js
new file mode 100644
index 000000000..1c9141794
--- /dev/null
+++ b/server/src/middleware/index.test.js
@@ -0,0 +1,156 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+vi.mock('../lib/logger.js', () => ({
+ default: { error: vi.fn(), warn: vi.fn() },
+}));
+
+const { default: Middleware } = await import('./index.js');
+const { default: logger } = await import('../lib/logger.js');
+
+function makeRes() {
+ const res = { status: vi.fn(), json: vi.fn() };
+ res.status.mockReturnValue(res);
+ return res;
+}
+
+function reqWith(headers) {
+ return { headers };
+}
+
+function socketWith(headers) {
+ return { handshake: { headers } };
+}
+
+beforeEach(() => {
+ vi.stubEnv('NODE_ENV', 'production');
+ vi.stubEnv('ALLOWED_ORIGINS', 'https://app.example.com,https://admin.example.com');
+ vi.clearAllMocks();
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe('Middleware.checkRequestIsComingFromDomain', () => {
+ async function run(headers) {
+ const res = makeRes();
+ const next = vi.fn();
+ await Middleware.checkRequestIsComingFromDomain(reqWith(headers), res, next);
+ return { res, next };
+ }
+
+ it('lets a request from an allowed Referer through', async () => {
+ const { res, next } = await run({ referer: 'https://app.example.com/dashboard?tab=1' });
+ expect(next).toHaveBeenCalledOnce();
+ expect(res.status).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the Origin header when there is no Referer', async () => {
+ const { res, next } = await run({ origin: 'https://admin.example.com' });
+ expect(next).toHaveBeenCalledOnce();
+ expect(res.status).not.toHaveBeenCalled();
+ });
+
+ it('answers 403 for a host that is not allowed', async () => {
+ const { res, next } = await run({ referer: 'https://evil.example.net/' });
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(403);
+ expect(res.json).toHaveBeenCalledWith({ message: 'Forbidden' });
+ });
+
+ it('answers 403 when neither Referer nor Origin is sent', async () => {
+ const { res, next } = await run({});
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(403);
+ });
+
+ it('answers 403, not 500, for a malformed Referer', async () => {
+ const { res, next } = await run({ referer: 'foo' });
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(403);
+ expect(res.json).toHaveBeenCalledWith({ message: 'Forbidden' });
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+
+ it('answers 403, not 500, for a malformed Origin', async () => {
+ const { res, next } = await run({ origin: 'not a url' });
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(403);
+ expect(res.json).toHaveBeenCalledWith({ message: 'Forbidden' });
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+
+ it('still allows a valid origin when ALLOWED_ORIGINS has a malformed entry', async () => {
+ vi.stubEnv('ALLOWED_ORIGINS', 'app.example.com,https://app.example.com');
+ const { res, next } = await run({ referer: 'https://app.example.com/' });
+ expect(next).toHaveBeenCalledOnce();
+ expect(res.status).not.toHaveBeenCalled();
+ });
+
+ it('answers 403, not 500, for a disallowed host when ALLOWED_ORIGINS has a malformed entry', async () => {
+ vi.stubEnv('ALLOWED_ORIGINS', 'app.example.com,https://app.example.com');
+ const { res, next } = await run({ referer: 'https://evil.example.net/' });
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(403);
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+});
+
+describe('Middleware.checkRequestIsComingFromDomainForSocket', () => {
+ async function run(headers) {
+ const next = vi.fn();
+ await Middleware.checkRequestIsComingFromDomainForSocket(socketWith(headers), next);
+ return next;
+ }
+
+ it('lets a handshake from an allowed Referer through', async () => {
+ const next = await run({ referer: 'https://app.example.com/dashboard' });
+ expect(next).toHaveBeenCalledOnce();
+ expect(next).toHaveBeenCalledWith();
+ });
+
+ it('falls back to the Origin header when there is no Referer', async () => {
+ const next = await run({ origin: 'https://admin.example.com' });
+ expect(next).toHaveBeenCalledOnce();
+ expect(next).toHaveBeenCalledWith();
+ });
+
+ it('rejects a host that is not allowed with Forbidden Socket', async () => {
+ const next = await run({ origin: 'https://evil.example.net' });
+ expect(next).toHaveBeenCalledOnce();
+ expect(next.mock.calls[0][0]).toBeInstanceOf(Error);
+ expect(next.mock.calls[0][0].message).toBe('Forbidden Socket');
+ });
+
+ it('rejects a handshake with neither Referer nor Origin', async () => {
+ const next = await run({});
+ expect(next.mock.calls[0][0].message).toBe('Forbidden Socket');
+ });
+
+ it('rejects a malformed Referer with Forbidden Socket, not Internal Error Socket', async () => {
+ const next = await run({ referer: 'foo' });
+ expect(next.mock.calls[0][0].message).toBe('Forbidden Socket');
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+
+ it('rejects a malformed Origin with Forbidden Socket, not Internal Error Socket', async () => {
+ const next = await run({ origin: 'not a url' });
+ expect(next.mock.calls[0][0].message).toBe('Forbidden Socket');
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+
+ it('still allows a valid origin when ALLOWED_ORIGINS has a malformed entry', async () => {
+ vi.stubEnv('ALLOWED_ORIGINS', 'app.example.com,https://app.example.com');
+ const next = await run({ origin: 'https://app.example.com' });
+ expect(next).toHaveBeenCalledOnce();
+ expect(next).toHaveBeenCalledWith();
+ });
+
+ it('rejects a disallowed host with Forbidden Socket when ALLOWED_ORIGINS has a malformed entry', async () => {
+ vi.stubEnv('ALLOWED_ORIGINS', 'app.example.com,https://app.example.com');
+ const next = await run({ origin: 'https://evil.example.net' });
+ expect(next.mock.calls[0][0].message).toBe('Forbidden Socket');
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/middleware/origin-check.js b/server/src/middleware/origin-check.js
new file mode 100644
index 000000000..3ef120ac4
--- /dev/null
+++ b/server/src/middleware/origin-check.js
@@ -0,0 +1,25 @@
+/**
+ * Hostname of an absolute URL, or '' when `value` is not one. `new URL()` throws
+ * on anything that is not an absolute URL (`foo`, `example.com`), and parses a
+ * scheme-less `localhost:3000` as scheme "localhost:" with no host at all.
+ */
+function hostnameOf(value) {
+ try {
+ return new URL(value).hostname;
+ } catch {
+ return '';
+ }
+}
+
+/**
+ * True when the host of `headerValue` (a Referer or Origin header) matches the
+ * host of one of `allowedOrigins`. Both sides are untrusted input, so neither
+ * may throw: a header that can't be parsed is not allowed, and an allow-list
+ * entry that can't be parsed is skipped so it can't break the valid ones.
+ */
+export function isAllowedOrigin(headerValue, allowedOrigins) {
+ const hostname = hostnameOf(headerValue);
+ if (!hostname) return false;
+
+ return allowedOrigins.some((origin) => hostnameOf(origin) === hostname);
+}
diff --git a/server/src/middleware/origin-check.test.js b/server/src/middleware/origin-check.test.js
new file mode 100644
index 000000000..f1538339b
--- /dev/null
+++ b/server/src/middleware/origin-check.test.js
@@ -0,0 +1,74 @@
+import { describe, it, expect } from 'vitest';
+import { isAllowedOrigin } from './origin-check.js';
+
+const allowed = ['https://app.example.com', 'https://admin.example.com'];
+
+describe('isAllowedOrigin', () => {
+ it('allows a header whose host is in the allow-list', () => {
+ expect(isAllowedOrigin('https://app.example.com', allowed)).toBe(true);
+ expect(isAllowedOrigin('https://admin.example.com', allowed)).toBe(true);
+ });
+
+ it('allows a full Referer URL with a path and query', () => {
+ expect(isAllowedOrigin('https://app.example.com/prompts?tab=1#top', allowed)).toBe(true);
+ });
+
+ it('compares hostnames only, ignoring scheme, port and case', () => {
+ expect(isAllowedOrigin('http://APP.example.com:8443/x', allowed)).toBe(true);
+ });
+
+ it('rejects a different host', () => {
+ expect(isAllowedOrigin('https://evil.example.net', allowed)).toBe(false);
+ });
+
+ it('rejects a host that only contains an allowed host', () => {
+ expect(isAllowedOrigin('https://app.example.com.evil.net', allowed)).toBe(false);
+ expect(isAllowedOrigin('https://notapp.example.com', allowed)).toBe(false);
+ });
+
+ it('rejects a malformed header instead of throwing', () => {
+ expect(isAllowedOrigin('foo', allowed)).toBe(false);
+ expect(isAllowedOrigin('not a url', allowed)).toBe(false);
+ expect(isAllowedOrigin('//app.example.com', allowed)).toBe(false);
+ expect(isAllowedOrigin('http://', allowed)).toBe(false);
+ });
+
+ it('rejects a missing or empty header', () => {
+ expect(isAllowedOrigin(undefined, allowed)).toBe(false);
+ expect(isAllowedOrigin(null, allowed)).toBe(false);
+ expect(isAllowedOrigin('', allowed)).toBe(false);
+ });
+
+ it('skips a malformed allow-list entry and still matches the valid ones', () => {
+ const mixed = ['app.example.com', 'https://admin.example.com'];
+ expect(isAllowedOrigin('https://admin.example.com', mixed)).toBe(true);
+ expect(isAllowedOrigin('https://evil.example.net', mixed)).toBe(false);
+ });
+
+ it('skips a malformed allow-list entry listed after the valid one', () => {
+ const mixed = ['https://app.example.com', 'not a url'];
+ expect(isAllowedOrigin('https://app.example.com', mixed)).toBe(true);
+ });
+
+ it('rejects everything when every allow-list entry is malformed', () => {
+ expect(isAllowedOrigin('https://app.example.com', ['app.example.com', 'foo'])).toBe(false);
+ });
+
+ it('rejects everything when the allow-list is empty', () => {
+ expect(isAllowedOrigin('https://app.example.com', [])).toBe(false);
+ });
+
+ it('does not let a scheme-less entry match a header that has no host', () => {
+ // `new URL('localhost:3000')` parses (scheme "localhost:") with an empty hostname,
+ // and so does `new URL('foo:bar')`. Neither side may match on that empty hostname.
+ expect(isAllowedOrigin('foo:bar', ['localhost:3000'])).toBe(false);
+ expect(isAllowedOrigin('javascript:alert(1)', ['localhost:3000'])).toBe(false);
+ expect(isAllowedOrigin('foo:bar', ['https://app.example.com'])).toBe(false);
+ });
+
+ it('still matches a valid entry that sits next to a scheme-less one', () => {
+ expect(
+ isAllowedOrigin('http://localhost:3000/', ['localhost:3000', 'http://localhost:3000']),
+ ).toBe(true);
+ });
+});