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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
security: harden provider-key endpoints and privacy URL fields against SSRF/XSS
[._.]/ Adam Eivy0fc19be49ed2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..e22e71ce9a--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,25 @@+# Unreleased++## Security++- Guard paid-provider API keys against SSRF / key-exfiltration: `streamCompletion` (askService), voice-LLM endpoint resolution, and the local-LLM playground now validate a provider's endpoint through the shared endpoint guard before attaching the `Authorization: Bearer` header, so a mistyped or malicious custom endpoint (including cloud-metadata hosts) never receives the key unless the provider opts in via `allowCustomEndpoint`.+- Reject non-`http(s)` schemes on Privacy Center URL fields (org website/portal, broker search/opt-out/screenshot/listing URLs), closing a stored-XSS vector where a `javascript:`/`data:` value would execute when rendered as a link. Added a shared server `isSafeHref` helper mirroring the client's `isHttpUrl`, applied at the Zod write layer and at every render site.++## Fixed++- `executeTuiRun`'s `finish()` now always settles its run promise even if a finalization step throws, so a one-shot TUI run can no longer hang forever (leaking the PTY and wedging `/runs`).+- `execGh` now times out (60s default, overridable) and kills a stalled `gh` CLI child, so a hung network/credential prompt can't wedge the scheduled PR-watcher / issue- and branch-reconcile / update-check jobs or orphan `gh` processes.+- `NextActionBanner`'s question fetch is guarded against stale responses, so a slow earlier request can no longer overwrite a newer question.+- The Login and ErrorBoundary full-screen layouts use dvh-capped min-height, so their content isn't pushed below the fold by mobile browser chrome.+- r3f `<Canvas>` backgrounds (goals tree, memory graph, brain graph) track the `port-bg` theme token instead of a hardcoded black, fixing a black rectangle under light themes.+- Accessibility: `<label htmlFor>`/`id` pairing on the Avatar Emoji/Color (AgentList), Folder path (Sharing), and AI-refinement (StoryBuilder) inputs; hand-rolled clickable elements (ElementsSong element tile, NotificationDropdown row, TaskAddForm template picker) now use the shared `clickableProps` helper, restoring Space-key activation.+- The ProactiveAlertsWidget chevron affordance is now visible on touch devices.++## Changed++- Route client `localStorage` access through the `safeStorage` helpers (Layout, MorseTrainer, calendar persisted-state, MoodBoard reference strip, VoiceWidget, WorkEditor, Tribe) — several sites previously threw uncaught in Safari private mode instead of degrading gracefully.+- Replace inline `new Promise(r => setTimeout(r, …))` delays with the shared `sleep(ms)` helper across nine server modules.++## Removed++- Drop the unused `featureFlags`/`lockPolicies` reserved config slots from `collectionStore`'s typedef.diff --git a/client/src/components/privacy/BrokerCaseDrawer.jsx b/client/src/components/privacy/BrokerCaseDrawer.jsxindex fb60d093f0..fac297ef40 100644--- a/client/src/components/privacy/BrokerCaseDrawer.jsx+++ b/client/src/components/privacy/BrokerCaseDrawer.jsx@@ -2,6 +2,7 @@ import { RotateCw, ExternalLink, CheckCircle2, XCircle, ListChecks } from 'lucidimport Drawer from '../Drawer';import { timeAgo, formatDateShort } from '../../utils/formatters';import { CASE_STATE_TONE, ACTION_TONES, manualCaseActions, labelFor, CASE_STATES } from './constants';+import { isHttpUrl } from '../../utils/urlNormalize';// Action icon by descriptor `icon` token (positive resolution vs dismiss).const ACTION_ICONS = { check: CheckCircle2, x: XCircle };@@ -82,7 +83,7 @@ export default function BrokerCaseDrawer({not confirmed. Open the same search in your own browser (real browsers pass these walls),then record what you find below.</p>- {searchUrl && (+ {searchUrl && isHttpUrl(searchUrl) && (<ahref={searchUrl}target="_blank"@@ -111,16 +112,20 @@ export default function BrokerCaseDrawer({<ul className="space-y-1">{listingUrls.map((u) => (<li key={u}>- <a href={u} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline break-all">- <ExternalLink size={12} /> {u}- </a>+ {isHttpUrl(u) ? (+ <a href={u} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline break-all">+ <ExternalLink size={12} /> {u}+ </a>+ ) : (+ <span className="inline-flex items-center gap-1 text-xs text-gray-400 break-all">{u}</span>+ )}</li>))}</ul>) : (<span className="text-gray-500 text-xs">No listing URLs recorded</span>)}- {evidence.screenshot && (+ {evidence.screenshot && isHttpUrl(evidence.screenshot) && (<a href={evidence.screenshot} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline mt-1"><ExternalLink size={12} /> Confirmation screenshot</a>@@ -159,7 +164,7 @@ export default function BrokerCaseDrawer({</button>);})}- {optoutUrl && (+ {optoutUrl && isHttpUrl(optoutUrl) && (<ahref={optoutUrl}target="_blank"diff --git a/client/src/components/privacy/PrivacyBrokersTab.jsx b/client/src/components/privacy/PrivacyBrokersTab.jsxindex 3ff3a83c73..94101b1b92 100644--- a/client/src/components/privacy/PrivacyBrokersTab.jsx+++ b/client/src/components/privacy/PrivacyBrokersTab.jsx@@ -17,6 +17,7 @@ import {CASE_STATES, CASE_STATE_TONE, EXPOSURE_MAP_STATES, BROKER_SOURCES, BROKER_CONFIDENCE,ACTION_TONES, manualCaseActions, labelFor,} from './constants';+import { isHttpUrl } from '../../utils/urlNormalize';// Digest action icon by descriptor `icon` token (positive resolution vs dismiss).const ACTION_ICONS = { check: CheckCircle2, x: XCircle };@@ -273,12 +274,12 @@ export default function PrivacyBrokersTab() {{item.reason && <div className="text-[11px] text-gray-500 mt-0.5">{item.reason}{item.channel ? ` · ${item.channel}` : ''}</div>}</div><div className="flex items-center gap-1 shrink-0">- {item.state === 'blocked' && item.searchUrl && (+ {item.state === 'blocked' && item.searchUrl && isHttpUrl(item.searchUrl) && (<a href={item.searchUrl} target="_blank" rel="noreferrer" title="Check manually in your browser" aria-label="Check manually in your browser" className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"><Search size={15} /></a>)}- {item.optoutUrl && (+ {item.optoutUrl && isHttpUrl(item.optoutUrl) && (<a href={item.optoutUrl} target="_blank" rel="noreferrer" title="Open opt-out page" aria-label="Open opt-out page" className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"><ExternalLink size={15} /></a>diff --git a/client/src/components/privacy/PrivacyChangesTab.jsx b/client/src/components/privacy/PrivacyChangesTab.jsxindex e842352c7b..9f52884fa9 100644--- a/client/src/components/privacy/PrivacyChangesTab.jsx+++ b/client/src/components/privacy/PrivacyChangesTab.jsx@@ -9,6 +9,7 @@ import {import toast from '../ui/Toast';import DeclareChangeDrawer from './DeclareChangeDrawer';import { VAULT_TYPES, CHANGE_KINDS, labelFor } from './constants';+import { isHttpUrl } from '../../utils/urlNormalize';// A slim progress bar over pending/updated/removed. Done = zero pending.function ProgressBar({ progress }) {@@ -49,7 +50,7 @@ function OrgRow({ org, status, eventId, hasReplacement, onChanged }) {{org.contactEmail && <span className="ml-2 text-[11px] text-gray-500">{org.contactEmail}</span>}</div><div className="flex items-center gap-1 shrink-0">- {org.website && (+ {org.website && isHttpUrl(org.website) && (<a href={org.website} target="_blank" rel="noreferrer" title="Open website" aria-label="Open website"className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"><ExternalLink size={14} />diff --git a/client/src/components/privacy/PrivacyOrgsTab.jsx b/client/src/components/privacy/PrivacyOrgsTab.jsxindex f450144716..2bbf8882d1 100644--- a/client/src/components/privacy/PrivacyOrgsTab.jsx+++ b/client/src/components/privacy/PrivacyOrgsTab.jsx@@ -10,6 +10,7 @@ import {ORG_CATEGORIES, ORG_TRUST_LEVELS, ORG_STATUSES, ORG_HOLDING_STATUSES,TRUST_TONE, HOLDING_TONE, labelFor,} from './constants';+import { isHttpUrl } from '../../utils/urlNormalize';// Filter chip row — a single-select toggle group over a list of {id,label}.function ChipFilter({ label, options, value, onChange }) {@@ -155,7 +156,7 @@ export default function PrivacyOrgsTab() {</div></div><div className="flex items-center gap-1 shrink-0">- {org.website && (+ {org.website && isHttpUrl(org.website) && (<ahref={org.website}target="_blank"diff --git a/server/lib/README.md b/server/lib/README.mdindex 3970ca2d98..010bfe3066 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -184,6 +184,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `syncWire.js` | Single source of truth for what fields cross the federated-peer wire (snapshot loop + per-record push agree). || `tailscale.js` | Locate the Tailscale CLI binary, flag the sandboxed macOS App-bundle build (which can't write `tailscale cert` output outside its container), and read backend state (`getTailscaleStatus` / `isTailscaleUp`) to know whether we're actually connected to the tailnet. || `httpsState.js` | Captures whether PortOS booted with HTTPS active. |+| `isSafeHref.js` | Pure http(s)-only scheme check (`isSafeHref`) for user-supplied URL fields that get rendered as a clickable `<a href>` — rejects `javascript:`/`data:`/etc. stored-XSS payloads. Mirrors client `urlNormalize.js`'s `isHttpUrl`. || `networkExposure.js` | Snapshot of scheme + bind + cert mode for the dashboard's Network Exposure widget. |## Search & indexingdiff --git a/server/lib/index.js b/server/lib/index.jsindex 8a8886f5fb..8baa0b5870 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -161,6 +161,7 @@ export * from './fetchWithTimeout.js';export * from './requestAbort.js';export * from './httpClient.js';export * from './httpsState.js';+export * from './isSafeHref.js';export * from './networkExposure.js';export * from './peerHttpClient.js';export * from './peerSelfHost.js';diff --git a/server/lib/isSafeHref.js b/server/lib/isSafeHref.jsnew file mode 100644index 0000000000..1e2642bb0d--- /dev/null+++ b/server/lib/isSafeHref.js@@ -0,0 +1,24 @@+/**+ * Pure http(s)-only scheme check for user-supplied URL fields that later get+ * rendered as a clickable `<a href>` (privacy-org website/portal links,+ * broker opt-out/search URLs, screenshot evidence, …).+ *+ * A stored `javascript:`/`data:`/`vbscript:` URL turns into a stored-XSS+ * payload the moment it's rendered as an href — validating the scheme at+ * write time (Zod `.refine`) and re-checking at render time (client) closes+ * both the write and the read side. Mirrors `isHttpUrl` in+ * `client/src/utils/urlNormalize.js` (kept as two small copies — server and+ * client don't share a build step — so keep both in sync if this changes).+ *+ * @param {string} url+ * @returns {boolean}+ */+export function isSafeHref(url) {+ if (typeof url !== 'string' || url.length === 0) return false;+ try {+ const parsed = new URL(url);+ return parsed.protocol === 'http:' || parsed.protocol === 'https:';+ } catch {+ return false;+ }+}diff --git a/server/lib/isSafeHref.test.js b/server/lib/isSafeHref.test.jsnew file mode 100644index 0000000000..d67041f229--- /dev/null+++ b/server/lib/isSafeHref.test.js@@ -0,0 +1,42 @@+import { describe, it, expect } from 'vitest';+import { isSafeHref } from './isSafeHref.js';++describe('isSafeHref', () => {+ it('allows http:// URLs', () => {+ expect(isSafeHref('http://x.com')).toBe(true);+ });++ it('allows https:// URLs', () => {+ expect(isSafeHref('https://x.com')).toBe(true);+ });++ it('rejects javascript: URLs', () => {+ expect(isSafeHref('javascript:alert(1)')).toBe(false);+ });++ it('rejects data: URLs', () => {+ expect(isSafeHref('data:text/html,x')).toBe(false);+ });++ it('rejects vbscript: URLs', () => {+ expect(isSafeHref('vbscript:x')).toBe(false);+ });++ it('rejects an empty string', () => {+ expect(isSafeHref('')).toBe(false);+ });++ it('rejects undefined', () => {+ expect(isSafeHref(undefined)).toBe(false);+ });++ it('rejects non-string input', () => {+ expect(isSafeHref(42)).toBe(false);+ expect(isSafeHref(null)).toBe(false);+ expect(isSafeHref({})).toBe(false);+ });++ it('rejects a garbage non-URL string', () => {+ expect(isSafeHref('not a url at all')).toBe(false);+ });+});diff --git a/server/lib/privacyValidation.js b/server/lib/privacyValidation.jsindex d7aeba42b5..91f6791e2b 100644--- a/server/lib/privacyValidation.js+++ b/server/lib/privacyValidation.js@@ -1,4 +1,12 @@import { z } from 'zod';+import { isSafeHref } from './isSafeHref.js';++// Reject non-http(s) schemes (`javascript:`/`data:`/etc.) on a URL field while+// preserving the field's existing empty/absent handling — an empty string or+// undefined value was allowed before and must stay allowed here; only a+// non-empty, non-http(s) value is a new rejection.+const safeUrlRefine = (val) => !val || isSafeHref(val);+const SAFE_URL_MESSAGE = 'must be an http(s) URL';// =============================================================================// PRIVACY CENTER SCHEMAS (issue #2140, epic #2138)@@ -112,14 +120,14 @@ export const PRIVACY_ORG_HOLDING_STATUSES = Object.freeze([const privacyOrgContactSchema = z.object({email: z.string().max(320).optional(),phone: z.string().max(64).optional(),- portalUrl: z.string().max(2000).optional(),+ portalUrl: z.string().max(2000).optional().refine(safeUrlRefine, SAFE_URL_MESSAGE),mailingAddress: z.string().max(2000).optional(),}).strict();export const privacyOrgCreateSchema = z.object({name: z.string().trim().min(1).max(200),category: z.enum(PRIVACY_ORG_CATEGORIES).optional(),- website: z.string().max(2000).optional(),+ website: z.string().max(2000).optional().refine(safeUrlRefine, SAFE_URL_MESSAGE),trust: z.enum(PRIVACY_ORG_TRUST_LEVELS).optional(),status: z.enum(PRIVACY_ORG_STATUSES).optional(),contact: privacyOrgContactSchema.optional(),@@ -131,7 +139,7 @@ export const privacyOrgCreateSchema = z.object({export const privacyOrgUpdateSchema = z.object({name: z.string().trim().min(1).max(200).optional(),category: z.enum(PRIVACY_ORG_CATEGORIES).optional(),- website: z.string().max(2000).optional(),+ website: z.string().max(2000).optional().refine(safeUrlRefine, SAFE_URL_MESSAGE),trust: z.enum(PRIVACY_ORG_TRUST_LEVELS).optional(),status: z.enum(PRIVACY_ORG_STATUSES).optional(),contact: privacyOrgContactSchema.optional(),diff --git a/server/lib/privacyValidation.test.js b/server/lib/privacyValidation.test.jsnew file mode 100644index 0000000000..251cf97225--- /dev/null+++ b/server/lib/privacyValidation.test.js@@ -0,0 +1,80 @@+import { describe, it, expect } from 'vitest';+import { privacyOrgCreateSchema, privacyOrgUpdateSchema } from './privacyValidation.js';++describe('privacyValidation — org website/portalUrl safe-scheme guard', () => {+ describe('privacyOrgCreateSchema', () => {+ it('rejects a javascript: website URL', () => {+ const result = privacyOrgCreateSchema.safeParse({ name: 'X', website: 'javascript:alert(1)' });+ expect(result.success).toBe(false);+ expect(result.error.issues.some((i) => i.path.join('.') === 'website' && i.message === 'must be an http(s) URL')).toBe(true);+ });++ it('accepts a valid https website URL', () => {+ const result = privacyOrgCreateSchema.safeParse({ name: 'X', website: 'https://ok.com' });+ expect(result.success).toBe(true);+ expect(result.data.website).toBe('https://ok.com');+ });++ it('accepts an absent website field (optional, unchanged)', () => {+ const result = privacyOrgCreateSchema.safeParse({ name: 'X' });+ expect(result.success).toBe(true);+ expect(result.data.website).toBeUndefined();+ });++ it('accepts an empty-string website (existing empty-handling preserved)', () => {+ const result = privacyOrgCreateSchema.safeParse({ name: 'X', website: '' });+ expect(result.success).toBe(true);+ expect(result.data.website).toBe('');+ });++ it('rejects a javascript: contact.portalUrl', () => {+ const result = privacyOrgCreateSchema.safeParse({+ name: 'X',+ contact: { portalUrl: 'javascript:alert(1)' },+ });+ expect(result.success).toBe(false);+ expect(result.error.issues.some((i) => i.path.join('.') === 'contact.portalUrl' && i.message === 'must be an http(s) URL')).toBe(true);+ });++ it('accepts a valid https contact.portalUrl', () => {+ const result = privacyOrgCreateSchema.safeParse({+ name: 'X',+ contact: { portalUrl: 'https://portal.ok.com' },+ });+ expect(result.success).toBe(true);+ expect(result.data.contact.portalUrl).toBe('https://portal.ok.com');+ });++ it('accepts an absent contact.portalUrl field (optional, unchanged)', () => {+ const result = privacyOrgCreateSchema.safeParse({ name: 'X', contact: { email: '[email protected]' } });+ expect(result.success).toBe(true);+ expect(result.data.contact.portalUrl).toBeUndefined();+ });++ it('accepts an empty-string contact.portalUrl (existing empty-handling preserved)', () => {+ const result = privacyOrgCreateSchema.safeParse({ name: 'X', contact: { portalUrl: '' } });+ expect(result.success).toBe(true);+ expect(result.data.contact.portalUrl).toBe('');+ });+ });++ describe('privacyOrgUpdateSchema', () => {+ it('rejects a javascript: website URL on partial update', () => {+ const result = privacyOrgUpdateSchema.safeParse({ website: 'data:text/html,x' });+ expect(result.success).toBe(false);+ expect(result.error.issues.some((i) => i.path.join('.') === 'website')).toBe(true);+ });++ it('accepts a valid https website URL on partial update', () => {+ const result = privacyOrgUpdateSchema.safeParse({ website: 'https://ok.com' });+ expect(result.success).toBe(true);+ expect(result.data.website).toBe('https://ok.com');+ });++ it('rejects a javascript: contact.portalUrl on partial update', () => {+ const result = privacyOrgUpdateSchema.safeParse({ contact: { portalUrl: 'vbscript:x' } });+ expect(result.success).toBe(false);+ expect(result.error.issues.some((i) => i.path.join('.') === 'contact.portalUrl')).toBe(true);+ });+ });+});diff --git a/server/services/askService.js b/server/services/askService.jsindex f43d392c1a..b05eba4251 100644--- a/server/services/askService.js+++ b/server/services/askService.js@@ -37,6 +37,7 @@ import { isGrokCommand, ensureGrokHeadlessArgs } from '../lib/grok.js';import { prepareCliPrompt } from '../lib/cliProviderArgs.js';import { prepareCliSpawn } from '../lib/bufferedSpawn.js';import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';+import { evaluateSecretEndpoint } from '../lib/aiToolkit/internal/endpointGuard.js';// Re-export so the route can keep importing modes via askService — but// askConversations is the source of truth (it owns the persistence schema).@@ -444,6 +445,16 @@ async function pickProvider(providerId) {*/async function* streamCompletion(provider, model, prompt, signal) {if (provider.type === 'api') {+ // Never send the API key to an arbitrary/metadata host (SSRF / key+ // exfiltration). Keyless local-LLM calls skip this guard entirely.+ if (provider.apiKey) {+ const guard = evaluateSecretEndpoint(provider.endpoint, {+ allowCustomEndpoint: provider.allowCustomEndpoint === true,+ });+ if (!guard.allowed) {+ throw new Error(`Provider endpoint blocked: ${guard.reason}`);+ }+ }const headers = { 'Content-Type': 'application/json' };if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;// Combine the per-provider timeout with the caller's abort signal sodiff --git a/server/services/askService.test.js b/server/services/askService.test.jsindex 55b059130f..3bb78c21a9 100644--- a/server/services/askService.test.js+++ b/server/services/askService.test.js@@ -237,6 +237,7 @@ describe('runAsk', () => {endpoint: 'https://example.test/v1',defaultModel: 'fake-model',timeout: 5000,+ allowCustomEndpoint: true,};}@@ -459,4 +460,83 @@ describe('runAsk', () => {expect(args[0]).toBe('run');expect(args[args.indexOf('--model') + 1]).toBe('ollama/qwen2.5:7b');});++ describe('endpoint guard (SSRF / key-exfiltration)', () => {+ it('blocks a keyed api provider pointed at a cloud-metadata endpoint and never calls fetch', async () => {+ providers.getActiveProvider.mockResolvedValue({+ id: 'fake', type: 'api', enabled: true, apiKey: 'secret-key',+ endpoint: 'http://169.254.169.254/latest/meta-data/', defaultModel: 'fake-model', timeout: 5000,+ // allowCustomEndpoint intentionally absent — must not matter for a+ // metadata endpoint (it's never overridable).+ });+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(buildSSEResponse(['should not reach here']));++ const events = [];+ for await (const evt of askService.runAsk({ question: 'hi' })) events.push(evt);+ const callCount = fetchSpy.mock.calls.length;+ fetchSpy.mockRestore();++ const errorEvt = events.find((e) => e.type === 'error');+ expect(errorEvt).toBeDefined();+ expect(errorEvt.error).toContain('Provider endpoint blocked');+ expect(errorEvt.error).toContain('cloud-metadata endpoint blocked');+ expect(events.find((e) => e.type === 'done')).toBeUndefined();+ expect(callCount).toBe(0);+ });++ it('blocks a keyed api provider on a non-allowlisted host when allowCustomEndpoint is not set', async () => {+ providers.getActiveProvider.mockResolvedValue({+ id: 'fake', type: 'api', enabled: true, apiKey: 'secret-key',+ endpoint: 'https://not-an-allowlisted-host.example', defaultModel: 'fake-model', timeout: 5000,+ });+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(buildSSEResponse(['should not reach here']));++ const events = [];+ for await (const evt of askService.runAsk({ question: 'hi' })) events.push(evt);+ const callCount = fetchSpy.mock.calls.length;+ fetchSpy.mockRestore();++ const errorEvt = events.find((e) => e.type === 'error');+ expect(errorEvt).toBeDefined();+ expect(errorEvt.error).toContain('Provider endpoint blocked');+ expect(errorEvt.error).toContain('refusing to send API key to non-allowlisted host');+ expect(events.find((e) => e.type === 'done')).toBeUndefined();+ expect(callCount).toBe(0);+ });++ it('allows a keyed api provider on a non-allowlisted host through when allowCustomEndpoint is true', async () => {+ providers.getActiveProvider.mockResolvedValue({+ id: 'fake', type: 'api', enabled: true, apiKey: 'secret-key',+ endpoint: 'https://not-an-allowlisted-host.example', defaultModel: 'fake-model', timeout: 5000,+ allowCustomEndpoint: true,+ });+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(buildSSEResponse(['Hello.']));++ const events = [];+ for await (const evt of askService.runAsk({ question: 'hi' })) events.push(evt);+ const callCount = fetchSpy.mock.calls.length;+ fetchSpy.mockRestore();++ expect(events.find((e) => e.type === 'error')).toBeUndefined();+ expect(events.find((e) => e.type === 'done')).toBeDefined();+ expect(callCount).toBe(1);+ });++ it('allows a keyless api provider on a non-allowlisted host through (guard only applies when apiKey is set)', async () => {+ providers.getActiveProvider.mockResolvedValue({+ id: 'fake-local', type: 'api', enabled: true, apiKey: undefined,+ endpoint: 'https://not-an-allowlisted-host.example', defaultModel: 'fake-model', timeout: 5000,+ });+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(buildSSEResponse(['Hello.']));++ const events = [];+ for await (const evt of askService.runAsk({ question: 'hi' })) events.push(evt);+ const callCount = fetchSpy.mock.calls.length;+ fetchSpy.mockRestore();++ expect(events.find((e) => e.type === 'error')).toBeUndefined();+ expect(events.find((e) => e.type === 'done')).toBeDefined();+ expect(callCount).toBe(1);+ });+ });});diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.jsindex bef738497c..8db5765668 100644--- a/server/services/localLlmPlayground.js+++ b/server/services/localLlmPlayground.js@@ -6,6 +6,7 @@ import { markProviderAvailable } from './providerStatus.js';import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';import { readResponseJson } from '../lib/readResponseJson.js';import { anyAbortSignal } from '../lib/requestAbort.js';+import { assertSecretEndpoint } from '../lib/aiToolkit/internal/endpointGuard.js';const PROVIDER_BY_BACKEND = { ollama: 'ollama', lmstudio: 'lmstudio' };@@ -101,6 +102,14 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system}}+ // Guard before attaching the API key so a hostile/mistyped endpoint on the+ // (normally keyless) ollama/lmstudio provider records can't harvest a key+ // or reach a cloud-metadata service (SSRF). No-ops when apiKey is unset.+ assertSecretEndpoint(provider.endpoint, {+ hasSecret: Boolean(provider.apiKey),+ allowCustomEndpoint: provider.allowCustomEndpoint === true,+ });+const headers = { 'Content-Type': 'application/json' };if (provider.apiKey) headers.Authorization = `Bearer ${provider.apiKey}`;diff --git a/server/services/voice/llm.js b/server/services/voice/llm.jsindex 82672f0098..55ad82cc5f 100644--- a/server/services/voice/llm.js+++ b/server/services/voice/llm.js@@ -7,6 +7,7 @@// provider is missing, not API-type, or the toolkit hasn't warmed yet.import { getProviderById } from '../providers.js';+import { assertSecretEndpoint } from '../../lib/aiToolkit/internal/endpointGuard.js';// Legacy env-based LM Studio default. Returns the OpenAI-compatible API base// INCLUDING the version path, so callers append `/models` / `/chat/completions`.@@ -25,8 +26,20 @@ export const resolveLlmEndpoint = async (providerId = 'lmstudio') => {// lmstudio provider, so installs that pointed it at another host keep// working without re-saving the provider endpoint.const useEnv = provider.id === 'lmstudio' && process.env.LM_STUDIO_URL;+ const apiBase = (useEnv ? LM_STUDIO_API_BASE() : provider.endpoint).replace(/\/+$/, '');+ // Guard non-built-in providers before attaching their API key to the+ // /models and /chat/completions fetches below — a hostile/mistyped+ // endpoint could otherwise harvest a paid LLM key or reach a+ // cloud-metadata service (SSRF). The built-in local `lmstudio` provider is+ // exempt: it's the trusted local-LLM fallback and normally carries no key.+ if (provider.id !== 'lmstudio') {+ assertSecretEndpoint(apiBase, {+ hasSecret: Boolean(provider.apiKey),+ allowCustomEndpoint: provider.allowCustomEndpoint === true,+ });+ }return {- apiBase: (useEnv ? LM_STUDIO_API_BASE() : provider.endpoint).replace(/\/+$/, ''),+ apiBase,apiKey: provider.apiKey || '',defaultModel: provider.defaultModel || null,providerName: provider.name || providerId,diff --git a/server/services/voice/llm.test.js b/server/services/voice/llm.test.jsindex e8e7bdd423..764b573768 100644--- a/server/services/voice/llm.test.js+++ b/server/services/voice/llm.test.js@@ -202,6 +202,7 @@ describe('resolveLlmEndpoint', () => {getProviderById.mockResolvedValue({id: 'nvidia-kimi', type: 'api', endpoint: 'https://integrate.api.nvidia.com/v1',apiKey: 'secret', defaultModel: 'moonshotai/kimi-k2-5', name: 'NVIDIA Kimi',+ allowCustomEndpoint: true,});const ep = await resolveLlmEndpoint('nvidia-kimi');expect(ep.apiBase).toBe('https://integrate.api.nvidia.com/v1');