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(models): der CivitAI-Schluessel liegt im Schluesselbund, nicht im localStorage

purplee371d4823797
diff --git a/src/App.tsx b/src/App.tsx
index fae8c083..87efb5b9 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -22,6 +22,13 @@ function App() {
const stored = await secretGet(HF_TOKEN_ACCOUNT).catch(() => null)
if (stored) await applyHfToken(stored).catch(() => {})
})
+
+ // Same store of record for the CivitAI key, on every platform that has a
+ // vault. This also moves an existing plaintext key out of localStorage,
+ // once, on the first boot after the update.
+ import('./stores/workflowStore').then(({ hydrateCivitaiApiKey }) => {
+ hydrateCivitaiApiKey().catch(() => {})
+ })
}
// Probe local Whisper (STT) once at boot and push the result into the voice
diff --git a/src/components/settings/CivitaiApiKeySetting.tsx b/src/components/settings/CivitaiApiKeySetting.tsx
index 59386235..462fe7b5 100644
--- a/src/components/settings/CivitaiApiKeySetting.tsx
+++ b/src/components/settings/CivitaiApiKeySetting.tsx
@@ -10,7 +10,9 @@
* and CivitAI answered with a bare 400 nobody could act on.
*
* Masked on purpose: this is a credential, and a settings page is a screen
- * people share in support threads.
+ * people share in support threads. The value itself goes into the OS vault
+ * where there is one (workflowStore.hydrateCivitaiApiKey), the same place the
+ * provider keys and the HuggingFace token live.
*/
import { useEffect, useState } from 'react'
import { KeyRound, Check } from 'lucide-react'
@@ -43,8 +45,9 @@ export function CivitaiApiKeySetting() {
<div className="text-[0.6rem] text-gray-500 leading-relaxed">
Used for the CivitAI search on the Models page and for the downloads it starts. Most CivitAI
downloads are refused without a key, which is the HTTP 400 or 401 you see on a download that
- never begins. Create one on your CivitAI account page under API Keys. It is stored on this
- machine and sent to CivitAI only.
+ never begins. Create one on your CivitAI account page under API Keys. It goes into your
+ system credential store where the OS has one, stays on this machine, and is sent to CivitAI
+ only.
</div>
<div className="flex items-center gap-2">
<input
diff --git a/src/components/settings/__tests__/civitai-key-field-renders.test.ts b/src/components/settings/__tests__/civitai-key-field-renders.test.ts
index 2a911ed8..19cda8e0 100644
--- a/src/components/settings/__tests__/civitai-key-field-renders.test.ts
+++ b/src/components/settings/__tests__/civitai-key-field-renders.test.ts
@@ -20,6 +20,11 @@ vi.mock('../../../api/backend', () => ({
backendCall: vi.fn(),
isTauri: () => true,
isMacOS: () => false,
+ // The store reaches for the OS vault; no vault in a test process, and the
+ // vault path itself is proven in stores/__tests__/civitai-key-keychain.
+ secretGet: vi.fn().mockRejectedValue(new Error('no keychain here')),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
}))
import { CivitaiApiKeySetting, CIVITAI_KEY_PAGE } from '../CivitaiApiKeySetting'
@@ -82,10 +87,13 @@ describe('the field exists and writes to the store', () => {
expect(screen.queryByText('Remove')).toBeNull()
})
- it('explains in English why the key matters', () => {
+ it('explains in English why the key matters, and where it is kept', () => {
show()
const text = document.body.textContent ?? ''
expect(text).toMatch(/Most CivitAI downloads are refused without a key/)
expect(text).toMatch(/HTTP 400 or 401/)
+ // Where it goes is part of the answer: it is a credential, and it is not
+ // sitting in plain text any more.
+ expect(text).toMatch(/system credential store/)
})
})
diff --git a/src/stores/__tests__/civitai-key-keychain.test.ts b/src/stores/__tests__/civitai-key-keychain.test.ts
new file mode 100644
index 00000000..6f60eee4
--- /dev/null
+++ b/src/stores/__tests__/civitai-key-keychain.test.ts
@@ -0,0 +1,138 @@
+/**
+ * The CivitAI API key belongs in the OS vault, like every other secret.
+ *
+ * The field added for goonerforporn wrote the key into localStorage in plain
+ * text, while provider keys (providerStore, security fix H5) and the
+ * HuggingFace token (MlxMediaSettings) already sit in Windows Credential
+ * Manager or the macOS Keychain. Same shape here, same limits: Linux desktop
+ * and the web build have no uniform vault and keep the localStorage path.
+ *
+ * `civitaiVaultReady` is module state, so every case re-imports the store
+ * (vi.resetModules) to start from "not yet probed".
+ *
+ * Run: npx vitest run src/stores/__tests__/civitai-key-keychain.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+const { secretGet, secretSet, secretDelete } = vi.hoisted(() => ({
+ secretGet: vi.fn(),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
+}))
+vi.mock('../../api/backend', () => ({ secretGet, secretSet, secretDelete }))
+
+async function freshStore() {
+ vi.resetModules()
+ return await import('../workflowStore')
+}
+
+// The default env here is node, and zustand persist reads
+// `window.localStorage`. Without a stand-in the persistence assertions below
+// would pass trivially.
+function installLocalStorage() {
+ const map = new Map<string, string>()
+ const ls = {
+ getItem: (k: string) => (map.has(k) ? map.get(k)! : null),
+ setItem: (k: string, v: string) => { map.set(k, String(v)) },
+ removeItem: (k: string) => { map.delete(k) },
+ clear: () => { map.clear() },
+ key: (i: number) => [...map.keys()][i] ?? null,
+ get length() { return map.size },
+ }
+ vi.stubGlobal('localStorage', ls)
+ vi.stubGlobal('window', { localStorage: ls })
+}
+
+const KEY = 'civitai-key-abcdef'
+
+beforeEach(() => {
+ secretGet.mockReset()
+ secretSet.mockReset()
+ secretDelete.mockReset()
+ installLocalStorage()
+})
+afterEach(() => { vi.unstubAllGlobals() })
+
+describe('the CivitAI key in the OS vault', () => {
+ it('reads the key back out of the vault at boot', async () => {
+ secretGet.mockResolvedValue(KEY)
+ const { useWorkflowStore, hydrateCivitaiApiKey, CIVITAI_KEY_ACCOUNT } = await freshStore()
+ await hydrateCivitaiApiKey()
+ expect(secretGet).toHaveBeenCalledWith(CIVITAI_KEY_ACCOUNT)
+ expect(useWorkflowStore.getState().civitaiApiKey).toBe(KEY)
+ })
+
+ it('moves a key that is still in localStorage into the vault, once', async () => {
+ secretGet.mockResolvedValue(null)
+ secretSet.mockResolvedValue(undefined)
+ const { useWorkflowStore, hydrateCivitaiApiKey, CIVITAI_KEY_ACCOUNT } = await freshStore()
+ useWorkflowStore.setState({ civitaiApiKey: 'from-the-old-build' })
+ await hydrateCivitaiApiKey()
+ expect(secretSet).toHaveBeenCalledWith(CIVITAI_KEY_ACCOUNT, 'from-the-old-build')
+ // And the plaintext copy stops being persisted.
+ const raw = localStorage.getItem('workflow-store') || ''
+ expect(raw).not.toContain('from-the-old-build')
+ })
+
+ it('writes every later edit to the vault and removes it when cleared', async () => {
+ secretGet.mockResolvedValue(null)
+ secretSet.mockResolvedValue(undefined)
+ secretDelete.mockResolvedValue(undefined)
+ const { useWorkflowStore, hydrateCivitaiApiKey, CIVITAI_KEY_ACCOUNT } = await freshStore()
+ await hydrateCivitaiApiKey()
+
+ useWorkflowStore.getState().setCivitaiApiKey(' typed-by-hand ')
+ expect(useWorkflowStore.getState().civitaiApiKey).toBe('typed-by-hand')
+ expect(secretSet).toHaveBeenCalledWith(CIVITAI_KEY_ACCOUNT, 'typed-by-hand')
+ expect(localStorage.getItem('workflow-store') || '').not.toContain('typed-by-hand')
+
+ useWorkflowStore.getState().setCivitaiApiKey('')
+ expect(secretDelete).toHaveBeenCalledWith(CIVITAI_KEY_ACCOUNT)
+ })
+
+ // Negative control 1: a host without a vault must behave exactly as it did.
+ // Dropping the key there would lose it, not protect it.
+ it('no vault: stays on localStorage and never writes one', async () => {
+ secretGet.mockRejectedValue(new Error('keychain unavailable (web build)'))
+ const { useWorkflowStore, hydrateCivitaiApiKey } = await freshStore()
+ await hydrateCivitaiApiKey()
+ useWorkflowStore.getState().setCivitaiApiKey(KEY)
+
+ expect(secretSet).not.toHaveBeenCalled()
+ expect(secretDelete).not.toHaveBeenCalled()
+ expect(useWorkflowStore.getState().civitaiApiKey).toBe(KEY)
+ expect(localStorage.getItem('workflow-store') || '').toContain(KEY)
+ })
+
+ // Negative control 2: a vault that accepts the probe but refuses the write
+ // (locked, full, policy) must keep the localStorage copy, or the key would
+ // vanish on the next restart with nothing left to read.
+ it('a failed vault write keeps the key in localStorage', async () => {
+ secretGet.mockResolvedValue(null)
+ secretSet.mockRejectedValue(new Error('keychain locked'))
+ const { useWorkflowStore, hydrateCivitaiApiKey } = await freshStore()
+ await hydrateCivitaiApiKey()
+
+ useWorkflowStore.getState().setCivitaiApiKey(KEY)
+ await new Promise((r) => setTimeout(r, 0))
+ // One more write so partialize runs again with the failure flag set.
+ useWorkflowStore.getState().setCivitaiApiKey(KEY)
+ await new Promise((r) => setTimeout(r, 0))
+
+ expect(useWorkflowStore.getState().civitaiApiKey).toBe(KEY)
+ expect(localStorage.getItem('workflow-store') || '').toContain(KEY)
+ })
+
+ // Negative control 3: the rest of the store keeps being persisted. A
+ // partialize that dropped more than the key would lose the user's workflows.
+ it('everything else in the store is still persisted', async () => {
+ secretGet.mockResolvedValue(KEY)
+ const { useWorkflowStore, hydrateCivitaiApiKey } = await freshStore()
+ await hydrateCivitaiApiKey()
+ useWorkflowStore.getState().setCivitaiHost('civitai.red')
+
+ const raw = localStorage.getItem('workflow-store') || ''
+ expect(raw).toContain('civitai.red')
+ expect(raw).not.toContain(KEY)
+ })
+})
diff --git a/src/stores/workflowStore.ts b/src/stores/workflowStore.ts
index daffebd7..195541d3 100644
--- a/src/stores/workflowStore.ts
+++ b/src/stores/workflowStore.ts
@@ -3,6 +3,68 @@ import { persist } from 'zustand/middleware'
import { v4 as uuid } from 'uuid'
import { isVideoModelType, type ModelType, } from '../api/comfyui'
import type { WorkflowTag, WorkflowTemplate } from '../types/workflows'
+import { secretGet, secretSet, secretDelete } from '../api/backend'
+
+// ── The CivitAI API key lives in the OS vault ──────────────────────────────
+//
+// Every other secret in the app already does (providerStore, the HuggingFace
+// token in MlxMediaSettings). This one sat in localStorage in plain text,
+// which is the same mistake providerStore's H5 fix was written for. Same
+// shape, same limits: Windows Credential Manager and the macOS Keychain hold
+// it, Linux desktop and the web build have no uniform vault and keep the
+// localStorage path unchanged.
+
+/** Keychain account for the CivitAI key. Keep it stable, changing it would
+ * orphan the stored key. */
+export const CIVITAI_KEY_ACCOUNT = 'civitai-api-key'
+
+// True once a secret_get has RESOLVED here, which is what proves the vault
+// works. Module level so the static `partialize` below can read it.
+let civitaiVaultReady = false
+// True when a vault WRITE failed this session. partialize then KEEPS the key
+// in localStorage, because a locked or full credential store must not make the
+// key vanish on the next restart with no trace.
+let civitaiVaultFailed = false
+
+/** Test seam: the flags are module state, so a test needs a way back. */
+export function __resetCivitaiVaultForTests(): void {
+ civitaiVaultReady = false
+ civitaiVaultFailed = false
+}
+
+/**
+ * Load the key from the OS vault, and move an existing localStorage key into it
+ * once. Called at boot.
+ *
+ * A reject on the very first probe means there is no vault here (web build, or
+ * Linux "unsupported"), and everything stays exactly as it was.
+ */
+export async function hydrateCivitaiApiKey(): Promise<void> {
+ let stored: string | null
+ try {
+ stored = await secretGet(CIVITAI_KEY_ACCOUNT)
+ } catch {
+ return // no vault on this host
+ }
+ civitaiVaultReady = true
+ if (stored) {
+ useWorkflowStore.setState({ civitaiApiKey: stored })
+ return
+ }
+ // Nothing in the vault. Read the CURRENT store value rather than a snapshot
+ // taken before the await: a key typed while a locked keychain kept us waiting
+ // must not be lost.
+ const existing = useWorkflowStore.getState().civitaiApiKey?.trim()
+ if (existing) {
+ try {
+ await secretSet(CIVITAI_KEY_ACCOUNT, existing)
+ } catch {
+ civitaiVaultFailed = true
+ }
+ }
+ // Re-persist, so partialize can now strip the plaintext copy.
+ useWorkflowStore.setState((s) => ({ ...s }))
+}
export type WorkflowTagMode = 'image' | 'video'
@@ -353,9 +415,20 @@ export const useWorkflowStore = create<WorkflowState>()(
})
},
- setCivitaiApiKey: (key) => set({
- civitaiApiKey: key,
- }),
+ setCivitaiApiKey: (key) => {
+ const trimmed = key.trim()
+ set({ civitaiApiKey: trimmed })
+ if (!civitaiVaultReady) return
+ civitaiVaultFailed = false
+ const write = trimmed
+ ? secretSet(CIVITAI_KEY_ACCOUNT, trimmed)
+ : secretDelete(CIVITAI_KEY_ACCOUNT)
+ write.catch(() => {
+ civitaiVaultFailed = true
+ // Re-persist so partialize retains the localStorage fallback.
+ set((s) => ({ ...s }))
+ })
+ },
setCivitaiHost: (host) => set({
civitaiHost:
@@ -438,6 +511,15 @@ export const useWorkflowStore = create<WorkflowState>()(
}),
{
name: 'workflow-store',
+ // The key is kept OUT of localStorage as soon as the OS vault has
+ // proven itself and holds it. Until then, and on a host without one,
+ // nothing changes: dropping it there would lose the key instead of
+ // protecting it.
+ partialize: (state) => {
+ if (!civitaiVaultReady || civitaiVaultFailed) return state
+ const { civitaiApiKey: _inTheVault, ...rest } = state
+ return rest as WorkflowState
+ },
},
),
)