Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(providers): HTTP Basic auth for OpenAI-compatible servers
it1ab88eea3387
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 02b18003..45a7fa25 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,9 @@## Unreleased+### Providers+- **Remote Ollama behind a username and password.** Set `username` and `password` on Ollama Local, OpenAI-compatible, LM Studio, LiteLLM or Atomic Chat in `mercury.yaml`. Mercury sends them as HTTP Basic auth for chat and for model lists, instead of a Bearer key.+## 1.5.1 — speech uses the voice you chose, Gemini included### Speechdiff --git a/README.md b/README.mdindex da4d9527..36f8b4f8 100644--- a/README.md+++ b/README.md@@ -252,6 +252,18 @@ Mercury tries your default provider first and falls back to the others if it faiLiteLLM and GitHub Copilot endpoints are also available through `mercury doctor`.+A server behind a reverse proxy with a username and password (for example Ollama behind nginx) works with Ollama Local, OpenAI-compatible, LM Studio, LiteLLM and Atomic Chat. Set `username` and `password` on the provider in `mercury.yaml`; Mercury then sends `Authorization: Basic ...` instead of the API key. Use `https://` for any server that is not on your own machine. Behind Cloudflare, set SSL/TLS mode to Full (strict): in Flexible mode the hop from Cloudflare to your server is plain http.++```yaml+providers:+ ollamaLocal:+ baseUrl: https://ollama.example.com/v1+ model: gemma4:12b+ username: me+ password: my-password+ enabled: true+```+</details>## Referencediff --git a/src/index.ts b/src/index.tsindex 639aef08..513b42e5 100644--- a/src/index.ts+++ b/src/index.ts@@ -96,6 +96,7 @@ import { runWithWatchdog } from './cli/watchdog.js';import { setGitHubToken } from './utils/github.js';import { selectWithArrowKeys } from './utils/arrow-select.js';import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/provider-models.js';+import { withBaseUrl } from './providers/basic-auth.js';import { initCloudTokenStore } from './cloud/token-store.js';import { clearCloudRuntimeOnline, markCloudRuntimeOnline } from './cloud/runtime-status.js';import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler, setMcpManager as setWebMcpManager, setStopCallback as setWebStop, setSessionBusyLookup as setWebSessionBusy, setQueueControls as setWebQueueControls, setResearchControls as setWebResearchControls, setBudgetControls as setWebBudgetControls } from './web/server.js';@@ -468,10 +469,7 @@ async function promptOllamaLocalModelSelection(config: MercuryConfig, isReconfigconsole.log(chalk.dim(' Fetching Ollama Local models...'));try {- const catalog = await fetchProviderModelCatalog('ollamaLocal', {- ...existingConfig,- baseUrl,- });+ const catalog = await fetchProviderModelCatalog('ollamaLocal', withBaseUrl(existingConfig, baseUrl));const model = await chooseProviderModel('Ollama Local',catalog.recommendedModel,@@ -526,10 +524,7 @@ async function promptLmStudioModelSelection(config: MercuryConfig, isReconfig: bconsole.log(chalk.dim(' Fetching LM Studio models...'));try {- const catalog = await fetchProviderModelCatalog('lmStudio', {- ...existingConfig,- baseUrl,- });+ const catalog = await fetchProviderModelCatalog('lmStudio', withBaseUrl(existingConfig, baseUrl));const model = await chooseProviderModel('LM Studio',catalog.recommendedModel,@@ -585,10 +580,7 @@ async function promptAtomicChatModelSelection(config: MercuryConfig, isReconfig:console.log(chalk.dim(' Fetching Atomic Chat models...'));try {- const catalog = await fetchProviderModelCatalog('atomicChat', {- ...existingConfig,- baseUrl,- });+ const catalog = await fetchProviderModelCatalog('atomicChat', withBaseUrl(existingConfig, baseUrl));const model = await chooseProviderModel('Atomic Chat',catalog.recommendedModel,@@ -637,8 +629,7 @@ async function promptOpenAICompatSetup(config: MercuryConfig, isReconfig: booleaconsole.log(chalk.dim(' Fetching models from server...'));try {const catalog = await fetchProviderModelCatalog('openaiCompat', {- ...existingConfig,- baseUrl,+ ...withBaseUrl(existingConfig, baseUrl),apiKey: resolvedApiKey,});const model = await chooseProviderModel(diff --git a/src/providers/basic-auth.test.ts b/src/providers/basic-auth.test.tsnew file mode 100644index 00000000..d2a827b6--- /dev/null+++ b/src/providers/basic-auth.test.ts@@ -0,0 +1,89 @@+import { describe, it, expect, vi } from 'vitest';+import { basicAuthHeaders, sendsPasswordInClear, withBaseUrl } from './basic-auth.js';+import type { ProviderConfig } from '../utils/config.js';+import { logger } from '../utils/logger.js';++const base: ProviderConfig = { name: 'openaiCompat', apiKey: '', baseUrl: 'https://x.test/v1', model: 'm', enabled: true };++describe('basicAuthHeaders', () => {+ it('returns nothing without a username', () => {+ expect(basicAuthHeaders(base)).toBeUndefined();+ expect(basicAuthHeaders({ ...base, username: '', password: 'p' })).toBeUndefined();+ });++ it('encodes username:password as a Basic header', () => {+ expect(basicAuthHeaders({ ...base, username: 'alice', password: 's3cret' }))+ .toEqual({ Authorization: `Basic ${Buffer.from('alice:s3cret').toString('base64')}` });+ });++ it('keeps non-Latin-1 characters and colons in the password', () => {+ const header = basicAuthHeaders({ ...base, username: 'bob', password: 'pä:߀' })!.Authorization;+ expect(Buffer.from(header.slice('Basic '.length), 'base64').toString('utf8')).toBe('bob:pä:߀');+ });++ it('treats a missing password as empty', () => {+ const header = basicAuthHeaders({ ...base, username: 'carol' })!.Authorization;+ expect(Buffer.from(header.slice('Basic '.length), 'base64').toString('utf8')).toBe('carol:');+ });+});++describe('sendsPasswordInClear', () => {+ const at = (baseUrl: string, username = 'alice') => sendsPasswordInClear({ baseUrl, username });++ it('flags a username on plain http to another machine', () => {+ expect(at('http://ollama.example.com/v1')).toBe(true);+ expect(at('http://192.168.1.20:11434/v1')).toBe(true);+ });++ it('stays quiet for https, loopback, no username, or a bad URL', () => {+ expect(at('https://ollama.example.com/v1')).toBe(false);+ expect(at('http://127.0.0.1:11434/v1')).toBe(false);+ expect(at('http://localhost:11434/v1')).toBe(false);+ expect(at('http://[::1]:11434/v1')).toBe(false);+ expect(at('http://ollama.example.com/v1', '')).toBe(false);+ expect(at('not a url')).toBe(false);+ });+});++describe('withBaseUrl', () => {+ const saved: ProviderConfig = { ...base, baseUrl: 'https://mine.test/v1', username: 'alice', password: 's3cret' };++ it('keeps the saved credentials for the same server, trailing slash or not', () => {+ expect(withBaseUrl(saved, 'https://mine.test/v1/')).toMatchObject({ username: 'alice', password: 's3cret' });+ });++ it('drops the saved credentials for a different server', () => {+ const next = withBaseUrl(saved, 'https://other.test/v1');+ expect(next.baseUrl).toBe('https://other.test/v1');+ expect(next.username).toBeUndefined();+ expect(next.password).toBeUndefined();+ });+});++describe('basicAuthHeaders plain-http warning', () => {+ it('warns once per server when the password would travel over plain http', () => {+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {});+ try {+ const cfg = { ...base, baseUrl: 'http://warn-once.example.test/v1', username: 'alice', password: 'pw' };+ basicAuthHeaders(cfg);+ basicAuthHeaders(cfg);+ expect(warn).toHaveBeenCalledTimes(1);+ expect(JSON.stringify(warn.mock.calls[0])).not.toContain('pw"');+ basicAuthHeaders({ ...cfg, baseUrl: 'https://safe.example.test/v1' });+ basicAuthHeaders({ ...cfg, baseUrl: 'http://127.0.0.1:11434/v1' });+ expect(warn).toHaveBeenCalledTimes(1);+ } finally {+ warn.mockRestore();+ }+ });++ it('keeps URL credentials out of the warning', () => {+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {});+ try {+ basicAuthHeaders({ ...base, baseUrl: 'http://bob:[email protected]/v1', username: 'alice', password: 'pw' });+ expect(JSON.stringify(warn.mock.calls)).not.toContain('urlpass');+ } finally {+ warn.mockRestore();+ }+ });+});diff --git a/src/providers/basic-auth.ts b/src/providers/basic-auth.tsnew file mode 100644index 00000000..87ffbb42--- /dev/null+++ b/src/providers/basic-auth.ts@@ -0,0 +1,46 @@+import type { ProviderConfig } from '../utils/config.js';+import { logger } from '../utils/logger.js';++const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);+const warnedOrigins = new Set<string>();++type BasicAuthConfig = Pick<ProviderConfig, 'baseUrl' | 'username' | 'password'>;++/**+ * HTTP Basic credentials for a server behind a reverse proxy (nginx, Caddy,+ * Cloudflare Access). The header replaces the Bearer one, and is sent only+ * when a username is set. Every request that carries it goes through here, so+ * the plain-http warning is raised here, once per server.+ */+export function basicAuthHeaders(config: BasicAuthConfig): Record<string, string> | undefined {+ if (!config.username) return undefined;+ warnIfClear(config);+ const token = Buffer.from(`${config.username}:${config.password ?? ''}`, 'utf8').toString('base64');+ return { Authorization: `Basic ${token}` };+}++function warnIfClear(config: BasicAuthConfig): void {+ if (!sendsPasswordInClear(config)) return;+ const origin = new URL(config.baseUrl).origin; // no user:pass@ part+ if (warnedOrigins.has(origin)) return;+ warnedOrigins.add(origin);+ logger.warn({ origin }, 'Username and password go over plain http to another machine; use https:// in baseUrl');+}++/** The saved config pointed at a URL typed now. Saved Basic credentials belong to the saved server, so another URL gets none. */+export function withBaseUrl(saved: ProviderConfig, baseUrl: string): ProviderConfig {+ const trim = (u: string) => u.replace(/\/+$/, '');+ const sameServer = trim(baseUrl) === trim(saved.baseUrl ?? '');+ return { ...saved, ...(sameServer ? {} : { username: undefined, password: undefined }), baseUrl };+}++/** Basic auth is only base64: over plain http to another machine the password is readable on the wire. */+export function sendsPasswordInClear(config: Pick<ProviderConfig, 'baseUrl' | 'username'>): boolean {+ if (!config.username) return false;+ try {+ const url = new URL(config.baseUrl);+ return url.protocol === 'http:' && !LOOPBACK_HOSTS.has(url.hostname);+ } catch {+ return false;+ }+}diff --git a/src/providers/openai-compat.basic-auth.test.ts b/src/providers/openai-compat.basic-auth.test.tsnew file mode 100644index 00000000..e32f05ce--- /dev/null+++ b/src/providers/openai-compat.basic-auth.test.ts@@ -0,0 +1,92 @@+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import { createServer, type Server } from 'node:http';+import type { AddressInfo } from 'node:net';+import { OpenAICompatProvider } from './openai-compat.js';+import type { ProviderConfig } from '../utils/config.js';+import { logger } from '../utils/logger.js';+import { redactSecrets } from '../utils/redact.js';++// A real HTTP server that behaves like nginx basic auth in front of Ollama.+const USER = 'alice';+const PASS = 's3cret';+const seen: Array<string | undefined> = [];+let server: Server;+let baseUrl: string;++beforeAll(async () => {+ server = createServer((req, res) => {+ seen.push(req.headers.authorization);+ const want = `Basic ${Buffer.from(`${USER}:${PASS}`).toString('base64')}`;+ if (req.headers.authorization !== want) {+ res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="ollama"' }).end('unauthorized');+ return;+ }+ req.resume();+ req.on('end', () => {+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({+ id: 'c1', object: 'chat.completion', created: 0, model: 'm',+ choices: [{ index: 0, finish_reason: 'stop', message: { role: 'assistant', content: 'pong' } }],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ }));+ });+ });+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));+ baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`;+});++afterAll(() => new Promise<void>((r) => server.close(() => r())));++const config = (over: Partial<ProviderConfig>): ProviderConfig => ({+ name: 'openaiCompat', apiKey: '', baseUrl, model: 'm', enabled: true, ...over,+});++describe('OpenAICompatProvider with username and password', () => {+ it('answers when the server demands Basic auth and the password is right', async () => {+ seen.length = 0;+ const p = new OpenAICompatProvider(config({ username: USER, password: PASS }), { useChatApi: true });+ const out = await p.generateText('ping', 'sys');+ expect(out.text).toBe('pong');+ expect(seen[0]).toMatch(/^Basic /);+ });++ it('replaces the Bearer header when both an API key and a username are set', async () => {+ seen.length = 0;+ const p = new OpenAICompatProvider(config({ apiKey: 'sk-ignored', username: USER, password: PASS }), { useChatApi: true });+ await p.generateText('ping', 'sys');+ expect(seen[0]).toMatch(/^Basic /);+ });++ it('fails with an authentication error when the password is wrong', async () => {+ const p = new OpenAICompatProvider(config({ username: USER, password: 'wrong' }), { useChatApi: true });+ await expect(p.generateText('ping', 'sys')).rejects.toThrow(/Authentication failed/);+ });++ it('keeps sending Bearer when no username is set', async () => {+ seen.length = 0;+ const p = new OpenAICompatProvider(config({ apiKey: 'sk-abc' }), { useChatApi: true });+ await expect(p.generateText('ping', 'sys')).rejects.toThrow();+ expect(seen[0]).toBe('Bearer sk-abc');+ });++ it('warns once when the password would travel over plain http to another machine', () => {+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {});+ try {+ new OpenAICompatProvider(config({ baseUrl: 'http://ollama.example.com/v1', username: USER, password: PASS }));+ expect(warn).toHaveBeenCalledTimes(1);+ new OpenAICompatProvider(config({ username: USER, password: PASS }));+ expect(warn).toHaveBeenCalledTimes(1);+ } finally {+ warn.mockRestore();+ }+ });++ it('registers the password so logs and tool output never show it', () => {+ new OpenAICompatProvider(config({ username: USER, password: 'registered-pw-123' }));+ expect(redactSecrets('config says registered-pw-123 here')).toBe('config says **** here');+ });++ it('is available with only a username (no API key)', () => {+ expect(new OpenAICompatProvider(config({ username: USER, password: PASS })).isAvailable()).toBe(true);+ expect(new OpenAICompatProvider(config({})).isAvailable()).toBe(false);+ });+});diff --git a/src/providers/openai-compat.ts b/src/providers/openai-compat.tsindex 5f6fa56b..4d390a6d 100644--- a/src/providers/openai-compat.ts+++ b/src/providers/openai-compat.ts@@ -5,6 +5,8 @@ import type { ProviderConfig } from '../utils/config.js';import type { LLMResponse, LLMStreamChunk } from './base.js';import { logger } from '../utils/logger.js';import { aimlapiHeaders } from './aimlapi-attribution.js';+import { basicAuthHeaders } from './basic-auth.js';+import { registerSecretValue } from '../utils/redact.js';import { applyReasoningToBody, effectiveReasoning, providerHasReasoningControl } from '../utils/model-prefs.js';/**@@ -40,12 +42,18 @@ export class OpenAICompatProvider extends BaseProvider {this.name = config.name;this.model = config.model;+ const attribution = aimlapiHeaders(config.baseUrl);+ const basicAuth = basicAuthHeaders(config);+ // So a `cat mercury.yaml` or an error that echoes it never shows the password.+ if (config.password) registerSecretValue(config.password);+this.client = createOpenAI({apiKey: config.apiKey || 'no-key',baseURL: config.baseUrl,// `undefined` for every host but AI/ML API's, so no other provider- // reached through this class sends anything extra.- headers: aimlapiHeaders(config.baseUrl),+ // reached through this class sends anything extra. Basic auth, when+ // configured, overrides the SDK's Bearer header.+ headers: basicAuth ? { ...attribution, ...basicAuth } : attribution,// Only providers with a reasoning control get the hook; the rest keep// the SDK's default fetch untouched.fetch: providerHasReasoningControl(config.name) ? withReasoningPref(config.name) : undefined,@@ -116,7 +124,7 @@ export class OpenAICompatProvider extends BaseProvider {if (this.config.name === 'litellm' || this.config.name === 'ollamaLocal') {return this.config.baseUrl.length > 0;}- return this.config.apiKey.length > 0;+ return this.config.apiKey.length > 0 || !!this.config.username;}getModelInstance(): any {diff --git a/src/utils/config.ts b/src/utils/config.tsindex 1ddf5923..5b5cdd4a 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -43,6 +43,12 @@ export interface ProviderConfig {* local Qwen-VL called `qwen3.8-flash-next` was refused for that reason.*/vision?: boolean;+ /**+ * HTTP Basic credentials for a server behind a reverse proxy. When `username`+ * is set, Mercury sends `Authorization: Basic ...` instead of the Bearer key.+ */+ username?: string;+ password?: string;}export interface TelegramAccessUser {diff --git a/src/utils/provider-models.test.ts b/src/utils/provider-models.test.tsindex 30b03f17..b0357830 100644--- a/src/utils/provider-models.test.ts+++ b/src/utils/provider-models.test.ts@@ -222,6 +222,23 @@ describe('fetchProviderModelCatalog', () => {});});+describe('model lists behind Basic auth', () => {+ const expected = `Basic ${Buffer.from('alice:s3cret').toString('base64')}`;+ const cfg = (name: 'ollamaLocal' | 'openaiCompat' | 'lmStudio' | 'litellm' | 'atomicChat') => ({+ name, apiKey: '', baseUrl: 'https://ollama.example.test/v1', model: 'm', enabled: true,+ username: 'alice', password: 's3cret',+ });++ it.each([['ollamaLocal'], ['openaiCompat'], ['lmStudio'], ['litellm'], ['atomicChat']] as const)('%s sends the Basic header when listing models', async (name) => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ models: [{ name: 'm' }], data: [{ id: 'm' }] }), { status: 200 }));+ vi.stubGlobal('fetch', fetchMock);++ await fetchProviderModelCatalog(name, cfg(name));++ expect(fetchMock.mock.calls[0][1].headers).toMatchObject({ Authorization: expected });+ });+});+describe('chat models only', () => {it('drops rerankers, embedders and speech models from model lists', async () => {const { isChatModelId, buildModelCatalog } = await import('./provider-models.js');diff --git a/src/utils/provider-models.ts b/src/utils/provider-models.tsindex 2e058b92..d2e6edb8 100644--- a/src/utils/provider-models.ts+++ b/src/utils/provider-models.ts@@ -3,6 +3,7 @@ import type { ProviderConfig, ProviderName } from './config.js';import { fetchChatGPTModels } from '../auth/chatgpt-models.js';import { fetchGitHubModels } from '../auth/github-models.js';import { MERCURY_CLOUD_API_URL } from '../cloud/endpoints.js';+import { basicAuthHeaders } from '../providers/basic-auth.js';export interface ProviderModelCatalog {models: string[];@@ -351,6 +352,7 @@ async function fetchOpenAICompatModels(provider: ProviderName, config: ProviderCif (config.apiKey) {headers['Authorization'] = `Bearer ${config.apiKey}`;}+ Object.assign(headers, basicAuthHeaders(config));let errorMessage: string;if (provider === 'grok') {@@ -475,7 +477,7 @@ async function fetchOllamaCloudModels(config: ProviderConfig): Promise<ProviderMasync function fetchLmStudioModels(config: ProviderConfig): Promise<ProviderModelCatalog> {const data = await fetchJson<OpenAIModelResponse>(`${trimTrailingSlash(config.baseUrl)}/models`,- {},+ { headers: basicAuthHeaders(config) },'Mercury could not fetch models from LM Studio. Make sure LM Studio is running and the Developer API is enabled.',);@@ -489,7 +491,7 @@ async function fetchLmStudioModels(config: ProviderConfig): Promise<ProviderModeasync function fetchOllamaLocalModels(config: ProviderConfig): Promise<ProviderModelCatalog> {const data = await fetchJson<OllamaTagsResponse>(`${trimTrailingSlash(config.baseUrl)}/tags`,- {},+ { headers: basicAuthHeaders(config) },'Mercury could not fetch models from this Ollama Local server. Please check the base URL and try again.',);diff --git a/src/utils/redact.test.ts b/src/utils/redact.test.tsindex 80463ea4..12628513 100644--- a/src/utils/redact.test.ts+++ b/src/utils/redact.test.ts@@ -33,6 +33,13 @@ describe('secret redaction', () => {expect(out).toContain(join('Bear****', '.sig'));});+ it('masks a short password in yaml and a Basic header in full', () => {+ expect(redactSecrets('username: alice\n password: s3cret\n')).toBe('username: alice\n password: ****\n');+ expect(redactSecrets('password = "hunter22hunter22"')).toBe('password = "****"');+ const token = Buffer.from('alice:s3cret').toString('base64');+ expect(redactSecrets(`Authorization: Basic ${token}`)).toBe('Authorization: Basic ****');+ });+it('leaves ordinary code and config untouched', () => {const code = 'const apiKeyField = "name";\nskylight.trim();\nconst tokenCount = 123456789012;';expect(redactSecrets(code)).toBe(code);diff --git a/src/utils/redact.ts b/src/utils/redact.tsindex 7e39d0f2..f8009230 100644--- a/src/utils/redact.ts+++ b/src/utils/redact.ts@@ -38,7 +38,14 @@ const SECRET_PATTERNS: RegExp[] = [// Bearer / authorization headers/\b(?:Bearer|token|authorization)\s+[:=]?\s*[A-Za-z0-9._~+/-]{24,}/gi,// Generic key=value secrets in config output- /\b(api[_-]?key|secret|password|access[_-]?token|refresh[_-]?token)\s*[:=]\s*["']?[A-Za-z0-9._~+/=-]{12,}/gi,+ /\b(api[_-]?key|secret|access[_-]?token|refresh[_-]?token)\s*[:=]\s*["']?[A-Za-z0-9._~+/=-]{12,}/gi,+];++// Masked whole: a password has no recognizable prefix worth keeping, and a short+// one would be mostly shown by maskMatch. Covers yaml/env values and Basic headers.+const FULL_MASK_PATTERNS: RegExp[] = [+ /(?<=\bpassword\s*[:=]\s*["']?)[^\s"']+/gi,+ /(?<=\bBasic\s+)[A-Za-z0-9+/]{8,}={0,2}/g,];/** Keep enough of the key to identify it, mask the rest. */@@ -62,6 +69,9 @@ export function redactSecrets(text: string): string {for (const pattern of SECRET_PATTERNS) {out = out.replace(pattern, maskMatch);}+ for (const pattern of FULL_MASK_PATTERNS) {+ out = out.replace(pattern, '****');+ }return out;}diff --git a/src/web/api/chat-models-basic-auth.test.ts b/src/web/api/chat-models-basic-auth.test.tsnew file mode 100644index 00000000..787209b3--- /dev/null+++ b/src/web/api/chat-models-basic-auth.test.ts@@ -0,0 +1,46 @@+import { rmSync } from 'node:fs';+import { afterAll, describe, expect, it, vi } from 'vitest';++const home = await vi.hoisted(async () => {+ const fs = await import('node:fs');+ const os = await import('node:os');+ const path = await import('node:path');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-basic-auth-route-'));+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), [+ 'identity:',+ ' owner: Test',+ 'providers:',+ ' default: ollamaLocal',+ ' ollamaLocal:',+ ' name: ollamaLocal',+ ' baseUrl: https://ollama.example.test/v1',+ ' model: qwen3.8:27b',+ ' username: alice',+ ' password: s3cret',+ ' enabled: true',+ '',+ ].join('\n'));+ process.env.MERCURY_HOME = dir;+ return dir;+});++import chat from './chat.js';++afterAll(() => rmSync(home, { recursive: true, force: true }));++describe('GET /api/chat/models behind Basic auth', () => {+ it('lists the remote Ollama models with the configured username and password', async () => {+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ new Response(JSON.stringify({ models: [{ name: 'gemma4:12b' }] }), { status: 200 }),+ );+ try {+ const res = await chat.request('http://127.0.0.1/api/chat/models');+ expect(res.status).toBe(200);+ const tags = fetchSpy.mock.calls.find(([url]) => String(url) === 'https://ollama.example.test/api/tags');+ expect(tags).toBeDefined();+ expect((tags![1] as RequestInit).headers).toEqual({ Authorization: `Basic ${Buffer.from('alice:s3cret').toString('base64')}` });+ } finally {+ fetchSpy.mockRestore();+ }+ });+});diff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex 01f00fb4..a7b466b8 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -14,7 +14,8 @@ import type { WebChannel } from '../../channels/web.js';import type { ProgrammingMode, ProgrammingModeState } from '../../core/programming-mode.js';import { existsSync, readFileSync, writeFileSync, readdirSync, statSync, rmSync } from 'node:fs';import { join, extname, basename, relative, resolve } from 'node:path';-import { getMercuryHome, loadConfig, getActiveProviders } from '../../utils/config.js';+import { getMercuryHome, loadConfig, getActiveProviders, type ProviderConfig } from '../../utils/config.js';+import { basicAuthHeaders } from '../../providers/basic-auth.js';import type { SessionRepository } from '../../sessions/index.js';import { loadPermissionMode, savePermissionMode } from '../../capabilities/permission-mode-store.js';import {@@ -423,12 +424,12 @@ function recentlyFailed(key: string): boolean {}/** Every model the local Ollama server has pulled (empty if unreachable). */-async function listOllamaModels(baseUrl: string): Promise<string[]> {- const root = baseUrl.replace(/\/+$/, '').replace(/\/(v1|api)$/, '');+async function listOllamaModels(server: Pick<ProviderConfig, 'baseUrl' | 'username' | 'password'>): Promise<string[]> {+ const root = server.baseUrl.replace(/\/+$/, '').replace(/\/(v1|api)$/, '');const lookup = `ollama:${root}`;if (recentlyFailed(lookup)) return [];try {- const res = await fetch(`${root}/api/tags`, { signal: AbortSignal.timeout(3000) });+ const res = await fetch(`${root}/api/tags`, { headers: basicAuthHeaders(server), signal: AbortSignal.timeout(3000) });if (!res.ok) throw new Error(`HTTP ${res.status}`);const data = (await res.json()) as { models?: { name?: string }[] };failedLookups.delete(lookup);@@ -464,8 +465,8 @@ async function listChatGPTModels(): Promise<string[]> {}/** Providers that serve many models list each one; others list their configured model. */-async function listProviderModels(p: { name: string; baseUrl: string }): Promise<string[]> {- if (p.name === 'ollamaLocal') return listOllamaModels(p.baseUrl);+async function listProviderModels(p: ProviderConfig): Promise<string[]> {+ if (p.name === 'ollamaLocal') return listOllamaModels(p);if (p.name === 'chatgptWeb') return [...(await listChatGPTModels())];return [];}diff --git a/src/web/api/providers-basic-auth-route.test.ts b/src/web/api/providers-basic-auth-route.test.tsnew file mode 100644index 00000000..b0914b32--- /dev/null+++ b/src/web/api/providers-basic-auth-route.test.ts@@ -0,0 +1,75 @@+import { readFileSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';++const home = await vi.hoisted(async () => {+ const fs = await import('node:fs');+ const os = await import('node:os');+ const path = await import('node:path');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-providers-basic-'));+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), [+ 'identity:',+ ' owner: Test',+ 'providers:',+ ' default: ollamaLocal',+ ' ollamaLocal:',+ ' name: ollamaLocal',+ ' baseUrl: https://ollama.example.test/v1',+ ' model: m',+ ' username: alice',+ ' password: s3cret',+ ' enabled: true',+ '',+ ].join('\n'));+ process.env.MERCURY_HOME = dir;+ return dir;+});++const catalog = vi.hoisted(() => ({ fn: vi.fn() }));+vi.mock('../../utils/provider-models.js', () => ({ fetchProviderModelCatalog: catalog.fn }));++import providers from './providers.js';++const REMOTE = { incoming: { socket: { remoteAddress: '10.0.0.7' } } };++function post(path: string, body: unknown, env?: unknown) {+ return providers.request(`http://127.0.0.1${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ }, env as never);+}++afterEach(() => catalog.fn.mockReset());+afterAll(() => rmSync(home, { recursive: true, force: true }));++describe('saved username and password stay with their server', () => {+ it('never returns the password to the dashboard', async () => {+ for (const path of ['/api/providers', '/api/providers/settings']) {+ const res = await providers.request(`http://127.0.0.1${path}`);+ expect(res.status).toBe(200);+ expect(await res.text()).not.toContain('s3cret');+ }+ });++ it('sends them when a check targets the saved server', async () => {+ catalog.fn.mockResolvedValue({ recommendedModel: 'm', models: ['m'] });+ await post('/api/providers/ollamaLocal/check', {});+ expect(catalog.fn.mock.calls[0][1]).toMatchObject({ username: 'alice', password: 's3cret' });+ });++ it('drops them when a check targets a different server', async () => {+ catalog.fn.mockResolvedValue({ recommendedModel: 'm', models: ['m'] });+ await post('/api/providers/ollamaLocal/check', { baseUrl: 'https://evil.example.test/v1' });+ const sent = catalog.fn.mock.calls[0][1];+ expect(sent.baseUrl).toBe('https://evil.example.test/v1');+ expect(sent.username).toBeUndefined();+ expect(sent.password).toBeUndefined();+ });++ it('asks the owner before a remote device points them at another server, even with a new key', async () => {+ const res = await post('/api/providers/ollamaLocal', { baseUrl: 'https://evil.example.test/v1', apiKey: 'sk-newkey0000000000000000' }, REMOTE);+ expect(res.status).toBe(428);+ expect(readFileSync(join(home, 'mercury.yaml'), 'utf-8')).toContain('https://ollama.example.test/v1');+ });+});diff --git a/src/web/api/providers.ts b/src/web/api/providers.tsindex c8d9213e..f35a7923 100644--- a/src/web/api/providers.ts+++ b/src/web/api/providers.ts@@ -95,9 +95,12 @@ function newBaseUrl(saved: ProviderConfig, body: { baseUrl?: unknown }): boolean*/function draft(saved: ProviderConfig, body: { apiKey?: unknown; baseUrl?: unknown; model?: unknown }, opts: { forCheck?: boolean } = {}): ProviderConfig {const typedKey = typeof body.apiKey === 'string' && body.apiKey.trim() ? body.apiKey.trim() : null;+ const toNewServer = opts.forCheck && newBaseUrl(saved, body);return {...saved,- apiKey: typedKey ?? (opts.forCheck && newBaseUrl(saved, body) ? '' : saved.apiKey),+ apiKey: typedKey ?? (toNewServer ? '' : saved.apiKey),+ username: toNewServer ? undefined : saved.username,+ password: toNewServer ? undefined : saved.password,baseUrl: typeof body.baseUrl === 'string' && body.baseUrl.trim() ? body.baseUrl.trim().replace(/\/+$/, '') : saved.baseUrl,model: typeof body.model === 'string' ? body.model.trim() : saved.model,};@@ -244,8 +247,9 @@ providers.post('/api/providers/:name', async (c) => {return c.json({ error: `${meta.label} signs in with your account (run \`mercury doctor\`); it has no key to set.` }, 400);}- // Pointing a saved key at another server, from another device, is the owner's call.- if (newBaseUrl(p, body) && !(typeof body.apiKey === 'string' && body.apiKey.trim())) {+ // Pointing a saved key or password at another server, from another device, is the owner's call.+ // A typed key replaces the saved key, but a saved username and password stay and would follow.+ if (newBaseUrl(p, body) && (p.username || !(typeof body.apiKey === 'string' && body.apiKey.trim()))) {const wait = requireOwner(c, { id: `providers.baseUrl:${name}`, title: `Send the ${meta.label} key to a different server`, detail: String(body.baseUrl) });if (wait) return wait;}