Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): secure native provider auth and worker bridge

Chris9bc83e84980c
diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
index 0e1387301d..663124c87a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
@@ -250,7 +250,7 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
expect((await getCustomProvider('openrouter'))?.name).toBe('Edited in another window');
});
- it('round-trips headers + dedupes models on normalize', async () => {
+ it('never persists headers and still dedupes models on normalize', async () => {
mountDb();
await createCustomProvider({
...valid,
@@ -271,7 +271,7 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
{ id: 'a', name: 'A', contextWindow: 1_000_000 },
{ id: 'hidden', name: 'Hidden', defaultEnabled: false },
]);
- expect(got?.runtimes.codex?.headers).toEqual({ 'X-Org': 'acme' });
+ expect(got?.runtimes.codex?.headers).toBeUndefined();
});
it('round-trips an explicit Chat Completions protocol', async () => {
diff --git a/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.ts b/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.ts
index 1bdade8e44..60892be9c3 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.ts
@@ -18,8 +18,8 @@ vi.mock('../auth-adapters.js', () => ({
readClaudeApiKey: () => 'REAL-GATEWAY-KEY',
desktopCodexAuthAdapter: { getState: async () => ({ authenticated: false }) },
}));
-vi.mock('../custom-provider-store.js', () => ({
- listCustomProviders: async () => [
+vi.mock('../custom-provider-header-secrets.js', () => ({
+ listCustomProvidersWithSecureHeaders: async () => [
{
id: 'ollama-local',
name: 'Local Ollama',
diff --git a/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts b/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts
index 46b4faff93..6a8b801cb3 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts
@@ -11,8 +11,8 @@ vi.mock('../auth-adapters.js', () => ({
readClaudeApiKey: () => null,
desktopCodexAuthAdapter: { getState: async () => ({ authenticated: false }) },
}));
-vi.mock('../custom-provider-store.js', () => ({
- listCustomProviders: async () => [
+vi.mock('../custom-provider-header-secrets.js', () => ({
+ listCustomProvidersWithSecureHeaders: async () => [
{
id: 'local-keyless',
name: 'Local keyless',
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
index 4a02e3e736..24f5c62ca4 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -90,6 +90,25 @@ describe('buildPiNativeProvidersFromConfigs', () => {
expect(skips).toContain('nokey');
});
+ it('allows apiKey providers authenticated entirely by custom headers', () => {
+ const { providers, env } = buildPiNativeProvidersFromConfigs(
+ [{
+ id: 'header-only',
+ name: 'Header Only',
+ auth: { method: 'apiKey' },
+ runtimes: {
+ pi: piRuntime({ headers: { Authorization: 'Bearer header-secret' } }),
+ },
+ }],
+ () => null,
+ );
+
+ expect(providers).toHaveLength(1);
+ expect(providers[0].apiKeyEnvVar).toBeUndefined();
+ expect(providers[0].headers?.Authorization).toMatch(/^\$CINDY_PI_KEY_/);
+ expect(Object.values(env)).toContain('Bearer header-secret');
+ });
+
it('oauth custom provider is skipped for pi native', () => {
const skips: string[] = [];
const { providers } = buildPiNativeProvidersFromConfigs(
diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
index d5347e5d97..b31b30a86f 100644
--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
@@ -51,7 +51,7 @@ import {
} from './model-discovery/anthropic.js';
import { createProviderService, type ProviderService } from './provider-service.js';
import { readModelDisableOverrides } from './model-disable-store.js';
-import { listCustomProviders } from './custom-provider-store.js';
+import { listCustomProvidersWithSecureHeaders } from './custom-provider-header-secrets.js';
import {
setCustomProviderKeyReader,
setOAuthTokenReader,
@@ -395,7 +395,7 @@ export async function refreshDiscoveredCodexModels(
*/
export async function refreshCustomProvidersIntoCatalog(): Promise<void> {
try {
- const configs = await listCustomProviders();
+ const configs = await listCustomProvidersWithSecureHeaders();
setCustomProviders(configs.map((c) => buildUserProvider(c)));
log.info('custom providers merged into active catalog', { count: configs.length });
} catch (err) {
diff --git a/apps/desktop/src/main/maker-host/custom-provider-header-secrets.ts b/apps/desktop/src/main/maker-host/custom-provider-header-secrets.ts
new file mode 100644
index 0000000000..9f5450d150
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/custom-provider-header-secrets.ts
@@ -0,0 +1,127 @@
+/**
+ * Custom-provider runtime headers are credential-bearing by design. Keep every
+ * value in owner-scoped Electron safeStorage and persist only the remaining
+ * provider configuration in SQLite. Encrypting the complete map avoids a
+ * brittle allow/deny list for vendor-specific auth header names.
+ */
+
+import type { AgentKind, CustomProviderConfig } from '@cindy/model-providers';
+
+import {
+ readCustomProviderHeaders,
+ readCustomProviderHeadersForMutation,
+ removeCustomProviderHeaders,
+ storeCustomProviderHeaders,
+} from '../secrets/providerSecretStore.js';
+import {
+ listCustomProviders,
+ updateCustomProvider,
+} from './custom-provider-store.js';
+
+export const CUSTOM_PROVIDER_RUNTIME_AGENTS: readonly AgentKind[] = [
+ 'claude-code',
+ 'codex',
+ 'pi',
+];
+
+export type CustomProviderHeaderSecrets = Partial<
+ Record<AgentKind, Record<string, string>>
+>;
+
+/** Return a clone safe to persist plus the header values that must be encrypted. */
+export function splitCustomProviderHeaders(config: CustomProviderConfig): {
+ config: CustomProviderConfig;
+ headers: CustomProviderHeaderSecrets;
+} {
+ const runtimes = { ...config.runtimes };
+ const headers: CustomProviderHeaderSecrets = {};
+ for (const agent of CUSTOM_PROVIDER_RUNTIME_AGENTS) {
+ const runtime = runtimes[agent];
+ if (!runtime) continue;
+ const values = runtime.headers && Object.keys(runtime.headers).length > 0
+ ? { ...runtime.headers }
+ : undefined;
+ if (values) headers[agent] = values;
+ const { headers: _removed, ...persistedRuntime } = runtime;
+ runtimes[agent] = persistedRuntime;
+ }
+ return { config: { ...config, runtimes }, headers };
+}
+
+/** Hydrate safeStorage-only runtime headers into a config used by routing/UI/Pi. */
+export function hydrateCustomProviderHeaders(
+ config: CustomProviderConfig,
+): CustomProviderConfig {
+ const runtimes = { ...config.runtimes };
+ for (const agent of CUSTOM_PROVIDER_RUNTIME_AGENTS) {
+ const runtime = runtimes[agent];
+ if (!runtime) continue;
+ const headers = readCustomProviderHeaders(config.id, agent);
+ if (headers && Object.keys(headers).length > 0) {
+ runtimes[agent] = { ...runtime, headers };
+ }
+ }
+ return { ...config, runtimes };
+}
+
+type HeaderSnapshot = {
+ agent: AgentKind;
+ previous: Record<string, string> | null;
+};
+
+function restoreHeaderSnapshots(
+ providerId: string,
+ snapshots: readonly HeaderSnapshot[],
+): boolean {
+ let restored = true;
+ for (const { agent, previous } of [...snapshots].reverse()) {
+ if (previous) {
+ if (!storeCustomProviderHeaders(providerId, agent, previous)) restored = false;
+ } else if (!removeCustomProviderHeaders(providerId, agent).success) {
+ restored = false;
+ }
+ }
+ return restored;
+}
+
+/**
+ * Load runtime-ready configs and lazily migrate legacy plaintext headers.
+ * The encrypted write happens before the SQLite scrub; any scrub failure rolls
+ * safeStorage back so the next load can retry without losing credentials.
+ */
+export async function listCustomProvidersWithSecureHeaders(): Promise<CustomProviderConfig[]> {
+ const configs = await listCustomProviders();
+ const result: CustomProviderConfig[] = [];
+ for (const original of configs) {
+ const split = splitCustomProviderHeaders(original);
+ const legacyAgents = CUSTOM_PROVIDER_RUNTIME_AGENTS.filter(
+ (agent) => split.headers[agent] && Object.keys(split.headers[agent]!).length > 0,
+ );
+ let persisted = split.config;
+ if (legacyAgents.length > 0) {
+ const snapshots: HeaderSnapshot[] = [];
+ try {
+ for (const agent of legacyAgents) {
+ const previous = readCustomProviderHeadersForMutation(original.id, agent);
+ snapshots.push({ agent, previous });
+ if (!storeCustomProviderHeaders(original.id, agent, split.headers[agent]!)) {
+ throw new Error(`failed to encrypt ${agent} custom provider headers`);
+ }
+ }
+ const updated = await updateCustomProvider(original.id, split.config);
+ if (!updated) throw new Error(`custom provider '${original.id}' disappeared during migration`);
+ persisted = updated;
+ } catch (err) {
+ if (!restoreHeaderSnapshots(original.id, snapshots)) {
+ throw new Error(
+ `custom provider '${original.id}' header migration failed and could not be rolled back`,
+ { cause: err },
+ );
+ }
+ throw err;
+ }
+ }
+ result.push(hydrateCustomProviderHeaders(persisted));
+ }
+ return result;
+}
diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.ts
index e2fce90456..6df8aa1e20 100644
--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts
+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts
@@ -1,9 +1,10 @@
/**
- * custom-provider-store —— 用户自定义供应商**配置**的 localDb CRUD(不含密钥)。
+ * custom-provider-store —— 用户自定义供应商**非凭证配置**的 localDb CRUD。
*
* 存储:localDb `custom_providers` 表。DB 文件本身按 userId 切片
* (`<userData>/xdt-maker-<userId>.db`,换账号 closeDb 重开),故本表天然账号隔离、
- * 无 owner 列(与 `sessions` 一致)。API key 不在此——按 runtime 单独走 safeStorage(见 routing)。
+ * 无 owner 列(与 `sessions` 一致)。API key 与 runtime headers 均不在此——按 runtime
+ * 单独走 safeStorage(见 custom-provider-header-secrets / routing)。
*
* 形状:行 ↔ `@cindy/model-providers` 的 `CustomProviderConfig`(per-runtime)。`runtimes` 列以
* TEXT 存 JSON,出入口转换、反序列化失败安全兜底({}),不抛错。
@@ -329,12 +330,9 @@ function normalizeRuntime(rt: CustomProviderRuntimeConfig): CustomProviderRuntim
seen.add(m.id);
return true;
});
- const headers =
- rt.headers && Object.keys(rt.headers).length > 0 ? { ...rt.headers } : undefined;
const out: CustomProviderRuntimeConfig = { baseUrl: rt.baseUrl.trim(), models };
if (rt.wireProtocol) out.wireProtocol = rt.wireProtocol;
if (rt.requestPath && rt.requestPath.trim()) out.requestPath = rt.requestPath.trim();
- if (headers) out.headers = headers;
if (rt.modelsUrl && rt.modelsUrl.trim()) out.modelsUrl = rt.modelsUrl.trim();
return out;
}
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 21eea2cfec..7930b03bdf 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -29,7 +29,7 @@ import type {
import type { ProviderWireProtocol } from '@cindy/model-providers';
import { getPiExtraSpawnConfig } from '../mcp-integrations/piEnvironment.js';
-import { listCustomProviders } from './custom-provider-store.js';
+import { listCustomProvidersWithSecureHeaders } from './custom-provider-header-secrets.js';
import { readCustomProviderKey } from '../secrets/providerSecretStore.js';
import { desktopCodexAuthAdapter, readClaudeApiKey } from './auth-adapters.js';
import { getClaudeEndpoint } from './anthropic-compat-proxy-host.js';
@@ -109,7 +109,7 @@ class DesktopPiAuthAdapter implements AuthAdapter {
}
if (providerId) {
try {
- const custom = (await listCustomProviders()).find(
+ const custom = (await listCustomProvidersWithSecureHeaders()).find(
(provider) => provider.id === providerId && provider.runtimes.pi,
);
if (custom) {
@@ -120,7 +120,8 @@ class DesktopPiAuthAdapter implements AuthAdapter {
return { authenticated: true, identity: custom.name, authSource: 'api-key' };
}
if (method === 'apiKey') {
- return readCustomProviderKey(providerId, 'pi')
+ const hasHeaderCredential = Object.keys(custom.runtimes.pi?.headers ?? {}).length > 0;
+ return readCustomProviderKey(providerId, 'pi') || hasHeaderCredential
? { authenticated: true, identity: custom.name, authSource: 'api-key' }
: { authenticated: false, errorReason: 'pi_native_api_key_unavailable' };
}
@@ -233,7 +234,7 @@ export function piNativeKeyEnvVar(providerId: string): string {
* key 读取经 `readKey` 注入(便于单测)。规则:
* - 无 pi runtime → 跳过;
* - oauth 形态 → 跳过(pi models.json 仅支持 radius oauth,不通用);
- * - apiKey 形态但读不到 key → 跳过(pi 无 key 不显示该模型,避免半可用);
+ * - apiKey 形态但 key / 自定义 headers 都没有 → 跳过(避免半可用);
* - none(keyless,本机 Ollama 等)→ apiKeyEnvVar 留空,models.json 写 dummy key;
* - 自定义 header 值全部搬进子进程 env,models.json 只保留 `$ENV` 引用。
* 直连用户端点,不过 anthropic-compat 代理(设计原则:pi 主导,禁双重转义)。
@@ -283,17 +284,7 @@ export function buildPiNativeProvidersFromConfigs(
onSkip?.(cfg.id, 'oauth not supported for pi native');
continue;
}
- let apiKeyEnvVar: string | undefined;
- if (authMethod === 'apiKey') {
- const key = readKey(cfg.id, 'pi');
- if (!key) {
- onSkip?.(cfg.id, 'apiKey provider missing pi key');
- continue;
- }
- apiKeyEnvVar = uniqueEnvVar(cfg.id);
- env[apiKeyEnvVar] = key;
- }
- const headers = rt.headers
+ const headers = rt.headers && Object.keys(rt.headers).length > 0
? Object.fromEntries(
Object.entries(rt.headers).map(([name, value]) => {
const envVar = uniqueEnvVar(`${cfg.id}_HEADER_${name}`);
@@ -302,6 +293,18 @@ export function buildPiNativeProvidersFromConfigs(
}),
)
: undefined;
+ let apiKeyEnvVar: string | undefined;
+ if (authMethod === 'apiKey') {
+ const key = readKey(cfg.id, 'pi');
+ if (!key && !headers) {
+ onSkip?.(cfg.id, 'apiKey provider missing pi key and custom headers');
+ continue;
+ }
+ if (key) {
+ apiKeyEnvVar = uniqueEnvVar(cfg.id);
+ env[apiKeyEnvVar] = key;
+ }
+ }
providers.push({
id: cfg.id,
name: cfg.name,
@@ -319,7 +322,7 @@ export function buildPiNativeProvidersFromConfigs(
async function resolvePiNativeProviders(): Promise<PiNativeProvidersResult> {
let configs;
try {
- configs = await listCustomProviders();
+ configs = await listCustomProvidersWithSecureHeaders();
} catch (err) {
log.warn('resolvePiNativeProviders: listCustomProviders failed, gateway-only', {
message: err instanceof Error ? err.message : String(err),
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 8324856c5c..17675104f9 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -6,6 +6,7 @@ import type {
AgentInputSendResult,
} from '../agent-input-coordinator.js';
import type {
+ AgentInputCreateOpts,
AgentInputProjection,
AgentInputQueuedMessage,
} from '../../../shared/agentInputQueue.js';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
index 5900885e80..3ccd1ffca9 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -97,6 +97,9 @@ function makeDeps(over: Partial<ProviderHandlerDeps> = {}): ProviderHandlerDeps
readCustomProviderKeyForMutation: vi.fn(() => null),
storeCustomProviderKey: vi.fn(() => true),
removeCustomProviderKey: vi.fn(() => ({ success: true })),
+ readCustomProviderHeadersForMutation: vi.fn(() => null),
+ storeCustomProviderHeaders: vi.fn(() => true),
+ removeCustomProviderHeaders: vi.fn(() => ({ success: true })),
scanLocalCli: vi.fn(async () => []),
setModelsDisabled: vi.fn(() => {}),
setProviderDisabled: vi.fn(() => {}),
@@ -139,6 +142,53 @@ describe('provider:list IPC handler', () => {
);
await expect(harness.invoke(MAKER_INVOKE.PROVIDER_LIST)).rejects.toThrow('boom');
});
+
+ it('redacts runtime header credentials for untrusted or synthetic callers', async () => {
+ const harness = new IpcHarness();
+ const provider = {
+ ...fakeView('custom', true),
+ routing: {
+ pi: {
+ upstream: 'https://custom.example/v1',
+ authStrategy: 'api-key-header',
+ headerOverride: { Authorization: 'Bearer secret' },
+ },
+ },
+ } as unknown as ProviderView;
+ registerProviderHandlers(harness, makeDeps({
+ listProviders: async () => [provider],
+ isTrustedSender: () => false,
+ }));
+
+ const result = await harness.invoke(MAKER_INVOKE.PROVIDER_LIST) as {
+ providers: ProviderView[];
+ };
+ expect(result.providers[0].routing.pi?.headerOverride).toBeUndefined();
+ expect(result.providers[0].routing.pi?.upstream).toBe('https://custom.example/v1');
+ });
+
+ it('keeps runtime headers for the trusted local settings editor', async () => {
+ const harness = new IpcHarness();
+ const provider = {
+ ...fakeView('custom', true),
+ routing: {
+ pi: {
+ headerOverride: { Authorization: 'Bearer secret' },
+ },
+ },
+ } as unknown as ProviderView;
+ registerProviderHandlers(harness, makeDeps({
+ listProviders: async () => [provider],
+ isTrustedSender: () => true,
+ }));
+
+ const result = await harness.invoke(MAKER_INVOKE.PROVIDER_LIST) as {
+ providers: ProviderView[];
+ };
+ expect(result.providers[0].routing.pi?.headerOverride).toEqual({
+ Authorization: 'Bearer secret',
+ });
+ });
});
describe('model-disable:set handler', () => {
@@ -700,6 +750,92 @@ describe('provider:custom:* CRUD handlers', () => {
expect(storeCustomProviderKey).toHaveBeenCalledWith('pi-native', 'pi', 'pi-secret');
});
+ it('encrypts runtime headers and never persists their values in SQLite', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const storeCustomProviderHeaders = vi.fn(() => true);
+ registerProviderHandlers(harness, makeDeps({ storeCustomProviderHeaders }));
+ const config: CustomProviderConfig = {
+ id: 'header-auth',
+ name: 'Header Auth',
+ auth: { method: 'apiKey' },
+ runtimes: {
+ pi: {
+ baseUrl: 'https://header-auth.example/v1',
+ models: [{ id: 'm', name: 'M' }],
+ headers: {
+ Authorization: 'Bearer top-secret',
+ 'X-Org': 'also-private',
+ },
+ },
+ },
+ };
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config),
+ ).resolves.toEqual({ ok: true });
+ expect(storeCustomProviderHeaders).toHaveBeenCalledWith(
+ 'header-auth',
+ 'pi',
+ config.runtimes.pi?.headers,
+ );
+ const row = raw?.prepare('SELECT runtimes FROM custom_providers WHERE id = ?').get(
+ 'header-auth',
+ ) as { runtimes: string };
+ expect(row.runtimes).not.toContain('top-secret');
+ expect(row.runtimes).not.toContain('also-private');
+ expect(JSON.parse(row.runtimes).pi.headers).toBeUndefined();
+ });
+
+ it('restores encrypted runtime headers when the config update fails', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const headers = new Map<AgentKind, Record<string, string>>();
+ registerProviderHandlers(harness, makeDeps({
+ readCustomProviderHeadersForMutation: vi.fn(
+ (_providerId, agent) => headers.get(agent) ?? null,
+ ),
+ storeCustomProviderHeaders: vi.fn((_providerId, agent, value) => {
+ headers.set(agent, { ...value });
+ return true;
+ }),
+ removeCustomProviderHeaders: vi.fn((_providerId, agent) => {
+ headers.delete(agent);
+ return { success: true };
+ }),
+ }));
+ const config: CustomProviderConfig = {
+ id: 'header-rollback',
+ name: 'Header Rollback',
+ runtimes: {
+ pi: {
+ baseUrl: 'https://header-rollback.example/v1',
+ models: [{ id: 'm', name: 'M' }],
+ headers: { Authorization: 'Bearer old' },
+ },
+ },
+ };
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config);
+ raw!.exec(`
+ CREATE TRIGGER fail_header_provider_update
+ BEFORE UPDATE ON custom_providers
+ BEGIN
+ SELECT RAISE(ABORT, 'simulated header write failure');
+ END
+ `);
+
+ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...config,
+ runtimes: {
+ pi: {
+ ...config.runtimes.pi!,
+ headers: { Authorization: 'Bearer replacement' },
+ },
+ },
+ })).rejects.toThrow(/simulated header write failure/);
+ expect(headers.get('pi')).toEqual({ Authorization: 'Bearer old' });
+ });
+
it('rolls back partial create keys before any provider config is committed', async () => {
mountDb();
const harness = new IpcHarness();
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index 42b2a95ed5..8d762e5f1c 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -47,6 +47,11 @@ import {
updateCustomProvider,
validateCustomProviderConfig,
} from '../maker-host/custom-provider-store.js';
+import {
+ CUSTOM_PROVIDER_RUNTIME_AGENTS,
+ splitCustomProviderHeaders,
+ type CustomProviderHeaderSecrets,
+} from '../maker-host/custom-provider-header-secrets.js';
import type { ProviderProbeSpec, ProviderTestInput, ProviderTestResult } from '../maker-host/provider-diagnostics.js';
import type {
ProviderModelsFetchResult,
@@ -163,6 +168,19 @@ function oauthDescriptorSignature(config: CustomProviderConfig | null): string |
});
}
+/** Never expose runtime header credentials to WebViews or synthetic remote events. */
+function withoutProviderHeaderCredentials(provider: ProviderView): ProviderView {
+ if (!provider.routing) return provider;
+ const routing = Object.fromEntries(
+ Object.entries(provider.routing).map(([agent, descriptor]) => {
+ if (!descriptor) return [agent, descriptor];
+ const { headerOverride: _secretHeaders, ...safeDescriptor } = descriptor;
+ return [agent, safeDescriptor];
+ }),
+ ) as ProviderView['routing'];
+ return { ...provider, routing };
+}
+
export interface ProviderHandlerDeps {
/**
* 当前供应商视图(含实时连接状态);见 createDesktopProviderService。
@@ -247,6 +265,20 @@ export interface ProviderHandlerDeps {
providerId: string,
agent: AgentKind,
): { success: boolean; error?: string };
+ /** Main-only encrypted runtime header blobs, transacted with config + API keys. */
+ readCustomProviderHeadersForMutation(
+ providerId: string,
+ agent: AgentKind,
+ ): Record<string, string> | null;
+ storeCustomProviderHeaders(
+ providerId: string,
+ agent: AgentKind,
+ headers: Record<string, string>,
+ ): boolean;
+ removeCustomProviderHeaders(
+ providerId: string,
+ agent: AgentKind,
+ ): { success: boolean; error?: string };
/**
* 本机 agent CLI 安装 / 登录态扫描(生产 = scanLocalCliAuth(createLocalCliScanDeps());
* 单测注入 stub 不碰真实 home)。只 stat 不读内容(规则 23)。
@@ -599,6 +631,101 @@ export function registerProviderHandlers(
throw error;
}
};
+ type HeaderSnapshot = {
+ agent: AgentKind;
+ previous: Record<string, string> | null;
+ };
+ type HeaderMutation = {
+ agent: AgentKind;
+ replacement: Record<string, string> | null;
+ };
+ const restoreProviderHeaders = (
+ providerId: string,
+ snapshots: readonly HeaderSnapshot[],
+ ): boolean => {
+ let restored = true;
+ for (const { agent, previous } of [...snapshots].reverse()) {
+ if (previous) {
+ if (!deps.storeCustomProviderHeaders(providerId, agent, previous)) restored = false;
+ } else if (!deps.removeCustomProviderHeaders(providerId, agent).success) {
+ restored = false;
+ }
+ }
+ return restored;
+ };
+ const planProviderHeaderMutations = (
+ config: CustomProviderConfig,
+ headers: CustomProviderHeaderSecrets,
+ mode: 'create' | 'update' | 'delete',
+ ): HeaderMutation[] => {
+ const mutations: HeaderMutation[] = [];
+ for (const agent of CUSTOM_PROVIDER_RUNTIME_AGENTS) {
+ const replacement = headers[agent];
+ if (mode === 'create') {
+ if (config.runtimes[agent] && replacement) mutations.push({ agent, replacement });
+ } else {
+ mutations.push({ agent, replacement: mode === 'delete' ? null : replacement ?? null });
+ }
+ }
+ return mutations;
+ };
+ const stageProviderHeaders = (
+ providerId: string,
+ mutations: readonly HeaderMutation[],
+ ): HeaderSnapshot[] => {
+ const snapshots: HeaderSnapshot[] = [];
+ try {
+ for (const { agent, replacement } of mutations) {
+ let previous: Record<string, string> | null;
+ try {
+ previous = deps.readCustomProviderHeadersForMutation(providerId, agent);
+ } catch {
+ throwIpcError('INTERNAL', `failed to read existing ${agent} provider headers`);
+ }
+ snapshots.push({ agent, previous });
+ const succeeded = replacement
+ ? deps.storeCustomProviderHeaders(providerId, agent, replacement)
+ : deps.removeCustomProviderHeaders(providerId, agent).success;
+ if (!succeeded) {
+ throwIpcError('INTERNAL', `failed to update ${agent} provider headers`);
+ }
+ }
+ return snapshots;
+ } catch (error) {
+ if (!restoreProviderHeaders(providerId, snapshots)) {
+ throwIpcError('INTERNAL', 'provider header update failed and could not be rolled back');
+ }
+ throw error;
+ }
+ };
+ const stageProviderCredentials = (
+ providerId: string,
+ keyMutations: readonly KeyMutation[],
+ headerMutations: readonly HeaderMutation[],
+ ): { keySnapshots: KeySnapshot[]; headerSnapshots: HeaderSnapshot[] } => {
+ const keySnapshots = stageProviderKeys(providerId, keyMutations);
+ try {
+ return {
+ keySnapshots,
+ headerSnapshots: stageProviderHeaders(providerId, headerMutations),
+ };
+ } catch (error) {
+ if (!restoreProviderKeys(providerId, keySnapshots)) {
+ throwIpcError('INTERNAL', 'provider credential update failed and could not be rolled back');
+ }
+ throw error;
+ }
+ };
+ const restoreProviderCredentials = (
+ providerId: string,
+ snapshots: { keySnapshots: readonly KeySnapshot[]; headerSnapshots: readonly HeaderSnapshot[] },
+ ): boolean => {
+ // Always attempt both restorations; a failed header rollback must not leave
+ // an API key at its staged replacement (or vice versa).
+ const headersRestored = restoreProviderHeaders(providerId, snapshots.headerSnapshots);
+ const keysRestored = restoreProviderKeys(providerId, snapshots.keySnapshots);
+ return headersRestored && keysRestored;
+ };
// 只读聚合:loadCatalog 永不抛(最差回退内置目录),故无需 throwIpcError 包裹。
registry.handle(
@@ -611,9 +738,12 @@ export function registerProviderHandlers(
}> => {
// 只有本机主页面能顺带触发绑定自愈与清单拉取:这条通道也服务 device-link(合成
// event)和可能不受信的渲染上下文,它们只该拿到只读快照(PR #548 review)。
- const allowSideEffects = deps.isTrustedSender?.(event) === true;
- const providers = await deps.listProviders({ allowSideEffects });
- return { providers, modelVisibilityOverrides: deps.getModelVisibilityOverrides() };
+ const trusted = deps.isTrustedSender?.(event) === true;
+ const providers = await deps.listProviders({ allowSideEffects: trusted });
+ return {
+ providers: trusted ? providers : providers.map(withoutProviderHeaderCredentials),
+ modelVisibilityOverrides: deps.getModelVisibilityOverrides(),
+ };
},
);
@@ -809,18 +939,20 @@ export function registerProviderHandlers(
const keys = parseRuntimeKeys(keyInput);
if (!keys) throwIpcError('INVALID_PARAMS', 'invalid provider runtime keys');
const config = input as CustomProviderConfig;
+ const separated = splitCustomProviderHeaders(config);
return withProviderConfigMutation(config.id, async () => {
if (await customProviderExists(config.id)) {
throwIpcError('ALREADY_EXISTS', `custom provider '${config.id}' already exists`);
}
- const keySnapshots = stageProviderKeys(
+ const credentialSnapshots = stageProviderCredentials(
config.id,
planProviderKeyMutations(config, keys, 'create'),
+ planProviderHeaderMutations(config, separated.headers, 'create'),
);
try {
- await createCustomProvider(config);
+ await createCustomProvider(separated.config);
} catch (error) {
- if (!restoreProviderKeys(config.id, keySnapshots)) {
+ if (!restoreProviderCredentials(config.id, credentialSnapshots)) {
throwIpcError(
'INTERNAL',
'provider creation failed and credentials could not be rolled back',
@@ -840,6 +972,7 @@ export function registerProviderHandlers(
const keys = parseRuntimeKeys(keyInput);
if (!keys) throwIpcError('INVALID_PARAMS', 'invalid provider runtime keys');
const config = input as CustomProviderConfig;
+ const separated = splitCustomProviderHeaders(config);
return withProviderConfigMutation(config.id, async () => {
let generation: symbol | null = null;
try {
@@ -853,9 +986,10 @@ export function registerProviderHandlers(
|| oauthDescriptorSignature(previous) !== oauthDescriptorSignature(config);
// API key 的写 / 删与配置更新处于同一 main 队列;若后续 OAuth 清理或 DB 写失败,
// 用原值回滚,确保并发窗口不能把另一份配置和密钥拼在一起。
- const keySnapshots = stageProviderKeys(
+ const credentialSnapshots = stageProviderCredentials(
config.id,
planProviderKeyMutations(config, keys, 'update'),
+ planProviderHeaderMutations(config, separated.headers, 'update'),
);
// 先阻止在途 flow 写回,再改描述符;否则旧 flow 可能在 clear 后迟到落一枚旧 token。
if (shouldResetOAuth) deps.oauthCancel(config.id);
@@ -871,11 +1005,11 @@ export function registerProviderHandlers(
throwIpcError('INTERNAL', 'failed to remove existing OAuth credentials');
}
}
- updated = await updateCustomProvider(config.id, config);
+ updated = await updateCustomProvider(config.id, separated.config);
} catch (err) {
const oauthRestored = !restoreOAuthCredentials || restoreOAuthCredentials();
- const keysRestored = restoreProviderKeys(config.id, keySnapshots);
- if (!oauthRestored || !keysRestored) {
+ const credentialsRestored = restoreProviderCredentials(config.id, credentialSnapshots);
+ if (!oauthRestored || !credentialsRestored) {
throwIpcError(
'INTERNAL',
'provider update failed and existing credentials could not be restored',
@@ -885,8 +1019,8 @@ export function registerProviderHandlers(
}
if (!updated) {
const oauthRestored = !restoreOAuthCredentials || restoreOAuthCredentials();
- const keysRestored = restoreProviderKeys(config.id, keySnapshots);
- if (!oauthRestored || !keysRestored) {
+ const credentialsRestored = restoreProviderCredentials(config.id, credentialSnapshots);
+ if (!oauthRestored || !credentialsRestored) {
throwIpcError(
'INTERNAL',
'provider disappeared during update and existing credentials could not be restored',
@@ -911,12 +1045,17 @@ export function registerProviderHandlers(
const generation = beginOAuthMutation(providerId);
try {
deps.oauthCancel(providerId);
- const keySnapshots = stageProviderKeys(
+ const credentialSnapshots = stageProviderCredentials(
providerId,
(VALID_AGENTS as readonly AgentKind[]).map((agent) => ({
agent,
replacement: null,
})),
+ planProviderHeaderMutations(
+ { id: providerId, name: providerId, runtimes: {} },
+ {},
+ 'delete',
+ ),
);
// OAuth 形态自定义供应商的凭证 blob 一并清掉(apiKey 形态无 blob,幂等无害)。
let restoreOAuthCredentials: (() => boolean) | null = null;
@@ -943,8 +1082,11 @@ export function registerProviderHandlers(
} catch (err) {
const overridesRestored = !restoreDisableOverrides || restoreDisableOverrides();
const oauthRestored = !restoreOAuthCredentials || restoreOAuthCredentials();
- const keysRestored = restoreProviderKeys(providerId, keySnapshots);
- if (!oauthRestored || !keysRestored || !overridesRestored) {
+ const credentialsRestored = restoreProviderCredentials(
+ providerId,
+ credentialSnapshots,
+ );
+ if (!oauthRestored || !credentialsRestored || !overridesRestored) {
throwIpcError(
'INTERNAL',
'provider deletion failed and existing credentials could not be restored',
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 1d49a0f590..1377892897 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -478,8 +478,11 @@ import {
updateCustomProviderIfUnchanged,
} from '../maker-host/custom-provider-store.js';
import {
+ readCustomProviderHeadersForMutation,
readCustomProviderKeyForMutation,
+ removeCustomProviderHeaders,
removeCustomProviderKey,
+ storeCustomProviderHeaders,
storeCustomProviderKey,
} from '../secrets/providerSecretStore.js';
import { setSessionEffort, setSessionFastMode } from '../maker-host/session-effort-store.js';
@@ -4227,6 +4230,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 停用写入的归属校验:入口捕获 / 持久化前复核,异步窗口内切账号即拒,防 A 的
// 点击写进 B 的 owner-scoped 偏好文件(PR #744 review 第七轮)。
currentOwnerId: () => getCurrentDataOwnerId(),
+ readCustomProviderHeadersForMutation,
+ storeCustomProviderHeaders,
+ removeCustomProviderHeaders,
// 通用 OAuth(目录 auth.oauth 描述符驱动):login 成功后 best-effort 拉动态模型发现
// (additions-only merge 进 active-catalog) 并广播 PROVIDER_CHANGED 让 UI 刷新连接态。
oauthLogin: async (providerId, isCurrent) => {
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts
index a181c0607e..5a703e7fa2 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts
@@ -15,6 +15,7 @@
import { afterEach, describe, expect, it } from 'vitest';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { getLiziMcpSessionContext } from '@cindy/mcps';
+import { createOrcaWorkerBridgeMcpProvider } from '@cindy/orca-workflow';
import type { Logger, McpProvider } from '@cindy/maker-core';
import { getPiExtraSpawnConfig, shutdownPiEnvironment } from '../piEnvironment.js';
@@ -159,4 +160,29 @@ describe('piEnvironment per-session identity', () => {
result: { content: [{ type: 'text', text: 'no-session' }] },
});
});
+
+ it('registers the worker bridge before the Pi session role is available', async () => {
+ const logger = noopLogger();
+ const provider = createOrcaWorkerBridgeMcpProvider({
+ logger,
+ getMaker: () => {
+ throw new Error('not called while registering the MCP server');
+ },
+ persistUserMessage: async () => {},
+ wireSession: () => undefined,
+ });
+ const config = await getPiExtraSpawnConfig([provider], logger, {
+ sessionId: 'pi-worker-1',
+ workingDir: '/repo',
+ vendorOptions: {
+ orcaRole: 'worker',
+ orcaWorkerId: 'worker-1',
+ orcaWorkerSessionId: 'pi-worker-1',
+ },
+ });
+
+ expect(config?.mcpBridge?.servers.map((server) => server.name)).toContain(
+ 'orca_worker_bridge',
+ );
+ });
});
diff --git a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts
index b5135eae98..e3a3a58019 100644
--- a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts
+++ b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts
@@ -42,6 +42,7 @@ import {
import {
providerSecretStorageKey,
customMcpSecretStorageKey,
+ customProviderHeaderStorageKey,
customProviderSecretStorageKey,
providerOAuthStorageKey,
ghostSecretStorageKey,
@@ -103,6 +104,13 @@ describe('providerSecrets registry', () => {
expect(isRendererAccessibleSafeStorageKey('PROVIDER_KEY_OPENAI_IMAGES')).toBe(false);
});
+ it('keeps custom-provider header blobs behind the main-only boundary', () => {
+ const key = customProviderHeaderStorageKey('my_or', 'pi');
+ expect(key).toBe('provider_headers_my_or_pi');
+ expect(isRendererAccessibleSafeStorageKey(key)).toBe(false);
+ expect(() => customProviderHeaderStorageKey('bad/path', 'pi')).toThrow(/illegal characters/);
+ });
+
it('动态键名构造前校验片段字符集,路径逃逸类 id 直接抛错', () => {
expect(providerOAuthStorageKey('acme-1')).toBe('provider_oauth_acme-1');
expect(customProviderSecretStorageKey('my_or', 'claude-code')).toBe('provider_key_my_or_claude-code');
diff --git a/apps/desktop/src/main/secrets/providerSecretStore.ts b/apps/desktop/src/main/secrets/providerSecretStore.ts
index 90a57354d2..784b944c59 100644
--- a/apps/desktop/src/main/secrets/providerSecretStore.ts
+++ b/apps/desktop/src/main/secrets/providerSecretStore.ts
@@ -5,9 +5,11 @@ import path from 'node:path';
import { createLogger } from '../logger.js';
import {
providerSecretStorageKey,
+ customProviderHeaderStorageKey,
customProviderSecretStorageKey,
customMcpSecretStorageKey,
CUSTOM_MCP_SECRET_PREFIX,
+ CUSTOM_PROVIDER_HEADER_SECRET_PREFIX,
providerOAuthStorageKey,
ghostSecretStorageKey,
ghostSecretHintStorageKey,
@@ -74,6 +76,7 @@ function secretDir(): string {
const DYNAMIC_SECRET_PREFIXES = [
CUSTOM_MCP_SECRET_PREFIX,
+ CUSTOM_PROVIDER_HEADER_SECRET_PREFIX,
'provider_key_',
'provider_oauth_',
GHOST_SECRET_PREFIX,
@@ -396,6 +399,35 @@ export function readCustomProviderKey(providerId: string, agent: string): string
}
}
+function parseCustomProviderHeaders(raw: string): Record<string, string> {
+ const value: unknown = JSON.parse(raw);
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error('custom provider headers must be an object');
+ }
+ const entries = Object.entries(value as Record<string, unknown>);
+ if (entries.some(([name, headerValue]) => !name || typeof headerValue !== 'string')) {
+ throw new Error('custom provider headers must be string pairs');
+ }
+ return Object.fromEntries(entries) as Record<string, string>;
+}
+
+/** Read one runtime's encrypted custom headers for routing/Pi injection. */
+export function readCustomProviderHeaders(
+ providerId: string,
+ agent: string,
+): Record<string, string> | null {
+ try {
+ const raw = electronSecretIo.read(customProviderHeaderStorageKey(providerId, agent));
+ return raw === null ? null : parseCustomProviderHeaders(raw);
+ } catch (err) {
+ log.warn(
+ { providerId, agent, err: err instanceof Error ? err.message : String(err) },
+ 'read custom provider headers failed',
+ );
+ return null;
+ }
+}
+
/**
* 配置 CRUD 回滚前的严格 API key 快照读取。
* 仅 ENOENT 表示“没有旧 key”;owner / 加密不可用、文件读取或解密失败都必须抛错,
@@ -435,6 +467,37 @@ export function readCustomProviderKeyForMutation(
}
}
+/** Strict mutation snapshot for an encrypted runtime header blob. */
+export function readCustomProviderHeadersForMutation(
+ providerId: string,
+ agent: string,
+): Record<string, string> | null {
+ const logicalKey = customProviderHeaderStorageKey(providerId, agent);
+ const scopedKey = resolveOwnerScopedSecretStorageKey(logicalKey);
+ if (!scopedKey) throw new Error('provider secret owner is unavailable');
+ let encoded: string;
+ try {
+ encoded = fs.readFileSync(path.join(secretDir(), `${scopedKey}.enc`), 'utf-8');
+ } catch (err) {
+ if (err instanceof Error && (err as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw new Error('existing provider header credentials are unreadable');
+ }
+ if (!safeStorage.isEncryptionAvailable()) {
+ throw new Error('provider credential encryption is unavailable');
+ }
+ try {
+ return parseCustomProviderHeaders(
+ safeStorage.decryptString(Buffer.from(encoded, 'base64')),
+ );
+ } catch (err) {
+ log.warn(
+ { providerId, agent, err: err instanceof Error ? err.message : String(err) },
+ 'decrypt custom provider headers snapshot failed',
+ );
+ throw new Error('existing provider header credentials are unreadable');
+ }
+}
+
/** 写入某自定义供应商 runtime 的 API key;供 main 侧原子配置更新使用。 */
export function storeCustomProviderKey(
providerId: string,
@@ -452,6 +515,26 @@ export function storeCustomProviderKey(
}
}
+/** Persist one runtime's complete custom-header map as a main-only encrypted blob. */
+export function storeCustomProviderHeaders(
+ providerId: string,
+ agent: string,
+ headers: Record<string, string>,
+): boolean {
+ try {
+ return electronSecretIo.write(
+ customProviderHeaderStorageKey(providerId, agent),
+ JSON.stringify(headers),
+ );
+ } catch (err) {
+ log.warn(
+ { providerId, agent, err: err instanceof Error ? err.message : String(err) },
+ 'write custom provider headers failed',
+ );
+ return false;
+ }
+}
+
/**
* 读取 SSH 远端 daemon 直连 MCP bridge 的 persistent bearer token
* (**main 侧 HTTP bridge 鉴权专用**)。不存在 / safeStorage 不可用 / 读失败
@@ -499,6 +582,22 @@ export function removeCustomProviderKey(
}
}
+/** Delete one runtime's encrypted custom-header blob; absence is success. */
+export function removeCustomProviderHeaders(
+ providerId: string,
+ agent: string,
+): { success: boolean; error?: string } {
+ try {
+ return electronSecretIo.remove(customProviderHeaderStorageKey(providerId, agent));
+ } catch (err) {
+ log.warn(
+ { providerId, agent, err: err instanceof Error ? err.message : String(err) },
+ 'remove custom provider headers failed',
+ );
+ return { success: false, error: 'remove_failed' };
+ }
+}
+
/**
* 读取某自定义 MCP 服务器的 bearer token(**main 侧 CustomMcpProvider resolve 专用**)。
* 不存在 / safeStorage 不可用 / 读失败均返回 null。与 renderer 经通用 safe-storage IPC
diff --git a/apps/desktop/src/shared/providerSecrets.ts b/apps/desktop/src/shared/providerSecrets.ts
index 27dc284ed8..1a995a889f 100644
--- a/apps/desktop/src/shared/providerSecrets.ts
+++ b/apps/desktop/src/shared/providerSecrets.ts
@@ -81,12 +81,19 @@ const MAIN_ONLY_PROVIDER_SECRET_STORAGE_KEYS = new Set<string>([
REMOTE_MCP_BRIDGE_TOKEN_STORAGE_KEY.toLowerCase(),
]);
+/** Custom-provider runtime header blobs are main-only credential material. */
+export const CUSTOM_PROVIDER_HEADER_SECRET_PREFIX = 'provider_headers_';
+
/**
* Whether the generic Renderer safeStorage bridge may access this logical
* key. Main-only credentials use dedicated IPC that never returns plaintext.
*/
export function isRendererAccessibleSafeStorageKey(storageKey: string): boolean {
- return !MAIN_ONLY_PROVIDER_SECRET_STORAGE_KEYS.has(storageKey.toLowerCase());
+ const normalized = storageKey.toLowerCase();
+ return (
+ !MAIN_ONLY_PROVIDER_SECRET_STORAGE_KEYS.has(normalized)
+ && !normalized.startsWith(CUSTOM_PROVIDER_HEADER_SECRET_PREFIX)
+ );
}
/**
@@ -117,6 +124,16 @@ export function customProviderSecretStorageKey(providerId: string, agent: string
return `provider_key_${providerId}_${agent}`;
}
+/**
+ * Main-only encrypted blob containing all custom headers for one provider runtime.
+ * Header values are never persisted in the custom_providers SQLite row.
+ */
+export function customProviderHeaderStorageKey(providerId: string, agent: string): string {
+ assertSafeKeyPart(providerId, 'providerId');
+ assertSafeKeyPart(agent, 'agent');
+ return `${CUSTOM_PROVIDER_HEADER_SECRET_PREFIX}${providerId}_${agent}`;
+}
+
/**
* 用户自定义 MCP 服务器 bearer token 的 safeStorage 键名前缀。
*
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index 1c6f834a99..744469ff28 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -531,7 +531,10 @@ export interface CustomProviderRuntimeConfig {
requestPath?: string;
/** 用户模型;contextWindow 可由预设带入,缺省时由 `buildUserProvider` 补保守默认。 */
models: ProviderRuntimeModelConfig[];
- /** 可选自定义请求头(非密钥鉴权头可放这里;API key 走 safeStorage,不放这里)。 */
+ /**
+ * 可选自定义请求头。运行时配置会从 main-only safeStorage 临时 hydrate;值不写
+ * custom_providers SQLite,也不通过非可信 / 远程 provider:list 返回。
+ */
headers?: Record<string, string>;
/**
* 可选的「列模型」端点(「获取模型列表」按钮用;缺省由 baseUrl 推导 `…/v1/models`)。
@@ -541,7 +544,8 @@ export interface CustomProviderRuntimeConfig {
}
/**
- * 用户自定义供应商的**持久化配置**(不含密钥)。
+ * 用户自定义供应商配置。runtime headers 仅在可信 main 运行期 hydrate,持久化时值在
+ * safeStorage;其余字段写 localDb。
*
* 由 host 持久化(desktop: localDb `custom_providers` 表,按账号隔离),加载时经
* `buildUserProvider`(见 user-provider.ts)展开成标准 `Provider`,与内置厂商同形状、
@@ -550,9 +554,9 @@ export interface CustomProviderRuntimeConfig {
* **per-runtime 独立配置**:`runtimes` 按 agent 索引,每个 runtime 各有独立的 baseUrl /
* 模型 / headers;用户在表单 Tab 里只配需要的那个,也可两个都配(该来源同时供两端)。至少一个。
*
- * API key **不在本结构里**:按 runtime 单独存 safeStorage(`provider_key_<id>_<agent>`,机制同
- * 内置 XD 网关 key),host 路由 resolve 时按 (id, agent) 读出注入鉴权头,绝不进 catalog /
- * 绝不回传 renderer 明文。
+ * API key 与 headers 值都不进 SQLite:按 runtime 分别存 safeStorage。host 路由 resolve
+ * 时按 (id, agent) hydrate;只有可信本机设置页可拿到 headers 以便编辑,远程和不可信
+ * renderer 投影一律剥离。
*/
export interface CustomProviderConfig {
/** 供应商 id,小写 slug(/^[a-z0-9_-]+$/),同账号内唯一,不撞内置 `anthropic|openai|xd`。 */
diff --git a/packages/orca-workflow/src/orca-bridge-mcp.ts b/packages/orca-workflow/src/orca-bridge-mcp.ts
index 3d622d5373..09b4b6a9d9 100644
--- a/packages/orca-workflow/src/orca-bridge-mcp.ts
+++ b/packages/orca-workflow/src/orca-bridge-mcp.ts
@@ -618,9 +618,19 @@ export function createOrcaWorkerBridgeMcpProvider(deps: OrcaBridgeMcpDeps): McpP
const leadCaptures = new CapturedSessionRegistry();
return {
name: 'orca_worker_bridge',
- isEnabled: (ctx) => ctx.vendorOptions?.orcaRole === 'worker' || ctx.agentKind === 'codex',
+ // Global HTTP bridges (Codex and Pi) bind the real session only at request time.
+ // Keep the server registered when a dynamic context resolver exists; every tool
+ // call still fails closed in resolveWorkerLink against that runtime identity.
+ isEnabled: (ctx) =>
+ ctx.vendorOptions?.orcaRole === 'worker'
+ || ctx.agentKind === 'codex'
+ || typeof ctx.getSessionContext === 'function',
toClaudeSdkConfig: (ctx) => {
- if (ctx.vendorOptions?.orcaRole !== 'worker' && ctx.agentKind !== 'codex') return null;
+ if (
+ ctx.vendorOptions?.orcaRole !== 'worker'
+ && ctx.agentKind !== 'codex'
+ && typeof ctx.getSessionContext !== 'function'
+ ) return null;
const server = new McpServer({ name: 'orca_worker_bridge', version: '0.1.0' });
async function resolveLead(workerId?: string) {