A motion design studio on your own machine: Claude makes the video step by step, you approve every stage. Bring your own Claude Code or API key.
Keys: one place to add them, asked for before a project needs them
Gerrod Noordsye6beb12289a9
diff --git a/OVERVIEW.html b/OVERVIEW.htmlindex 37b479b..8c34baa 100644--- a/OVERVIEW.html+++ b/OVERVIEW.html@@ -283,8 +283,8 @@ flowchart LRflowchart LRroot["~/Mortiflix ($MORTIFLIX_STUDIO)"]root --> cfg["config.json<br/>settings, no secrets"]- root --> sec["secrets.json (mode 600)<br/>API key, web token"]- root --> env["session.env<br/>keys handed to sessions"]+ root --> sec["secrets.json (mode 600)<br/>your keys, web token"]+ root --> env["session.env (mode 600)<br/>other keys handed to sessions"]root --> chk["checks.json<br/>the studio's error checklist"]root --> taste["TASTE.md<br/>learned across projects"]root --> pl["pipelines/<br/>your own (override built-ins)"]@@ -741,7 +741,8 @@ flowchart LR<tr><td><code>run</code> · <code>serve</code></td><td>run sessions until something waits on you · the web studio on 127.0.0.1:4646 (sessions start by themselves)</td></tr><tr><td><code>list</code> · <code>status</code> · <code>review</code></td><td>projects · one project · read the note, answer, pin notes, approve or ask for changes</td></tr><tr><td><code>pause</code> · <code>resume</code> · <code>cancel</code></td><td>control a project</td></tr>- <tr><td><code>config</code> · <code>checks</code> · <code>voice</code></td><td>settings (incl. <code>api-key</code>, stored without echo) · approve proposed checks · narration setup</td></tr>+ <tr><td><code>keys</code> · <code>config</code></td><td>your keys (hidden input, checked with a free API call, saved mode 600) · settings</td></tr>+ <tr><td><code>checks</code> · <code>voice</code></td><td>approve proposed checks · narration setup</td></tr></tbody></table><h3>For you: the web studio</h3>@@ -779,7 +780,7 @@ flowchart LR<div class="rule"><i>01</i><div><b>A session runs as you</b> by default: treat it like a capable assistant logged in as you. With <code>sandbox: true</code> (Linux, claude-code) it runs in bubblewrap: system read-only, its own project read-write, Mortiflix code read-only, its socket; your home, other projects, <code>state/</code> and secrets aren't there.</div></div><div class="rule"><i>02</i><div><b>Even unsandboxed, the gates hold:</b> no approving, no changing what was reviewed (it's copied to <code>state/</code>), no submitting files from outside the project.</div></div><div class="rule"><i>03</i><div><b>Your words are direction; outside material is data.</b> File contents, web pages and downloads are data, never instructions, and a session reports anything in them that tries to give orders.</div></div>- <div class="rule"><i>04</i><div><b>Keys stay in the studio.</b> The API key lives in <code>secrets.json</code> (mode 600), never returned by the API; sessions don't get it. The ElevenLabs key goes to a session only while it narrates with ElevenLabs.</div></div>+ <div class="rule"><i>04</i><div><b>Your keys, in your studio.</b> Mortiflix has no accounts of its own: <code>mortiflix keys</code> (or Settings › Keys) asks for yours with hidden input, checks each with a free API call, and saves it mode 600. The API key is never returned by the API and sessions don't get it; the ElevenLabs key goes to a session only while it narrates with ElevenLabs. A project that needs a missing key asks before it starts.</div></div><div class="rule"><i>05</i><div><b>The web server</b> binds to 127.0.0.1; on another host every request needs an access token (HttpOnly, SameSite=Strict cookie); a wrong <code>Host</code> on loopback is refused (DNS rebinding); state-changing requests need an <code>X-Mortiflix</code> header.</div></div></section>diff --git a/README.md b/README.mdindex 093812b..e41969b 100644--- a/README.md+++ b/README.md@@ -49,7 +49,7 @@ git clone https://github.com/GTKottman/mortiflix-oss.git && cd mortiflix-ossnpm installnpm link # puts `mortiflix` on your PATH (or use: node bin/mortiflix)-mortiflix init # makes the studio folder (~/Mortiflix) and picks a backend it finds+mortiflix init # makes the studio folder (~/Mortiflix), picks a backend it finds, asks for your keysmortiflix demo # a full walk-through with placeholder work: free, no Claude needed```@@ -85,7 +85,22 @@ your network).| `demo` | a scripted stand-in that walks every gate with placeholder frames and a test-pattern video | nobody |Pick one with `mortiflix init --backend …`, `mortiflix config backend …`, or Settings in the web studio.-`mortiflix config api-key` stores a key without echoing it (it never leaves the studio folder except to the API).++## Your keys++Mortiflix runs on your own accounts: there's nothing to sign up for. `mortiflix init` asks for your keys, and+`mortiflix keys` changes them any time (Settings › Keys in the web studio does the same):++```+Anthropic API key only for the anthropic-api backend (Claude Code uses your own login)+ElevenLabs API key only for ElevenLabs narration, sound effects and music+Other keys anything a pipeline's tools read from the environment, e.g. GEMINI_API_KEY+```++Typing is hidden, each key is checked with a free API call before it's saved, and they're written to the studio+folder only (`secrets.json` and `session.env`, mode 600). If a project needs a key you haven't added, it asks+**before it starts** (`mortiflix new`, or the web studio's Start button) instead of failing halfway through.+For scripts: `echo "$KEY" | mortiflix keys set elevenlabs`.## What it can make todaydiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 81b999b..bccea43 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -17,8 +17,8 @@ studio.```~/Mortiflix/ ($MORTIFLIX_STUDIO or --studio to move it)config.json settings, no secrets- secrets.json API key, web token (mode 600)- session.env KEY=value lines handed to sessions (e.g. ELEVENLABS_API_KEY)+ secrets.json Anthropic and ElevenLabs keys, web token (mode 600; `mortiflix keys`)+ session.env other KEY=value lines handed to sessions, e.g. GEMINI_API_KEY (mode 600; `mortiflix keys`)checks.json the studio's error checklist: proposed by sessions, approved by youTASTE.md what you like, learned across projects (sessions add with `mfx taste`)pipelines/ your own pipelines (same slug overrides a built-in one)@@ -103,6 +103,16 @@ returns `{ ok, error?, usage?, cost_usd? }`; `available(config, root)` says whetAdding a backend is adding a module with those two functions to `BACKENDS` in `runner.mjs`.+## Keys (`src/keys.mjs`)++One registry of the keys a studio can hold (Anthropic, ElevenLabs), what each is for, and when a project needs it:+`anthropic` when it runs on the `anthropic-api` backend, `elevenlabs` when the studio narrates with ElevenLabs and the+work makes sound. `verifyKey` proves a key with a free, read-only call (`GET /v1/models`, ElevenLabs'+`/v1/user/subscription`) and tells a refused key (`ok: false`) apart from an unreachable API (`ok: null`). The CLI+(`mortiflix keys`, `init`, `new`), the web server (`/api/keys`, and `409 needs_keys` from `/start`) and the runner (a+project that lacks a key for its next steps pauses with `NEEDS_YOU` instead of starting a session) all ask it. Other+keys for sessions go to `session.env` through `setSessionKey`; only their names are ever shown.+## Narration (`src/voice/`)`voice/index.mjs` holds the studio's choice (`config.json` › `voice`: `none`, `elevenlabs` or `qwen`) and hands adiff --git a/docs/SECURITY.md b/docs/SECURITY.mdindex 50beca2..67c82ab 100644--- a/docs/SECURITY.md+++ b/docs/SECURITY.md@@ -44,12 +44,19 @@ rule it out. If you hand a session files or links from sources you don't trust,## Keys-- The Anthropic API key (Settings or `mortiflix config api-key`) is stored in `secrets.json` (mode 600) and is never- returned by the API or shown in the UI. Sessions don't get it.-- The ElevenLabs key (Settings › Narration or `mortiflix voice elevenlabs`) is stored in `secrets.json` too, and- given to a session only while ElevenLabs is the narration engine.-- `session.env` keys are given to every session's environment. Only put keys there that- sessions need, and prefer keys with spending limits.+Every key is yours: Mortiflix has no accounts of its own. You add them with `mortiflix keys` (asked at+`mortiflix init`, and before a project starts if it needs one) or Settings › Keys. Typing is never echoed, and each+key is checked with a free, read-only API call before it's saved.++- A new studio folder is created mode 700 (only you can open it).+- The Anthropic API key is stored in `secrets.json` (mode 600) and is never returned by the API or shown in the UI.+ Sessions don't get it.+- The ElevenLabs key is stored in `secrets.json` too, and given to a session only while ElevenLabs is the narration+ engine.+- Other keys go to `session.env` (mode 600) and are given to every session's environment. The UI shows their names,+ never their values. Only add keys that sessions need, and prefer keys with spending limits.+- The runner checks a project's keys before each session: if one is missing, the project pauses and tells you which,+ instead of starting a session that would fail.## The web serverdiff --git a/docs/VOICE.md b/docs/VOICE.mdindex a829f37..b6e0b93 100644--- a/docs/VOICE.md+++ b/docs/VOICE.md@@ -17,7 +17,7 @@ is made again, and the timings of every word go to the animation.## ElevenLabs1. Get an API key: elevenlabs.io › Developers › API keys.-2. Settings › Narration › ElevenLabs, paste it, **Connect**. You'll see your plan, credits left, when they reset,+2. `mortiflix keys` (or Settings › Narration › ElevenLabs), paste it, **Connect**. You'll see your plan, credits left, when they reset,and whether you may use the audio commercially.3. **Choose a voice**: your voices and the default voices, or **Browse the Voice Library** (thousands of communityvoices; "Add & use" copies one into your account). ▶ plays each voice's own preview, free.diff --git a/src/cli.mjs b/src/cli.mjsindex c90a71e..7dfcd4b 100644--- a/src/cli.mjs+++ b/src/cli.mjs@@ -3,12 +3,13 @@ import { createInterface } from 'node:readline';import { existsSync, createReadStream, statSync, writeFileSync } from 'node:fs';import { join, basename, resolve } from 'node:path';import { spawnSync, spawn } from 'node:child_process';-import { studioRoot, ensureStudio, loadConfig, saveConfig, writeSecret, paths, readJson } from './studio.mjs';+import { studioRoot, ensureStudio, loadConfig, saveConfig, paths, readJson } from './studio.mjs';import { listPipelines, findPipeline } from './pipelines.mjs';import { createProject, addIntakeFile, startProject, listProjects, loadProject, projectPaths, projectPipeline, readEvents } from './projects.mjs';import * as gates from './gates.mjs';import { Runner, BACKENDS } from './runner.mjs';import * as voice from './voice/index.mjs';+import * as keys from './keys.mjs';const C = process.stdout.isTTY && !process.env.NO_COLOR? { b: (s) => `\x1b[1m${s}\x1b[0m`, dim: (s) => `\x1b[2m${s}\x1b[0m`, acc: (s) => `\x1b[38;5;208m${s}\x1b[0m`, red: (s) => `\x1b[31m${s}\x1b[0m`, green: (s) => `\x1b[32m${s}\x1b[0m` }@@ -18,6 +19,7 @@ const HELP = `${C.b('mortiflix')}: a motion design studio on your machine. Claud${C.b('Getting started')}mortiflix init [--backend claude-code|anthropic-api|demo] set up the studio (~/Mortiflix, or $MORTIFLIX_STUDIO)+ mortiflix keys add or change your keys (Anthropic, ElevenLabs, others)mortiflix doctor check the tools a pipeline needsmortiflix demo a full walk-through with placeholder work (free)@@ -42,7 +44,8 @@ const HELP = `${C.b('mortiflix')}: a motion design studio on your machine. Claud${C.b('Settings')}mortiflix config [key [value]] show or change settings- mortiflix config api-key store an Anthropic API key (asked, not echoed)+ mortiflix keys set <anthropic|elevenlabs|NAME> set one key (typed hidden, or piped on stdin)+ mortiflix keys remove <anthropic|elevenlabs|NAME>mortiflix checks [approve|reject <id>] the error checklist sessions proposed--studio <dir> works with every command.`;@@ -67,6 +70,7 @@ export async function run(argv = process.argv.slice(2)) {const dispatch = async () => {switch (cmd) {case 'init': return init(root, a);+ case 'keys': return keysCmd(root, rest);case 'doctor': return doctor(root);case 'demo': return demo(root);case 'pipelines': return pipelines(root);@@ -140,7 +144,7 @@ function detectBackend(root) {return 'demo';}-function init(root, a) {+async function init(root, a) {const fresh = !existsSync(paths(root).config);ensureStudio(root);const backend = typeof a.backend === 'string' ? a.backend : (fresh ? detectBackend(root) : loadConfig(root).backend);@@ -148,7 +152,12 @@ function init(root, a) {saveConfig(root, { backend });console.log(`${C.green('✔')} Studio ready at ${C.b(root)}`);console.log(` Backend: ${C.b(backend)} ${C.dim(BACKENDS[backend].available(loadConfig(root), root).detail)}`);- if (backend === 'demo') console.log(C.dim(' (No Claude Code login or API key found: the demo backend makes placeholder work. Install Claude Code, or `mortiflix config api-key`.)'));+ if (backend === 'demo') console.log(C.dim(' (No Claude Code login or API key found: the demo backend makes placeholder work. Install Claude Code, or add an API key with `mortiflix keys`.)'));+ if (process.stdin.isTTY && !a.yes) {+ console.log(`\n ${C.b('Keys')}: Mortiflix runs on your own accounts. Keys stay in this studio folder, readable by you alone.`);+ const go = (await prompterOnce(` Add them now? ${C.dim('[Y/n]')} `)).trim().toLowerCase();+ if (!go.startsWith('n')) await keysWalk(root);+ } else console.log(`\n ${C.b('Keys')}: ${C.b('mortiflix keys')} when you want an API backend or ElevenLabs narration.`);console.log(`\n ${C.b('Narration')} (optional): ${voiceOffer()}`);console.log(`\n Next: ${C.b('mortiflix demo')} for a free walk-through, or ${C.b('mortiflix serve')} to open the studio in your browser.`);}@@ -168,8 +177,11 @@ function doctor(root) {row(r.status === 0 || (bin === 'npx' && spawnSync('npx', ['--version']).status === 0), bin, why);}if (process.platform === 'linux') row(spawnSync('bwrap', ['--version']).status === 0, 'bwrap', `optional session sandbox (${config?.sandbox ? 'on' : 'off'})`);- const env = existsSync(paths(root).sessionEnv);- row(true, 'session.env', env ? 'present (keys handed to sessions)' : 'none (optional: e.g. ELEVENLABS_API_KEY for narration)');+ for (const k of keys.keyStatus(root)) {+ row(Boolean(k.source) || !k.in_use, k.id, k.source ? `${k.name}: ${k.source}${k.in_use ? ' ← in use' : ''}` : k.in_use ? `${k.name} missing: mortiflix keys` : `${k.name}: not set (optional)`);+ }+ const extra = keys.sessionKeyNames(root);+ row(true, 'session.env', extra.length ? `other keys for sessions: ${extra.join(', ')}` : 'no other keys (optional: mortiflix keys)');}function pipelines(root) {@@ -216,6 +228,13 @@ async function newProject(root, slug, a) {}}for (const q of pipeline.intake) if (q.type === 'choice' && answers[q.id] === undefined && q.default) answers[q.id] = q.default;+ // Before anything is made: the keys this project will need, asked for here instead of failing mid-project.+ const missing = keys.missingKeys(root, { backend: typeof a.backend === 'string' ? a.backend : null, pipeline });+ if (missing.length) {+ if (!tty) throw new Error(keys.missingKeysText(missing, 'run this again'));+ console.log(`\n${C.acc('●')} Before it starts: this project needs your ${missing.map((id) => keys.KEYS[id].name).join(' and ')}.`);+ for (const id of missing) if (!(await askKey(root, id, { required: true }))) throw new Error(`no ${keys.KEYS[id].name}: nothing was created`);+ }const p = createProject(root, { pipeline: slug, title, answers, backend: typeof a.backend === 'string' ? a.backend : null });for (const f of files) {if (!existsSync(f.path) || !statSync(f.path).isFile()) throw new Error(`no file ${f.path}`);@@ -363,11 +382,7 @@ async function serve(root, a) {async function config(root, [key, value]) {needStudio(root);- if (key === 'api-key') {- const k = (await hiddenPrompt('Anthropic API key (blank to remove): ')).trim();- writeSecret(root, 'anthropic_api_key', k || null);- return console.log(k ? `${C.green('✔')} Saved (only in ${paths(root).secrets}, readable by you alone).` : 'Removed.');- }+ if (key === 'api-key') return keysCmd(root, ['set', 'anthropic']); // older spelling of `mortiflix keys set anthropic`const cur = loadConfig(root);if (!key) {for (const [k, v] of Object.entries(cur)) console.log(`${k.padEnd(18)} ${JSON.stringify(v)}`);@@ -408,6 +423,88 @@ function hiddenPrompt(question) {});}+// ---- keys ----++const SOURCE_WORDS = { saved: 'saved in this studio', 'session.env': 'from session.env', environment: 'from your environment' };++function showKeys(root) {+ console.log(`${C.b('Your keys')} ${C.dim(`(in ${paths(root).secrets} and session.env, readable by you alone; never shown)`)}`);+ for (const k of keys.keyStatus(root)) {+ const mark = k.source ? C.green('✔') : k.in_use ? C.red('✖') : C.dim('·');+ console.log(` ${mark} ${k.name.padEnd(20)} ${k.source ? SOURCE_WORDS[k.source] : k.in_use ? C.red('missing: your studio uses it') : C.dim('not set')}${k.source && k.in_use ? C.dim(' ← in use') : ''}`);+ }+ const extra = keys.sessionKeyNames(root);+ console.log(` ${C.dim('·')} ${'Other keys'.padEnd(20)} ${extra.length ? extra.join(', ') : C.dim('none')} ${C.dim('(handed to every session)')}`);+}++// Ask for one key without echoing it, check it with a free call, and save it. Returns where the key now comes from+// (null if there's none). Enter keeps what's there (or skips), "-" removes a saved key.+async function askKey(root, id, { required = false } = {}) {+ const k = keys.KEYS[id];+ const source = keys.keySource(root, id);+ console.log(`\n${C.b(k.name)} ${C.dim(`For ${k.for}`)}`);+ console.log(C.dim(` Get one at ${k.get}`));+ const hint = source ? `Enter keeps the one ${SOURCE_WORDS[source].replace(/^saved /, '')}${source === 'saved' ? ', - removes it' : ''}` : required ? 'Enter to stop' : 'Enter skips';+ for (;;) {+ const v = (await hiddenPrompt(` Paste it ${C.dim(`(hidden; ${hint})`)}: `)).trim();+ if (!v) return source;+ if (v === '-') { keys.saveKey(root, id, null); console.log(' Removed.'); return keys.keySource(root, id); }+ process.stdout.write(C.dim(' Checking… '));+ const r = await keys.verifyKey(root, id, v);+ if (r.ok === false) { console.log(C.red(`✖ ${r.detail}. Try again.`)); continue; }+ keys.saveKey(root, id, v);+ if (r.tier) voice.saveVoice(root, { elevenlabs: { tier: r.tier } });+ console.log(r.ok ? `${C.green('✔')} ${r.detail}. Saved.` : `${C.acc('●')} Saved, but ${r.detail}.`);+ return 'saved';+ }+}++// The walk-through: every key in turn, then any others sessions should get.+async function keysWalk(root) {+ for (const id of Object.keys(keys.KEYS)) await askKey(root, id);+ console.log(`\n${C.b('Other keys for sessions')} ${C.dim('Anything a pipeline\'s tools read from the environment, e.g. GEMINI_API_KEY.')}`);+ for (;;) {+ const name = (await prompterOnce(` Name ${C.dim('(Enter when done)')}: `)).trim().toUpperCase();+ if (!name) break;+ const value = (await hiddenPrompt(` ${name} ${C.dim('(hidden; Enter removes it)')}: `)).trim();+ try { keys.setSessionKey(root, name, value); console.log(value ? ` ${C.green('✔')} Saved.` : ' Removed.'); } catch (e) { console.log(C.red(` ✖ ${e.message}`)); }+ }+ console.log();+ showKeys(root);+ const v = voice.voiceConfig(root);+ if (keys.keySource(root, 'elevenlabs') && v.engine !== 'elevenlabs') console.log(`\n To narrate with it: ${C.b('mortiflix voice elevenlabs')} (pick a voice and model).`);+}++async function keysCmd(root, [sub, name]) {+ needStudio(root);+ if (sub === 'set' || sub === 'remove') {+ if (!name) throw new Error(`mortiflix keys ${sub} <${Object.keys(keys.KEYS).join('|')}|NAME>`);+ const id = keys.KEYS[name.toLowerCase()] ? name.toLowerCase() : null;+ if (sub === 'remove') {+ if (id) keys.saveKey(root, id, null); else keys.setSessionKey(root, name, null);+ return console.log('Removed.');+ }+ if (id && process.stdin.isTTY) return askKey(root, id);+ const value = (await hiddenPrompt(process.stdin.isTTY ? `${name} ${C.dim('(hidden)')}: ` : '')).trim();+ if (!value) throw new Error('no key given');+ if (!id) { keys.setSessionKey(root, name, value); return console.log(`${C.green('✔')} ${name} saved in session.env.`); }+ const r = await keys.verifyKey(root, id, value);+ if (r.ok === false) throw new Error(r.detail);+ keys.saveKey(root, id, value);+ if (r.tier) voice.saveVoice(root, { elevenlabs: { tier: r.tier } });+ return console.log(`${C.green('✔')} ${keys.KEYS[id].name} saved${r.ok ? ` (${r.detail})` : `, but ${r.detail}`}.`);+ }+ if (sub) throw new Error('mortiflix keys [set|remove <name>]');+ if (!process.stdin.isTTY) return showKeys(root);+ return keysWalk(root);+}++// One visible line from the terminal (a fresh readline each time, so it can take turns with hiddenPrompt).+async function prompterOnce(question) {+ const rl = prompter();+ try { return (await rl.question(question)) ?? ''; } catch { return ''; } finally { rl.close(); }+}+function checks(root, [action, id]) {needStudio(root);if (action === 'approve' || action === 'reject') {@@ -450,9 +547,7 @@ async function voiceCmd(root, [sub, ...words]) {if (sub === 'elevenlabs') {if (!voice.elevenKey(root)) {rl.close();- const key = (await hiddenPrompt('ElevenLabs API key (elevenlabs.io › Developers › API keys): ')).trim();- if (!key) throw new Error('no key given');- voice.setElevenKey(root, key);+ if (!(await askKey(root, 'elevenlabs', { required: true }))) throw new Error('no key given');return voiceCmd(root, ['elevenlabs']);}const el = new voice.eleven.ElevenLabs({ key: voice.elevenKey(root), server: v.elevenlabs.server });@@ -521,7 +616,7 @@ async function voiceTest(root, text) {// The walk-through: a logo sting made by the demo backend, so the whole loop can be tried for free.async function demo(root) {- if (!existsSync(paths(root).config)) init(root, {});+ if (!existsSync(paths(root).config)) await init(root, { yes: true });const logo = join(paths(root).run, 'demo-logo.svg');writeFileSync(logo, '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200"><circle cx="100" cy="100" r="80" fill="#f97316"/><text x="100" y="118" text-anchor="middle" font-size="56" font-family="sans-serif" fill="#fff">M</text></svg>');const id = await newProject(root, 'logo-sting', { _: [], set: ['mood=calm and premium'], file: [`logo=${logo}`], title: 'Demo sting', backend: 'demo', yes: true });diff --git a/src/keys.mjs b/src/keys.mjsnew file mode 100644index 0000000..237a4e8--- /dev/null+++ b/src/keys.mjs@@ -0,0 +1,123 @@+// The studio's keys in one place: what each one is for, when a project needs it, where it's kept, and a free check+// that it works. Values live in secrets.json (mode 600, in the studio folder) and are never printed, served or logged.+// Extra keys for sessions (anything a pipeline's tools read from the environment) live in session.env, also mode 600.+import { readSecret, writeSecret, loadConfig, readSessionEnv, writeSessionEnv, UserError } from './studio.mjs';+import { loadProject, projectPipeline } from './projects.mjs';+import { stepView } from './gates.mjs';+import { credentials as anthropicCredentials } from './backends/anthropic-api.mjs';+import { voiceConfig } from './voice/index.mjs';+import { ElevenLabs } from './voice/elevenlabs.mjs';++export const KEYS = {+ anthropic: {+ name: 'Anthropic API key',+ secret: 'anthropic_api_key',+ env: 'ANTHROPIC_API_KEY',+ get: 'console.anthropic.com › Settings › API keys',+ for: 'the Claude API backend (you pay per token). Not needed with Claude Code, which uses your own login.',+ },+ elevenlabs: {+ name: 'ElevenLabs API key',+ secret: 'elevenlabs_api_key',+ env: 'ELEVENLABS_API_KEY',+ get: 'elevenlabs.io › Developers › API keys',+ for: 'narration, sound effects and music with ElevenLabs. Not needed for local narration (Qwen3-TTS) or none.',+ },+};++// Where a key comes from: saved in this studio, session.env, the environment Mortiflix was started with, or nowhere.+export function keySource(root, id) {+ const k = KEYS[id];+ if (!k) throw new UserError(`unknown key "${id}" (${Object.keys(KEYS).join(', ')})`);+ if (readSecret(root, k.secret)) return 'saved';+ if (id === 'elevenlabs' && readSessionEnv(root)[k.env]) return 'session.env';+ if (process.env[k.env]) return 'environment';+ if (id === 'anthropic' && anthropicCredentials(root).other) return 'environment';+ return null;+}++// Which keys a project uses, given how the studio is set up. `steps` narrows it to the work that's about to run.+// anthropic: the project runs on the Claude API backend+// elevenlabs: the studio narrates with ElevenLabs and the work makes sound (voice, effects, music)+export function keysFor(root, { backend, pipeline, steps } = {}) {+ const using = backend || loadConfig(root).backend;+ if (using === 'demo') return [];+ const need = [];+ if (using === 'anthropic-api') need.push('anthropic');+ const work = (steps || pipeline?.steps || []).flatMap((s) => s.work || []);+ if (voiceConfig(root).engine === 'elevenlabs' && work.includes('audio')) need.push('elevenlabs');+ return need;+}++export function missingKeys(root, opts) {+ return keysFor(root, opts).filter((id) => !keySource(root, id));+}++// What a project still lacks: for the whole project before it starts, or (`upcoming`) for the steps that can run now.+export function projectMissingKeys(root, projectId, { upcoming = false } = {}) {+ const p = loadProject(root, projectId);+ const pipeline = projectPipeline(root, projectId);+ const steps = upcoming ? stepView(p, pipeline).filter((s) => ['ready', 'working', 'changes'].includes(s.state)) : pipeline.steps;+ return missingKeys(root, { backend: p.backend, steps });+}++export function missingKeysText(ids, then = 'resume') {+ const names = ids.map((id) => KEYS[id].name);+ const fix = ids.includes('elevenlabs') ? ' (or pick another narration engine in Settings › Narration)' : '';+ return `This project needs your ${names.join(' and ')}. Add ${ids.length > 1 ? 'them' : 'it'} with \`mortiflix keys\` or in Settings › Keys${fix}, then ${then}.`;+}++export function keyStatus(root) {+ const config = loadConfig(root);+ const inUse = keysFor(root, { backend: config.backend, steps: [{ work: ['audio'] }] });+ return Object.entries(KEYS).map(([id, k]) => ({ id, name: k.name, get: k.get, for: k.for, env: k.env, source: keySource(root, id), in_use: inUse.includes(id) }));+}++export function saveKey(root, id, value) {+ const k = KEYS[id];+ if (!k) throw new UserError(`unknown key "${id}" (${Object.keys(KEYS).join(', ')})`);+ const v = value ? String(value).trim() : '';+ if (/\s/.test(v)) throw new UserError(`that doesn't look like an ${k.name} (it has spaces in it)`);+ writeSecret(root, k.secret, v || null);+}++// A free, read-only call that proves the key works. ok: true (works), false (refused), null (couldn't reach the API).+export async function verifyKey(root, id, value, { fetch = globalThis.fetch } = {}) {+ const key = String(value || '').trim();+ try {+ if (id === 'anthropic') {+ const res = await fetch('https://api.anthropic.com/v1/models?limit=1', { headers: { 'x-api-key': key, 'anthropic-version': '2023-06-01' } });+ if (res.ok) return { ok: true, detail: 'the Claude API accepted it' };+ if (res.status === 401 || res.status === 403) return { ok: false, detail: 'the Claude API refused it (check that you copied the whole key)' };+ return { ok: null, detail: `couldn't check it (Claude API answered ${res.status})` };+ }+ if (id === 'elevenlabs') {+ const a = await new ElevenLabs({ key, server: voiceConfig(root).elevenlabs.server, fetch }).account();+ const left = Number.isFinite(a.characters_left) ? ` · ${a.characters_left.toLocaleString()} credits left` : '';+ return { ok: true, detail: `${a.tier} plan${left}${a.commercial_use ? ' · commercial use' : ' · free plan: non-commercial, credit ElevenLabs'}`, tier: a.tier };+ }+ } catch (e) {+ if (e.status === 401 && /permission/i.test(e.message)) return { ok: true, detail: 'it works, but can\'t read your plan (give the key the "User: read" permission to see credits here)' };+ if (e.status === 401 || e.status === 403) return { ok: false, detail: 'ElevenLabs refused it (check that you copied the whole key)' };+ return { ok: null, detail: `couldn't check it (${e.message})` };+ }+ throw new UserError(`unknown key "${id}"`);+}++// ---- session.env: other keys handed to every session (names are shown, values never) ----++const ENV_NAME = /^[A-Z][A-Z0-9_]{1,63}$/;++export function sessionKeyNames(root) {+ return Object.keys(readSessionEnv(root));+}++export function setSessionKey(root, name, value) {+ if (!ENV_NAME.test(name || '')) throw new UserError('key names are UPPER_CASE, e.g. GEMINI_API_KEY');+ if (Object.values(KEYS).some((k) => k.env === name)) throw new UserError(`${name} has its own place: \`mortiflix keys\` (or Settings › Keys)`);+ const v = value ? String(value).trim() : '';+ if (/[\r\n]/.test(v)) throw new UserError('a key is one line');+ const env = readSessionEnv(root);+ if (v) env[name] = v; else delete env[name];+ writeSessionEnv(root, env);+}diff --git a/src/runner.mjs b/src/runner.mjsindex fdfe432..af4f90d 100644--- a/src/runner.mjs+++ b/src/runner.mjs@@ -6,7 +6,8 @@ import { join } from 'node:path';import { REPO, paths, loadConfig, readSessionEnv } from './studio.mjs';import { sessionVoiceEnv } from './voice/index.mjs';import { listProjects, loadProject, projectPaths, projectPipeline, update, event, readEvents, now } from './projects.mjs';-import { settle } from './gates.mjs';+import { settle, needsYou } from './gates.mjs';+import { projectMissingKeys, missingKeysText } from './keys.mjs';import { prepareWorkdir, writeTorch, sessionReason } from './torch.mjs';import { openBridge } from './bridge.mjs';import { RenderQueue } from './renderq.mjs';@@ -96,6 +97,14 @@ export class Runner extends EventEmitter {async runSession(projectId) {const root = this.root;+ // A key the next steps need is missing: ask for it now, rather than let a session fail halfway through.+ const missing = projectMissingKeys(root, projectId, { upcoming: true });+ if (missing.length) {+ needsYou(root, projectId, missingKeysText(missing));+ this.log(`‖ ${projectId}: needs a key (${missing.join(', ')})`);+ this.emit('change');+ return;+ }const config = loadConfig(root);// A project can pin its own backend (the demo project does); otherwise the studio's setting.const backendName = loadProject(root, projectId).backend || config.backend;diff --git a/src/studio.mjs b/src/studio.mjsindex 0636a71..ef52f58 100644--- a/src/studio.mjs+++ b/src/studio.mjs@@ -2,8 +2,8 @@//// <studio>/// config.json settings (backend, model, port...). No secrets.-// secrets.json the Anthropic API key, if you gave one here (mode 600). Never served, never logged.-// session.env extra keys handed to sessions (e.g. ELEVENLABS_API_KEY=...), mode 600+// secrets.json your Anthropic and ElevenLabs keys (mode 600), set with `mortiflix keys`. Never served, never logged.+// session.env other keys handed to every session (e.g. GEMINI_API_KEY=...), mode 600, also set with `mortiflix keys`// checks.json the studio's error checklist (grows from your feedback)// pipelines/<slug>/ your own pipelines (override the built-in ones with the same slug)// projects/<id>/ the session's working folder (it runs here)@@ -55,7 +55,9 @@ export function paths(root) {export function ensureStudio(root) {const p = paths(root);- for (const d of [p.root, p.pipelines, p.projects, p.state, p.run]) mkdirSync(d, { recursive: true });+ // A new studio is yours alone: it holds your keys and your clients' material.+ if (!existsSync(p.root)) mkdirSync(p.root, { recursive: true, mode: 0o700 });+ for (const d of [p.pipelines, p.projects, p.state, p.run]) mkdirSync(d, { recursive: true });if (!existsSync(p.config)) writeJson(p.config, { backend: DEFAULT_CONFIG.backend });if (!existsSync(p.checks)) writeJson(p.checks, { active: [], proposed: [] });return p;@@ -101,6 +103,15 @@ export function readSessionEnv(root) {return env;}+export function writeSessionEnv(root, env) {+ const p = paths(root).sessionEnv;+ const lines = Object.entries(env).map(([k, v]) => `${k}=${v}`);+ const tmp = `${p}.${process.pid}.tmp`;+ writeFileSync(tmp, lines.length ? `${lines.join('\n')}\n` : '', { mode: 0o600 });+ chmodSync(tmp, 0o600);+ renameSync(tmp, p);+}+// ---- small file helpers used everywhere ----export function readJson(file) {diff --git a/src/web/server.mjs b/src/web/server.mjsindex 711130d..c69860c 100644--- a/src/web/server.mjs+++ b/src/web/server.mjs@@ -15,6 +15,7 @@ import { createProject, addIntakeFile, startProject, listProjects, loadProject,import * as gates from '../gates.mjs';import { Runner, BACKENDS } from '../runner.mjs';import * as voice from '../voice/index.mjs';+import * as keys from '../keys.mjs';const MIME = {'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',@@ -104,6 +105,21 @@ export async function startServer(root, { port = 4646, host = '127.0.0.1', runnereturn after(studioInfo(root, runner));}if (p.startsWith('/voice')) return voiceApi(root, req, res, url, p, method, after);+ // Keys: their status (never their values), and setting one (checked with a free call before it's saved).+ if (p === '/keys' && method === 'GET') return send(res, 200, keysInfo(root));+ if ((m = p.match(/^\/keys\/([A-Za-z][A-Za-z0-9_]*)$/)) && (method === 'PUT' || method === 'DELETE')) {+ const id = keys.KEYS[m[1]] ? m[1] : null;+ const value = method === 'PUT' ? String((await json(req)).value || '').trim() : '';+ if (method === 'PUT' && !value) throw new BadRequest('paste a key');+ let check = null;+ if (id && value) {+ check = await keys.verifyKey(root, id, value);+ if (check.ok === false) throw new BadRequest(check.detail);+ if (check.tier) voice.saveVoice(root, { elevenlabs: { tier: check.tier } });+ }+ if (id) keys.saveKey(root, id, value || null); else keys.setSessionKey(root, m[1], value || null);+ return after({ ...keysInfo(root), check });+ }if (p === '/pipelines' && method === 'GET') {return send(res, 200, listPipelines(root).map(({ dir, ...x }) => x));}@@ -130,7 +146,12 @@ export async function startServer(root, { port = 4646, host = '127.0.0.1', runneconst rel = await addIntakeFile(root, id, { field, name, stream: req });return after({ path: rel });}- if (sub === '/start' && method === 'POST') return after(startProject(root, id) && { ok: true });+ if (sub === '/start' && method === 'POST') {+ // Ask for the keys this project will need now, not halfway through it.+ const missing = keys.projectMissingKeys(root, id);+ if (missing.length) return send(res, 409, { error: keys.missingKeysText(missing, 'start it'), needs_keys: missing });+ return after(startProject(root, id) && { ok: true });+ }if (sub === '/pause' && method === 'POST') { gates.pause(root, id); runner.stopProject(id); return after(); }if (sub === '/resume' && method === 'POST') { gates.resume(root, id); return after(); }if (sub === '/cancel' && method === 'POST') { gates.cancel(root, id); runner.stopProject(id); return after(); }@@ -309,6 +330,10 @@ function json(req, limit = 2_000_000) {});}+function keysInfo(root) {+ return { keys: keys.keyStatus(root), other: keys.sessionKeyNames(root) };+}+function studioInfo(root, runner) {const config = loadConfig(root);const backends = {};diff --git a/test/keys.test.mjs b/test/keys.test.mjsnew file mode 100644index 0000000..f0ba418--- /dev/null+++ b/test/keys.test.mjs@@ -0,0 +1,130 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { randomBytes } from 'node:crypto';+import { request } from 'node:http';+import { tempStudio } from './helpers.mjs';+import { paths, readSessionEnv } from '../src/studio.mjs';+import * as keys from '../src/keys.mjs';+import { saveVoice, sessionVoiceEnv } from '../src/voice/index.mjs';+import { findPipeline } from '../src/pipelines.mjs';+import { createProject, addIntakeFile, startProject, loadProject } from '../src/projects.mjs';+import { Runner } from '../src/runner.mjs';+import { startServer } from '../src/web/server.mjs';++// Keys from the machine running the tests must not count as "set".+for (const k of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_PROFILE', 'ELEVENLABS_API_KEY']) delete process.env[k];++const mode = (f) => statSync(f).mode & 0o777;++test('keys: which a project needs follows the backend and the narration engine', (t) => {+ const root = tempStudio(t);+ const explainer = findPipeline(root, 'explainer');+ assert.deepEqual(keys.keysFor(root, { backend: 'demo', pipeline: explainer }), []);+ assert.deepEqual(keys.keysFor(root, { backend: 'claude-code', pipeline: explainer }), []);+ assert.deepEqual(keys.keysFor(root, { backend: 'anthropic-api', pipeline: explainer }), ['anthropic']);+ saveVoice(root, { engine: 'elevenlabs' });+ assert.deepEqual(keys.keysFor(root, { backend: 'claude-code', pipeline: explainer }), ['elevenlabs']);+ // Only work that makes sound needs the narration key.+ assert.deepEqual(keys.keysFor(root, { backend: 'claude-code', steps: explainer.steps.filter((s) => s.key === 'script') }), []);+ saveVoice(root, { engine: 'qwen' });+ assert.deepEqual(keys.keysFor(root, { backend: 'claude-code', pipeline: explainer }), []);+});++test('keys: saved mode 600, reported by where they come from, never by value', (t) => {+ const root = tempStudio(t);+ assert.equal(mode(root), 0o700);+ keys.saveKey(root, 'elevenlabs', ' xi-secret ');+ assert.equal(mode(paths(root).secrets), 0o600);+ assert.equal(keys.keySource(root, 'elevenlabs'), 'saved');+ assert.equal(sessionVoiceEnv(root).ELEVENLABS_API_KEY, undefined); // narration is off: sessions don't get it+ saveVoice(root, { engine: 'elevenlabs' });+ assert.equal(sessionVoiceEnv(root).ELEVENLABS_API_KEY, 'xi-secret');+ assert.ok(!JSON.stringify(keys.keyStatus(root)).includes('xi-secret'));+ assert.throws(() => keys.saveKey(root, 'elevenlabs', 'two words'), /spaces/);+ assert.throws(() => keys.saveKey(root, 'nope', 'x'), /unknown key/);+ keys.saveKey(root, 'elevenlabs', null);+ assert.equal(keys.keySource(root, 'elevenlabs'), null);+});++test('keys: other keys go to session.env (mode 600), with names checked', (t) => {+ const root = tempStudio(t);+ keys.setSessionKey(root, 'GEMINI_API_KEY', 'g-secret');+ keys.setSessionKey(root, 'OTHER_KEY', 'o-secret');+ assert.equal(mode(paths(root).sessionEnv), 0o600);+ assert.deepEqual(readSessionEnv(root), { GEMINI_API_KEY: 'g-secret', OTHER_KEY: 'o-secret' });+ assert.deepEqual(keys.sessionKeyNames(root), ['GEMINI_API_KEY', 'OTHER_KEY']);+ keys.setSessionKey(root, 'OTHER_KEY', '');+ assert.equal(readFileSync(paths(root).sessionEnv, 'utf8'), 'GEMINI_API_KEY=g-secret\n');+ assert.throws(() => keys.setSessionKey(root, 'lower', 'x'), /UPPER_CASE/);+ assert.throws(() => keys.setSessionKey(root, 'ELEVENLABS_API_KEY', 'x'), /its own place/);+ assert.throws(() => keys.setSessionKey(root, 'A_KEY', 'x\ny'), /one line/);+});++test('keys: checked with a free call, and a refused key is told apart from an unreachable API', async (t) => {+ const root = tempStudio(t);+ const reply = (status, body = {}) => async () => new Response(JSON.stringify(body), { status });+ assert.equal((await keys.verifyKey(root, 'anthropic', 'k', { fetch: reply(200, { data: [] }) })).ok, true);+ assert.equal((await keys.verifyKey(root, 'anthropic', 'k', { fetch: reply(401) })).ok, false);+ assert.equal((await keys.verifyKey(root, 'anthropic', 'k', { fetch: async () => { throw new Error('offline'); } })).ok, null);+ const plan = await keys.verifyKey(root, 'elevenlabs', 'k', { fetch: reply(200, { tier: 'creator', character_count: 1000, character_limit: 100000 }) });+ assert.equal(plan.ok, true);+ assert.match(plan.detail, /creator plan · 99,000 credits left · commercial use/);+ assert.equal((await keys.verifyKey(root, 'elevenlabs', 'k', { fetch: reply(401, { detail: { message: 'Invalid API key' } }) })).ok, false);+});++test('the runner asks for a missing key instead of starting a session that would fail', async (t) => {+ const root = tempStudio(t);+ const p = createProject(root, { pipeline: 'logo-sting', title: 'Keyless', backend: 'anthropic-api' });+ await addIntakeFile(root, p.id, { field: 'logo', name: 'logo.svg', buffer: Buffer.from('<svg/>') });+ startProject(root, p.id);+ const runner = new Runner(root);+ runner.acquire();+ t.after(() => runner.release());+ await runner.loop();+ const after = loadProject(root, p.id);+ assert.equal(after.state, 'paused');+ assert.match(after.needs_you.text, /Anthropic API key.*mortiflix keys/);+ assert.equal(after.usage.sessions, 0);+});++function call(socketPath, method, path, body) {+ return new Promise((ok, fail) => {+ const req = request({ socketPath, method, path, headers: { host: 'localhost', ...(method !== 'GET' ? { 'x-mortiflix': '1', 'content-type': 'application/json' } : {}) } }, (res) => {+ let data = '';+ res.on('data', (c) => { data += c; });+ res.on('end', () => ok({ status: res.statusCode, text: data, json: JSON.parse(data || '{}') }));+ });+ req.on('error', fail);+ req.end(body === undefined ? null : JSON.stringify(body));+ });+}++test('web: a project that needs a key says which before it starts; keys are set but never shown', async (t) => {+ const root = tempStudio(t, { backend: 'claude-code' });+ saveVoice(root, { engine: 'elevenlabs' });+ const socketPath = join(tmpdir(), `mfx-keys-${randomBytes(4).toString('hex')}.sock`);+ const srv = await startServer(root, { socketPath, quiet: true, runner: false });+ t.after(() => srv.close());+ const s = (...a) => call(socketPath, ...a);++ const { json: created } = await s('POST', '/api/projects', { pipeline: 'explainer', title: 'Needs a voice', answers: { topic: 'bikes' } });+ const refused = await s('POST', `/api/projects/${created.id}/start`);+ assert.equal(refused.status, 409);+ assert.deepEqual(refused.json.needs_keys, ['elevenlabs']);+ assert.equal(loadProject(root, created.id).state, 'draft');++ const other = await s('PUT', '/api/keys/GEMINI_API_KEY', { value: 'g-secret' });+ assert.deepEqual(other.json.other, ['GEMINI_API_KEY']);+ assert.ok(!other.text.includes('g-secret'));+ assert.equal((await s('PUT', '/api/keys/elevenlabs', { value: '' })).status, 400);++ keys.saveKey(root, 'elevenlabs', 'xi-secret'); // as a successful PUT would (that one checks with ElevenLabs first)+ const listed = await s('GET', '/api/keys');+ assert.equal(listed.json.keys.find((k) => k.id === 'elevenlabs').source, 'saved');+ assert.ok(!listed.text.includes('xi-secret'));+ assert.equal((await s('POST', `/api/projects/${created.id}/start`)).status, 200);+ assert.equal((await s('DELETE', '/api/keys/GEMINI_API_KEY')).json.other.length, 0);+});diff --git a/web/app.js b/web/app.jsindex 3f5c59a..17fa3bb 100644--- a/web/app.js+++ b/web/app.js@@ -34,13 +34,13 @@ async function api(path, { method = 'GET', body, raw } = {}) {else if (body !== undefined) { opts.body = JSON.stringify(body); opts.headers['content-type'] = 'application/json'; }const res = await fetch(path, opts);const data = await res.json().catch(() => ({}));- if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);+ if (!res.ok) throw Object.assign(new Error(data.error || `HTTP ${res.status}`), { status: res.status, data });return data;}function toast(text, bad = false) {const t = h('div', { class: `toast${bad ? ' bad' : ''}`, role: 'status' }, text);- document.add(body, t);+ add(document.body, t);setTimeout(() => t.remove(), bad ? 6000 : 2600);}@@ -511,7 +511,9 @@ async function newView(slug) {for (const q of p.intake) if (q.type === 'choice' && q.default) answers[q.id] = q.default;let title = '';let backend = null;+ let createdId = null;const err = h('div', { class: 'err' });+ const keysBox = h('div');const field = (label, control, { help, optional } = {}) => h('div', { class: 'field' }, h('label', null, label, optional ? h('div', { class: 'opt' }, 'optional') : null), h('div', null, control, help ? h('div', { class: 'help' }, help) : null));const fields = p.intake.map((q) => {@@ -527,14 +529,28 @@ async function newView(slug) {err.textContent = '';startBtn.disabled = true;try {- const { id } = await api('/api/projects', { method: 'POST', body: { pipeline: slug, title, answers, backend } });- for (const [fieldId, list] of Object.entries(files)) {- for (const f of list) {- startBtn.textContent = `Uploading ${f.name}…`;- await api(`/api/projects/${id}/files?field=${encodeURIComponent(fieldId)}&name=${encodeURIComponent(f.name)}`, { method: 'POST', raw: f });+ if (!createdId) {+ const { id } = await api('/api/projects', { method: 'POST', body: { pipeline: slug, title, answers, backend } });+ for (const [fieldId, list] of Object.entries(files)) {+ for (const f of list) {+ startBtn.textContent = `Uploading ${f.name}…`;+ await api(`/api/projects/${id}/files?field=${encodeURIComponent(fieldId)}&name=${encodeURIComponent(f.name)}`, { method: 'POST', raw: f });+ }}+ createdId = id;+ }+ const id = createdId;+ try {+ await api(`/api/projects/${id}/start`, { method: 'POST' });+ } catch (e) {+ // Keys this project needs: ask for them right here, then Start again.+ if (!e.data?.needs_keys) { location.hash = `#/p/${id}`; throw e; }+ const { keys } = await api('/api/keys');+ const drawKeys = (list) => fill(keysBox, h('section', null, h('h2', null, 'Before it starts'), h('p', { class: 'meta' }, e.message),+ list.filter((k) => e.data.needs_keys.includes(k.id)).map((k) => keyRow(k, (r) => drawKeys(r.keys)))));+ drawKeys(keys);+ throw new Error('Add the key above, then Start.');}- await api(`/api/projects/${id}/start`, { method: 'POST' }).catch((e) => { location.hash = `#/p/${id}`; throw e; });location.hash = `#/p/${id}`;} catch (e) {err.textContent = e.message;@@ -551,6 +567,7 @@ async function newView(slug) {fields,studio?.config.backend === 'demo' ? null: field('Made by', choiceChips([BACKEND_NAMES[studio?.config.backend] || 'Studio default', 'Demo (placeholder work, free)'], BACKEND_NAMES[studio?.config.backend] || 'Studio default', (v) => { backend = v.startsWith('Demo') ? 'demo' : null; }), { help: 'The demo walks every stage with placeholder work: handy to learn the review room.' })),+ keysBox,h('div', { class: 'form-end' }, err, startBtn),);}@@ -629,14 +646,66 @@ async function settingsView() {h('div', { class: 'main' }, h('span', { class: 'title' }, k.title), h('div', { class: 'meta', style: { whiteSpace: 'normal' } }, k.how)),h('div', { class: 'end' }, h('button', { class: 'btn', onclick: decideCheck(k.id, true) }, 'Add'), h('button', { class: 'btn link', onclick: decideCheck(k.id, false) }, 'Dismiss'))))) : null,checks.active.length ? h('ul', { class: 'rows' }, checks.active.map((k) => h('li', { class: 'row' }, icon('done'), h('div', { class: 'main' }, h('span', { class: 'title' }, k.title)), h('div', { class: 'end' }, (k.applies_to || []).join(', '))))) : h('p', { class: 'meta' }, 'No studio checks yet (each pipeline has its own).')),- h('section', null, h('h2', null, 'Keys for sessions'),- h('p', null, studio.session_env ? 'session.env is set: its keys are handed to every session.' : 'Optional. To give sessions other keys, put KEY=value lines in session.env in the studio folder. (Narration keys belong in Narration above.)'),- h('p', { class: 'meta' }, `Studio folder: ${studio.root}`)),+ await keysSection(),);mount(h('div', { class: 'head' }, h('h1', null, 'Settings')), body);draw();}+// ---------- keys (Settings › Keys, and New video when one is missing) ----------++const KEY_SOURCES = { saved: 'saved in this studio', 'session.env': 'from session.env', environment: 'from your environment' };++// One key: where it comes from (never its value) and a hidden field to set it. The server checks it with a free call+// before saving it.+function keyRow(k, onChange) {+ const input = h('input', { type: 'password', autocomplete: 'off', 'aria-label': k.name, placeholder: k.source === 'saved' ? 'Saved (paste to replace)' : k.source ? `Using ${k.env} ${KEY_SOURCES[k.source]}` : 'Paste your key' });+ const note = h('div', { class: 'help' }, `For ${k.for} Get one at ${k.get}.`);+ const save = h('button', { class: 'btn', onclick: async () => {+ if (!input.value.trim()) return input.focus();+ save.disabled = true;+ save.textContent = 'Checking…';+ try {+ const r = await api(`/api/keys/${k.id}`, { method: 'PUT', body: { value: input.value } });+ input.value = '';+ toast(r.check?.ok ? `${k.name}: ${r.check.detail}` : `${k.name} saved${r.check ? `, but ${r.check.detail}` : ''}`);+ onChange(r);+ } catch (e) {+ fill(note, h('span', { class: 'err' }, e.message));+ save.disabled = false;+ save.textContent = 'Save';+ }+ } }, 'Save');+ const remove = k.source === 'saved' ? h('button', { class: 'btn link', onclick: async () => { try { onChange(await api(`/api/keys/${k.id}`, { method: 'DELETE' })); } catch (e) { toast(e.message, true); } } }, 'Remove') : null;+ const chip = h('span', { class: `chip ${k.source ? 'ok' : k.in_use ? 'bad' : ''}` }, k.source ? KEY_SOURCES[k.source] : k.in_use ? 'needed' : 'not set');+ return h('div', { class: 'field' }, h('label', null, k.name, h('div', null, chip)), h('div', null, h('div', { class: 'actions' }, input, save, remove), note));+}++async function keysSection() {+ const wrap = h('section', { id: 'keys' });+ const draw = ({ keys, other }) => {+ let name = '';+ let value = '';+ const addOther = async () => {+ try { draw(await api(`/api/keys/${encodeURIComponent(name.trim().toUpperCase())}`, { method: 'PUT', body: { value } })); } catch (e) { toast(e.message, true); }+ };+ fill(wrap, h('h2', null, 'Keys'),+ h('p', { class: 'meta' }, 'Mortiflix runs on your own accounts. Keys stay in the studio folder (secrets.json and session.env, readable by you alone) and are never shown again.'),+ keys.map((k) => keyRow(k, draw)),+ h('div', { class: 'field' }, h('label', null, 'Other keys', h('div', { class: 'opt' }, 'handed to every session')),+ h('div', null,+ other.length ? h('div', { class: 'actions' }, other.map((n) => h('span', { class: 'chip' }, n, h('button', { class: 'btn link', 'aria-label': `Remove ${n}`, onclick: async () => { try { draw(await api(`/api/keys/${n}`, { method: 'DELETE' })); } catch (e) { toast(e.message, true); } } }, '×')))) : null,+ h('div', { class: 'actions', style: { marginTop: other.length ? '10px' : '0' } },+ h('input', { type: 'text', placeholder: 'NAME, e.g. GEMINI_API_KEY', 'aria-label': 'Key name', oninput: (e) => { name = e.target.value; }, style: { maxWidth: '240px' } }),+ h('input', { type: 'password', autocomplete: 'off', placeholder: 'value', 'aria-label': 'Key value', oninput: (e) => { value = e.target.value; } }),+ h('button', { class: 'btn', onclick: addOther }, 'Add')),+ h('div', { class: 'help' }, 'For tools a pipeline uses that read a key from the environment.'))),+ h('p', { class: 'meta' }, `Studio folder: ${studio.root}`));+ };+ draw(await api('/api/keys'));+ return wrap;+}+// ---------- narration (Settings › Voice) ----------const ENGINE_LABELS = {