Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): a setting that can hold a key, on a bridge that only goes one way

esengine9040f006719c
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index e34d9de1e..c7ce815e2 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -44,6 +44,7 @@ import { ensureSdkTypes } from './syncSdkTypes';
import { ensureProjectShaderTwins } from './shaderTwins';
import { installCrashCapture, logsDir } from './resilience';
import { mcpMode, startMcpEndpoint, stopMcpEndpoint, mcpEndpointStatus } from './mcpEndpoint';
+import { secretStatus, setSecret, clearSecret } from './secrets';
import {
discoverPlugins, compilePlugin, isTrusted, trustPlugin, revokeTrust, isDisabled, setPluginEnabled,
PROJECT_PLUGIN_DIR, USER_PLUGIN_DIR,
@@ -639,6 +640,14 @@ ipcMain.handle('mcp:status', () => mcpEndpointStatus());
ipcMain.handle('mcp:setEnabled', (_e, on: boolean) =>
on ? startMcpEndpoint(() => win) : stopMcpEndpoint());
+// — Credentials a setting holds (secrets.ts) —
+// Three handlers and deliberately no `get`: a secret crosses from the renderer
+// once and never comes back, so the only thing the window can learn is whether
+// one is stored.
+ipcMain.handle('secret:status', (_e, id: string) => secretStatus(id));
+ipcMain.handle('secret:set', (_e, id: string, value: string) => setSecret(id, value));
+ipcMain.handle('secret:clear', (_e, id: string) => clearSecret(id));
+
// — Custom window controls (frameless Windows/Linux; macOS uses native traffic lights) —
ipcMain.handle('window:minimize', () => win?.minimize());
ipcMain.handle('window:toggleMaximize', () => {
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index fa55780ec..005acae17 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -20,6 +20,7 @@ import type { ScaffoldPluginOptions, ScaffoldPluginResult } from './pluginScaffo
import type { PluginPackageInfo, InstallPluginResult } from './pluginPackage';
import type { NativeTemplateEntry, InstallResult } from './nativeTemplates';
import type { McpEndpointStatus } from './mcpEndpoint';
+import type { SecretStatus } from './secrets';
// The privileged bridge the renderer is allowed to touch. Keep this surface small
// and explicit — anything the editor needs from the OS or Node goes through here.
@@ -93,6 +94,18 @@ const api = {
setEnabled: (on: boolean): Promise<McpEndpointStatus> => ipcRenderer.invoke('mcp:setEnabled', on),
},
+ // — Credentials a setting holds (the built-in agent's API key). The value
+ // crosses this bridge ONCE, inbound, when the user types it: main seals it with
+ // the OS keychain and hands it only to the client that must send it, and there
+ // is no way to read it back (electron/secrets.ts). —
+ secrets: {
+ /** Whether one is stored under `id`, and what this machine can store it with. */
+ status: (id: string): Promise<SecretStatus> => ipcRenderer.invoke('secret:status', id),
+ /** Store it; resolves with the resulting status, including a refusal. */
+ set: (id: string, value: string): Promise<SecretStatus> => ipcRenderer.invoke('secret:set', id, value),
+ clear: (id: string): Promise<SecretStatus> => ipcRenderer.invoke('secret:clear', id),
+ },
+
// — Project / workspace (RC12 §E7) —
project: {
/** Show a directory picker and open the chosen Estella project (null if cancelled). */
diff --git a/desktop/electron/secrets.ts b/desktop/electron/secrets.ts
new file mode 100644
index 000000000..a5a25e90f
--- /dev/null
+++ b/desktop/electron/secrets.ts
@@ -0,0 +1,176 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file secrets.ts — main's keeper of the credentials a setting can hold (the
+ * built-in agent's API key today).
+ *
+ * The direction of travel is the whole feature: a secret comes IN from the
+ * renderer once, when the user types it, and never goes back out. There is no
+ * `get` over IPC — only main reads one ({@link readSecret}), and only to hand it
+ * to the client that must send it. The window learns exactly one bit, whether
+ * something is stored, which is what the settings row renders.
+ *
+ * At rest it is sealed with Electron's safeStorage, i.e. the OS keychain (macOS
+ * Keychain, Windows DPAPI, libsecret/kwallet on Linux). Where there is no
+ * keychain to seal with, storing is REFUSED rather than quietly downgraded to a
+ * plaintext file — an API key written in the clear because the machine made it
+ * inconvenient not to is the bug this file exists to not have.
+ */
+import { app, safeStorage } from 'electron';
+import { readFileSync, writeFileSync, renameSync } from 'node:fs';
+import path from 'node:path';
+
+const log = (...a: unknown[]) => process.stderr.write(`[secrets] ${a.join(' ')}\n`);
+
+/**
+ * What this machine can seal a secret with.
+ *
+ * `obfuscated` is Linux's `basic_text` backend: safeStorage answers that
+ * encryption is "available" and then encrypts with a hardcoded password, which
+ * is not a keychain and should not be presented as one.
+ */
+export type SecretStorage = 'keychain' | 'obfuscated' | 'unavailable';
+
+/** Everything the renderer is allowed to know about a secret. */
+export interface SecretStatus {
+ id: string;
+ /** A secret is stored AND this machine can still open it. */
+ configured: boolean;
+ storage: SecretStorage;
+ /** Why the stored one could not be opened, if there is one that cannot. */
+ error: string | null;
+}
+
+/** Ciphertext as it sits on disk, read once per process. */
+let stored: Map<string, Buffer> | null = null;
+/** Per-id decrypt verdict — null when it opened, else the failure. Memoised so
+ * a status read is not a keychain round trip. */
+const checked = new Map<string, string | null>();
+
+function file(): string {
+ return path.join(app.getPath('userData'), 'secrets.json');
+}
+
+function storage(): SecretStorage {
+ if (!safeStorage.isEncryptionAvailable()) return 'unavailable';
+ if (process.platform !== 'linux') return 'keychain';
+ try {
+ return safeStorage.getSelectedStorageBackend() === 'basic_text' ? 'obfuscated' : 'keychain';
+ } catch {
+ // The call is Linux-only and documented to exist there; a build without it
+ // still has working encryption, so don't downgrade what we report over it.
+ return 'keychain';
+ }
+}
+
+/** The file, or an empty set — an absent one is the ordinary first-run state. */
+function load(): Map<string, Buffer> {
+ if (stored) return stored;
+ stored = new Map();
+ let raw: string;
+ try {
+ raw = readFileSync(file(), 'utf8');
+ } catch {
+ return stored;
+ }
+ try {
+ for (const [id, b64] of Object.entries(JSON.parse(raw) as Record<string, string>)) {
+ stored.set(id, Buffer.from(b64, 'base64'));
+ }
+ } catch (e) {
+ // Keep the empty map: a file we cannot parse is one we cannot honour, and
+ // the next `set` rewrites it. Reported so it is not a silent forgetting.
+ log('ignoring an unreadable secrets file:', String(e));
+ }
+ return stored;
+}
+
+function persist(): void {
+ const out: Record<string, string> = {};
+ for (const [id, cipher] of load()) out[id] = cipher.toString('base64');
+ const target = file();
+ const tmp = `${target}.tmp`;
+ // Write-then-rename, 0600: the contents are ciphertext, but a half-written
+ // file would lose every secret in it, and the mode is what keeps it out of
+ // another account's reach on a shared machine.
+ writeFileSync(tmp, `${JSON.stringify(out)}\n`, { mode: 0o600 });
+ renameSync(tmp, target);
+}
+
+/**
+ * Whether the entry for `id` still opens: null yes, a string why not, undefined
+ * when there is no entry. A secret sealed by a keychain this machine no longer
+ * has is not a secret we have, and reporting it as configured would send the
+ * user looking for the fault anywhere but here.
+ */
+function check(id: string): string | null | undefined {
+ const cipher = load().get(id);
+ if (!cipher) return undefined;
+ if (!checked.has(id)) {
+ try {
+ safeStorage.decryptString(cipher);
+ checked.set(id, null);
+ } catch (e) {
+ checked.set(id, String((e as Error)?.message ?? e));
+ }
+ }
+ return checked.get(id);
+}
+
+export function secretStatus(id: string): SecretStatus {
+ const store = storage();
+ // Nothing can be open when nothing can be sealed, and `storage` already says
+ // why — an error here would say it twice.
+ if (store === 'unavailable') return { id, configured: false, storage: store, error: null };
+ const failure = check(id);
+ return { id, configured: failure === null, storage: store, error: failure ?? null };
+}
+
+/**
+ * Seal `value` under `id`. Blank is a no-op rather than a clear: the row's own
+ * control never submits one, so a blank arriving here is a mistake, and taking
+ * a configured key away over it is not the helpful reading.
+ */
+export function setSecret(id: string, value: string): SecretStatus {
+ const secret = value.trim();
+ if (!secret) return secretStatus(id);
+ const store = storage();
+ if (store === 'unavailable') return { id, configured: false, storage: store, error: null };
+ const previous = load().get(id);
+ try {
+ load().set(id, safeStorage.encryptString(secret));
+ checked.set(id, null);
+ persist();
+ } catch (e) {
+ // Put back what was there. A store that fails must not also lose the working
+ // key it was replacing — the file on disk still has that one, so dropping it
+ // here would only make the two disagree until the next restart.
+ if (previous) load().set(id, previous);
+ else load().delete(id);
+ checked.delete(id);
+ const message = String((e as Error)?.message ?? e);
+ log(`could not store ${id}:`, message);
+ return { ...secretStatus(id), error: message };
+ }
+ return secretStatus(id);
+}
+
+export function clearSecret(id: string): SecretStatus {
+ checked.delete(id);
+ if (load().delete(id)) persist();
+ return secretStatus(id);
+}
+
+/**
+ * The plaintext, for the one caller that has to send it. Main-process only —
+ * this is deliberately not behind an IPC handler, see the file header.
+ */
+export function readSecret(id: string): string | null {
+ const cipher = load().get(id);
+ if (!cipher) return null;
+ try {
+ return safeStorage.decryptString(cipher);
+ } catch {
+ return null;
+ }
+}
diff --git a/desktop/src/components/SettingsDialog.tsx b/desktop/src/components/SettingsDialog.tsx
index 4a1df71d1..7ca2b0745 100644
--- a/desktop/src/components/SettingsDialog.tsx
+++ b/desktop/src/components/SettingsDialog.tsx
@@ -11,7 +11,7 @@ import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
import type { PointerEvent as ReactPointerEvent } from 'react';
import { createPortal } from 'react-dom';
import { useShallow } from 'zustand/react/shallow';
-import { Settings as SettingsIcon, X, RotateCcw, FolderSearch, Plus, Trash2, ChevronRight } from 'lucide-react';
+import { Settings as SettingsIcon, X, RotateCcw, FolderSearch, Plus, Trash2, ChevronRight, Check } from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import { useSettings } from '@/store/settingsStore';
import { settingsRegistry } from '@/settings/registry';
@@ -24,7 +24,8 @@ import { SearchField } from '@/components/SearchField';
import { Segmented } from '@/components/Segmented';
import { Select } from '@/components/Select';
import { ColorControl } from '@/components/ColorControl';
-import type { Setting, NumberSetting, KeybindingSetting, StringListSetting, PathSetting, MatrixSetting, FlagListSetting, ObjectListSetting, ObjectListColumn } from '@/settings/types';
+import { refreshSecret, secretStatus, storeSecret, forgetSecret, subscribeSecrets } from '@/store/SecretStore';
+import type { Setting, NumberSetting, KeybindingSetting, StringListSetting, PathSetting, SecretSetting, MatrixSetting, FlagListSetting, ObjectListSetting, ObjectListColumn } from '@/settings/types';
import { t } from '@/i18n';
// A bound list setting's getter returns a fresh array each call; useShallow below
@@ -207,6 +208,69 @@ function PathControl({ setting }: { setting: PathSetting }) {
const basename = (p: string): string => p.split(/[\\/]/).pop() || p;
+/**
+ * A credential: type it once, and from then on the row can only say that one is
+ * held, or forget it. There is no reveal affordance because there is nothing to
+ * reveal — main never hands the value back (see settings/types.ts) — and a row
+ * that could show it would have to keep it here, which is the thing being
+ * avoided. The draft survives a refused store so a paste is never lost.
+ */
+function SecretControl({ setting }: { setting: SecretSetting }) {
+ const status = useSyncExternalStore(subscribeSecrets, () => secretStatus(setting.id));
+ const [draft, setDraft] = useState('');
+ useEffect(() => {
+ void refreshSecret(setting.id);
+ }, [setting.id]);
+
+ // Main has not answered yet. Rendering either state would be a guess, and one
+ // of the two guesses reads as "your key is gone".
+ if (!status) return null;
+
+ if (status.configured) {
+ return (
+ <div className="set-secret">
+ <span className="set-secret-on">
+ <Check size={12} strokeWidth={2} />
+ {t('set.secret.stored')}
+ </span>
+ <IconButton title={t('set.secret.forget')} onClick={() => void forgetSecret(setting.id)}>
+ <Trash2 size={13} />
+ </IconButton>
+ </div>
+ );
+ }
+
+ // Nothing can be sealed on this machine, so the field is shown refused rather
+ // than accepting a key it would have to drop. The row's status line says why.
+ const blocked = status.storage === 'unavailable';
+ const submit = () => {
+ if (!draft.trim() || blocked) return;
+ void storeSecret(setting.id, draft).then((s) => {
+ if (s?.configured) setDraft('');
+ });
+ };
+ return (
+ <div className="set-secret">
+ <input
+ className="set-str"
+ type="password"
+ value={draft}
+ disabled={blocked}
+ placeholder={setting.placeholder ?? ''}
+ spellCheck={false}
+ autoComplete="off"
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') submit();
+ }}
+ />
+ <IconButton title={t('set.secret.store')} disabled={blocked || !draft.trim()} onClick={submit}>
+ <Check size={13} />
+ </IconButton>
+ </div>
+ );
+}
+
function StringListControl({ setting }: { setting: StringListSetting }) {
const setValue = useSettings((s) => s.setValue);
const value = useSettings(useShallow((s) => s.getValue<string[]>(setting.id) ?? (EMPTY_LIST as string[])));
@@ -516,6 +580,8 @@ function Control({ setting }: { setting: Setting }) {
);
case 'path':
return <PathControl setting={setting} />;
+ case 'secret':
+ return <SecretControl setting={setting} />;
case 'stringList':
return <StringListControl setting={setting} />;
case 'matrix':
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index 4fe55bf2d..0b8fc8c8c 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -93,9 +93,32 @@ export const settingsMessages = defineMessages({
'set.group.background': { en: 'Background', zh: '后台' },
'set.group.console': { en: 'Console', zh: '控制台' },
'set.group.renderer': { en: 'Renderer', zh: '渲染器' },
+ 'set.group.builtinAgent': { en: 'Built-in Agent', zh: '内置 Agent' },
'set.group.agents': { en: 'External Agents', zh: '外部代理' },
+ // — A credential the editor holds but never shows —
+ 'set.secret.stored': { en: 'Stored', zh: '已配置' },
+ 'set.secret.store': { en: 'Store it', zh: '保存' },
+ 'set.secret.forget': { en: 'Forget it', zh: '清除' },
+ 'set.secret.noKeychain': {
+ en: 'This machine has no keychain to encrypt with, so nothing can be stored here. On Linux, install GNOME Keyring or KWallet, or start the editor with --password-store=gnome-libsecret.',
+ zh: '这台机器没有可用于加密的密钥库,因此无法保存。Linux 上请安装 GNOME Keyring 或 KWallet,或以 --password-store=gnome-libsecret 启动编辑器。',
+ },
+ 'set.secret.obfuscated': {
+ en: 'No system keychain was found, so this is only obfuscated on disk — anyone with your files can read it back. Installing GNOME Keyring or KWallet upgrades it.',
+ zh: '没有找到系统密钥库,因此只是在磁盘上做了混淆——拿到你文件的人即可还原。安装 GNOME Keyring 或 KWallet 后会自动改用它。',
+ },
+ 'set.secret.damaged': {
+ en: 'The stored value cannot be decrypted on this machine ({message}) — it was most likely sealed by another one. Enter it again.',
+ zh: '已保存的值在这台机器上无法解密({message}),多半是在另一台机器上加密的。请重新输入。',
+ },
+
// — AI Agents —
+ 'set.agents.apiKey': { en: 'Anthropic API key', zh: 'Anthropic API 密钥' },
+ 'set.agents.apiKey.desc': {
+ en: 'What the built-in agent authenticates with. Held by the system keychain — never written to the project or the settings file, and never handed back to this window.',
+ zh: '内置 Agent 用它调用模型。密钥存在系统钥匙串里——不写进项目、不写进设置文件,也不会交回给这个窗口。',
+ },
'set.agents.mcpEnabled': { en: 'Allow AI agents to connect', zh: '允许 AI 代理连接' },
'set.agents.mcpEnabled.desc': {
en: 'Serve this editor over MCP on a local-only port, so an agent set up with --attach can drive the project you have open. Off means nothing is listening.',
diff --git a/desktop/src/settings/editorSettings.ts b/desktop/src/settings/editorSettings.ts
index f5df37e12..5c69e8850 100644
--- a/desktop/src/settings/editorSettings.ts
+++ b/desktop/src/settings/editorSettings.ts
@@ -18,6 +18,8 @@ import { setUseLessCpuInBackground } from '@/engine/backgroundThrottle';
import { EngineHost } from '@/engine/EngineHost';
import { Toasts } from '@/store/Toasts';
import { mcpStatus, setMcpEnabled, subscribeMcp } from '@/store/McpStore';
+import { secretStatusLine, subscribeSecrets } from '@/store/SecretStore';
+import { AGENT_API_KEY } from './secretIds';
import { t, editorLocale, systemDefaultLocale, EDITOR_LOCALES, LANGUAGE_SETTING_ID } from '@/i18n';
const root = () => document.documentElement.style;
@@ -231,7 +233,28 @@ settingsRegistry.register({
effect: (v) => LogStore.setCap(v),
});
-// ── AI Agents (main-owned endpoint, driven from here) ───────────────────────
+// ── AI Agents ───────────────────────────────────────────────────────────────
+// The built-in agent's credential. Registered before the MCP row because it is
+// the one an ordinary user needs; the endpoint below is for agents that live
+// outside the editor.
+//
+// The value is never here: this descriptor carries no more than its id, and the
+// key itself lives in main behind the OS keychain (electron/secrets.ts). That is
+// what keeps it out of localStorage, which is where every OTHER setting is.
+settingsRegistry.register({
+ id: AGENT_API_KEY,
+ type: 'secret',
+ scope: 'editor',
+ section: 'agents',
+ group: t('set.group.builtinAgent'),
+ label: t('set.agents.apiKey'),
+ description: t('set.agents.apiKey.desc'),
+ placeholder: 'sk-ant-…',
+ default: false,
+ status: { read: () => secretStatusLine(AGENT_API_KEY), subscribe: subscribeSecrets },
+});
+
+// ── External agents (main-owned endpoint, driven from here) ─────────────────
// An external agent reaches this editor through the MCP endpoint main can expose,
// and `--attach` finds it through the discovery file the endpoint writes. An
// editor launched the ordinary way — by double-clicking it — wrote no such file,
diff --git a/desktop/src/settings/secretIds.ts b/desktop/src/settings/secretIds.ts
new file mode 100644
index 000000000..edf5b7a93
--- /dev/null
+++ b/desktop/src/settings/secretIds.ts
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file secretIds.ts — the ids a secret is stored under.
+ *
+ * Shared by both sides on purpose: the settings row registers under one of these
+ * and main reads back under the same one, and a secret written under an id
+ * nobody reads is indistinguishable from a machine that lost its keychain. A
+ * leaf module with no imports, so main can take it without pulling the editor in
+ * (the same reason plugins/paths.ts exists).
+ */
+
+/** The built-in agent's model credential. Also its settings-row id. */
+export const AGENT_API_KEY = 'agents.apiKey';
diff --git a/desktop/src/settings/types.ts b/desktop/src/settings/types.ts
index 56bfc0a2e..640872fde 100644
--- a/desktop/src/settings/types.ts
+++ b/desktop/src/settings/types.ts
@@ -104,6 +104,20 @@ export interface PathSetting extends BaseSetting<string> {
detect?: boolean;
}
+/**
+ * A credential the editor holds but can never show. The value goes to main,
+ * which seals it with the OS keychain (electron/secrets.ts); nothing reads it
+ * back — not this process, not localStorage, not the project — so the only
+ * "value" here is the one bit main reports, and it lives there rather than in
+ * the settings store. The row is therefore set-or-forget, and `status` is where
+ * a machine with no keychain to seal with gets to say so.
+ */
+export interface SecretSetting extends BaseSetting<boolean> {
+ type: 'secret';
+ /** Shape of the expected credential, e.g. `sk-ant-…`. */
+ placeholder?: string;
+}
+
export interface ColorSetting extends BaseSetting<string> {
type: 'color';
/** Preset swatches (hex). */
@@ -207,6 +221,7 @@ export type Setting =
| EnumSetting
| StringSetting
| PathSetting
+ | SecretSetting
| ColorSetting
| ColorPickerSetting
| KeybindingSetting
diff --git a/desktop/src/store/SecretStore.ts b/desktop/src/store/SecretStore.ts
new file mode 100644
index 000000000..e8f8aa816
--- /dev/null
+++ b/desktop/src/store/SecretStore.ts
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file SecretStore.ts
+ * @brief The credentials main holds, as the UI is allowed to see them.
+ *
+ * Main owns the secrets themselves (electron/secrets.ts) — it seals them
+ * with the OS keychain and never hands one back. This mirrors the one bit
+ * it does report, so a settings row can render "stored" or an entry field
+ * without the value ever reaching this process or localStorage.
+ *
+ * A vanilla store, not a hook: the settings registry is plain data and a
+ * descriptor's `status` is read outside React (SettingsDialog subscribes
+ * it to a row through useSyncExternalStore), the same as McpStore.
+ */
+import { createStore } from 'zustand/vanilla';
+import type { SecretStatus } from '../../electron/secrets';
+import { t } from '@/i18n';
+
+export type { SecretStatus };
+
+const store = createStore<{ byId: Record<string, SecretStatus> }>(() => ({ byId: {} }));
+
+const adopt = (status: SecretStatus): SecretStatus => {
+ store.setState((prev) => ({ byId: { ...prev.byId, [status.id]: status } }));
+ return status;
+};
+
+/**
+ * What main last said about `id` — undefined until it has said anything. The
+ * unknown state is kept distinct on purpose: "not configured" is a claim, and
+ * making it before asking would tell a user their key had gone missing.
+ */
+export const secretStatus = (id: string): SecretStatus | undefined => store.getState().byId[id];
+
+/** Re-render on any change (useSyncExternalStore / plain subscriber). */
+export const subscribeSecrets = (fn: () => void): (() => void) => store.subscribe(fn);
+
+export async function refreshSecret(id: string): Promise<SecretStatus | undefined> {
+ const status = await window.estella?.secrets?.status(id);
+ return status && adopt(status);
+}
+
+/** Hand main a secret to seal. This is the only direction it travels. */
+export async function storeSecret(id: string, value: string): Promise<SecretStatus | undefined> {
+ const status = await window.estella?.secrets?.set(id, value);
+ return status && adopt(status);
+}
+
+export async function forgetSecret(id: string): Promise<SecretStatus | undefined> {
+ const status = await window.estella?.secrets?.clear(id);
+ return status && adopt(status);
+}
+
+/**
+ * The row's live line — what the machine actually did with the secret, not what
+ * was asked of it. Silent in the ordinary cases (nothing stored yet, or stored
+ * in a real keychain): the control itself says which of those it is, and a line
+ * that is always there stops being read.
+ *
+ * Returns a string so useSyncExternalStore can compare it with Object.is; see
+ * settings/types.ts.
+ */
+export function secretStatusLine(id: string): string | null {
+ const s = secretStatus(id);
+ if (!s) return null;
+ if (s.storage === 'unavailable') return t('set.secret.noKeychain');
+ if (s.error) return t('set.secret.damaged', { message: s.error });
+ if (s.storage === 'obfuscated') return t('set.secret.obfuscated');
+ return null;
+}
diff --git a/desktop/src/theme/settings.css b/desktop/src/theme/settings.css
index f47fa3c7b..78252a640 100644
--- a/desktop/src/theme/settings.css
+++ b/desktop/src/theme/settings.css
@@ -166,6 +166,14 @@
Cocos-style field hard to read at a glance. */
.set-path { display: flex; align-items: center; gap: 4px; }
.set-path .set-str { width: 300px; }
+/* A credential: an entry field until one is held, then a statement that one is.
+ Uncolored on purpose — "configured" is a fact, not a warning or a success. */
+.set-secret { display: flex; align-items: center; justify-content: flex-end; gap: 4px; width: 100%; }
+/* Fills the row's control column rather than naming a width: the field plus its
+ button has to stay inside it, and one that spills lands on the description. */
+.set-secret .set-str { flex: 1; min-width: 0; }
+.set-secret .set-str:disabled { color: var(--text-mute); cursor: not-allowed; }
+.set-secret-on { display: inline-flex; align-items: center; gap: 5px; color: var(--text-dim); font-size: var(--fs-xs); }
.set-reset { width: 16px; height: 16px; display: grid; place-items: center; color: var(--warn); opacity: 0; }
.set-row:hover .set-reset.show, .set-row.changed .set-reset.show { opacity: 0.85; }
.set-reset.show { cursor: pointer; }
diff --git a/desktop/tests/secrets.test.ts b/desktop/tests/secrets.test.ts
new file mode 100644
index 000000000..06cf2e3c9
--- /dev/null
+++ b/desktop/tests/secrets.test.ts
@@ -0,0 +1,211 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The credential store behind the `secret` setting type. Three things have to
+// hold, and only the first is about happy paths:
+//
+// 1. A stored secret survives a restart and comes back to MAIN, plaintext.
+// 2. It is never on disk in the clear — a machine that cannot encrypt is told
+// "no", not quietly given a plaintext file.
+// 3. What the renderer is told is TRUE: a secret sealed by a keychain this
+// machine no longer has reads as not-configured, not as configured-and-then
+// mysteriously broken at the first API call.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, existsSync, readFileSync, writeFileSync, statSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { AGENT_API_KEY } from '../src/settings/secretIds';
+
+let userData: string;
+let available = true;
+let backend = 'gnome_libsecret';
+/** Which "machine" sealed a ciphertext — a mismatch is a restored backup. */
+let keyring = 'this-machine';
+let sealFails = false;
+
+vi.mock('electron', () => ({
+ app: { getPath: () => userData },
+ safeStorage: {
+ isEncryptionAvailable: () => available,
+ getSelectedStorageBackend: () => backend,
+ encryptString: (plain: string) => {
+ if (!available || sealFails) throw new Error('the keychain refused');
+ return Buffer.from(`${keyring}:${plain}`);
+ },
+ decryptString: (buf: Buffer) => {
+ const [sealedBy, ...rest] = buf.toString().split(':');
+ if (sealedBy !== keyring) throw new Error('failed to decrypt');
+ return rest.join(':');
+ },
+ },
+}));
+
+async function load() {
+ vi.resetModules();
+ return import('../electron/secrets');
+}
+
+const file = () => path.join(userData, 'secrets.json');
+const onDisk = () => readFileSync(file(), 'utf8');
+
+beforeEach(() => {
+ userData = mkdtempSync(path.join(tmpdir(), 'estella-secrets-'));
+ available = true;
+ backend = 'gnome_libsecret';
+ keyring = 'this-machine';
+ sealFails = false;
+});
+
+afterEach(() => {
+ rmSync(userData, { recursive: true, force: true });
+});
+
+describe('storing a secret', () => {
+ it('reports nothing configured before anything is stored, and writes no file', async () => {
+ const { secretStatus } = await load();
+ expect(secretStatus(AGENT_API_KEY)).toEqual({
+ id: AGENT_API_KEY, configured: false, storage: 'keychain', error: null,
+ });
+ expect(existsSync(file())).toBe(false);
+ });
+
+ it('hands the value back to main and never writes it in the clear', async () => {
+ const { setSecret, readSecret } = await load();
+ expect(setSecret(AGENT_API_KEY, 'sk-ant-secret')).toMatchObject({ configured: true, error: null });
+ expect(readSecret(AGENT_API_KEY)).toBe('sk-ant-secret');
+ expect(onDisk()).not.toContain('sk-ant-secret');
+ });
+
+ it('keeps the file to this account', async () => {
+ const { setSecret } = await load();
+ setSecret(AGENT_API_KEY, 'sk-ant-secret');
+ if (process.platform === 'win32') return; // POSIX modes only
+ expect(statSync(file()).mode & 0o777).toBe(0o600);
+ });
+
+ it('survives a restart', async () => {
+ const first = await load();
+ first.setSecret(AGENT_API_KEY, 'sk-ant-secret');
+
+ const restarted = await load();
+ expect(restarted.secretStatus(AGENT_API_KEY)).toMatchObject({ configured: true });
+ expect(restarted.readSecret(AGENT_API_KEY)).toBe('sk-ant-secret');
+ });
+
+ it('replaces rather than accumulates', async () => {
+ const { setSecret, readSecret } = await load();
+ setSecret(AGENT_API_KEY, 'first');
+ setSecret(AGENT_API_KEY, 'second');
+ expect(readSecret(AGENT_API_KEY)).toBe('second');
+ expect(Object.keys(JSON.parse(onDisk()) as object)).toEqual([AGENT_API_KEY]);
+ });
+
+ it('trims what was pasted', async () => {
+ const { setSecret, readSecret } = await load();
+ setSecret(AGENT_API_KEY, ' sk-ant-secret\n');
+ expect(readSecret(AGENT_API_KEY)).toBe('sk-ant-secret');
+ });
+
+ // A blank submission is a mistake, and reading it as "forget my key" is not the
+ // helpful interpretation of one.
+ it('ignores a blank instead of taking the stored one away', async () => {
+ const { setSecret, readSecret } = await load();
+ setSecret(AGENT_API_KEY, 'sk-ant-secret');
+ expect(setSecret(AGENT_API_KEY, ' ')).toMatchObject({ configured: true });
+ expect(readSecret(AGENT_API_KEY)).toBe('sk-ant-secret');
+ });
+
+ // The file on disk still holds the old one, so dropping it in memory would only
+ // make the two disagree until the next restart.
+ it('keeps the working key when replacing it fails', async () => {
+ const { setSecret, readSecret, secretStatus } = await load();
+ setSecret(AGENT_API_KEY, 'sk-ant-works');
+
+ sealFails = true; // the keychain refuses mid-session
+ const failed = setSecret(AGENT_API_KEY, 'sk-ant-new');
+ sealFails = false;
+
+ expect(failed.error).toContain('refused');
+ expect(secretStatus(AGENT_API_KEY)).toMatchObject({ configured: true });
+ expect(readSecret(AGENT_API_KEY)).toBe('sk-ant-works');
+ });
+
+ it('forgets one on request, on disk too', async () => {
+ const { setSecret, clearSecret, readSecret } = await load();
+ setSecret(AGENT_API_KEY, 'sk-ant-secret');
+ expect(clearSecret(AGENT_API_KEY)).toMatchObject({ configured: false });
+ expect(readSecret(AGENT_API_KEY)).toBeNull();
+ expect(JSON.parse(onDisk())).toEqual({});
+ });
+});
+
+describe('a machine that cannot encrypt', () => {
+ it('refuses to store rather than falling back to plaintext', async () => {
+ available = false;
+ const { setSecret, secretStatus } = await load();
+ expect(setSecret(AGENT_API_KEY, 'sk-ant-secret')).toEqual({
+ id: AGENT_API_KEY, configured: false, storage: 'unavailable', error: null,
+ });
+ expect(existsSync(file())).toBe(false);
+ expect(secretStatus(AGENT_API_KEY).storage).toBe('unavailable');
+ });
+
+ // Linux's basic_text backend encrypts with a hardcoded password. safeStorage
+ // answers "available" for it, and calling that a keychain in the UI would be
+ // the one claim a user might act on.
+ it('names Linux obfuscation as what it is', async () => {
+ const platform = process.platform;
+ Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
+ backend = 'basic_text';
+ try {
+ const { setSecret } = await load();
+ expect(setSecret(AGENT_API_KEY, 'sk-ant-secret')).toMatchObject({
+ configured: true, storage: 'obfuscated',
+ });
+ } finally {
+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });
+ }
+ });
+});
+
+describe('a stored secret this machine cannot open', () => {
+ it('reads as not configured, and says why', async () => {
+ const first = await load();
+ first.setSecret(AGENT_API_KEY, 'sk-ant-secret');
+
+ keyring = 'another-machine'; // restored from a backup / a rotated keychain
+ const restarted = await load();
+ const status = restarted.secretStatus(AGENT_API_KEY);
+ expect(status.configured).toBe(false);
+ expect(status.error).toContain('decrypt');
+ expect(restarted.readSecret(AGENT_API_KEY)).toBeNull();
+ });
+
+ it('is replaced by simply entering it again', async () => {
+ const first = await load();
+ first.setSecret(AGENT_API_KEY, 'sk-ant-secret');
+
+ keyring = 'another-machine';
+ const restarted = await load();
+ expect(restarted.setSecret(AGENT_API_KEY, 'sk-ant-new')).toMatchObject({ configured: true, error: null });
+ expect(restarted.readSecret(AGENT_API_KEY)).toBe('sk-ant-new');
+ });
+
+ it('treats an unparseable file as nothing stored rather than throwing', async () => {
+ writeFileSync(file(), '{ this is not json');
+ const { secretStatus, setSecret } = await load();
+ expect(secretStatus(AGENT_API_KEY)).toMatchObject({ configured: false, error: null });
+ expect(setSecret(AGENT_API_KEY, 'sk-ant-secret')).toMatchObject({ configured: true });
+ });
+});
+
+// The invariant is enforced by an absence, so it is worth a test that notices the
+// absence going away: main exposes set/clear/status and nothing that reads a
+// secret back out. Adding a fourth channel here should be a decision, not a diff.
+describe('the IPC surface', () => {
+ it('offers no way to read a secret back', async () => {
+ const main = readFileSync(new URL('../electron/main.ts', import.meta.url), 'utf8');
+ const channels = [...main.matchAll(/ipcMain\.handle\('(secret:[^']+)'/g)].map((m) => m[1]);
+ expect(channels.sort()).toEqual(['secret:clear', 'secret:set', 'secret:status']);
+ });
+});