Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(providers): R9-Verdrahtung, verdraengter API-Schluessel geht in den Schluesselbund

purpled04f7719b502
diff --git a/src/api/__tests__/secret-park-commands.test.ts b/src/api/__tests__/secret-park-commands.test.ts
new file mode 100644
index 00000000..75f6a163
--- /dev/null
+++ b/src/api/__tests__/secret-park-commands.test.ts
@@ -0,0 +1,102 @@
+/**
+ * R9 (3.0.1): the JS-side contract for the three new keychain commands
+ * (`secret_park_set`/`_get`/`_delete`, src-tauri/src/commands/secret.rs). Mocks
+ * `@tauri-apps/api/core`'s `invoke` directly, same pattern as
+ * local-fetch-cancel.test.ts, one level below providerStore.keychain.test.ts's
+ * mock of the whole `api/backend` module.
+ *
+ * Run: npx vitest run src/api/__tests__/secret-park-commands.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+const invokeMock = vi.fn()
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: (...args: unknown[]) => invokeMock(...args),
+}))
+
+import { secretParkSet, secretParkGet, secretParkDelete } from '../backend'
+import { isRecord } from '../../types/json-guards'
+
+function tauriMode(on: boolean) {
+ const existing: unknown = Reflect.get(globalThis, 'window')
+ const w: Record<string, unknown> = isRecord(existing) ? existing : {}
+ Reflect.set(globalThis, 'window', w)
+ if (on) w.__TAURI_INTERNALS__ = {}
+ else { delete w.__TAURI_INTERNALS__; delete w.__TAURI__ }
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ tauriMode(true)
+})
+
+afterEach(() => {
+ tauriMode(false)
+})
+
+describe('secretParkSet', () => {
+ it('calls secret_park_set with backendId (camelCase) and value', async () => {
+ invokeMock.mockResolvedValue(undefined)
+ await secretParkSet('lm-studio', 'sk-secret-value')
+ expect(invokeMock).toHaveBeenCalledWith('secret_park_set', { backendId: 'lm-studio', value: 'sk-secret-value' })
+ })
+
+ it('rejects with "keychain unavailable" on the web build, without calling invoke', async () => {
+ tauriMode(false)
+ await expect(secretParkSet('lm-studio', 'sk-secret-value')).rejects.toThrow(/keychain unavailable/)
+ expect(invokeMock).not.toHaveBeenCalled()
+ })
+
+ it('propagates a Rust refusal untouched (never rewrites the error text)', async () => {
+ invokeMock.mockRejectedValue(new Error('refused: invalid backend id'))
+ await expect(secretParkSet('BAD ID', 'sk-secret-value')).rejects.toThrow(/refused:/)
+ })
+})
+
+describe('secretParkGet', () => {
+ it('calls secret_park_get with backendId and returns the value', async () => {
+ invokeMock.mockResolvedValue('sk-restored-value')
+ const value = await secretParkGet('lm-studio')
+ expect(invokeMock).toHaveBeenCalledWith('secret_park_get', { backendId: 'lm-studio' })
+ expect(value).toBe('sk-restored-value')
+ })
+
+ it('returns null when nothing was parked', async () => {
+ invokeMock.mockResolvedValue(null)
+ expect(await secretParkGet('jan')).toBeNull()
+ })
+
+ it('rejects with "keychain unavailable" on the web build, without calling invoke', async () => {
+ tauriMode(false)
+ await expect(secretParkGet('lm-studio')).rejects.toThrow(/keychain unavailable/)
+ expect(invokeMock).not.toHaveBeenCalled()
+ })
+})
+
+describe('secretParkDelete', () => {
+ it('calls secret_park_delete with backendId', async () => {
+ invokeMock.mockResolvedValue(undefined)
+ await secretParkDelete('lm-studio')
+ expect(invokeMock).toHaveBeenCalledWith('secret_park_delete', { backendId: 'lm-studio' })
+ })
+
+ it('rejects with "keychain unavailable" on the web build, without calling invoke', async () => {
+ tauriMode(false)
+ await expect(secretParkDelete('lm-studio')).rejects.toThrow(/keychain unavailable/)
+ expect(invokeMock).not.toHaveBeenCalled()
+ })
+})
+
+describe('NEGATIVE CONTROL: the three commands stay on their own namespace', () => {
+ it('never calls the plain secret_set/get/delete commands used by the four fixed slots', async () => {
+ invokeMock.mockResolvedValue(null)
+ await secretParkSet('lm-studio', 'x').catch(() => {})
+ await secretParkGet('lm-studio').catch(() => {})
+ await secretParkDelete('lm-studio').catch(() => {})
+ const calledCommands = invokeMock.mock.calls.map((c) => c[0])
+ expect(calledCommands).toEqual(['secret_park_set', 'secret_park_get', 'secret_park_delete'])
+ expect(calledCommands).not.toContain('secret_set')
+ expect(calledCommands).not.toContain('secret_get')
+ expect(calledCommands).not.toContain('secret_delete')
+ })
+})
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 1b000938..acd6987b 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -815,6 +815,35 @@ export async function secretDelete(account: string): Promise<void> {
await invoke('secret_delete', { account })
}
+// ── Parked provider key keychain (R9) ────────────────────────────
+// Same vault as secretSet/Get/Delete above, but a second, narrower namespace
+// (Rust: PARKED_PREFIX "parked-key:") for a backend that is NOT one of the
+// four fixed provider slots, e.g. an OpenAI-compatible backend the shared
+// `openai` slot just displaced. `backendId` must already be a valid slug
+// ([a-z0-9-]{1,64}, see lib/parked-key.ts) before it reaches here; an
+// invalid one is rejected on the Rust side with an error starting
+// "refused:", which never echoes the id or the value, and is a caller bug,
+// not a "no keychain here" signal (that is "keychain unavailable"/
+// "keychain unsupported", same two strings secretSet/Get/Delete's callers
+// already check for).
+export async function secretParkSet(backendId: string, value: string): Promise<void> {
+ if (!isTauri()) throw new Error('keychain unavailable (web build)')
+ const invoke = await getInvoke()
+ await invoke('secret_park_set', { backendId, value })
+}
+
+export async function secretParkGet(backendId: string): Promise<string | null> {
+ if (!isTauri()) throw new Error('keychain unavailable (web build)')
+ const invoke = await getInvoke()
+ return (await invoke('secret_park_get', { backendId })) as string | null
+}
+
+export async function secretParkDelete(backendId: string): Promise<void> {
+ if (!isTauri()) throw new Error('keychain unavailable (web build)')
+ const invoke = await getInvoke()
+ await invoke('secret_park_delete', { backendId })
+}
+
// OAuth loopback (LU Cloud Google/GitHub login): bind a 127.0.0.1 port from
// the fixed ladder, then await the browser round-trip. Rust side single-shots
// the accept; the returned string is the raw callback query (code=… / error=…).
diff --git a/src/components/settings/ProviderConfig.tsx b/src/components/settings/ProviderConfig.tsx
index b9fcb818..f8fd33d6 100644
--- a/src/components/settings/ProviderConfig.tsx
+++ b/src/components/settings/ProviderConfig.tsx
@@ -23,6 +23,7 @@ import { reachVerdict, liveSlotStatus, type SlotStatus } from '../../lib/builtin
import type { ProviderId, ProviderConfig } from '../../api/providers/types'
import { disabledSlotNote } from '../../lib/disabled-slot-note'
import { HINWEIS_TEXT, PUNKT_FARBE } from '../../lib/hinweis'
+import { parkApiKeyForBackend, restoreParkedApiKeyForBackend } from '../../lib/parked-key'
const isTauri = typeof window !== 'undefined' && !!window.__TAURI_INTERNALS__
@@ -244,18 +245,23 @@ export function ProviderSettings() {
run()
}
- // Opus-Review Nachbesserung 6 (3.0.1, F3): every path below that hands the
- // shared `openai` slot to a REMEMBERED backend (Remove on the occupant,
- // Enable on the standby card, Disable swapping it back in) must restore
- // that backend's own parked key too, not just its name/URL. Through
+ // Opus-Review Nachbesserung 6 (3.0.1, F3) + R9: every path below that hands
+ // the shared `openai` slot to a REMEMBERED backend (Remove on the
+ // occupant, Enable on the standby card, Disable swapping it back in) must
+ // restore that backend's own key too, not just its name/URL. R9's OS
+ // keychain (secret_park_get, via restoreParkedApiKeyForBackend) is tried
+ // FIRST, since a key parked there survives an app restart; `displaced.
+ // apiKey` (F3, session-only) is the fallback for a device with no
+ // keychain, or a `displaced` record written before R9 existed. Through
// setProviderApiKey, not a plain field merge: that is the call that keeps
// the OS keychain in step with the store, and it has to run AFTER
// setProviderConfig so it is the last word on `openai`'s key field. No
- // parked key (an older `displaced` record, written before this fix, or a
- // backend that never had one) clears it instead of leaving the key of
- // whichever backend just left sitting there under a new name.
- function restoreParkedApiKey(parkedObfuscated: string | undefined) {
- setProviderApiKey('openai', parkedObfuscated !== undefined ? deobfuscate(parkedObfuscated) : '')
+ // parked key anywhere (a backend that never had one) clears it instead of
+ // leaving the key of whichever backend just left sitting there under a
+ // new name.
+ async function restoreParkedApiKey(backendName: string | undefined, parkedObfuscated: string | undefined) {
+ const fromKeychain = backendName ? await restoreParkedApiKeyForBackend(backendName) : null
+ setProviderApiKey('openai', fromKeychain !== null ? fromKeychain : (parkedObfuscated !== undefined ? deobfuscate(parkedObfuscated) : ''))
}
// Remove on the backend that holds the shared local slot: the slot goes back
@@ -263,12 +269,12 @@ export function ProviderSettings() {
// instead of parked on standby. Offered only where `displaced` knows a state
// to return to, so the app's own engine and the three other slots have no
// Remove at all.
- function removeOccupant() {
+ async function removeOccupant() {
const update = slotRemoveOccupantUpdate(providers.openai)
if (!update) return
- const parked = providers.openai.displaced?.apiKey
+ const displaced = providers.openai.displaced
setProviderConfig('openai', update)
- restoreParkedApiKey(parked)
+ await restoreParkedApiKey(displaced?.name, displaced?.apiKey)
setStatuses(prev => ({ ...prev, openai: 'idle' }))
setExpandedProvider('openai')
}
@@ -285,39 +291,41 @@ export function ProviderSettings() {
// Reset button has for this one slot, without resetting anything else, and
// it swaps rather than forgets: the backend now leaving the slot takes the
// standby card in its turn.
- function handBackSlot() {
+ async function handBackSlot() {
const update = slotHandbackUpdate(providers.openai)
if (!update) return
- const parked = providers.openai.displaced?.apiKey
+ const displaced = providers.openai.displaced
setProviderConfig('openai', update)
- restoreParkedApiKey(parked)
+ await restoreParkedApiKey(displaced?.name, displaced?.apiKey)
setStatuses(prev => ({ ...prev, openai: 'idle' }))
setExpandedProvider('openai')
}
- // Review-Runde 2, Punkt 5: whether accepting `preset` into the shared
- // `openai` slot would destroy a currently-set, non-empty API key with no
- // way to bring it back. The displaced key only survives in
- // `displaced.apiKey` for the running session (F3 Nachbesserung 6); a
- // restart between takeover and handback still loses it, because the OS
- // keychain layer (src-tauri/src/commands/secret.rs) only accepts a fixed,
- // exact-match set of account names and refuses a synthetic per-backend
- // "parked key" entry by design. Told up front, so the loss is a choice
- // made with eyes open instead of a 401 the next time the backend returns.
- function wouldLoseApiKeyOnRestart(preset: typeof PROVIDER_PRESETS[0]): boolean {
+ // Review-Runde 2, Punkt 5 (F3) + R9: whether accepting `preset` into the
+ // shared `openai` slot would destroy a currently-set, non-empty API key
+ // with no way to bring it back. R9 tries to prevent that outright: the
+ // outgoing key is parked in the OS keychain (parkApiKeyForBackend,
+ // survives an app restart) before this function answers, and only a
+ // FAILED park still counts as a loss, e.g. no keychain on this device
+ // (Linux, or the LU_NO_KEYCHAIN test switch), in which case F3's warning
+ // card is shown so the loss is a choice made with eyes open instead of a
+ // 401 the next time the backend returns.
+ async function wouldLoseApiKeyOnRestart(preset: typeof PROVIDER_PRESETS[0]): Promise<boolean> {
if (preset.providerId === 'ollama' || preset.providerId === 'anthropic') return false
const incoming = { name: preset.name, baseUrl: preset.baseUrl, isLocal: preset.isLocal, managed: preset.managed }
- return takeoverClearsApiKey(providers.openai, incoming) && getProviderApiKey('openai') !== ''
+ if (!(takeoverClearsApiKey(providers.openai, incoming) && getProviderApiKey('openai') !== '')) return false
+ const parked = await parkApiKeyForBackend(providers.openai.name, getProviderApiKey('openai'))
+ return !parked
}
// Add a preset (enable a provider without disabling others)
- function selectPreset(preset: typeof PROVIDER_PRESETS[0]) {
+ async function selectPreset(preset: typeof PROVIDER_PRESETS[0]) {
if (!preset.isLocal) {
setPendingPreset(preset)
setShowCloudWarning(true)
return
}
- if (wouldLoseApiKeyOnRestart(preset)) {
+ if (await wouldLoseApiKeyOnRestart(preset)) {
setPendingPreset(preset)
setShowKeyLossWarning(true)
return
@@ -383,9 +391,9 @@ export function ProviderSettings() {
if (!nextEnabled && id === 'openai') {
const handback = slotDisableOccupantUpdate(providers.openai)
if (handback) {
- const parked = providers.openai.displaced?.apiKey
+ const displaced = providers.openai.displaced
setProviderConfig('openai', handback)
- restoreParkedApiKey(parked)
+ void restoreParkedApiKey(displaced?.name, displaced?.apiKey)
setStatuses(prev => ({ ...prev, openai: 'idle' }))
return
}
@@ -850,12 +858,14 @@ export function ProviderSettings() {
<button
onClick={() => {
setShowCloudWarning(false)
- if (pendingPreset && wouldLoseApiKeyOnRestart(pendingPreset)) {
- setShowKeyLossWarning(true)
- return
- }
- if (pendingPreset) applyPreset(pendingPreset)
- setPendingPreset(null)
+ void (async () => {
+ if (pendingPreset && await wouldLoseApiKeyOnRestart(pendingPreset)) {
+ setShowKeyLossWarning(true)
+ return
+ }
+ if (pendingPreset) applyPreset(pendingPreset)
+ setPendingPreset(null)
+ })()
}}
className="px-4 py-1.5 rounded-lg text-[0.7rem] font-medium bg-white/5 border border-white/10 text-gray-300 hover:bg-white/10 transition-colors"
>
@@ -865,12 +875,15 @@ export function ProviderSettings() {
</div>
</Modal>
- {/* Review-Runde 2, Punkt 5: standby key not surviving a restart */}
+ {/* Review-Runde 2, Punkt 5: standby key not surviving a restart. Only
+ reached now (R9) when parkApiKeyForBackend already tried and
+ failed to place the key in the OS keychain, so it stays accurate:
+ this device really has nowhere durable to keep it. */}
<Modal open={showKeyLossWarning} onClose={() => { setShowKeyLossWarning(false); setPendingPreset(null) }} title="">
<div className="space-y-4 text-center" data-testid="key-loss-warning-modal">
<h3 className="text-base font-semibold text-white">API Key Will Be Lost</h3>
<p className="t-control text-gray-400 leading-relaxed">
- The current OpenAI-compatible backend has an API key set. Switching backends clears it from this slot, and it will NOT survive an app restart while parked.
+ The current OpenAI-compatible backend has an API key set, and this device has no OS keychain LU could safely park it in. Switching backends clears it from this slot, and it will NOT survive an app restart while parked.
</p>
<p className="t-control text-gray-400 leading-relaxed">
If you switch back to this backend later, you will need to enter the key again.
diff --git a/src/lib/__tests__/builtin-card-survives-add-provider.test.ts b/src/lib/__tests__/builtin-card-survives-add-provider.test.ts
index 6a7d2aaa..52c792b0 100644
--- a/src/lib/__tests__/builtin-card-survives-add-provider.test.ts
+++ b/src/lib/__tests__/builtin-card-survives-add-provider.test.ts
@@ -242,66 +242,74 @@ describe('the wiring, so the rule reaches the screen', () => {
expect(pane.slice(start, end)).not.toMatch(/[–—]/)
})
- // Opus-Review Nachbesserung 6 (3.0.1, F3): Enable on the standby card used
- // to come back with no key and a silent 401, the slot's name/URL were
+ // Opus-Review Nachbesserung 6 (3.0.1, F3) + R9: Enable on the standby card
+ // used to come back with no key and a silent 401, the slot's name/URL were
// restored through slotHandbackUpdate, but nothing ever restored the
// parked backend's own apiKey. Every path that hands the slot to a
- // REMEMBERED backend must read `displaced.apiKey` and push it through
- // setProviderApiKey (store + keychain), not just merge the plain patch.
+ // REMEMBERED backend must read `displaced` (its name, for R9's keychain
+ // lookup, and its apiKey, for F3's session-only fallback) and push the
+ // result through setProviderApiKey (store + keychain), not just merge the
+ // plain patch.
it('handBackSlot restores the parked key through setProviderApiKey, not a plain merge', () => {
const start = pane.indexOf('function handBackSlot()')
const end = pane.indexOf('\n }', start)
const body = pane.slice(start, end)
- expect(body).toMatch(/const parked = providers\.openai\.displaced\?\.apiKey/)
- expect(body).toMatch(/restoreParkedApiKey\(parked\)/)
- // Reads the parked value BEFORE overwriting `providers.openai` with the
- // handback patch, read-after-write here would read the NEW (wrong) slot.
- expect(body.indexOf('const parked')).toBeLessThan(body.indexOf("setProviderConfig('openai', update)"))
+ expect(body).toMatch(/const displaced = providers\.openai\.displaced/)
+ expect(body).toMatch(/restoreParkedApiKey\(displaced\?\.name, displaced\?\.apiKey\)/)
+ // Reads the displaced record BEFORE overwriting `providers.openai` with
+ // the handback patch, read-after-write here would read the NEW (wrong) slot.
+ expect(body.indexOf('const displaced')).toBeLessThan(body.indexOf("setProviderConfig('openai', update)"))
})
it('removeOccupant restores the parked key too, same as Enable on standby', () => {
- const start = pane.indexOf('function removeOccupant()')
+ const start = pane.indexOf('async function removeOccupant()')
const end = pane.indexOf('\n }', start)
const body = pane.slice(start, end)
- expect(body).toMatch(/const parked = providers\.openai\.displaced\?\.apiKey/)
- expect(body).toMatch(/restoreParkedApiKey\(parked\)/)
+ expect(body).toMatch(/const displaced = providers\.openai\.displaced/)
+ expect(body).toMatch(/restoreParkedApiKey\(displaced\?\.name, displaced\?\.apiKey\)/)
})
it('Disable swapping the built-in engine back in restores the parked key too', () => {
const start = pane.indexOf('const handback = slotDisableOccupantUpdate(providers.openai)')
const end = pane.indexOf('\n }', start)
const body = pane.slice(start, end)
- expect(body).toMatch(/const parked = providers\.openai\.displaced\?\.apiKey/)
- expect(body).toMatch(/restoreParkedApiKey\(parked\)/)
+ expect(body).toMatch(/const displaced = providers\.openai\.displaced/)
+ expect(body).toMatch(/restoreParkedApiKey\(displaced\?\.name, displaced\?\.apiKey\)/)
})
- it('restoreParkedApiKey decodes the parked value and clears when nothing was parked', () => {
- const start = pane.indexOf('function restoreParkedApiKey(')
+ // R9: the OS keychain (restoreParkedApiKeyForBackend) is tried before the
+ // F3 session-only fallback, so a key parked before a restart still comes
+ // back on a device with a keychain; only an empty keychain answer falls
+ // through to `parkedObfuscated`.
+ it('restoreParkedApiKey tries the keychain first and falls back to the parked session value', () => {
+ const start = pane.indexOf('async function restoreParkedApiKey(')
const end = pane.indexOf('\n }', start)
const body = pane.slice(start, end)
- expect(body).toMatch(/setProviderApiKey\('openai', parkedObfuscated !== undefined \? deobfuscate\(parkedObfuscated\) : ''\)/)
+ expect(body).toMatch(/restoreParkedApiKeyForBackend\(backendName\)/)
+ expect(body).toMatch(/setProviderApiKey\('openai', fromKeychain !== null \? fromKeychain : \(parkedObfuscated !== undefined \? deobfuscate\(parkedObfuscated\) : ''\)\)/)
})
- // Review-Runde 2, Punkt 5: displaced.apiKey only survives in memory for the
- // running session (Nachbesserung 6). The OS keychain layer
- // (src-tauri/src/commands/secret.rs) enforces a fixed, exact-match account
- // allowlist and refuses a synthetic "parked key" entry, so a restart
- // between takeover and handback still loses the displaced key. Since a
- // durable per-backend keychain entry needs a Rust change out of scope
- // here, the takeover instead warns before it happens.
- it('a takeover that would clear a non-empty key is guarded before it runs', () => {
- const start = pane.indexOf('function wouldLoseApiKeyOnRestart(')
+ // Review-Runde 2, Punkt 5 (F3) + R9: F3's `displaced.apiKey` only survives
+ // in memory for the running session, and R9 gives it a durable place to go
+ // instead, the OS keychain (parked-key: namespace, secret.rs). Only when
+ // that park attempt itself fails, no keychain on this device, does the
+ // takeover still warn before it happens; on a device that has one, this
+ // no longer counts as a loss.
+ it('a takeover that would clear a non-empty key tries to park it, and only warns if that fails', () => {
+ const start = pane.indexOf('async function wouldLoseApiKeyOnRestart(')
const end = pane.indexOf('\n }', start)
const body = pane.slice(start, end)
expect(body).toMatch(/takeoverClearsApiKey\(providers\.openai, incoming\)/)
expect(body).toMatch(/getProviderApiKey\('openai'\) !== ''/)
+ expect(body).toMatch(/parkApiKeyForBackend\(providers\.openai\.name, getProviderApiKey\('openai'\)\)/)
+ expect(body).toMatch(/return !parked/)
})
it('selectPreset asks before a local preset takeover that would lose the key', () => {
- const start = pane.indexOf('function selectPreset(')
+ const start = pane.indexOf('async function selectPreset(')
const end = pane.indexOf('\n }', start)
const body = pane.slice(start, end)
- expect(body).toMatch(/if \(wouldLoseApiKeyOnRestart\(preset\)\)/)
+ expect(body).toMatch(/if \(await wouldLoseApiKeyOnRestart\(preset\)\)/)
expect(body).toMatch(/setShowKeyLossWarning\(true\)/)
})
@@ -311,7 +319,7 @@ describe('the wiring, so the rule reaches the screen', () => {
expect(cloudModalStart).toBeGreaterThan(-1)
expect(keyLossModalStart).toBeGreaterThan(cloudModalStart)
const between = pane.slice(cloudModalStart, keyLossModalStart)
- expect(between).toMatch(/if \(pendingPreset && wouldLoseApiKeyOnRestart\(pendingPreset\)\)/)
+ expect(between).toMatch(/if \(pendingPreset && await wouldLoseApiKeyOnRestart\(pendingPreset\)\)/)
expect(between).toMatch(/setShowKeyLossWarning\(true\)/)
})
diff --git a/src/lib/__tests__/parked-key.test.ts b/src/lib/__tests__/parked-key.test.ts
new file mode 100644
index 00000000..20284824
--- /dev/null
+++ b/src/lib/__tests__/parked-key.test.ts
@@ -0,0 +1,151 @@
+// R9 (3.0.1): parking a displaced OpenAI-compatible API key in the OS
+// keychain so it survives an app restart, instead of only the session-only
+// `displaced.apiKey` field F3 built. Mocks `invoke` at the `api/backend`
+// boundary (secretParkSet/Get/Delete), the same layer providerStore.keychain.test.ts
+// mocks for the four fixed provider slots.
+//
+// Run: npx vitest run src/lib/__tests__/parked-key.test.ts
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const { secretParkSet, secretParkGet, secretParkDelete } = vi.hoisted(() => ({
+ secretParkSet: vi.fn(),
+ secretParkGet: vi.fn(),
+ secretParkDelete: vi.fn(),
+}))
+
+vi.mock('../../api/backend', () => ({ secretParkSet, secretParkGet, secretParkDelete }))
+
+import { slugifyBackendId, isKeychainMissing, parkApiKeyForBackend, restoreParkedApiKeyForBackend } from '../parked-key'
+
+beforeEach(() => {
+ secretParkSet.mockReset()
+ secretParkGet.mockReset()
+ secretParkDelete.mockReset()
+})
+
+describe('slugifyBackendId', () => {
+ it('lowercases a plain name into a valid backend id', () => {
+ expect(slugifyBackendId('LM Studio')).toBe('lm-studio')
+ })
+
+ it('collapses non [a-z0-9] runs into one hyphen and trims the ends', () => {
+ expect(slugifyBackendId(' My. Custom / Server!! ')).toBe('my-custom-server')
+ })
+
+ it('truncates to 64 characters', () => {
+ const long = 'a'.repeat(100)
+ const id = slugifyBackendId(long)
+ expect(id).not.toBeNull()
+ expect(id!.length).toBeLessThanOrEqual(64)
+ })
+
+ it('is null for a name with nothing sluggable', () => {
+ expect(slugifyBackendId('!!!')).toBeNull()
+ expect(slugifyBackendId('')).toBeNull()
+ })
+})
+
+describe('isKeychainMissing', () => {
+ it('recognises both stub/test-switch strings secret.rs can return', () => {
+ expect(isKeychainMissing(new Error('keychain unavailable (LU_NO_KEYCHAIN test mode)'))).toBe(true)
+ expect(isKeychainMissing(new Error('keychain unsupported on this platform'))).toBe(true)
+ })
+
+ it('does not treat a refused backend id as a missing keychain', () => {
+ expect(isKeychainMissing(new Error('refused: invalid backend id'))).toBe(false)
+ })
+})
+
+describe('parkApiKeyForBackend', () => {
+ it('parks the key under the slugified backend id and reports success', async () => {
+ secretParkSet.mockResolvedValue(undefined)
+ const ok = await parkApiKeyForBackend('LM Studio', 'sk-secret-value')
+ expect(ok).toBe(true)
+ expect(secretParkSet).toHaveBeenCalledWith('lm-studio', 'sk-secret-value')
+ })
+
+ it('reports failure, without throwing, when the keychain is unavailable', async () => {
+ secretParkSet.mockRejectedValue(new Error('keychain unavailable (web build)'))
+ const ok = await parkApiKeyForBackend('Jan', 'sk-secret-value')
+ expect(ok).toBe(false)
+ })
+
+ it('reports failure, without throwing, when the backend id is refused', async () => {
+ secretParkSet.mockRejectedValue(new Error('refused: invalid backend id'))
+ const ok = await parkApiKeyForBackend('Jan', 'sk-secret-value')
+ expect(ok).toBe(false)
+ })
+
+ it('does nothing when there is no key to park', async () => {
+ const ok = await parkApiKeyForBackend('Jan', '')
+ expect(ok).toBe(false)
+ expect(secretParkSet).not.toHaveBeenCalled()
+ })
+
+ it('does nothing when the name has no valid slug', async () => {
+ const ok = await parkApiKeyForBackend('!!!', 'sk-secret-value')
+ expect(ok).toBe(false)
+ expect(secretParkSet).not.toHaveBeenCalled()
+ })
+})
+
+describe('restoreParkedApiKeyForBackend', () => {
+ it('returns the parked value and deletes the entry afterwards', async () => {
+ secretParkGet.mockResolvedValue('sk-restored-value')
+ secretParkDelete.mockResolvedValue(undefined)
+ const value = await restoreParkedApiKeyForBackend('LM Studio')
+ expect(value).toBe('sk-restored-value')
+ expect(secretParkGet).toHaveBeenCalledWith('lm-studio')
+ expect(secretParkDelete).toHaveBeenCalledWith('lm-studio')
+ })
+
+ it('returns null, and never deletes, when nothing was parked', async () => {
+ secretParkGet.mockResolvedValue(null)
+ const value = await restoreParkedApiKeyForBackend('Jan')
+ expect(value).toBeNull()
+ expect(secretParkDelete).not.toHaveBeenCalled()
+ })
+
+ it('returns null when the keychain is unavailable, without throwing', async () => {
+ secretParkGet.mockRejectedValue(new Error('keychain unsupported on this platform'))
+ const value = await restoreParkedApiKeyForBackend('Jan')
+ expect(value).toBeNull()
+ })
+
+ it('still returns the value even if the best-effort cleanup delete fails', async () => {
+ secretParkGet.mockResolvedValue('sk-restored-value')
+ secretParkDelete.mockRejectedValue(new Error('refused: invalid backend id'))
+ const value = await restoreParkedApiKeyForBackend('LM Studio')
+ expect(value).toBe('sk-restored-value')
+ })
+})
+
+describe('NEGATIVE CONTROL: the key value never reaches a log call', () => {
+ it('a refused park logs the backend id at most, never the api key', async () => {
+ const logSpy = vi.fn()
+ vi.doMock('../logger', () => ({ log: { error: logSpy, warn: vi.fn(), info: vi.fn(), debug: vi.fn() } }))
+ vi.resetModules()
+ const { secretParkSet: freshSet } = await import('../../api/backend') as unknown as { secretParkSet: ReturnType<typeof vi.fn> }
+ freshSet.mockRejectedValue(new Error('refused: invalid backend id'))
+ const { parkApiKeyForBackend: freshPark } = await import('../parked-key')
+ await freshPark('Jan', 'sk-should-never-be-logged')
+ for (const call of logSpy.mock.calls) {
+ expect(JSON.stringify(call)).not.toContain('sk-should-never-be-logged')
+ }
+ vi.doUnmock('../logger')
+ })
+})
+
+describe('NEGATIVE CONTROL: without the keychain-missing guard, a refused id would be swallowed silently', () => {
+ it('is distinguished from a real keychain absence, so a caller bug is not mistaken for "no keychain here"', () => {
+ // If isKeychainMissing matched everything (the bug this guards against),
+ // a `refused:` failure from an invalid backend id would be indistinguishable
+ // from a genuinely absent keychain, hiding a real programming error behind
+ // the ordinary, expected fallback path.
+ const refused = new Error('refused: invalid backend id')
+ const missing = new Error('keychain unavailable (LU_NO_KEYCHAIN test mode)')
+ expect(isKeychainMissing(refused)).toBe(false)
+ expect(isKeychainMissing(missing)).toBe(true)
+ })
+})
diff --git a/src/lib/parked-key.ts b/src/lib/parked-key.ts
new file mode 100644
index 00000000..036a2a0a
--- /dev/null
+++ b/src/lib/parked-key.ts
@@ -0,0 +1,118 @@
+/**
+ * R9 (3.0.1): OS keychain parking for a displaced OpenAI-compatible API key.
+ *
+ * Switching the shared `openai` provider slot to a different backend (or
+ * turning the current one off) used to leave the outgoing backend's API key
+ * with nowhere permanent to go: F3 (Nachbesserung 6) parked it in
+ * `providers.openai.displaced.apiKey`, a plain store field that survives
+ * Enable/Disable within the running session but is stripped out of
+ * localStorage before every write (`providerStore.ts`'s `partialize`), so a
+ * restart between "switch away" and "switch back" always lost it.
+ *
+ * R9 adds a real place for it to live: a second, narrow account namespace in
+ * the OS keychain (`secret_park_set`/`_get`/`_delete`, `src-tauri/src/commands/secret.rs`),
+ * separate from the four fixed provider slots so it cannot collide with a
+ * real account. This module is the thin TS-side glue: turning a backend's
+ * display name into the `[a-z0-9-]{1,64}` id the Rust command requires, and
+ * telling "no keychain on this device" apart from "the id was rejected"
+ * (a bug here, not a fallback signal).
+ *
+ * What must never happen, checked by this module's own tests: the key value
+ * itself, or a rejected id, reaching `console`, a thrown `Error` message, or
+ * any other logged/telemetry surface.
+ */
+
+import { secretParkSet, secretParkGet, secretParkDelete } from '../api/backend'
+import { log } from './logger'
+
+/**
+ * Mirrors the Rust `is_valid_backend_id` pattern (secret.rs): lowercase
+ * letters, digits and hyphens only, 1 to 64 characters. A backend's display
+ * name (free text: presets, or whatever a user typed for a custom
+ * OpenAI-compatible endpoint) is turned into that shape here; a name that
+ * collapses to nothing usable (all-symbols, empty) has no valid id and
+ * parking is skipped rather than sent to Rust to be refused.
+ */
+export function slugifyBackendId(name: string): string | null {
+ const slug = name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 64)
+ .replace(/-+$/g, '')
+ return slug.length > 0 ? slug : null
+}
+
+/**
+ * The exact two strings `secret.rs` returns for "no keychain here" (Linux/
+ * web stub, or the `LU_NO_KEYCHAIN` test switch), same check
+ * `api/cloud/supabase.ts`'s `keychainMissing` already makes for the ordinary
+ * `secret_*` commands. A `refused: ...` error (invalid id, a programming
+ * error since ids are validated on this side too before the call) is
+ * deliberately NOT one of these two, so it never gets mistaken for "this
+ * device has no keychain" and silently swallowed the same way.
+ */
+export function isKeychainMissing(err: unknown): boolean {
+ const msg = err instanceof Error ? err.message : String(err)
+ return msg.includes('keychain unavailable') || msg.includes('keychain unsupported')
+}
+
+/**
+ * Best-effort: park `apiKey` under `backendName`'s slug so it survives an
+ * app restart while the backend is displaced. Returns whether it actually
+ * landed in the keychain; the caller decides what to tell the user when it
+ * did not (F3's "Switch Anyway" warning stays the fallback for exactly that
+ * case, see ProviderConfig.tsx).
+ *
+ * Never throws: a keychain-missing failure is expected on some platforms, a
+ * `refused:` failure is a real bug worth a log line, but neither should ever
+ * take down the provider switch itself. Neither `backendId` (a display-name
+ * slug, not a secret) nor `apiKey` is ever passed to `log`.
+ */
+export async function parkApiKeyForBackend(backendName: string, apiKey: string): Promise<boolean> {
+ if (!apiKey) return false
+ const backendId = slugifyBackendId(backendName)
+ if (!backendId) return false
+ try {
+ await secretParkSet(backendId, apiKey)
+ return true
+ } catch (err) {
+ if (!isKeychainMissing(err)) {
+ log.error('parked-key: secret_park_set refused', { backendId })
+ }
+ return false
+ }
+}
+
+/**
+ * The other half: read a parked key back for `backendName` and, once read,
+ * remove the parked entry (a park-then-restore is meant to be one-shot, not
+ * a copy that keeps living in the keychain after the key is back in active
+ * use). Returns `null` when there is nothing to restore, whether because
+ * the keychain has no entry (nothing was ever parked, or the initial park
+ * failed) or because there is no keychain at all on this device, so the
+ * caller's own session-only fallback (`displaced.apiKey`, if it has one)
+ * applies unchanged either way.
+ */
+export async function restoreParkedApiKeyForBackend(backendName: string): Promise<string | null> {
+ const backendId = slugifyBackendId(backendName)
+ if (!backendId) return null
+ let value: string | null
+ try {
+ value = await secretParkGet(backendId)
+ } catch (err) {
+ if (!isKeychainMissing(err)) {
+ log.error('parked-key: secret_park_get refused', { backendId })
+ }
+ return null
+ }
+ if (value === null) return null
+ try {
+ await secretParkDelete(backendId)
+ } catch {
+ // Best-effort cleanup only: a stray leftover entry under a valid id is
+ // harmless (it is overwritten the next time this backend is displaced
+ // again) and must not undo a restore that already succeeded.
+ }
+ return value
+}