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.

security: deferred items — Codex shell-confirm gate, provider-key keychain, cloudflared/Actions/dev-proxy hardening (H2/H5/M6/M7/M8)

purple52b416f95bd9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6b5e7ba7..fa3148d8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,16 +6,20 @@ on:
pull_request:
branches: [master]
+# Third-party actions are pinned to a full commit SHA (not a moving tag) so a
+# compromised or retagged upstream release can't silently run in our CI with
+# secrets in scope. The trailing comment records the human-readable version.
+# To bump: resolve the new tag to its SHA (`gh api repos/<owner>/<repo>/commits/<tag> --jq .sha`).
jobs:
lint-and-build:
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
- uses: actions/checkout@v4
+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- name: Setup Node.js
- uses: actions/setup-node@v4
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: '.nvmrc'
cache: 'npm'
@@ -40,13 +44,13 @@ jobs:
steps:
- name: Checkout repository
- uses: actions/checkout@v4
+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- name: Install Rust stable
- uses: dtolnay/rust-toolchain@stable
+ uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
- name: Rust cache
- uses: swatinem/rust-cache@v2
+ uses: swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2
with:
workspaces: './src-tauri -> target'
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index c861c00f..98950f2f 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -13,6 +13,10 @@ on:
permissions:
contents: write
+# Third-party actions are pinned to a full commit SHA (not a moving tag) so a
+# compromised or retagged upstream release can't run with our signing secrets
+# in scope. This job has TAURI_SIGNING_PRIVATE_KEY in env — pinning matters most
+# here. The trailing comment records the human-readable version.
jobs:
build-tauri:
strategy:
@@ -30,7 +34,7 @@ jobs:
steps:
- name: Checkout repository
- uses: actions/checkout@v4
+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
# Build from the release's target branch (master) instead of the tag ref.
# Prevents shipping a stale snapshot when fixes land after tag creation
@@ -38,17 +42,17 @@ jobs:
ref: ${{ github.event.release.target_commitish || 'master' }}
- name: Setup Node.js
- uses: actions/setup-node@v4
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 22
- name: Install Rust stable
- uses: dtolnay/rust-toolchain@stable
+ uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
with:
targets: ${{ matrix.rust_targets }}
- name: Rust cache
- uses: swatinem/rust-cache@v2
+ uses: swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2
with:
workspaces: './src-tauri -> target'
@@ -75,7 +79,7 @@ jobs:
run: npm ci
- name: Build and release Tauri app
- uses: tauri-apps/[email protected]
+ uses: tauri-apps/tauri-action@51a9f1156b33df106d827c3a78f8f894946c5faa # v0.5.25
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 8d7bfe62..bced04ad 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2025,7 +2025,7 @@ dependencies = [
"libc",
"percent-encoding",
"pin-project-lite",
- "socket2 0.5.10",
+ "socket2 0.6.3",
"system-configuration",
"tokio",
"tower-service",
@@ -2045,7 +2045,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
- "windows-core 0.57.0",
+ "windows-core 0.61.2",
]
[[package]]
@@ -2413,6 +2413,20 @@ dependencies = [
"unicode-segmentation",
]
+[[package]]
+name = "keyring"
+version = "3.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
+dependencies = [
+ "byteorder",
+ "log",
+ "security-framework 2.11.1",
+ "security-framework 3.7.0",
+ "windows-sys 0.60.2",
+ "zeroize",
+]
+
[[package]]
name = "kuchikiki"
version = "0.8.8-speedreader"
@@ -2524,6 +2538,7 @@ dependencies = [
"hostname",
"image",
"jsonwebtoken",
+ "keyring",
"local-ip-address",
"num_cpus",
"once_cell",
@@ -2759,7 +2774,7 @@ dependencies = [
"openssl-probe",
"openssl-sys",
"schannel",
- "security-framework",
+ "security-framework 3.7.0",
"security-framework-sys",
"tempfile",
]
@@ -4095,7 +4110,7 @@ dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
- "security-framework",
+ "security-framework 3.7.0",
]
[[package]]
@@ -4122,7 +4137,7 @@ dependencies = [
"rustls-native-certs",
"rustls-platform-verifier-android",
"rustls-webpki",
- "security-framework",
+ "security-framework 3.7.0",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
@@ -4238,6 +4253,19 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "security-framework"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
+dependencies = [
+ "bitflags 2.11.0",
+ "core-foundation 0.9.4",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
[[package]]
name = "security-framework"
version = "3.7.0"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 3f43d9f5..e21b4e3a 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -58,6 +58,16 @@ windows-sys = { version = "0.59", features = ["Win32_System_JobObjects", "Win32_
# installs in C:\Program Files\LM Studio that techx69 reported on v2.4.3).
winreg = "0.55"
+# OS keychain for provider API keys (H5). Windows Credential Manager + macOS
+# Keychain only — both backends are built into the OS, so no extra system
+# libraries are pulled in. Deliberately NOT on Linux: the secret-service
+# backend needs libdbus/gnome-keyring and fails on headless/minimal desktops,
+# so Linux keeps the obfuscated-localStorage path (the frontend falls back when
+# the secret_* commands report unsupported). default-features off avoids the
+# crate's sync-secret-service default.
+[target.'cfg(any(target_os = "windows", target_os = "macos"))'.dependencies]
+keyring = { version = "3", default-features = false, features = ["apple-native", "windows-native"] }
+
[profile.release]
panic = "abort"
codegen-units = 1
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index 25d73357..e52783f0 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -11,6 +11,7 @@ pub mod process;
pub mod proxy;
pub mod remote;
pub mod search;
+pub mod secret;
pub mod shell;
pub mod system;
pub mod tts;
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index 515d9713..4529646e 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -4265,6 +4265,36 @@ pub async fn start_tunnel(
return Err(format!("Download HTTP {}", resp.status()));
}
let bytes = resp.bytes().await.map_err(|e| e.to_string())?;
+
+ // Integrity gate before we write + chmod +x + spawn a downloaded binary.
+ // cloudflared pins to `releases/latest` on purpose (the self-heal design:
+ // a frozen version 500's once trycloudflare's tunnel API moves on), so a
+ // static SHA-256 pin isn't compatible here. Instead verify the three
+ // things we *can* assert about `latest`: it came over HTTPS from the
+ // official host, it's a plausible binary size, and it has the platform's
+ // executable magic bytes. This rejects a MITM'd HTML error page, a
+ // truncated download, or a swapped host before any of it is executed.
+ if !download_url.starts_with("https://github.com/") {
+ return Err("Refusing to fetch cloudflared from a non-github.com URL".into());
+ }
+ if bytes.len() < 1_000_000 {
+ // cloudflared is tens of MB; under 1 MB is an error page / truncation.
+ return Err(format!(
+ "cloudflared download too small ({} bytes) — looks like an error page, not the binary",
+ bytes.len()
+ ));
+ }
+ let magic_ok = if cfg!(windows) {
+ bytes.starts_with(b"MZ") // PE executable
+ } else if cfg!(target_os = "linux") {
+ bytes.starts_with(&[0x7f, b'E', b'L', b'F']) // ELF
+ } else {
+ bytes.starts_with(&[0x1f, 0x8b]) // gzip (.tgz for darwin)
+ };
+ if !magic_ok {
+ return Err("cloudflared download failed integrity check (unexpected file header)".into());
+ }
+
std::fs::write(&cf_path, &bytes).map_err(|e| format!("write: {}", e))?;
// Make executable on Unix
diff --git a/src-tauri/src/commands/secret.rs b/src-tauri/src/commands/secret.rs
new file mode 100644
index 00000000..0dd90a9c
--- /dev/null
+++ b/src-tauri/src/commands/secret.rs
@@ -0,0 +1,79 @@
+//! OS keychain storage for provider API keys (security fix H5).
+//!
+//! Provider keys used to live in localStorage under reversible base64
+//! (providerStore.ts). On Windows + macOS we store them in the OS credential
+//! vault instead — Windows Credential Manager / macOS Keychain, via the
+//! `keyring` crate. Both backends ship with the OS, so no extra system library
+//! is pulled in, and the secret is bound to the user's login.
+//!
+//! Linux desktop and the web build have no robust uniform secret store here
+//! (the secret-service backend needs libdbus/gnome-keyring and breaks on
+//! headless/minimal setups), so those keep the obfuscated-localStorage path:
+//! on those targets the commands compile to a stub that reports "unsupported",
+//! and the frontend (providerStore.hydrateProviderKeys) falls back.
+
+/// Keychain service name. The "account" is the provider id (ollama / openai /
+/// anthropic). Keep this stable — changing it would orphan stored keys.
+#[cfg(any(target_os = "windows", target_os = "macos"))]
+const SERVICE: &str = "com.locallyuncensored.providerkeys";
+
+#[cfg(any(target_os = "windows", target_os = "macos"))]
+#[tauri::command]
+pub fn secret_set(account: String, value: String) -> Result<(), String> {
+ let entry = keyring::Entry::new(SERVICE, &account).map_err(|e| e.to_string())?;
+ // An empty value means "no key" — delete rather than store an empty secret,
+ // so a cleared key never lingers in the vault.
+ if value.is_empty() {
+ return match entry.delete_credential() {
+ Ok(()) => Ok(()),
+ Err(keyring::Error::NoEntry) => Ok(()),
+ Err(e) => Err(e.to_string()),
+ };
+ }
+ entry.set_password(&value).map_err(|e| e.to_string())
+}
+
+#[cfg(any(target_os = "windows", target_os = "macos"))]
+#[tauri::command]
+pub fn secret_get(account: String) -> Result<Option<String>, String> {
+ let entry = keyring::Entry::new(SERVICE, &account).map_err(|e| e.to_string())?;
+ match entry.get_password() {
+ Ok(v) => Ok(Some(v)),
+ Err(keyring::Error::NoEntry) => Ok(None),
+ Err(e) => Err(e.to_string()),
+ }
+}
+
+#[cfg(any(target_os = "windows", target_os = "macos"))]
+#[tauri::command]
+pub fn secret_delete(account: String) -> Result<(), String> {
+ let entry = keyring::Entry::new(SERVICE, &account).map_err(|e| e.to_string())?;
+ match entry.delete_credential() {
+ Ok(()) => Ok(()),
+ Err(keyring::Error::NoEntry) => Ok(()),
+ Err(e) => Err(e.to_string()),
+ }
+}
+
+// ── Non-keychain platforms (Linux desktop) ──────────────────────────────
+// The commands still exist so `invoke('secret_get', …)` resolves, but they
+// report unsupported. The frontend treats any error here as "no keychain" and
+// keeps using the obfuscated-localStorage path — identical to today's behavior.
+
+#[cfg(not(any(target_os = "windows", target_os = "macos")))]
+#[tauri::command]
+pub fn secret_set(_account: String, _value: String) -> Result<(), String> {
+ Err("keychain unsupported on this platform".into())
+}
+
+#[cfg(not(any(target_os = "windows", target_os = "macos")))]
+#[tauri::command]
+pub fn secret_get(_account: String) -> Result<Option<String>, String> {
+ Err("keychain unsupported on this platform".into())
+}
+
+#[cfg(not(any(target_os = "windows", target_os = "macos")))]
+#[tauri::command]
+pub fn secret_delete(_account: String) -> Result<(), String> {
+ Err("keychain unsupported on this platform".into())
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index b4746550..504df7d9 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -173,6 +173,10 @@ fn main() {
commands::download::resume_download,
commands::download::detect_model_path,
commands::download::check_model_sizes,
+ // Provider API-key keychain (H5)
+ commands::secret::secret_set,
+ commands::secret::secret_get,
+ commands::secret::secret_delete,
// Web search
commands::search::web_search,
commands::search::web_fetch,
diff --git a/src/api/backend.ts b/src/api/backend.ts
index a0d50cbb..ea61d435 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -617,6 +617,29 @@ export async function downloadComfyFile(filename: string, subfolder: string = ''
}
}
+// ── Provider key keychain (H5) ──────────────────────────────────
+// Thin wrappers over the Rust secret_* commands (Windows Credential Manager /
+// macOS Keychain). They reject on the web build (no Tauri) and on Linux desktop
+// (the command reports unsupported), which is how providerStore detects "no
+// keychain here" and falls back to the obfuscated-localStorage path.
+export async function secretSet(account: string, value: string): Promise<void> {
+ if (!isTauri()) throw new Error('keychain unavailable (web build)')
+ const invoke = await getInvoke()
+ await invoke('secret_set', { account, value })
+}
+
+export async function secretGet(account: string): Promise<string | null> {
+ if (!isTauri()) throw new Error('keychain unavailable (web build)')
+ const invoke = await getInvoke()
+ return (await invoke('secret_get', { account })) as string | null
+}
+
+export async function secretDelete(account: string): Promise<void> {
+ if (!isTauri()) throw new Error('keychain unavailable (web build)')
+ const invoke = await getInvoke()
+ await invoke('secret_delete', { account })
+}
+
/** Fetch an external URL as text — works in both Tauri and dev mode */
export async function fetchExternal(url: string): Promise<string> {
if (isTauri()) {
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index fa3e7ef2..e643a70b 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -647,6 +647,11 @@ function CodexAgentSettings() {
enabled={settings.codexReviewMode}
onChange={() => updateSettings({ codexReviewMode: !settings.codexReviewMode })}
/>
+ <InlineToggle
+ label="Confirm shell & code commands (prevents prompt-injection from auto-running commands)"
+ enabled={settings.codexConfirmShell}
+ onChange={() => updateSettings({ codexConfirmShell: !settings.codexConfirmShell })}
+ />
</div>
)
}
diff --git a/src/hooks/__tests__/codexShellGate.test.ts b/src/hooks/__tests__/codexShellGate.test.ts
new file mode 100644
index 00000000..b7f0da72
--- /dev/null
+++ b/src/hooks/__tests__/codexShellGate.test.ts
@@ -0,0 +1,46 @@
+import { describe, it, expect } from 'vitest'
+import { CODEX_CONFIRM_TOOLS, codexNeedsConfirm } from '../codexShellGate'
+
+// H2: the coding-agent shell/code confirm gate. These tests lock the contract
+// that (a) the autonomous workflow is unchanged when the gate is off, (b) the
+// gate covers exactly the arbitrary-exec tools, and (c) file_write — which is
+// path-jailed + stageable — is never caught by it.
+
+describe('codexShellGate (H2)', () => {
+ describe('CODEX_CONFIRM_TOOLS membership', () => {
+ it('includes the arbitrary-exec tools', () => {
+ expect(CODEX_CONFIRM_TOOLS.has('shell_execute')).toBe(true)
+ expect(CODEX_CONFIRM_TOOLS.has('code_execute')).toBe(true)
+ expect(CODEX_CONFIRM_TOOLS.has('shell_execute_background')).toBe(true)
+ })
+
+ it('does NOT include file_write (path-jailed + Stage mode handles it)', () => {
+ expect(CODEX_CONFIRM_TOOLS.has('file_write')).toBe(false)
+ })
+
+ it('does NOT include read-only tools', () => {
+ for (const t of ['file_read', 'file_list', 'file_search', 'git_status', 'web_search']) {
+ expect(CODEX_CONFIRM_TOOLS.has(t)).toBe(false)
+ }
+ })
+ })
+
+ describe('codexNeedsConfirm', () => {
+ it('off by default: never confirms even for shell_execute (autonomous workflow preserved)', () => {
+ expect(codexNeedsConfirm('shell_execute', false)).toBe(false)
+ expect(codexNeedsConfirm('code_execute', false)).toBe(false)
+ })
+
+ it('on: confirms the arbitrary-exec tools', () => {
+ expect(codexNeedsConfirm('shell_execute', true)).toBe(true)
+ expect(codexNeedsConfirm('code_execute', true)).toBe(true)
+ expect(codexNeedsConfirm('shell_execute_background', true)).toBe(true)
+ })
+
+ it('on: does NOT confirm file_write or read-only tools', () => {
+ expect(codexNeedsConfirm('file_write', true)).toBe(false)
+ expect(codexNeedsConfirm('file_read', true)).toBe(false)
+ expect(codexNeedsConfirm('web_search', true)).toBe(false)
+ })
+ })
+})
diff --git a/src/hooks/codexShellGate.ts b/src/hooks/codexShellGate.ts
new file mode 100644
index 00000000..2f93ee15
--- /dev/null
+++ b/src/hooks/codexShellGate.ts
@@ -0,0 +1,21 @@
+// H2 security gate — shared, pure, testable.
+//
+// The coding agent (useCodex) auto-runs tools unattended by design. These are
+// the arbitrary-code-execution tools — the prompt-injection RCE surface (a tool
+// result or a read file steering the model into running a command). When the
+// user enables `settings.codexConfirmShell`, each of these pauses for an
+// explicit confirm before dispatch.
+//
+// file_write is deliberately NOT here: it is path-jailed to the workspace (C2)
+// and has its own Stage-and-Approve mode, so it is not part of this gate.
+export const CODEX_CONFIRM_TOOLS: ReadonlySet<string> = new Set([
+ 'shell_execute',
+ 'code_execute',
+ 'shell_execute_background',
+])
+
+/** True when this tool call must be confirmed: the gate is enabled AND the tool
+ * is one of the arbitrary-exec tools. */
+export function codexNeedsConfirm(toolName: string, confirmEnabled: boolean): boolean {
+ return confirmEnabled && CODEX_CONFIRM_TOOLS.has(toolName)
+}
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 150ab007..689719a8 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -8,6 +8,7 @@ import { getProviderForModel, getProviderIdFromModel } from '../api/providers'
import { toolRegistry } from '../api/mcp'
import { usePermissionStore } from '../stores/permissionStore'
import { getToolCallingStrategy } from '../lib/model-compatibility'
+import { CODEX_CONFIRM_TOOLS } from './codexShellGate'
import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
import { chatNonStreaming } from '../api/agents'
import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel } from '../api/agent-context'
@@ -1180,9 +1181,26 @@ export function useCodex() {
execute: (name: string, args: Record<string, any>) => dispatchTool(name, args),
lookupCache: convId ? makeInTurnCacheLookup({ convId, turnStartMs }) : undefined,
explainError: (toolName, err) => explainToolError(toolName, err),
- // Codex is auto-approve (coding agent runs unattended). The
- // awaitApproval hook is intentionally omitted so the executor
- // dispatches immediately.
+ // Codex is auto-approve by default (the coding agent runs unattended).
+ // H2 gate: when settings.codexConfirmShell is on, pause the
+ // arbitrary-exec tools for an explicit confirm — the mitigation for a
+ // prompt-injected model auto-running shell/code. window.confirm works
+ // in this Tauri webview (the app uses it elsewhere, e.g. Gallery).
+ awaitApproval: settings.codexConfirmShell
+ ? async (req) => {
+ if (!CODEX_CONFIRM_TOOLS.has(req.toolName)) return true
+ const a = req.args || {}
+ const preview = String(a.command ?? a.code ?? a.script ?? '').slice(0, 800)
+ const msg =
+ `Coding agent wants to run "${req.toolName}":\n\n` +
+ `${preview || '(no command preview)'}\n\n` +
+ `Allow it to run?`
+ if (typeof window !== 'undefined' && typeof window.confirm === 'function') {
+ return window.confirm(msg)
+ }
+ return true
+ }
+ : undefined,
recordAudit: (entry) => {
if (!convId) return
if (entry.kind === 'start') {
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 335989ac..640be649 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -59,6 +59,9 @@ export const DEFAULT_SETTINGS: Settings = {
codexRepoMapLimit: 20,
codexStageMode: false,
codexReviewMode: false,
+ // H2 security gate. OFF by default = the autonomous coding agent keeps
+ // running shell/code unattended; ON pauses each exec for a confirm.
+ codexConfirmShell: false,
defaultWorkspace: null,
// v8: user-uploaded profile picture (base64 data URL, ≤256px). '' = default icon.
userAvatarDataUrl: '',
diff --git a/src/main.tsx b/src/main.tsx
index 03107c86..4b991609 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -17,6 +17,17 @@ async function boot() {
import('./App.tsx'),
import('./components/ui/ErrorBoundary'),
])
+ // H5: load provider API keys from the OS keychain (Win/macOS) before the UI
+ // can issue a provider call, migrating any old localStorage key into the
+ // vault. Time-boxed so a wedged keychain can never block launch; no-op /
+ // localStorage fallback on Linux + the web build.
+ try {
+ const { useProviderStore } = await import('./stores/providerStore')
+ await Promise.race([
+ useProviderStore.getState().hydrateProviderKeys(),
+ new Promise((resolve) => setTimeout(resolve, 3000)),
+ ])
+ } catch { /* keychain hydration is best-effort */ }
createRoot(rootEl).render(
<StrictMode>
<ErrorBoundary root>
diff --git a/src/stores/__tests__/providerStore.keychain.test.ts b/src/stores/__tests__/providerStore.keychain.test.ts
new file mode 100644
index 00000000..d329aef9
--- /dev/null
+++ b/src/stores/__tests__/providerStore.keychain.test.ts
@@ -0,0 +1,114 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// H5: provider API keys move to the OS keychain on Win/macOS, with a
+// localStorage fallback (Linux + web build). These tests mock the Rust
+// secret_* bridge and the registry, then exercise hydrateProviderKeys,
+// setProviderApiKey, migration, and the localStorage-strip via partialize.
+//
+// `keychainReady` is module-level state, so each case re-imports the store
+// fresh (vi.resetModules) to start from a clean "not yet probed" flag.
+
+const { secretGet, secretSet, secretDelete } = vi.hoisted(() => ({
+ secretGet: vi.fn(),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
+}))
+
+vi.mock('../../api/providers/registry', () => ({ clearProviderCache: vi.fn() }))
+vi.mock('../../api/backend', () => ({ secretGet, secretSet, secretDelete }))
+
+async function freshStore() {
+ vi.resetModules()
+ const mod = await import('../providerStore')
+ return mod.useProviderStore
+}
+
+const obf = (k: string) => btoa(k.split('').reverse().join(''))
+
+// The default vitest env here is 'node' (no DOM). zustand persist needs a
+// localStorage; install a minimal Map-backed one BEFORE the store module loads
+// (createJSONStorage reads it at import time, which freshStore triggers).
+function installLocalStorage() {
+ const map = new Map<string, string>()
+ vi.stubGlobal('localStorage', {
+ 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 },
+ })
+}
+
+describe('providerStore keychain (H5)', () => {
+ beforeEach(() => {
+ secretGet.mockReset()
+ secretSet.mockReset()
+ secretDelete.mockReset()
+ installLocalStorage()
+ })
+
+ it('no keychain (secret_get rejects on first probe) → stays on localStorage, never writes the vault', async () => {
+ secretGet.mockRejectedValue(new Error('keychain unavailable (web build)'))
+ const useStore = await freshStore()
+ await useStore.getState().hydrateProviderKeys()
+
+ useStore.getState().setProviderApiKey('anthropic', 'sk-test')
+ expect(secretSet).not.toHaveBeenCalled()
+ // getter still works via the obfuscated localStorage path
+ expect(useStore.getState().getProviderApiKey('anthropic')).toBe('sk-test')
+ })
+
+ it('loads a key stored in the vault into memory', async () => {
+ secretGet.mockImplementation(async (id: string) => (id === 'anthropic' ? 'sk-vault' : null))
+ const useStore = await freshStore()
+ await useStore.getState().hydrateProviderKeys()
+ expect(useStore.getState().getProviderApiKey('anthropic')).toBe('sk-vault')
+ })
+
+ it('after hydrate, setProviderApiKey writes the real key to the vault', async () => {
+ secretGet.mockResolvedValue(null)
+ secretSet.mockResolvedValue(undefined)
+ const useStore = await freshStore()
+ await useStore.getState().hydrateProviderKeys()
+
+ useStore.getState().setProviderApiKey('openai', 'sk-new')
+ expect(secretSet).toHaveBeenCalledWith('openai', 'sk-new')
+ })
+
+ it('migrates an existing localStorage key into the vault on hydrate', async () => {
+ secretGet.mockResolvedValue(null) // vault empty
+ secretSet.mockResolvedValue(undefined)
+ const useStore = await freshStore()
+
+ // Seed a key the old way BEFORE hydrate (keychain not yet active).
+ useStore.getState().setProviderApiKey('anthropic', 'sk-old-localstorage')
+ expect(secretSet).not.toHaveBeenCalled() // not active yet
+ secretSet.mockClear()
+
+ await useStore.getState().hydrateProviderKeys()
+ expect(secretSet).toHaveBeenCalledWith('anthropic', 'sk-old-localstorage')
+ })
+
+ it('after hydrate, partialize strips the key from persisted localStorage', async () => {
+ secretGet.mockImplementation(async (id: string) => (id === 'anthropic' ? 'sk-vault' : null))
+ secretSet.mockResolvedValue(undefined)
+ const useStore = await freshStore()
+ await useStore.getState().hydrateProviderKeys()
+
+ const raw = localStorage.getItem('lu-providers') || ''
+ expect(raw).not.toContain('sk-vault')
+ expect(raw).not.toContain(obf('sk-vault'))
+ })
+
+ it('resetProvider deletes the key from the vault when active', async () => {
+ secretGet.mockResolvedValue(null)
+ secretSet.mockResolvedValue(undefined)
+ secretDelete.mockResolvedValue(undefined)
+ const useStore = await freshStore()
+ await useStore.getState().hydrateProviderKeys()
+
+ useStore.getState().resetProvider('anthropic')
+ expect(secretDelete).toHaveBeenCalledWith('anthropic')
+ })
+})
diff --git a/src/stores/providerStore.ts b/src/stores/providerStore.ts
index 40935d22..8d24773b 100644
--- a/src/stores/providerStore.ts
+++ b/src/stores/providerStore.ts
@@ -9,11 +9,18 @@ import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { ProviderId, ProviderConfig } from '../api/providers/types'
import { clearProviderCache } from '../api/providers/registry'
-
-// ── API Key Encryption ─────────────────────────────────────────
-// Simple base64 obfuscation. Not true encryption, but prevents
-// plaintext keys in localStorage and casual inspection.
-// Full WebCrypto would be better but requires async init.
+import { secretGet, secretSet, secretDelete } from '../api/backend'
+
+// ── API Key storage ────────────────────────────────────────────
+// Two-tier (H5):
+// • Windows + macOS desktop → the real key lives in the OS credential vault
+// (Credential Manager / Keychain) via the Rust secret_* commands.
+// `keychainReady` flips true once hydrateProviderKeys confirms the vault
+// works; partialize then keeps the key out of localStorage entirely.
+// • Linux desktop + the web build → no robust uniform vault, so the key stays
+// in localStorage under the base64 obfuscation below (unchanged behavior).
+// In-memory we always hold the OBFUSCATED form so the sync getters
+// (getProviderApiKey / getEnabledProviders) are identical on every platform.
function obfuscate(key: string): string {
if (!key) return ''
@@ -33,6 +40,12 @@ function deobfuscate(encoded: string): string {
}
}
+// Flipped true by hydrateProviderKeys when the OS keychain is usable on this
+// platform. Until then (and forever on Linux/web) the store behaves exactly as
+// before. Module-level so the static `partialize` can read it.
+let keychainReady = false
+const PROVIDER_IDS: ProviderId[] = ['ollama', 'openai', 'anthropic']
+
// ── Default provider configs ───────────────────────────────────
const DEFAULT_PROVIDERS: Record<ProviderId, ProviderConfig> = {
@@ -77,6 +90,10 @@ interface ProviderState {
getEnabledProviders: () => ProviderConfig[]
resetProvider: (id: ProviderId) => void
setHideBackendSelector: (hide: boolean) => void
+ /** H5: load provider keys from the OS keychain (Win/macOS), migrating any
+ * existing localStorage key into the vault. No-op / fallback elsewhere.
+ * Call once at app startup, before the first provider client is built. */
+ hydrateProviderKeys: () => Promise<void>
}
// ── Zustand Store ──────────────────────────────────────────────
@@ -106,6 +123,12 @@ export const useProviderStore = create<ProviderState>()(
[id]: { ...state.providers[id], apiKey: obfuscate(key) },
},
}))
+ // When the OS vault is active, store the real key there; partialize
+ // keeps it out of localStorage. Fire-and-forget — the in-memory
+ // obfuscated value already serves this session's reads.
+ if (keychainReady) {
+ void secretSet(id, key).catch(() => { /* vault write best-effort */ })
+ }
clearProviderCache()
},
@@ -130,15 +153,59 @@ export const useProviderStore = create<ProviderState>()(
[id]: DEFAULT_PROVIDERS[id],
},
}))
+ if (keychainReady) {
+ void secretDelete(id).catch(() => { /* vault delete best-effort */ })
+ }
+ clearProviderCache()
+ },
+
+ hydrateProviderKeys: async () => {
+ // Probe + load keys from the OS keychain. The first secret_get that
+ // RESOLVES (even returning null) proves the vault is usable here; a
+ // reject on the very first probe means no keychain (web build, or Linux
+ // "unsupported") → stay on the localStorage path and do nothing.
+ const next = { ...get().providers }
+ let usable: boolean | null = null
+ for (const id of PROVIDER_IDS) {
+ try {
+ const stored = await secretGet(id)
+ usable = true
+ if (stored != null && stored !== '') {
+ next[id] = { ...next[id], apiKey: obfuscate(stored) }
+ } else {
+ // Nothing in the vault yet. Migrate an existing localStorage key
+ // (an upgrading user) into the vault, once.
+ const existing = deobfuscate(next[id]?.apiKey || '')
+ if (existing) {
+ try { await secretSet(id, existing) } catch { /* migrate best-effort */ }
+ }
+ }
+ } catch {
+ if (usable === null) { usable = false; break } // no keychain here
+ // otherwise a transient per-key error — keep the others
+ }
+ }
+ if (!usable) return
+ keychainReady = true
+ // Apply loaded keys and re-persist; partialize (now that keychainReady
+ // is true) strips the redundant localStorage copy. clearProviderCache
+ // rebuilds any client constructed during startup with an empty key.
+ set({ providers: next })
clearProviderCache()
},
}),
{
name: 'lu-providers',
version: 1,
- // Don't persist transient state, only configs + user's "don't show again" preference
+ // Don't persist transient state, only configs + user's "don't show again" preference.
+ // When the OS keychain is active (H5), strip apiKey so the secret never
+ // touches localStorage; otherwise keep the obfuscated key as before.
partialize: (state) => ({
- providers: state.providers,
+ providers: keychainReady
+ ? (Object.fromEntries(
+ Object.entries(state.providers).map(([id, p]) => [id, { ...p, apiKey: '' }])
+ ) as Record<ProviderId, ProviderConfig>)
+ : state.providers,
hideBackendSelector: state.hideBackendSelector,
}),
}
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 764bf4b2..ade58c36 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -135,6 +135,16 @@ export interface Settings {
* touching anything.
*/
codexReviewMode: boolean
+ /**
+ * Confirm shell / code execution in the coding agent (security gate, H2).
+ * The coding agent auto-runs tools unattended by design. When this is on,
+ * every `shell_execute` / `code_execute` / background-shell call pauses for
+ * an explicit confirm first — the mitigation for prompt-injection RCE
+ * (a tool result or read file steering the model into running a command).
+ * Default OFF preserves the autonomous workflow; file_write is unaffected
+ * (it is path-jailed and has its own Stage mode).
+ */
+ codexConfirmShell: boolean
/**
* Shared default workspace for Codex AND Agent (Underlying refactor —
* workspace unification). When set, both surfaces resolve relative paths
diff --git a/vite.config.ts b/vite.config.ts
index 9c886c8d..b9866985 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -10,6 +10,70 @@ import { config } from 'dotenv'
import { fileURLToPath } from 'url'
import { dirname } from 'path'
import os from 'os'
+import dns from 'node:dns'
+import net from 'node:net'
+
+// ── Dev-server SSRF guard ───────────────────────────────────────
+// The dev proxies that fetch a *user-supplied* ?url= (proxy-image,
+// proxy-download) are an SSRF sink: a markdown image / download link could
+// point the server at an internal address (169.254.169.254 metadata, LAN
+// boxes, localhost services). The packaged desktop app routes these through
+// the Rust proxy, which has the strong validate_public_url guard
+// (src-tauri/src/commands/proxy.rs); this is the parity guard for the
+// `npm run dev` / web build (konata's SSH-tunnel path). Best-effort against
+// DNS-rebind — this is a dev server, not the production trust boundary.
+function isBlockedIp(ip: string): boolean {
+ const v = net.isIP(ip)
+ if (v === 4) {
+ const p = ip.split('.').map(Number)
+ if (p.length !== 4 || p.some((n) => Number.isNaN(n) || n < 0 || n > 255)) return true
+ const [a, b] = p
+ if (a === 0) return true // 0.0.0.0/8 "this host"
+ if (a === 10) return true // 10/8 private
+ if (a === 127) return true // loopback
+ if (a === 169 && b === 254) return true // link-local + 169.254.169.254 cloud metadata
+ if (a === 172 && b >= 16 && b <= 31) return true // 172.16/12 private
+ if (a === 192 && b === 168) return true // 192.168/16 private
+ if (a === 100 && b >= 64 && b <= 127) return true // 100.64/10 CGNAT
+ if (a >= 224) return true // multicast + reserved
+ return false
+ }
+ if (v === 6) {
+ const lc = ip.toLowerCase().replace(/^\[|\]$/g, '')
+ if (lc === '::1' || lc === '::') return true // loopback / unspecified
+ if (lc.startsWith('fe80')) return true // link-local
+ if (lc.startsWith('fc') || lc.startsWith('fd')) return true // ULA fc00::/7
+ const mapped = lc.match(/::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)
+ if (mapped) return isBlockedIp(mapped[1]) // IPv4-mapped IPv6
+ return false
+ }
+ return false // not an IP literal — caller resolves DNS and re-checks
+}
+
+async function assertPublicUrl(urlStr: string): Promise<URL> {
+ let u: URL
+ try {
+ u = new URL(urlStr)
+ } catch {
+ throw new Error('invalid url')
+ }
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error('scheme not allowed')
+ const host = u.hostname.replace(/^\[|\]$/g, '')
+ if (!host) throw new Error('no host')
+ if (host === 'localhost' || host.toLowerCase().endsWith('.localhost')) throw new Error('blocked host')
+ // Reject all-digit decimal / 0x-hex integer hosts (inet_aton SSRF encodings).
+ if (/^\d+$/.test(host) || /^0x[0-9a-f]+$/i.test(host)) throw new Error('blocked numeric host')
+ if (net.isIP(host)) {
+ if (isBlockedIp(host)) throw new Error('blocked ip')
+ return u
+ }
+ const addrs = await dns.promises.lookup(host, { all: true })
+ if (!addrs.length) throw new Error('dns empty')
+ for (const a of addrs) {
+ if (isBlockedIp(a.address)) throw new Error('blocked resolved ip')
+ }
+ return u
+}
// Load .env file from project root
const __dirname = dirname(fileURLToPath(import.meta.url))
@@ -454,24 +518,34 @@ function comfyLauncher(): Plugin {
server.middlewares.use('/local-api/proxy-image', (req, res) => {
const imgUrl = new URL(req.url || '', 'http://localhost').searchParams.get('url')
if (!imgUrl) { res.writeHead(400); res.end(); return }
- const proto = imgUrl.startsWith('https') ? https : http
- proto.get(imgUrl, { headers: { 'User-Agent': 'Mozilla/5.0' } }, (upstream) => {
- if (upstream.statusCode && upstream.statusCode >= 300 && upstream.statusCode < 400 && upstream.headers.location) {
- proto.get(upstream.headers.location, { headers: { 'User-Agent': 'Mozilla/5.0' } }, (redir) => {
- res.writeHead(redir.statusCode || 200, {
- 'Content-Type': redir.headers['content-type'] || 'image/jpeg',
- 'Cache-Control': 'public, max-age=86400',
- })
- redir.pipe(res)
- }).on('error', () => { res.writeHead(502); res.end() })
- return
- }
- res.writeHead(upstream.statusCode || 200, {
- 'Content-Type': upstream.headers['content-type'] || 'image/jpeg',
- 'Cache-Control': 'public, max-age=86400',
- })
- upstream.pipe(res)
- }).on('error', () => { res.writeHead(502); res.end() })
+ const deny = () => { res.writeHead(403, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'blocked by SSRF guard' })) }
+ // Validate the original URL, then re-validate the redirect target (a
+ // public host can 30x to an internal one).
+ assertPublicUrl(imgUrl).then((u) => {
+ const proto = u.protocol === 'https:' ? https : http
+ proto.get(imgUrl, { headers: { 'User-Agent': 'Mozilla/5.0' } }, (upstream) => {
+ if (upstream.statusCode && upstream.statusCode >= 300 && upstream.statusCode < 400 && upstream.headers.location) {
+ const loc = upstream.headers.location
+ upstream.resume() // drain the redirect body
+ assertPublicUrl(loc).then((lu) => {
+ const lproto = lu.protocol === 'https:' ? https : http
+ lproto.get(loc, { headers: { 'User-Agent': 'Mozilla/5.0' } }, (redir) => {
+ res.writeHead(redir.statusCode || 200, {
+ 'Content-Type': redir.headers['content-type'] || 'image/jpeg',
+ 'Cache-Control': 'public, max-age=86400',
+ })
+ redir.pipe(res)
+ }).on('error', () => { res.writeHead(502); res.end() })
+ }).catch(deny)
+ return
+ }
+ res.writeHead(upstream.statusCode || 200, {
+ 'Content-Type': upstream.headers['content-type'] || 'image/jpeg',
+ 'Cache-Control': 'public, max-age=86400',
+ })
+ upstream.pipe(res)
+ }).on('error', () => { res.writeHead(502); res.end() })
+ }).catch(deny)
})
// API: Proxy download (follows redirects server-side, avoids CORS)
@@ -483,26 +557,34 @@ function comfyLauncher(): Plugin {
return
}
- const protocol = url.startsWith('https') ? https : http
const fetchUrl = (targetUrl: string, redirectCount = 0) => {
if (redirectCount > 5) {
res.writeHead(502, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Too many redirects' }))
return
}
- protocol.get(targetUrl, { headers: { 'User-Agent': 'LocallyUncensored/1.0' } }, (upstream) => {
- if (upstream.statusCode && upstream.statusCode >= 300 && upstream.statusCode < 400 && upstream.headers.location) {
- fetchUrl(upstream.headers.location, redirectCount + 1)
- return
- }
- res.writeHead(upstream.statusCode || 200, {
- 'Content-Type': upstream.headers['content-type'] || 'application/octet-stream',
- 'Content-Length': upstream.headers['content-length'] || '',
+ // Validate every hop (initial URL + each redirect target) so a public
+ // host can't 30x the server into an internal address.
+ assertPublicUrl(targetUrl).then((u) => {
+ const protocol = u.protocol === 'https:' ? https : http
+ protocol.get(targetUrl, { headers: { 'User-Agent': 'LocallyUncensored/1.0' } }, (upstream) => {
+ if (upstream.statusCode && upstream.statusCode >= 300 && upstream.statusCode < 400 && upstream.headers.location) {
+ upstream.resume()
+ fetchUrl(upstream.headers.location, redirectCount + 1)
+ return
+ }
+ res.writeHead(upstream.statusCode || 200, {
+ 'Content-Type': upstream.headers['content-type'] || 'application/octet-stream',
+ 'Content-Length': upstream.headers['content-length'] || '',
+ })
+ upstream.pipe(res)
+ }).on('error', (err) => {
+ res.writeHead(502, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: err.message }))
})
- upstream.pipe(res)
- }).on('error', (err) => {
- res.writeHead(502, { 'Content-Type': 'application/json' })
- res.end(JSON.stringify({ error: err.message }))
+ }).catch(() => {
+ res.writeHead(403, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'blocked by SSRF guard' }))
})
}
fetchUrl(url)