Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 旧密文不可解密时允许显式新 key 覆盖自定义供应商凭证 (#3821) (#3836)
Luu Thaia6cf92c13dbb
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.tsindex aedc513c5a..3db551eafb 100644--- a/apps/desktop/src/main/maker-host/custom-provider-header-secrets.ts+++ b/apps/desktop/src/main/maker-host/custom-provider-header-secrets.ts@@ -11,6 +11,7 @@ import {readCustomProviderHeadersForMutation,removeCustomProviderHeaders,storeCustomProviderHeaders,+ UNRECOVERABLE_PROVIDER_CREDENTIAL,} from '../secrets/providerSecretStore.js';import {listCustomProviders,@@ -58,7 +59,10 @@ export function hydrateCustomProviderHeaders(if (!runtime) continue;try {const headers = readCustomProviderHeadersForMutation(config.id, agent);- if (headers && Object.keys(headers).length > 0) {+ if (headers === UNRECOVERABLE_PROVIDER_CREDENTIAL) {+ // 密文头存在但解不开:与读失败同样标为 unknown,由用户重填后覆盖。+ runtimes[agent] = { ...runtime, headersState: 'unknown' };+ } else if (headers && Object.keys(headers).length > 0) {runtimes[agent] = { ...runtime, headers, headersState: 'configured' };}} catch {@@ -125,6 +129,10 @@ export async function listCustomProvidersWithSecureHeaders(): Promise<CustomProvassertSameOwner('header encryption');for (const agent of legacyAgents) {const previous = readCustomProviderHeadersForMutation(original.id, agent);+ // 解不开的旧密文头没有可回滚的快照:保持此前抛错中止迁移的语义,不覆盖它。+ if (previous === UNRECOVERABLE_PROVIDER_CREDENTIAL) {+ throw new Error(`existing ${agent} custom provider headers are unreadable`);+ }snapshots.push({ agent, previous });if (!storeCustomProviderHeaders(original.id, agent, split.headers[agent]!)) {throw new Error(`failed to encrypt ${agent} custom provider headers`);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.tsindex a8dd89a317..803d27a692 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts@@ -15,6 +15,10 @@ import {getProviderRouteCredentialRevision,isProviderRouteMutationInProgress,} from '../../maker-host/provider-route.js';+import {+ UNRECOVERABLE_PROVIDER_CREDENTIAL,+ type UnrecoverableProviderCredential,+} from '../../secrets/providerSecretStore.js';import { throwIpcError } from '../../utils/ipcValidate.js';import { MAKER_INVOKE } from '../channels.js';import { registerProviderHandlers, type ProviderHandlerDeps } from '../providerHandlers.js';@@ -2432,6 +2436,202 @@ describe('provider:custom:* CRUD handlers', () => {expect((await listCustomProviders())[0]?.name).toBe(config.name);});+ // #3821:旧密文对当前 safeStorage 主密钥解不开时,快照是「存在但不可恢复」而不是读失败。+ // 只有显式替换值能覆盖它;保留 / 仅删除 / 端点变更清理维持严格失败。+ function undecryptableKeyFixture() {+ mountDb();+ const harness = new IpcHarness();+ const keys = new Map<AgentKind, string | UnrecoverableProviderCredential>();+ const calls: string[] = [];+ const storeCustomProviderKey = vi.fn((_providerId, agent: AgentKind, value: string) => {+ calls.push(`store:${agent}:${value}`);+ keys.set(agent, value);+ return true;+ });+ const removeCustomProviderKey = vi.fn((_providerId, agent: AgentKind) => {+ calls.push(`remove:${agent}`);+ keys.delete(agent);+ return { success: true };+ });+ registerProviderHandlers(harness, makeDeps({+ readCustomProviderKeyForMutation: vi.fn(+ (_providerId, agent: AgentKind) => keys.get(agent) ?? null,+ ),+ storeCustomProviderKey,+ removeCustomProviderKey,+ }));+ const claudeRuntime = {+ baseUrl: 'https://api.example/v1',+ models: [{ id: 'claude-model', name: 'Claude model' }],+ };+ return { harness, keys, calls, storeCustomProviderKey, removeCustomProviderKey, claudeRuntime };+ }++ it('overwrites an API key whose ciphertext cannot be decrypted when a replacement is supplied', async () => {+ const { harness, keys, storeCustomProviderKey, removeCustomProviderKey, claudeRuntime } =+ undecryptableKeyFixture();+ const config: CustomProviderConfig = {+ ...validConfig,+ id: 'undecryptable-key',+ runtimes: { 'claude-code': claudeRuntime },+ };+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config, { 'claude-code': 'old-key' });+ // 模拟钥匙串条目已变:旧密文还在磁盘上,但解不开。+ keys.set('claude-code', UNRECOVERABLE_PROVIDER_CREDENTIAL);+ storeCustomProviderKey.mockClear();+ removeCustomProviderKey.mockClear();++ await expect(+ harness.invoke(+ MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE,+ { ...config, name: 'Recovered' },+ { 'claude-code': 'replacement-key' },+ ),+ ).resolves.toEqual({ ok: true });++ expect(keys.get('claude-code')).toBe('replacement-key');+ expect(storeCustomProviderKey).toHaveBeenCalledOnce();+ expect(removeCustomProviderKey).not.toHaveBeenCalled();+ expect((await listCustomProviders())[0]?.name).toBe('Recovered');+ });++ it('still refuses an endpoint change that would clear an undecryptable API key without a replacement', async () => {+ const { harness, keys, storeCustomProviderKey, removeCustomProviderKey, claudeRuntime } =+ undecryptableKeyFixture();+ const config: CustomProviderConfig = {+ ...validConfig,+ id: 'undecryptable-key-strict',+ runtimes: { 'claude-code': claudeRuntime },+ };+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config, { 'claude-code': 'old-key' });+ keys.set('claude-code', UNRECOVERABLE_PROVIDER_CREDENTIAL);+ storeCustomProviderKey.mockClear();+ removeCustomProviderKey.mockClear();++ // 端点变更且未填新 key = 清理旧密钥的语义:拿不到可回滚快照,维持严格失败,不碰旧 blob。+ await expect(+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {+ ...config,+ runtimes: { 'claude-code': { ...claudeRuntime, baseUrl: 'https://moved.example/v1' } },+ }),+ ).rejects.toThrow(/existing claude-code provider credential cannot be decrypted/);++ expect(keys.get('claude-code')).toBe(UNRECOVERABLE_PROVIDER_CREDENTIAL);+ expect(storeCustomProviderKey).not.toHaveBeenCalled();+ expect(removeCustomProviderKey).not.toHaveBeenCalled();+ expect((await listCustomProviders())[0]?.runtimes['claude-code']?.baseUrl).toBe(+ claudeRuntime.baseUrl,+ );+ });++ it('removes a replacement written over undecryptable ciphertext when the config write fails', async () => {+ const { harness, keys, calls, claudeRuntime } = undecryptableKeyFixture();+ const config: CustomProviderConfig = {+ ...validConfig,+ id: 'undecryptable-key-rollback',+ runtimes: {+ codex: { baseUrl: 'https://api.example/v1', models: [{ id: 'codex-model', name: 'Codex model' }] },+ 'claude-code': claudeRuntime,+ },+ };+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config, {+ codex: 'old-codex',+ 'claude-code': 'old-claude',+ });+ keys.set('claude-code', UNRECOVERABLE_PROVIDER_CREDENTIAL);+ calls.length = 0;+ raw!.exec(`+ CREATE TRIGGER fail_custom_provider_update+ BEFORE UPDATE ON custom_providers+ BEGIN+ SELECT RAISE(ABORT, 'simulated write failure');+ END+ `);++ await expect(+ harness.invoke(+ MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE,+ { ...config, name: 'Must not persist' },+ { codex: 'new-codex', 'claude-code': 'new-claude' },+ ),+ ).rejects.toThrow(/simulated write failure/);++ // 可恢复的 runtime 回滚到旧值;不可恢复的 runtime 只删掉新写入的值,不去恢复旧 blob。+ expect(calls).toHaveLength(4);+ expect(calls.slice(0, 2).sort()).toEqual(['store:claude-code:new-claude', 'store:codex:new-codex']);+ expect(calls.slice(2).sort()).toEqual(['remove:claude-code', 'store:codex:old-codex']);+ expect(keys.get('codex')).toBe('old-codex');+ expect(keys.has('claude-code')).toBe(false);+ expect((await listCustomProviders())[0]?.name).toBe(config.name);+ });++ it('overwrites undecryptable runtime headers only when replacement headers are supplied', async () => {+ mountDb();+ const harness = new IpcHarness();+ const headers = new Map<AgentKind, Record<string, string> | UnrecoverableProviderCredential>();+ const storeCustomProviderHeaders = vi.fn(+ (_providerId, agent: AgentKind, value: Record<string, string>) => {+ headers.set(agent, { ...value });+ return true;+ },+ );+ const removeCustomProviderHeaders = vi.fn((_providerId, agent: AgentKind) => {+ headers.delete(agent);+ return { success: true };+ });+ registerProviderHandlers(harness, makeDeps({+ readCustomProviderHeadersForMutation: vi.fn(+ (_providerId, agent: AgentKind) => headers.get(agent) ?? null,+ ),+ storeCustomProviderHeaders,+ removeCustomProviderHeaders,+ }));+ const runtime = {+ baseUrl: 'https://api.example/v1',+ models: [{ id: 'claude-model', name: 'Claude model' }],+ };+ const config: CustomProviderConfig = {+ ...validConfig,+ id: 'undecryptable-headers',+ runtimes: { 'claude-code': { ...runtime, headers: { Authorization: 'Bearer old' } } },+ };+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config);+ headers.set('claude-code', UNRECOVERABLE_PROVIDER_CREDENTIAL);+ storeCustomProviderHeaders.mockClear();+ removeCustomProviderHeaders.mockClear();++ // 未回传 headers = 保留旧值:不动那份解不开的密文头,纯改名照常成功。+ await expect(+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {+ ...config,+ name: 'Renamed',+ runtimes: { 'claude-code': runtime },+ }),+ ).resolves.toEqual({ ok: true });+ expect(headers.get('claude-code')).toBe(UNRECOVERABLE_PROVIDER_CREDENTIAL);++ // 端点变更且未回传 headers = 清理旧密文头的语义:维持严格失败。+ await expect(+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {+ ...config,+ runtimes: { 'claude-code': { ...runtime, baseUrl: 'https://moved.example/v1' } },+ }),+ ).rejects.toThrow(/existing claude-code provider headers cannot be decrypted/);+ expect(headers.get('claude-code')).toBe(UNRECOVERABLE_PROVIDER_CREDENTIAL);+ expect(removeCustomProviderHeaders).not.toHaveBeenCalled();++ // 显式回传新 headers:允许覆盖。+ await expect(+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {+ ...config,+ runtimes: { 'claude-code': { ...runtime, headers: { Authorization: 'Bearer new' } } },+ }),+ ).resolves.toEqual({ ok: true });+ expect(headers.get('claude-code')).toEqual({ Authorization: 'Bearer new' });+ expect(storeCustomProviderHeaders).toHaveBeenCalledOnce();+ expect(removeCustomProviderHeaders).not.toHaveBeenCalled();+ });+it('serializes create key staging with a later cross-window update', 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.tsindex 5a7e714881..7a11419d84 100644--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts@@ -56,6 +56,7 @@ import {} from '../../shared/providerModelRefresh.js';import { createLogger } from '../logger.js';+import type { UnrecoverableProviderCredential } from '../secrets/providerSecretStore.js';import { throwIpcError } from '../utils/ipcValidate.js';import {createCustomProvider,@@ -312,10 +313,14 @@ export interface ProviderHandlerDeps {*/removeOAuthCredentials(providerId: string): (() => boolean) | null;/**- * 自定义 provider API key 的严格快照读取:不存在返回 null,不可解密 / 不可读时抛错。+ * 自定义 provider API key 的严格快照读取:不存在返回 null,密文存在但解不开返回+ * UNRECOVERABLE_PROVIDER_CREDENTIAL,暂时不可读(owner / 加密不可用、文件读取失败)时抛错。* 与配置 CRUD 共用 per-provider mutation queue。*/- readCustomProviderKeyForMutation(providerId: string, agent: AgentKind): string | null;+ readCustomProviderKeyForMutation(+ providerId: string,+ agent: AgentKind,+ ): string | null | UnrecoverableProviderCredential;storeCustomProviderKey(providerId: string, agent: AgentKind, value: string): boolean;removeCustomProviderKey(providerId: string,@@ -325,7 +330,7 @@ export interface ProviderHandlerDeps {readCustomProviderHeadersForMutation(providerId: string,agent: AgentKind,- ): Record<string, string> | null;+ ): Record<string, string> | null | UnrecoverableProviderCredential;storeCustomProviderHeaders(providerId: string,agent: AgentKind,@@ -646,7 +651,10 @@ export function registerProviderHandlers(finishRouteMutation();}};- type KeySnapshot = { agent: AgentKind; previous: string | null };+ type KeySnapshot = {+ agent: AgentKind;+ previous: string | null | UnrecoverableProviderCredential;+ };type KeyMutation = { agent: AgentKind; replacement: string | null };// Stored API keys and main-only credential headers are endpoint-bound. If a runtime moves to a// different base/models URL without an explicit replacement, clear the old secret atomically.@@ -667,7 +675,8 @@ export function registerProviderHandlers(const restoreProviderKeys = (providerId: string, snapshots: readonly KeySnapshot[]): boolean => {let restored = true;for (const { agent, previous } of [...snapshots].reverse()) {- if (previous !== null) {+ // 旧密文解不开的 runtime 没有可恢复的值:回滚 = 删掉本次写入的新值,不碰旧 blob。+ if (typeof previous === 'string') {if (!deps.storeCustomProviderKey(providerId, agent, previous)) restored = false;} else if (!deps.removeCustomProviderKey(providerId, agent).success) {restored = false;@@ -714,7 +723,7 @@ export function registerProviderHandlers(mutations: readonly KeyMutation[],): KeyMutation[] =>mutations.filter((mutation) => {- let previous: string | null;+ let previous: string | null | UnrecoverableProviderCredential;try {previous = deps.readCustomProviderKeyForMutation(providerId, mutation.agent);} catch {@@ -730,13 +739,23 @@ export function registerProviderHandlers(const snapshots: KeySnapshot[] = [];try {for (const { agent, replacement } of mutations) {- let previous: string | null;+ let previous: string | null | UnrecoverableProviderCredential;try {previous = deps.readCustomProviderKeyForMutation(providerId, agent);} catch {throwIpcError('INTERNAL', `failed to read existing ${agent} provider credential`);}- snapshots.push({ agent, previous });+ const unrecoverable = typeof previous === 'symbol';+ // 旧密文存在但解不开:只有本次带了显式替换值才允许覆盖它。保留旧值、仅删除、+ // 端点变更清理、删除整个 provider 这些语义拿不到可回滚的快照,维持严格失败且+ // 不碰那份 blob(#3821)。文案对 update 与 delete 两条路径都成立。+ if (unrecoverable && replacement === null) {+ throwIpcError(+ 'INTERNAL',+ `existing ${agent} provider credential cannot be decrypted; enter a new API key to replace it first`,+ );+ }+ if (!unrecoverable) snapshots.push({ agent, previous });const succeeded =replacement === null? deps.removeCustomProviderKey(providerId, agent).success@@ -744,6 +763,8 @@ export function registerProviderHandlers(if (!succeeded) {throwIpcError('INTERNAL', `failed to update ${agent} provider credential`);}+ // 覆盖成功后才登记不可恢复快照:回滚语义是删掉新值;写入失败时旧文件原样保留。+ if (unrecoverable) snapshots.push({ agent, previous });}return snapshots;} catch (error) {@@ -756,7 +777,7 @@ export function registerProviderHandlers(};type HeaderSnapshot = {agent: AgentKind;- previous: Record<string, string> | null;+ previous: Record<string, string> | null | UnrecoverableProviderCredential;};type HeaderMutation = {agent: AgentKind;@@ -768,7 +789,8 @@ export function registerProviderHandlers(): boolean => {let restored = true;for (const { agent, previous } of [...snapshots].reverse()) {- if (previous) {+ // 与 restoreProviderKeys 同口径:解不开的旧密文头没有可恢复的值,回滚只删新值。+ if (previous && typeof previous === 'object') {if (!deps.storeCustomProviderHeaders(providerId, agent, previous)) restored = false;} else if (!deps.removeCustomProviderHeaders(providerId, agent).success) {restored = false;@@ -839,13 +861,13 @@ export function registerProviderHandlers(mutations: readonly HeaderMutation[],): HeaderMutation[] =>mutations.filter((mutation) => {- let previous: Record<string, string> | null;+ let previous: Record<string, string> | null | UnrecoverableProviderCredential;try {previous = deps.readCustomProviderHeadersForMutation(providerId, mutation.agent);} catch {throwIpcError('INTERNAL', `failed to read existing ${mutation.agent} provider headers`);}- return !providerHeadersEqual(previous, mutation.replacement);+ return typeof previous === 'symbol' || !providerHeadersEqual(previous, mutation.replacement);});const stageProviderHeaders = (providerId: string,@@ -855,19 +877,28 @@ export function registerProviderHandlers(const snapshots: HeaderSnapshot[] = [];try {for (const { agent, replacement } of mutations) {- let previous: Record<string, string> | null;+ let previous: Record<string, string> | null | UnrecoverableProviderCredential;try {previous = deps.readCustomProviderHeadersForMutation(providerId, agent);} catch {throwIpcError('INTERNAL', `failed to read existing ${agent} provider headers`);}- snapshots.push({ agent, previous });+ const unrecoverable = typeof previous === 'symbol';+ // 与 stageProviderKeys 同口径:解不开的旧密文头只能被显式新 headers 覆盖。+ if (unrecoverable && !replacement) {+ throwIpcError(+ 'INTERNAL',+ `existing ${agent} provider headers cannot be decrypted; enter new headers to replace them first`,+ );+ }+ if (!unrecoverable) 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`);}+ if (unrecoverable) snapshots.push({ agent, previous });}return snapshots;} catch (error) {@@ -1754,10 +1785,12 @@ export function registerProviderHandlers(parsed.modelsUrl = savedRoute.modelsUrl;let storedHeaders: Record<string, string> | null = null;try {- storedHeaders = deps.readCustomProviderHeadersForMutation(+ const snapshot = deps.readCustomProviderHeadersForMutation(parsed.savedProviderId,parsed.agent,);+ // 解不开的旧密文头与读失败同样处理:不注入任何已存头。+ storedHeaders = typeof snapshot === 'symbol' ? null : snapshot;} catch {storedHeaders = null;}diff --git a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.tsindex 5cc9fdb551..1c8808b995 100644--- a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts+++ b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts@@ -1,3 +1,7 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { describe, it, expect, vi, beforeEach } from 'vitest';const sessionState = vi.hoisted(() => ({@@ -8,12 +12,19 @@ const sessionState = vi.hoisted(() => ({// providerSecretStore 顶层 `import { app, safeStorage } from 'electron'` —— 这些测试// 注入自己的 SecretStorageIo,不会走默认 electronSecretIo,因此 electron mock 只为// 让 import 链在 node 测试环境下可加载(app.getPath 给个 tmp 目录即可)。+// 严格快照用例走真实 fs + safeStorage 分支,通过 electronState 切换目录与解密结果。+const electronState = vi.hoisted(() => ({+ userData: '/tmp/xdt-provider-secret-test',+ encryptionAvailable: false,+ decryptString: (): string => '',+}));+vi.mock('electron', () => ({- app: { getPath: () => '/tmp/xdt-provider-secret-test' },+ app: { getPath: () => electronState.userData },safeStorage: {- isEncryptionAvailable: () => false,+ isEncryptionAvailable: () => electronState.encryptionAvailable,encryptString: () => Buffer.from(''),- decryptString: () => '',+ decryptString: () => electronState.decryptString(),},}));@@ -34,10 +45,13 @@ vi.mock('../../appSessionState', () => ({import {createProviderSecretStore,+ readCustomProviderHeadersForMutation,readCustomProviderKeyForMutation,readGhostSecretStrict,readGhostSecretTailFromIo,+ resolveOwnerScopedSecretStorageKey,setProviderSecretsClearedListener,+ UNRECOVERABLE_PROVIDER_CREDENTIAL,type SecretStorageIo,} from '../providerSecretStore';import {@@ -184,6 +198,61 @@ describe('providerSecrets registry', () => {}});+ it('strict custom-provider snapshot reports ciphertext that exists but cannot be decrypted', () => {+ const previousMode = sessionState.mode;+ const previousOwnerId = sessionState.dataOwnerId;+ const previousElectron = { ...electronState };+ const userData = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-provider-secret-'));+ const ownerId = 'undecryptable-owner';+ const providerId = 'undecryptable-provider';+ sessionState.mode = 'cloud';+ sessionState.dataOwnerId = ownerId;+ electronState.userData = userData;+ electronState.encryptionAvailable = true;+ electronState.decryptString = () => {+ throw new Error('Error while decrypting the ciphertext provided to safeStorage.decryptString.');+ };+ try {+ const secretDir = path.join(userData, 'safe-storage');+ fs.mkdirSync(secretDir, { recursive: true });+ const garbage = Buffer.from('not-a-safe-storage-blob').toString('base64');+ for (const logicalKey of [+ customProviderSecretStorageKey(providerId, 'codex'),+ customProviderHeaderStorageKey(providerId, 'codex'),+ ]) {+ const scopedKey = resolveOwnerScopedSecretStorageKey(logicalKey);+ if (!scopedKey) throw new Error('test owner session is not scoped');+ fs.writeFileSync(path.join(secretDir, `${scopedKey}.enc`), garbage, 'utf-8');+ }++ // 密文存在但解不开:第三态,而不是抛错(#3821)。+ expect(readCustomProviderKeyForMutation(providerId, 'codex')).toBe(+ UNRECOVERABLE_PROVIDER_CREDENTIAL,+ );+ expect(readCustomProviderHeadersForMutation(providerId, 'codex')).toBe(+ UNRECOVERABLE_PROVIDER_CREDENTIAL,+ );+ // 解得开但不是合法头 map:同样是内容层面的永久损坏。+ electronState.decryptString = () => '["not","an","object"]';+ expect(readCustomProviderHeadersForMutation(providerId, 'codex')).toBe(+ UNRECOVERABLE_PROVIDER_CREDENTIAL,+ );+ // 文件在、但 safeStorage 暂时不可用:仍然抛错,不能当成可覆盖。+ electronState.encryptionAvailable = false;+ expect(() => readCustomProviderKeyForMutation(providerId, 'codex')).toThrow(+ /encryption is unavailable/,+ );+ expect(() => readCustomProviderHeadersForMutation(providerId, 'codex')).toThrow(+ /encryption is unavailable/,+ );+ } finally {+ sessionState.mode = previousMode;+ sessionState.dataOwnerId = previousOwnerId;+ Object.assign(electronState, previousElectron);+ fs.rmSync(userData, { recursive: true, force: true });+ }+ });+it('strict Ghost reconciliation treats a missing file as absent when encryption is unavailable', () => {const previousMode = sessionState.mode;const previousOwnerId = sessionState.dataOwnerId;diff --git a/apps/desktop/src/main/secrets/providerSecretStore.ts b/apps/desktop/src/main/secrets/providerSecretStore.tsindex d6b6f74327..dc3b48bc8d 100644--- a/apps/desktop/src/main/secrets/providerSecretStore.ts+++ b/apps/desktop/src/main/secrets/providerSecretStore.ts@@ -434,15 +434,24 @@ export function readCustomProviderHeaders(}}+/**+ * 严格快照的第三态:密文文件存在,但用当前 safeStorage 主密钥解不开(钥匙串条目变更、+ * 由另一签名 / 构建写入等,见 #871)。重试无意义,只有显式替换值才允许覆盖它;回滚时+ * 不尝试恢复这份旧 blob,而是删掉本次写入的新值(#3821)。+ */+export const UNRECOVERABLE_PROVIDER_CREDENTIAL = Symbol('unrecoverable-provider-credential');+export type UnrecoverableProviderCredential = typeof UNRECOVERABLE_PROVIDER_CREDENTIAL;+/*** 配置 CRUD 回滚前的严格 API key 快照读取。- * 仅 ENOENT 表示“没有旧 key”;owner / 加密不可用、文件读取或解密失败都必须抛错,- * 防止调用方把暂时不可读的现有凭证误判为空并永久删除。+ * 仅 ENOENT 表示“没有旧 key”;密文存在但解不开返回 UNRECOVERABLE_PROVIDER_CREDENTIAL;+ * owner / 加密不可用、文件读取失败都必须抛错,防止调用方把暂时不可读的现有凭证误判为空+ * 并永久删除。*/export function readCustomProviderKeyForMutation(providerId: string,agent: string,-): string | null {+): string | null | UnrecoverableProviderCredential {const logicalKey = customProviderSecretStorageKey(providerId, agent);const scopedKey = resolveOwnerScopedSecretStorageKey(logicalKey);if (!scopedKey) throw new Error('provider secret owner is unavailable');@@ -469,15 +478,19 @@ export function readCustomProviderKeyForMutation({ providerId, agent, err: err instanceof Error ? err.message : String(err) },'decrypt custom provider key snapshot failed',);- throw new Error('existing provider credential is unreadable');+ return UNRECOVERABLE_PROVIDER_CREDENTIAL;}}-/** Strict mutation snapshot for an encrypted runtime header blob. */+/**+ * Strict mutation snapshot for an encrypted runtime header blob. Same three states as+ * readCustomProviderKeyForMutation: a blob that exists but cannot be decrypted (or parsed)+ * is reported as UNRECOVERABLE_PROVIDER_CREDENTIAL instead of thrown.+ */export function readCustomProviderHeadersForMutation(providerId: string,agent: string,-): Record<string, string> | null {+): Record<string, string> | null | UnrecoverableProviderCredential {const logicalKey = customProviderHeaderStorageKey(providerId, agent);const scopedKey = resolveOwnerScopedSecretStorageKey(logicalKey);if (!scopedKey) throw new Error('provider secret owner is unavailable');@@ -500,7 +513,7 @@ export function readCustomProviderHeadersForMutation({ 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');+ return UNRECOVERABLE_PROVIDER_CREDENTIAL;}}