feat(http): hardens rebinding defenses (#317)

This commit is contained in:
Sampson authored and GitHub committed 2026-07-18 14:18:54 -05:00
1 parent fd28e3e7b3
commit 576bd312d7
10 files changed
+680 -7

No files matched your search

+5
View File
@@ -26,6 +26,11 @@ COPY --from=builder /app/package-lock.json /app/package-lock.json
ENV NODE_ENV=production
# The server defaults to binding 127.0.0.1 for safe local execution. Inside a
# container the port must be reachable through the published mapping, so bind to
# all interfaces here. Deployments can still override BRAVE_MCP_HOST.
ENV BRAVE_MCP_HOST=0.0.0.0
RUN npm ci --ignore-scripts --omit-dev
USER node
+6 -2
View File
@@ -173,7 +173,9 @@ The server supports the following environment variables:
- `BRAVE_API_KEY_FILE`: Path to a file containing your Brave Search API key. When set, this takes precedence over `BRAVE_API_KEY`. Useful for Docker secrets and similar mounted-secret setups.
- `BRAVE_MCP_TRANSPORT`: Transport mode ("http" or "stdio", default: "stdio")
- `BRAVE_MCP_PORT`: HTTP server port (default: 8080)
- `BRAVE_MCP_HOST`: HTTP server host (default: "0.0.0.0")
- `BRAVE_MCP_HOST`: HTTP server host (default: "127.0.0.1"). Binds to loopback only by default; set to "0.0.0.0" to expose the server on all interfaces (required inside containers and on Amazon Bedrock AgentCore). Only do this on a trusted network, since the HTTP endpoint is unauthenticated.
- `BRAVE_MCP_ALLOWED_ORIGINS`: Space- or comma-separated list of additional `Origin` header values permitted for the HTTP transport. Loopback origins are always allowed; browser requests carrying any other `Origin` are rejected with HTTP 403 to guard against DNS rebinding. Set this when a browser-based client on a real domain needs access.
- `BRAVE_MCP_ALLOWED_HOSTS`: Space- or comma-separated list of hostnames permitted in the `Host` header of the HTTP transport. Matching is on the hostname only and is case-insensitive; a numeric port in an entry (e.g. `mcp.example.com:8080`) is accepted but ignored for matching. Optional, opt-in defense-in-depth: when unset (default) the `Host` header is not validated, so reverse-proxy and custom-domain deployments are unaffected. When set, only loopback hosts and the listed hostnames are accepted; any other `Host` (including malformed/non-numeric ports) is rejected with HTTP 403.
- `BRAVE_MCP_LOG_LEVEL`: Desired logging level("debug", "info", "notice", "warning", "error", "critical", "alert", or "emergency", default: "info")
- `BRAVE_MCP_ENABLED_TOOLS`: When used, specifies a space-separated whitelist for supported tools
- `BRAVE_MCP_DISABLED_TOOLS`: When used, specifies a space-separated blacklist for supported tools
@@ -189,7 +191,9 @@ Options:
--brave-api-key-file <string> Path to file containing Brave API key
--transport <stdio|http> Transport type (default: stdio)
--port <number> HTTP server port (default: 8080)
--host <string> HTTP server host (default: 0.0.0.0)
--host <string> HTTP server host (default: 127.0.0.1)
--allowed-origins <origins...> Allowed Origin header values for HTTP transport (DNS rebinding protection)
--allowed-hosts <hosts...> Allowed Host header values for HTTP transport (opt-in DNS rebinding protection)
--logging-level <string> Desired logging level (one of _debug_, _info_, _notice_, _warning_, _error_, _critical_, _alert_, or _emergency_)
--enabled-tools Tools whitelist (only the specified tools will be enabled)
--disabled-tools Tools blacklist (included tools will be disabled)
+119
View File
@@ -14,21 +14,28 @@ const CONFIG_ENV_VARS = [
'BRAVE_MCP_DISABLED_TOOLS',
'BRAVE_MCP_PORT',
'BRAVE_MCP_HOST',
'BRAVE_MCP_ALLOWED_ORIGINS',
'BRAVE_MCP_ALLOWED_HOSTS',
'BRAVE_MCP_STATELESS',
] as const;
describe('getOptions', () => {
const originalArgv = process.argv;
const originalEnv = Object.fromEntries(CONFIG_ENV_VARS.map((key) => [key, process.env[key]]));
const originalConsoleError = console.error;
beforeEach(() => {
for (const key of CONFIG_ENV_VARS) {
delete process.env[key];
}
// getOptions() logs validation failures via console.error; silence it so the
// expected-failure cases don't add noise to the test output.
console.error = () => {};
});
afterEach(() => {
process.argv = originalArgv;
console.error = originalConsoleError;
for (const key of CONFIG_ENV_VARS) {
if (originalEnv[key] === undefined) {
delete process.env[key];
@@ -78,4 +85,116 @@ describe('getOptions', () => {
assert.equal(options.braveApiKey, 'from-file');
}
});
it('defaults host to loopback (127.0.0.1)', () => {
process.argv = ['node', 'index.js', '--brave-api-key', 'key', '--transport', 'http'];
const options = getOptions();
assert.notEqual(options, false);
if (options) {
assert.equal(options.host, '127.0.0.1');
}
});
it('honors BRAVE_MCP_HOST override', () => {
process.env.BRAVE_MCP_HOST = '0.0.0.0';
process.argv = ['node', 'index.js', '--brave-api-key', 'key', '--transport', 'http'];
const options = getOptions();
assert.notEqual(options, false);
if (options) {
assert.equal(options.host, '0.0.0.0');
}
});
it('defaults allowedOrigins to an empty list', () => {
process.argv = ['node', 'index.js', '--brave-api-key', 'key'];
const options = getOptions();
assert.notEqual(options, false);
if (options) {
assert.deepEqual(options.allowedOrigins, []);
}
});
it('parses BRAVE_MCP_ALLOWED_ORIGINS (comma/space separated)', () => {
process.env.BRAVE_MCP_ALLOWED_ORIGINS =
'https://a.example, https://b.example https://c.example';
process.argv = ['node', 'index.js', '--brave-api-key', 'key'];
const options = getOptions();
assert.notEqual(options, false);
if (options) {
assert.deepEqual(options.allowedOrigins, [
'https://a.example',
'https://b.example',
'https://c.example',
]);
}
});
it('parses --allowed-origins from the CLI', () => {
process.argv = [
'node',
'index.js',
'--brave-api-key',
'key',
'--allowed-origins',
'https://a.example',
'https://b.example',
];
const options = getOptions();
assert.notEqual(options, false);
if (options) {
assert.deepEqual(options.allowedOrigins, ['https://a.example', 'https://b.example']);
}
});
it('defaults allowedHosts to an empty list', () => {
process.argv = ['node', 'index.js', '--brave-api-key', 'key'];
const options = getOptions();
assert.notEqual(options, false);
if (options) {
assert.deepEqual(options.allowedHosts, []);
}
});
it('parses BRAVE_MCP_ALLOWED_HOSTS (comma/space separated)', () => {
process.env.BRAVE_MCP_ALLOWED_HOSTS = 'a.example:8080, b.example c.example';
process.argv = ['node', 'index.js', '--brave-api-key', 'key'];
const options = getOptions();
assert.notEqual(options, false);
if (options) {
assert.deepEqual(options.allowedHosts, ['a.example:8080', 'b.example', 'c.example']);
}
});
it('parses --allowed-hosts from the CLI', () => {
process.argv = [
'node',
'index.js',
'--brave-api-key',
'key',
'--allowed-hosts',
'a.example',
'b.example',
];
const options = getOptions();
assert.notEqual(options, false);
if (options) {
assert.deepEqual(options.allowedHosts, ['a.example', 'b.example']);
}
});
});
+25 -3
View File
@@ -2,7 +2,7 @@ import { LoggingLevel, LoggingLevelSchema } from '@modelcontextprotocol/sdk/type
import { Command } from 'commander';
import dotenv from 'dotenv';
import tools from './tools/index.js';
import { parsePort, readBraveApiKeyFromFile } from './utils.js';
import { parseDelimitedList, parsePort, readBraveApiKeyFromFile } from './utils.js';
dotenv.config({ debug: false, quiet: true });
@@ -25,18 +25,22 @@ type Configuration = {
enabledTools: string[];
disabledTools: string[];
stateless: boolean;
allowedOrigins: string[];
allowedHosts: string[];
};
const state: Configuration & { ready: boolean } = {
transport: 'stdio',
port: 8080,
host: '0.0.0.0',
host: '127.0.0.1',
braveApiKey: process.env.BRAVE_API_KEY ?? '',
loggingLevel: 'info',
ready: false,
enabledTools: [],
disabledTools: [],
stateless: false,
allowedOrigins: [],
allowedHosts: [],
};
export function isToolPermittedByUser(toolName: string): boolean {
@@ -77,7 +81,17 @@ export function getOptions(): Configuration | false {
.option(
'--host <string>',
'desired host for HTTP transport',
process.env.BRAVE_MCP_HOST ?? '0.0.0.0'
process.env.BRAVE_MCP_HOST ?? '127.0.0.1'
)
.option(
'--allowed-origins <origins...>',
'allowed Origin header values for HTTP transport (DNS rebinding protection)',
process.env.BRAVE_MCP_ALLOWED_ORIGINS ?? ''
)
.option(
'--allowed-hosts <hosts...>',
'allowed Host header values for HTTP transport (opt-in DNS rebinding protection)',
process.env.BRAVE_MCP_ALLOWED_HOSTS ?? ''
)
.option(
'--stateless <boolean>',
@@ -164,6 +178,12 @@ export function getOptions(): Configuration | false {
options.stateless = options.stateless === true || options.stateless === 'true';
options.braveApiKey = braveApiKey;
const allowedOrigins = parseDelimitedList(options.allowedOrigins);
options.allowedOrigins = allowedOrigins;
const allowedHosts = parseDelimitedList(options.allowedHosts);
options.allowedHosts = allowedHosts;
// Update state
state.braveApiKey = braveApiKey;
state.transport = options.transport;
@@ -173,6 +193,8 @@ export function getOptions(): Configuration | false {
state.enabledTools = enabledTools;
state.disabledTools = disabledTools;
state.stateless = options.stateless;
state.allowedOrigins = allowedOrigins;
state.allowedHosts = allowedHosts;
state.ready = true;
return options as Configuration;
+216
View File
@@ -0,0 +1,216 @@
import assert from 'node:assert/strict';
import http, { type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { after, before, describe, it } from 'node:test';
import config from '../config.js';
import httpServer from './http.js';
// Raw HTTP client so we can set the Host header (fetch/undici forbids overriding it).
const rawRequest = (
port: number,
headers: Record<string, string>
): Promise<{ status: number; body: string }> =>
new Promise((resolve, reject) => {
const body = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} });
const req = http.request(
{
host: '127.0.0.1',
port,
path: '/mcp',
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json, text/event-stream',
'content-length': Buffer.byteLength(body),
...headers,
},
},
(res) => {
let data = '';
res.on('data', (chunk) => (data += chunk));
res.on('end', () => resolve({ status: res.statusCode ?? 0, body: data }));
}
);
req.on('error', reject);
req.write(body);
req.end();
});
describe('http Origin validation', () => {
let server: Server;
let baseUrl: string;
let port: number;
const originalAllowedOrigins = [...config.allowedOrigins];
const post = (origin: string | undefined) =>
fetch(`${baseUrl}/mcp`, {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json, text/event-stream',
...(origin ? { origin } : {}),
},
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }),
});
before(async () => {
config.allowedOrigins = ['https://allowed.example'];
const app = httpServer.createApp();
server = app.listen(0);
await new Promise<void>((resolve) => server.once('listening', resolve));
port = (server.address() as AddressInfo).port;
baseUrl = `http://127.0.0.1:${port}`;
});
after(async () => {
config.allowedOrigins = originalAllowedOrigins;
await new Promise<void>((resolve, reject) =>
server.close((err) => (err ? reject(err) : resolve()))
);
});
it('rejects a disallowed browser Origin with 403 and a JSON-RPC error', async () => {
const res = await post('https://evil.example');
const body = await res.json();
assert.equal(res.status, 403);
assert.deepEqual(body, {
jsonrpc: '2.0',
error: { code: -32600, message: 'Forbidden: invalid Origin' },
id: null,
});
});
it('allows loopback Origins', async () => {
const res = await post('http://localhost:3000');
await res.text();
assert.notEqual(res.status, 403);
});
it('allows explicitly allow-listed Origins', async () => {
const res = await post('https://allowed.example');
await res.text();
assert.notEqual(res.status, 403);
});
it('matches allow-listed Origins case-insensitively', async () => {
const res = await post('https://ALLOWED.example');
await res.text();
assert.notEqual(res.status, 403);
});
it('matches allow-listed Origins ignoring the default port', async () => {
const res = await post('https://allowed.example:443');
await res.text();
assert.notEqual(res.status, 403);
});
it('allows requests without an Origin header', async () => {
const res = await post(undefined);
await res.text();
assert.notEqual(res.status, 403);
});
it('rejects a present but empty Origin header', async () => {
const res = await rawRequest(port, { origin: '' });
assert.equal(res.status, 403);
});
});
describe('http Host validation (disabled by default)', () => {
let server: Server;
let port: number;
before(async () => {
const app = httpServer.createApp();
server = app.listen(0);
await new Promise<void>((resolve) => server.once('listening', resolve));
port = (server.address() as AddressInfo).port;
});
after(async () => {
await new Promise<void>((resolve, reject) =>
server.close((err) => (err ? reject(err) : resolve()))
);
});
it('allows an arbitrary Host when allowedHosts is empty', async () => {
const res = await rawRequest(port, { host: 'anything.example.com' });
assert.notEqual(res.status, 403);
});
});
describe('http Host validation (opt-in)', () => {
let server: Server;
let port: number;
const originalAllowedHosts = [...config.allowedHosts];
before(async () => {
config.allowedHosts = ['allowed.example.com'];
const app = httpServer.createApp();
server = app.listen(0);
await new Promise<void>((resolve) => server.once('listening', resolve));
port = (server.address() as AddressInfo).port;
});
after(async () => {
config.allowedHosts = originalAllowedHosts;
await new Promise<void>((resolve, reject) =>
server.close((err) => (err ? reject(err) : resolve()))
);
});
it('rejects a disallowed Host with 403 and a JSON-RPC error', async () => {
const res = await rawRequest(port, { host: 'evil.example.com' });
assert.equal(res.status, 403);
assert.deepEqual(JSON.parse(res.body), {
jsonrpc: '2.0',
error: { code: -32600, message: 'Forbidden: invalid Host' },
id: null,
});
});
it('allows loopback Hosts', async () => {
const res = await rawRequest(port, { host: `127.0.0.1:${port}` });
assert.notEqual(res.status, 403);
});
it('allows explicitly allow-listed Hosts', async () => {
const res = await rawRequest(port, { host: 'allowed.example.com' });
assert.notEqual(res.status, 403);
});
it('allows an allow-listed Host regardless of port', async () => {
const res = await rawRequest(port, { host: 'allowed.example.com:9999' });
assert.notEqual(res.status, 403);
});
it('matches allow-listed Hosts case-insensitively', async () => {
const res = await rawRequest(port, { host: 'ALLOWED.EXAMPLE.COM' });
assert.notEqual(res.status, 403);
});
it('rejects a malformed bracketed IPv6 Host that spoofs loopback', async () => {
const res = await rawRequest(port, { host: '[::1]evil.example.com' });
assert.equal(res.status, 403);
});
it('rejects an allow-listed Host with a malformed (non-numeric) port', async () => {
const res = await rawRequest(port, { host: 'allowed.example.com:80evil' });
assert.equal(res.status, 403);
});
});
+10 -1
View File
@@ -4,6 +4,7 @@ import config from '../config.js';
import createMcpServer from '../server.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { ListToolsRequest, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { createDnsRebindingGuard } from './rebinding.js';
const yieldGenericServerError = (res: Response) => {
res.status(500).json({
@@ -62,7 +63,15 @@ const getTransport = async (request: Request): Promise<StreamableHTTPServerTrans
const createApp = () => {
const app = express();
app.use(express.json());
app.use(
'/mcp',
createDnsRebindingGuard({
allowedHosts: config.allowedHosts,
allowedOrigins: config.allowedOrigins,
})
);
app.use('/mcp', express.json());
app.all('/mcp', async (req: Request, res: Response) => {
try {
+76
View File
@@ -0,0 +1,76 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { canonicalizeOrigin, normalizeHost } from './rebinding.js';
describe('canonicalizeOrigin', () => {
it('returns the canonical scheme://host[:port] form', () => {
assert.equal(canonicalizeOrigin('https://example.com'), 'https://example.com');
assert.equal(canonicalizeOrigin('https://example.com:8443'), 'https://example.com:8443');
assert.equal(canonicalizeOrigin('http://localhost:3000'), 'http://localhost:3000');
});
it('lowercases scheme and host', () => {
assert.equal(canonicalizeOrigin('HTTPS://Example.COM'), 'https://example.com');
});
it('drops the default port for the scheme', () => {
assert.equal(canonicalizeOrigin('https://example.com:443'), 'https://example.com');
assert.equal(canonicalizeOrigin('http://example.com:80'), 'http://example.com');
});
it('ignores path, query, and fragment', () => {
assert.equal(canonicalizeOrigin('https://example.com/a/b?c=d#e'), 'https://example.com');
});
it('returns null for unparseable values', () => {
assert.equal(canonicalizeOrigin(''), null);
assert.equal(canonicalizeOrigin('not a url'), null);
assert.equal(canonicalizeOrigin('example.com'), null);
});
});
describe('normalizeHost', () => {
it('returns the bare, lowercased hostname', () => {
assert.equal(normalizeHost('example.com'), 'example.com');
assert.equal(normalizeHost('Example.COM'), 'example.com');
assert.equal(normalizeHost('127.0.0.1'), '127.0.0.1');
});
it('strips the port', () => {
assert.equal(normalizeHost('example.com:8080'), 'example.com');
assert.equal(normalizeHost('example.com:443'), 'example.com');
});
it('unwraps bracketed IPv6 literals', () => {
assert.equal(normalizeHost('[::1]'), '::1');
assert.equal(normalizeHost('[::1]:8080'), '::1');
assert.equal(normalizeHost('[2001:DB8::1]:443'), '2001:db8::1');
});
it('returns null for empty or whitespace-only values', () => {
assert.equal(normalizeHost(''), null);
assert.equal(normalizeHost(' '), null);
});
it('returns null for a non-numeric port', () => {
assert.equal(normalizeHost('example.com:80evil'), null);
assert.equal(normalizeHost('example.com:99999999'), null);
});
it('returns null for schemes', () => {
assert.equal(normalizeHost('https://example.com'), null);
assert.equal(normalizeHost('http://example.com'), null);
});
it('returns null for malformed bracketed IPv6 with trailing junk', () => {
assert.equal(normalizeHost('[::1]evil.example'), null);
assert.equal(normalizeHost('[::1'), null);
});
it('returns null when userinfo, path, query, or fragment is present', () => {
assert.equal(normalizeHost('evil.com@example.com'), null);
assert.equal(normalizeHost('example.com/path'), null);
assert.equal(normalizeHost('example.com?q=1'), null);
assert.equal(normalizeHost('example.com#frag'), null);
});
});
+138
View File
@@ -0,0 +1,138 @@
import type { NextFunction, Request, RequestHandler, Response } from 'express';
import { isLoopbackHostname } from '../utils.js';
// 403 with a JSON-RPC error and no id, per the MCP Streamable HTTP spec.
const sendForbidden = (res: Response, message: string): void => {
res.status(403).json({ jsonrpc: '2.0', error: { code: -32600, message }, id: null });
};
const stripBrackets = (hostname: string): string => hostname.replace(/^\[|\]$/g, '').toLowerCase();
// Canonical origin ("scheme://host[:port]", lowercased with the default port
// dropped) or null when the value is not a parseable origin. Using URL.origin
// makes comparisons case- and default-port-insensitive.
export const canonicalizeOrigin = (value: string): string | null => {
const trimmed = value.trim();
if (trimmed.length === 0) return null;
try {
const origin = new URL(trimmed).origin;
// URL.origin may be 'null' for opaque origins, e.g. 'blob:'.
return origin === 'null' ? null : origin;
} catch {
return null;
}
};
/**
* Returns the bare, lowercased hostname (port and IPv6 brackets removed), or
* null when the value is not a clean "host[:port]". Parsing via URL rejects
* malformed authorities (bad ports, embedded userinfo, paths, etc.) by
* returning null so they fail closed.
* @returns The canonicalized hostname, or null if the value is not a clean "host[:port]".
* @example normalizeHost('example.com:8080') === 'example.com'
* @example normalizeHost('example.com') === 'example.com'
* @example normalizeHost('example.com/path') === null
* @example normalizeHost('example.com?q=1') === null
* @example normalizeHost('example.com#frag') === null
* @example normalizeHost('example.com@user:pass') === null
* @example normalizeHost('example.com:80evil') === null
* @example normalizeHost('example.com:99999999') === null
* @example normalizeHost('[::1]') === '::1'
*/
export const normalizeHost = (value: string): string | null => {
const trimmed = value.trim();
if (trimmed.length === 0) return null;
// A Host header carries only "host[:port]"; any path delimiter is malformed.
if (trimmed.includes('/') || trimmed.includes('\\')) return null;
let url: URL;
try {
url = new URL(`http://${trimmed}`);
} catch {
return null;
}
// A Host header carries only "host[:port]"; anything else is malformed.
if (url.username || url.password || url.search || url.hash || url.pathname !== '/') {
return null;
}
return stripBrackets(url.hostname);
};
const toNormalizedSet = (
values: string[],
normalize: (value: string) => string | null
): Set<string> => {
const set = new Set<string>();
for (const value of values) {
const normalized = normalize(value);
if (normalized !== null) set.add(normalized);
}
return set;
};
const isOriginAllowed = (origin: string, allowedOrigins: Set<string>): boolean => {
const trimmed = origin.trim();
if (trimmed.length === 0) return false;
let url: URL;
try {
url = new URL(trimmed);
// URL.origin may be 'null' for opaque origins, e.g. 'blob:'.
if (url.origin === 'null') return false;
} catch {
return false;
}
return isLoopbackHostname(stripBrackets(url.hostname)) || allowedOrigins.has(url.origin);
};
const isHostAllowed = (hostHeader: string, allowedHosts: Set<string>): boolean => {
const host = normalizeHost(hostHeader);
if (host === null) return false;
return isLoopbackHostname(host) || allowedHosts.has(host);
};
// Builds Express middleware that guards against DNS rebinding:
// - Origin is always validated. A request with no Origin header passes through
// (non-browser MCP clients omit it), but any present Origin must be loopback
// or explicitly allow-listed.
// - Host is validated only when allowedHosts is configured (opt-in), so
// reverse-proxy / custom-domain deployments are unaffected by default.
export const createDnsRebindingGuard = (options: {
allowedOrigins: string[];
allowedHosts: string[];
}): RequestHandler => {
const allowedOrigins = toNormalizedSet(options.allowedOrigins, canonicalizeOrigin);
const allowedHosts = toNormalizedSet(options.allowedHosts, normalizeHost);
const enforceHost = allowedHosts.size > 0;
return (req: Request, res: Response, next: NextFunction) => {
const origin = req.headers.origin;
if (origin !== undefined) {
// Origin may be undefined (non-browser MCP clients omit it), but any
// present Origin must be validated.
if (typeof origin !== 'string' || !isOriginAllowed(origin, allowedOrigins)) {
sendForbidden(res, 'Forbidden: invalid Origin');
return;
}
}
if (enforceHost) {
// Host is validated only when allowedHosts is configured (opt-in), so
// reverse-proxy / custom-domain deployments are unaffected by default.
const host = req.headers.host;
if (typeof host !== 'string' || !isHostAllowed(host, allowedHosts)) {
sendForbidden(res, 'Forbidden: invalid Host');
return;
}
}
next();
};
};
+50 -1
View File
@@ -3,7 +3,7 @@ import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, it } from 'node:test';
import { parsePort, readBraveApiKeyFromFile } from './utils.js';
import { isLoopbackHostname, parsePort, readBraveApiKeyFromFile } from './utils.js';
describe('parsePort', () => {
it('accepts valid integer ports', () => {
@@ -26,6 +26,55 @@ describe('parsePort', () => {
});
});
describe('isLoopbackHostname', () => {
it('accepts localhost and the IPv6 loopback', () => {
assert.equal(isLoopbackHostname('localhost'), true);
assert.equal(isLoopbackHostname('::1'), true);
});
it('accepts addresses across the whole IPv4 127.0.0.0/8 range', () => {
assert.equal(isLoopbackHostname('127.0.0.1'), true);
assert.equal(isLoopbackHostname('127.0.0.0'), true);
assert.equal(isLoopbackHostname('127.1.2.3'), true);
assert.equal(isLoopbackHostname('127.255.255.255'), true);
assert.equal(isLoopbackHostname('127.0.0.255'), true);
});
it('rejects non-loopback IPv4 addresses', () => {
assert.equal(isLoopbackHostname('128.0.0.1'), false);
assert.equal(isLoopbackHostname('126.255.255.255'), false);
assert.equal(isLoopbackHostname('0.0.0.0'), false);
assert.equal(isLoopbackHostname('192.168.0.1'), false);
assert.equal(isLoopbackHostname('10.0.0.1'), false);
});
it('rejects IPv4 octets outside 0-255', () => {
assert.equal(isLoopbackHostname('127.0.0.256'), false);
assert.equal(isLoopbackHostname('127.0.0.999'), false);
});
it('rejects addresses without exactly four octets', () => {
assert.equal(isLoopbackHostname('127'), false);
assert.equal(isLoopbackHostname('127.0.0'), false);
assert.equal(isLoopbackHostname('127.0.0.1.2'), false);
assert.equal(isLoopbackHostname(''), false);
});
it('rejects non-numeric or malformed IPv4 octets', () => {
assert.equal(isLoopbackHostname('127.0.0.x'), false);
assert.equal(isLoopbackHostname('127.0.0.-1'), false);
assert.equal(isLoopbackHostname('127.0.0.1abc'), false);
assert.equal(isLoopbackHostname('127.0.0. 1'), false);
assert.equal(isLoopbackHostname('0127.0.0.1'), false);
});
it('rejects non-loopback hostnames and non-normalized input', () => {
assert.equal(isLoopbackHostname('example.com'), false);
// Callers normalize (lowercase) before calling, so uppercase is not matched.
assert.equal(isLoopbackHostname('LOCALHOST'), false);
});
});
describe('readBraveApiKeyFromFile', () => {
it('reads and trims API keys from a file', () => {
const dir = mkdtempSync(join(tmpdir(), 'brave-api-key-'));
+35
View File
@@ -42,6 +42,41 @@ export function readBraveApiKeyFromFile(filePath: string): ReadBraveApiKeyFromFi
}
}
export function parseDelimitedList(value: string | string[] | undefined | null): string[] {
if (value == null) return [];
// Value may be variadic as string[]. Normalize to a single string first.
const raw = Array.isArray(value) ? value.join(' ') : value;
return raw
.split(/[\s,]+/)
.map((o: string) => o.trim())
.filter((o: string) => o.length > 0);
}
function isIpv4Loopback(value: string): boolean {
// Check complete range of loopback addresses: 127.0.0.0/8
const parts = value.split('.');
return (
parts.length === 4 &&
parts[0] === '127' &&
parts.every((part: string) => {
if (!/^\d+$/.test(part)) return false;
// Leading zeros are not allowed.
if (part.length > 1 && part.startsWith('0')) return false;
// Parse the part as an integer and check if it's in the range 0-255.
const num = Number.parseInt(part, 10);
return num >= 0 && num <= 255;
})
);
}
// Determines whether a bare hostname refers to the loopback interface: any
// IPv4 127.0.0.0/8 address, the IPv6 loopback (::1), or "localhost".
export function isLoopbackHostname(value: string): boolean {
return value === 'localhost' || value === '::1' || isIpv4Loopback(value);
}
export function parsePort(value: unknown): number | null {
if (value === undefined || value === null || value === '') {
return null;