Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: harden AI provider custom endpoints against SSRF/key exfil (#2514)

Adam Eivy036266ceb6ba
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8ea0db9e43..95962882d5 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased
+## Security
+
+- **[issue-2514] Harden AI provider custom endpoints against SSRF / API-key exfiltration.** A provider's `endpoint` is a free-form URL, and model-refresh / API-run paths attached the paid `Authorization: Bearer <apiKey>` and fetched that host with no host checks — a hostile or mistyped endpoint could receive the user's paid LLM key and prompts, or be pointed at a cloud-metadata service (`169.254.169.254`). A new `endpointGuard` now gates every secret-bearing request: loopback/LAN (Tailscale) and known paid-provider hosts are allowed, cloud-metadata hosts are always blocked, and any other host requires the new per-provider **Allow custom endpoint** opt-in. Keyless local-LLM calls (Ollama/LM Studio) are unaffected.
+
## Fixed
- **[issue-2510] MidiPianoRoll: clear the stale hover overlay when the transcription data changes.** The piano-roll kept its hovered note/chord identity (objects from the previous parse) when the `data`/`chords` props swapped on a mounted instance, so a re-transcription or Retry while a hover was active and the pointer sat still would keep stroking the old note at coordinates mapped into the new file until the next pointer move or Escape. A `useEffect` now drops the hover identity whenever `data`/`chords` change.
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 21c0941ee7..d314db9d45 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -717,6 +717,7 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
args: provider?.args?.join(' ') || '',
endpoint: provider?.endpoint || '',
apiKey: '',
+ allowCustomEndpoint: provider?.allowCustomEndpoint === true,
models: provider?.models || [],
defaultModel: provider?.defaultModel || '',
lightModel: provider?.lightModel || '',
@@ -961,6 +962,23 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
/>
</FormField>
+
+ <FormField label="Custom endpoint">
+ <label htmlFor="allowCustomEndpoint" className="flex items-start gap-2 cursor-pointer">
+ <input
+ id="allowCustomEndpoint"
+ type="checkbox"
+ checked={formData.allowCustomEndpoint}
+ onChange={(e) => setFormData(prev => ({ ...prev, allowCustomEndpoint: e.target.checked }))}
+ className="mt-1"
+ />
+ <span className="text-sm text-gray-300">
+ Allow sending the API key to this custom (non-local, non-allowlisted) endpoint.
+ Loopback/LAN and known providers (OpenAI, Anthropic, OpenRouter, …) are always allowed;
+ cloud-metadata hosts are always blocked. Leave off unless you trust this host.
+ </span>
+ </label>
+ </FormField>
</>
)}
diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.js
index e67b832cac..1a630fee11 100644
--- a/server/lib/aiProvider.js
+++ b/server/lib/aiProvider.js
@@ -11,6 +11,7 @@ import { ensureProviderReady as ensureOllamaProviderReady, isOllamaProvider } fr
// eagerly import fileUtils `PATHS`) into every aiProvider consumer's module
// graph, breaking suites that partial-mock fileUtils without PATHS.
import { readResponseJson } from './readResponseJson.js';
+import { evaluateSecretEndpoint } from './aiToolkit/internal/endpointGuard.js';
const isAPI = (p) => p && p.type === 'api' && p.enabled !== false;
@@ -132,7 +133,17 @@ async function ensureLMStudioModelLoaded(provider, statusOp) {
async function postChatCompletion(provider, model, prompt, { temperature, max_tokens, timeout }) {
const headers = { 'Content-Type': 'application/json' };
- if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ if (provider.apiKey) {
+ // Never send the API key to an arbitrary/metadata host (SSRF / key
+ // exfiltration). Keyless local-LLM calls skip this guard entirely.
+ const guard = evaluateSecretEndpoint(provider.endpoint, {
+ allowCustomEndpoint: provider.allowCustomEndpoint === true,
+ });
+ if (!guard.allowed) {
+ return { error: `Provider endpoint blocked: ${guard.reason}` };
+ }
+ headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ }
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
diff --git a/server/lib/aiToolkit/internal/endpointGuard.js b/server/lib/aiToolkit/internal/endpointGuard.js
new file mode 100644
index 0000000000..2aa59203af
--- /dev/null
+++ b/server/lib/aiToolkit/internal/endpointGuard.js
@@ -0,0 +1,163 @@
+/**
+ * SSRF / key-exfiltration guard for provider `endpoint` URLs.
+ *
+ * Provider `endpoint` is a free-form URL the user types. Model-refresh and
+ * API-run paths attach the provider's `Authorization: Bearer <apiKey>` (a
+ * paid/quota-billed LLM key) and `fetch` that host. A hostile or mistyped
+ * endpoint could therefore receive the user's paid API key and prompts, or be
+ * pointed at a cloud metadata service (169.254.169.254) to exfiltrate instance
+ * credentials — classic SSRF.
+ *
+ * The guard is intentionally scoped to **secret-bearing** requests only. A
+ * local LLM (Ollama / LM Studio) with no API key is never restricted, so the
+ * loopback local-LLM story is unaffected. When a key IS attached we require the
+ * destination to be one of:
+ * - loopback (localhost / 127.0.0.0/8 / ::1)
+ * - a private / link-local / CGNAT (Tailscale) range — the user's own LAN,
+ * where self-hosted LLM servers legitimately live on this Tailscale-only,
+ * single-user product
+ * - a known paid-LLM provider host (the built-in allowlist)
+ * - an arbitrary host the user has *explicitly* opted into via the provider's
+ * `allowCustomEndpoint` flag
+ *
+ * Cloud-metadata endpoints are ALWAYS blocked, even with `allowCustomEndpoint`
+ * — a bearer token has no business going there and it's the canonical SSRF
+ * credential-theft target.
+ *
+ * Kept in `aiToolkit/internal/` (pure, no imports) so the toolkit stays
+ * self-contained; `server/lib/aiProvider.js` imports it from here too.
+ *
+ * NOTE: checks are performed on the URL's literal host. We do not resolve DNS,
+ * so a user-supplied hostname that resolves to a private/metadata IP is treated
+ * as the user's own choice (they typed it) rather than defended against — this
+ * matches PortOS's single-user private-network trust model. The metadata and
+ * private-range literals below still block the direct-IP SSRF vector.
+ */
+
+// Cloud-metadata hosts that must NEVER receive a bearer token (IMDS credential
+// theft is the classic SSRF payoff). Blocked regardless of opt-in.
+const METADATA_HOSTS = new Set([
+ '169.254.169.254', // AWS / Azure / GCP / OpenStack / DigitalOcean IMDS (IPv4)
+ '100.100.100.200', // Alibaba Cloud metadata
+ 'fd00:ec2::254', // AWS IMDS (IPv6)
+ 'metadata.google.internal',
+ 'metadata.goog',
+ 'metadata',
+]);
+
+// Known paid / quota-billed LLM provider hosts — safe to receive their own key.
+const ALLOWED_PROVIDER_HOSTS = new Set([
+ 'api.openai.com',
+ 'api.anthropic.com',
+ 'generativelanguage.googleapis.com',
+ 'api.groq.com',
+ 'api.mistral.ai',
+ 'api.deepseek.com',
+ 'api.x.ai',
+ 'api.together.xyz',
+ 'api.together.ai',
+ 'openrouter.ai',
+ 'api.openrouter.ai',
+ 'api.perplexity.ai',
+ 'api.cohere.ai',
+ 'api.cohere.com',
+ 'api.fireworks.ai',
+]);
+
+const IPV4_RE = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
+
+/** Strip an IPv4-mapped IPv6 prefix (`::ffff:127.0.0.1`) down to the v4 literal. */
+function unwrapMappedV4(host) {
+ const m = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i.exec(host);
+ return m ? m[1] : host;
+}
+
+function isLoopbackOrPrivateV4(host) {
+ const m = IPV4_RE.exec(host);
+ if (!m) return false;
+ const [a, b] = [Number(m[1]), Number(m[2])];
+ if ([a, Number(m[3]), Number(m[4])].some((n) => n > 255) || a > 255) return false;
+ if (a === 127) return true; // 127.0.0.0/8 loopback
+ if (a === 0) return true; // 0.0.0.0 — treated as local
+ if (a === 10) return true; // 10.0.0.0/8 private
+ if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12 private
+ if (a === 192 && b === 168) return true; // 192.168.0.0/16 private
+ if (a === 169 && b === 254) return true; // 169.254.0.0/16 link-local (metadata IP blocked earlier)
+ if (a === 100 && b >= 64 && b <= 127) return true; // 100.64.0.0/10 CGNAT / Tailscale
+ return false;
+}
+
+function isLoopbackOrPrivateV6(host) {
+ const h = host.toLowerCase();
+ if (h === '::1') return true; // loopback
+ if (h === '::') return true; // unspecified — local
+ if (/^fc[0-9a-f]{2}:/.test(h) || /^fd[0-9a-f]{2}:/.test(h)) return true; // fc00::/7 ULA
+ if (/^fe[89ab][0-9a-f]:/.test(h)) return true; // fe80::/10 link-local
+ return false;
+}
+
+function isLocalHost(host) {
+ if (host === 'localhost' || host.endsWith('.localhost')) return true;
+ const v4 = unwrapMappedV4(host);
+ return isLoopbackOrPrivateV4(v4) || isLoopbackOrPrivateV6(host);
+}
+
+/**
+ * Decide whether it's safe to attach a secret (API key) to a request to
+ * `endpoint`. Pure — returns `{ allowed, reason }` and never throws.
+ *
+ * @param {string} endpoint - the provider endpoint URL
+ * @param {object} [opts]
+ * @param {boolean} [opts.allowCustomEndpoint] - user explicitly opted this
+ * provider into sending secrets to an arbitrary (non-local, non-allowlisted)
+ * host.
+ */
+export function evaluateSecretEndpoint(endpoint, { allowCustomEndpoint = false } = {}) {
+ if (!endpoint || typeof endpoint !== 'string') {
+ return { allowed: false, reason: 'missing endpoint URL' };
+ }
+
+ let url;
+ try {
+ url = new URL(endpoint);
+ } catch {
+ return { allowed: false, reason: `invalid endpoint URL: ${endpoint}` };
+ }
+
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+ return { allowed: false, reason: `unsupported protocol: ${url.protocol}` };
+ }
+
+ // WHATWG URL keeps brackets on IPv6 literals (`[::1]`); strip them so the
+ // host compares/regexes below see the bare address.
+ const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
+
+ // Metadata hosts are blocked unconditionally — even with opt-in.
+ if (METADATA_HOSTS.has(host) || METADATA_HOSTS.has(unwrapMappedV4(host))) {
+ return { allowed: false, reason: `cloud-metadata endpoint blocked: ${host}` };
+ }
+
+ if (isLocalHost(host)) return { allowed: true, reason: null };
+ if (ALLOWED_PROVIDER_HOSTS.has(host)) return { allowed: true, reason: null };
+ if (allowCustomEndpoint) return { allowed: true, reason: null };
+
+ return {
+ allowed: false,
+ reason:
+ `refusing to send API key to non-allowlisted host "${host}". ` +
+ 'Enable "allow custom endpoint" on this provider to opt in.',
+ };
+}
+
+/**
+ * Throwing convenience wrapper for call sites that already return/propagate an
+ * Error. Only enforces when a secret is actually being attached (`hasSecret`),
+ * so keyless local-LLM calls are never blocked.
+ */
+export function assertSecretEndpoint(endpoint, { hasSecret, allowCustomEndpoint } = {}) {
+ if (!hasSecret) return;
+ const { allowed, reason } = evaluateSecretEndpoint(endpoint, { allowCustomEndpoint });
+ if (!allowed) {
+ throw new Error(`Blocked outbound API-key request: ${reason}`);
+ }
+}
diff --git a/server/lib/aiToolkit/internal/endpointGuard.test.js b/server/lib/aiToolkit/internal/endpointGuard.test.js
new file mode 100644
index 0000000000..b454d1dc0b
--- /dev/null
+++ b/server/lib/aiToolkit/internal/endpointGuard.test.js
@@ -0,0 +1,117 @@
+import { describe, it, expect } from 'vitest';
+import { evaluateSecretEndpoint, assertSecretEndpoint } from './endpointGuard.js';
+
+describe('endpointGuard — evaluateSecretEndpoint', () => {
+ describe('loopback / local endpoints (local LLM story stays supported)', () => {
+ it('allows localhost', () => {
+ expect(evaluateSecretEndpoint('http://localhost:11434/v1').allowed).toBe(true);
+ });
+ it('allows 127.0.0.1', () => {
+ expect(evaluateSecretEndpoint('http://127.0.0.1:1234/v1').allowed).toBe(true);
+ });
+ it('allows IPv6 loopback ::1', () => {
+ expect(evaluateSecretEndpoint('http://[::1]:11434/v1').allowed).toBe(true);
+ });
+ it('allows a *.localhost host', () => {
+ expect(evaluateSecretEndpoint('http://ollama.localhost/v1').allowed).toBe(true);
+ });
+ });
+
+ describe('private / LAN / Tailscale ranges (self-hosted LLM on your own network)', () => {
+ it('allows 192.168.x.x', () => {
+ expect(evaluateSecretEndpoint('http://192.168.1.50:11434/v1').allowed).toBe(true);
+ });
+ it('allows 10.x.x.x', () => {
+ expect(evaluateSecretEndpoint('http://10.0.0.5:1234/v1').allowed).toBe(true);
+ });
+ it('allows 172.16-31.x.x', () => {
+ expect(evaluateSecretEndpoint('http://172.20.1.1:11434/v1').allowed).toBe(true);
+ expect(evaluateSecretEndpoint('http://172.15.1.1:11434/v1').allowed).toBe(false);
+ expect(evaluateSecretEndpoint('http://172.32.1.1:11434/v1').allowed).toBe(false);
+ });
+ it('allows CGNAT / Tailscale 100.64.0.0/10', () => {
+ expect(evaluateSecretEndpoint('http://100.100.50.1:11434/v1').allowed).toBe(true);
+ // ...but not 100.100.100.200 (Alibaba metadata) — see metadata tests
+ });
+ it('allows fc00::/7 ULA and fe80::/10 link-local IPv6', () => {
+ expect(evaluateSecretEndpoint('http://[fd12:3456::1]:11434/v1').allowed).toBe(true);
+ expect(evaluateSecretEndpoint('http://[fe80::1]:11434/v1').allowed).toBe(true);
+ });
+ });
+
+ describe('cloud-metadata endpoints are ALWAYS blocked', () => {
+ it('blocks 169.254.169.254 (AWS/GCP/Azure IMDS)', () => {
+ const r = evaluateSecretEndpoint('http://169.254.169.254/latest/meta-data/');
+ expect(r.allowed).toBe(false);
+ expect(r.reason).toMatch(/metadata/i);
+ });
+ it('blocks it even with allowCustomEndpoint opt-in', () => {
+ const r = evaluateSecretEndpoint('http://169.254.169.254/latest/', { allowCustomEndpoint: true });
+ expect(r.allowed).toBe(false);
+ });
+ it('blocks metadata.google.internal', () => {
+ expect(evaluateSecretEndpoint('http://metadata.google.internal/', { allowCustomEndpoint: true }).allowed).toBe(false);
+ });
+ it('blocks Alibaba 100.100.100.200', () => {
+ expect(evaluateSecretEndpoint('http://100.100.100.200/', { allowCustomEndpoint: true }).allowed).toBe(false);
+ });
+ it('blocks AWS IPv6 IMDS fd00:ec2::254', () => {
+ expect(evaluateSecretEndpoint('http://[fd00:ec2::254]/', { allowCustomEndpoint: true }).allowed).toBe(false);
+ });
+ });
+
+ describe('known paid-LLM provider hosts are allowed', () => {
+ it('allows api.openai.com', () => {
+ expect(evaluateSecretEndpoint('https://api.openai.com/v1').allowed).toBe(true);
+ });
+ it('allows openrouter.ai', () => {
+ expect(evaluateSecretEndpoint('https://openrouter.ai/api/v1').allowed).toBe(true);
+ });
+ it('allows generativelanguage.googleapis.com', () => {
+ expect(evaluateSecretEndpoint('https://generativelanguage.googleapis.com/v1beta').allowed).toBe(true);
+ });
+ });
+
+ describe('arbitrary public hosts require explicit opt-in', () => {
+ it('blocks an unknown public host by default', () => {
+ const r = evaluateSecretEndpoint('https://evil.example.com/v1');
+ expect(r.allowed).toBe(false);
+ expect(r.reason).toMatch(/allow custom endpoint/i);
+ });
+ it('allows the same host once allowCustomEndpoint is true', () => {
+ expect(evaluateSecretEndpoint('https://my-proxy.example.com/v1', { allowCustomEndpoint: true }).allowed).toBe(true);
+ });
+ });
+
+ describe('malformed / unsupported endpoints', () => {
+ it('blocks a non-URL string', () => {
+ expect(evaluateSecretEndpoint('not a url').allowed).toBe(false);
+ });
+ it('blocks a missing endpoint', () => {
+ expect(evaluateSecretEndpoint('').allowed).toBe(false);
+ expect(evaluateSecretEndpoint(null).allowed).toBe(false);
+ });
+ it('blocks non-http(s) protocols', () => {
+ expect(evaluateSecretEndpoint('file:///etc/passwd').allowed).toBe(false);
+ expect(evaluateSecretEndpoint('ftp://api.openai.com/v1').allowed).toBe(false);
+ });
+ });
+});
+
+describe('endpointGuard — assertSecretEndpoint', () => {
+ it('does nothing when no secret is attached (keyless local LLM)', () => {
+ expect(() => assertSecretEndpoint('https://evil.example.com/v1', { hasSecret: false })).not.toThrow();
+ });
+ it('throws when a secret would go to a blocked host', () => {
+ expect(() => assertSecretEndpoint('https://evil.example.com/v1', { hasSecret: true })).toThrow(/Blocked outbound API-key request/);
+ });
+ it('does not throw for an allowlisted host with a secret', () => {
+ expect(() => assertSecretEndpoint('https://api.openai.com/v1', { hasSecret: true })).not.toThrow();
+ });
+ it('does not throw for loopback with a secret', () => {
+ expect(() => assertSecretEndpoint('http://127.0.0.1:1234/v1', { hasSecret: true })).not.toThrow();
+ });
+ it('throws for a metadata host even with opt-in', () => {
+ expect(() => assertSecretEndpoint('http://169.254.169.254/', { hasSecret: true, allowCustomEndpoint: true })).toThrow();
+ });
+});
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 1de55d48f9..5dea6b839a 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -2,6 +2,7 @@ import { readFile, rename } from 'fs/promises';
import { existsSync } from 'fs';
import { join, dirname, delimiter, isAbsolute } from 'path';
import { atomicWrite } from './internal/atomicWrite.js';
+import { assertSecretEndpoint, evaluateSecretEndpoint } from './internal/endpointGuard.js';
import { fileURLToPath } from 'url';
import { execFile } from 'child_process';
import { promisify } from 'util';
@@ -452,6 +453,10 @@ export function createProviderService(config = {}) {
// Claude Ollama marker — preserve so adopting the sample via POST drives
// ollama-backed model refresh (see isOllamaBackedProvider).
...(providerData.ollamaBacked === true ? { ollamaBacked: true } : {}),
+ // Explicit opt-in to send the API key to an arbitrary (non-local,
+ // non-allowlisted) endpoint — see internal/endpointGuard.js. Only
+ // persisted when true so existing keyless/local providers stay clean.
+ ...(providerData.allowCustomEndpoint === true ? { allowCustomEndpoint: true } : {}),
envVars: providerData.envVars || {},
secretEnvVars: providerData.secretEnvVars || [],
headlessArgs: providerData.headlessArgs || [],
@@ -596,6 +601,16 @@ export function createProviderService(config = {}) {
}
if (provider.type === 'api') {
+ // Never send the API key to an arbitrary/metadata host (SSRF / key
+ // exfiltration). Keyless local-LLM checks are unaffected.
+ if (provider.apiKey) {
+ const guard = evaluateSecretEndpoint(provider.endpoint, {
+ allowCustomEndpoint: provider.allowCustomEndpoint === true,
+ });
+ if (!guard.allowed) {
+ return { success: false, error: `Endpoint blocked: ${guard.reason}` };
+ }
+ }
const modelsUrl = `${provider.endpoint}/models`;
const response = await fetch(modelsUrl, {
headers: provider.apiKey ? { 'Authorization': `Bearer ${provider.apiKey}` } : {},
@@ -670,6 +685,13 @@ export function createProviderService(config = {}) {
}
}
+ // Guard before attaching the API key to a generic /models fetch so a
+ // hostile/mistyped endpoint can't harvest a paid LLM key (SSRF).
+ assertSecretEndpoint(provider.endpoint, {
+ hasSecret: Boolean(provider.apiKey),
+ allowCustomEndpoint: provider.allowCustomEndpoint === true,
+ });
+
const modelsUrl = `${provider.endpoint}/models`;
const headers = {};
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index 2637d06096..b0ebd3e29f 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -575,6 +575,8 @@ describe('Provider Service', () => {
type: 'api',
endpoint: 'https://api.example.com/v1',
apiKey: 'sk-test',
+ // custom (non-allowlisted) host + secret ⇒ requires explicit opt-in
+ allowCustomEndpoint: true,
});
const result = await providerService.testProvider(p.id);
@@ -598,6 +600,24 @@ describe('Provider Service', () => {
expect(result.error).toMatch(/API not reachable/);
});
+ it('blocks a keyed custom endpoint that has not opted in (SSRF / key exfil guard)', async () => {
+ const spy = vi.fn();
+ vi.stubGlobal('fetch', spy);
+
+ const p = await providerService.createProvider({
+ name: 'Hostile API',
+ type: 'api',
+ endpoint: 'https://evil.example.com/v1',
+ apiKey: 'sk-secret',
+ });
+
+ const result = await providerService.testProvider(p.id);
+ expect(result.success).toBe(false);
+ expect(result.error).toMatch(/Endpoint blocked/);
+ // key must never leave the box — fetch is not even called
+ expect(spy).not.toHaveBeenCalled();
+ });
+
it('returns failure shape when server responds with non-ok status', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: false,
@@ -739,6 +759,8 @@ describe('Provider Service', () => {
type: 'api',
endpoint: 'https://api.generic.com/v1',
apiKey: 'sk-key',
+ // custom (non-allowlisted) host + secret ⇒ requires explicit opt-in
+ allowCustomEndpoint: true,
});
const updated = await providerService.refreshProviderModels(p.id);
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 91b2c95e60..7235c41fcc 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -1,5 +1,6 @@
import { mkdir, readFile, readdir, rm } from 'fs/promises';
import { atomicWrite } from './internal/atomicWrite.js';
+import { evaluateSecretEndpoint } from './internal/endpointGuard.js';
import { existsSync } from 'fs';
import { join, extname, basename, isAbsolute, delimiter } from 'path';
import { spawn, ChildProcess } from 'child_process';
@@ -542,9 +543,19 @@ export function createRunnerService(config = {}) {
messageContent = prompt;
}
+ // Never send the API key to an arbitrary/metadata host (SSRF / key
+ // exfiltration). Keyless local-LLM runs are unaffected.
+ const endpointGuard = provider.apiKey
+ ? evaluateSecretEndpoint(provider.endpoint, { allowCustomEndpoint: provider.allowCustomEndpoint === true })
+ : { allowed: true, reason: null };
+
const ensureProviderReady = hooks.ensureProviderReady || (async () => ({ success: true }));
- const ready = await ensureProviderReady(provider).catch((err) => ({ success: false, error: err.message }));
- const response = ready.success
+ const ready = endpointGuard.allowed
+ ? await ensureProviderReady(provider).catch((err) => ({ success: false, error: err.message }))
+ : { success: false, error: `Endpoint blocked: ${endpointGuard.reason}` };
+ const response = !endpointGuard.allowed
+ ? { ok: false, error: `Endpoint blocked: ${endpointGuard.reason}`, status: 0 }
+ : ready.success
? await fetch(`${provider.endpoint}/chat/completions`, {
method: 'POST',
headers,
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index 650929c626..adbabcdb9b 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -82,6 +82,11 @@ export const providerSchema = z.object({
// local Ollama daemon — the "Claude Ollama" pattern. Drives model refresh to
// pull tool-use-capable Ollama models instead of the static Anthropic list.
ollamaBacked: z.boolean().optional(),
+ // Explicit opt-in to attach the provider's API key to an arbitrary
+ // (non-local, non-allowlisted) endpoint. Guards against SSRF / key
+ // exfiltration to a hostile or mistyped host — see
+ // internal/endpointGuard.js. Metadata endpoints stay blocked even when true.
+ allowCustomEndpoint: z.boolean().optional(),
envVars: z.record(z.string()).optional(),
secretEnvVars: z.array(z.string()).optional(),
headlessArgs: z.array(z.string()).optional(),
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 588e8fd9eb..83d0a0c1c7 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -272,6 +272,10 @@ export const providerSchema = z.object({
defaultModel: z.string().nullable().optional(),
timeout: z.number().int().min(1000).max(600000).optional(),
enabled: z.boolean().optional(),
+ // Explicit opt-in to attach the API key to an arbitrary (non-local,
+ // non-allowlisted) endpoint — mirrors the aiToolkit providerSchema. Guards
+ // SSRF / key exfiltration (server/lib/aiToolkit/internal/endpointGuard.js).
+ allowCustomEndpoint: z.boolean().optional(),
envVars: z.record(z.string()).optional(),
headlessArgs: z.array(z.string()).optional(),
tuiPromptDelayMs: z.number().int().min(250).max(60000).optional(),