Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(control-key): allow a user-chosen Control Key via PUT /api/control/api-key

Ruben Lütked54dc7beb23f
diff --git a/docs/jarvis-control-api.md b/docs/jarvis-control-api.md
index 806ba9535f..e9a0e0c7ee 100644
--- a/docs/jarvis-control-api.md
+++ b/docs/jarvis-control-api.md
@@ -26,9 +26,12 @@ gets a unique key.
keyring → file → `JARVIS_CONTROL_API_KEY` env seed.
- **Never exported into `os.environ`** during normal operation (a spawned worker
would inherit it and leak it via `/proc/<pid>/environ`). Read on demand.
-- **Where the user finds it:** desktop app → **Settings → Jarvis API** (masked by
- default, Show/Hide, one-click Copy, Regenerate). Headless: `GET
- /api/control/api-key` from the loopback interface, or read the key file.
+- **Where the user finds it:** desktop app → **API Keys → Access &
+ Integrations → Control Key** (masked by default, Show/Hide, one-click Copy,
+ Regenerate behind a confirm dialog, or replace it with a user-chosen key —
+ min 12 chars, `[A-Za-z0-9._~-]`). The browser lock screen (AuthGate) points
+ to this section. Headless: `GET /api/control/api-key` from the loopback
+ interface, or read the key file.
## Auth
@@ -56,7 +59,8 @@ Settings panel can bootstrap the key before the user has it.
| GET | `/api/control/secrets` | list secret slots (masked) |
| PUT/DELETE | `/api/control/secrets/{key}` | set / delete a provider key |
| GET | `/api/control/api-key` | reveal the key (loopback or Bearer) |
-| POST | `/api/control/api-key/rotate` | regenerate (`{confirm:true}`) |
+| POST | `/api/control/api-key/rotate` | regenerate randomly (`{confirm:true}`) |
+| PUT | `/api/control/api-key` | set a user-chosen key (`{value, confirm:true}`; 422 on weak/invalid values, response is masked-only) |
### Two languages (interface vs reply)
diff --git a/jarvis/core/control_key.py b/jarvis/core/control_key.py
index 32cd7054fd..8b3707858b 100644
--- a/jarvis/core/control_key.py
+++ b/jarvis/core/control_key.py
@@ -1,4 +1,9 @@
-"""Per-user Jarvis Control API key — generation, cross-platform storage, rotation.
+"""Per-user Jarvis Control key — generation, cross-platform storage, rotation.
+
+One credential, two doors: the key unlocks the browser UI (the AuthGate's
+"Control Key" prompt mints an HttpOnly session from it) AND authenticates the
+local Control API. It is auto-generated on first boot; the user may replace it
+with a memorable value of their own via :func:`set_control_key`.
Open-source contract: every install owns a unique key (no shared secret baked
into the package). The key authenticates the local Control API (``/api/control/*``)
@@ -22,6 +27,7 @@ from __future__ import annotations
import logging
import os
+import re
import secrets
import stat
from pathlib import Path
@@ -36,6 +42,18 @@ ENV_VAR = "JARVIS_CONTROL_API_KEY"
_FILE_NAME = ".control_api_key"
_TOKEN_BYTES = 32 # 256-bit
+# User-chosen key rules. The key doubles as an RFC-6750 Bearer token (CLI /
+# local agents) and as the value typed into the browser unlock form, so it
+# must stay header-safe: no spaces, URL-safe characters only. The minimum
+# length keeps a memorable passphrase from degrading into a guessable PIN.
+MIN_CUSTOM_KEY_LENGTH = 12
+MAX_CUSTOM_KEY_LENGTH = 128
+_CUSTOM_KEY_RE = re.compile(r"^[A-Za-z0-9._~-]+$")
+
+
+class ControlKeyValidationError(ValueError):
+ """A user-chosen control key failed the format/strength rules."""
+
# The literal value shipped as the default in docker-compose.yml. It is
# world-known (public repo, public image) the moment it is ever used
# unmodified, so it must never be accepted as a real key — wherever it is
@@ -72,11 +90,17 @@ def generate_control_key() -> str:
def mask_control_key(key: str | None) -> str:
- """``jctl_…last4`` for logs / UI lists. Empty string for a missing key."""
+ """``jctl_…last4`` (or ``…last4`` for a user-chosen key) for logs / UI.
+
+ Empty string for a missing key. The ``jctl_`` prefix is only echoed when
+ the key actually carries it — a user-chosen key must not be dressed up as
+ a generated one.
+ """
if not key:
return ""
tail = key[-4:] if len(key) >= 4 else key
- return f"{KEY_PREFIX}…{tail}"
+ prefix = KEY_PREFIX if key.startswith(KEY_PREFIX) else ""
+ return f"{prefix}…{tail}"
def control_key_file() -> Path:
@@ -188,14 +212,13 @@ def ensure_control_key() -> str:
return key
-def rotate_control_key() -> str:
- """Generate a NEW key, overwrite the old one everywhere, return it.
+def _replace_key_everywhere(key: str) -> str:
+ """Overwrite the active key in keyring AND file; fail loudly on total miss.
The single-key model means writing the new value invalidates the old (no
separate revocation list). The file copy is overwritten too so a stale file
cannot resurrect the previous key on the next boot.
"""
- key = generate_control_key()
keyring_ok = cfg.set_secret(KEYRING_SLOT, key)
file_ok = _write_file_key(key)
if not keyring_ok and not file_ok:
@@ -203,12 +226,54 @@ def rotate_control_key() -> str:
# caller: the NEXT get_control_key() reads the OLD key, so verify() of
# the just-returned key fails. Fail loudly instead — the old key stays.
raise RuntimeError(
- "Control key rotation failed: neither the OS keyring nor the file "
- "fallback accepted the new key. The previous key remains active."
+ "Control key replacement failed: neither the OS keyring nor the "
+ "file fallback accepted the new key. The previous key remains active."
)
return key
+def rotate_control_key() -> str:
+ """Generate a NEW random key, overwrite the old one everywhere, return it."""
+ return _replace_key_everywhere(generate_control_key())
+
+
+def validate_custom_control_key(value: str) -> str:
+ """Return the trimmed user-chosen key or raise ``ControlKeyValidationError``.
+
+ The messages are user-facing (surfaced verbatim by the UI/CLI), so they
+ state the exact rule that failed.
+ """
+ candidate = (value or "").strip()
+ if len(candidate) < MIN_CUSTOM_KEY_LENGTH:
+ raise ControlKeyValidationError(
+ f"The control key must be at least {MIN_CUSTOM_KEY_LENGTH} characters long."
+ )
+ if len(candidate) > MAX_CUSTOM_KEY_LENGTH:
+ raise ControlKeyValidationError(
+ f"The control key must be at most {MAX_CUSTOM_KEY_LENGTH} characters long."
+ )
+ if not _CUSTOM_KEY_RE.fullmatch(candidate):
+ raise ControlKeyValidationError(
+ "The control key may only contain letters, digits, and . _ ~ - "
+ "(no spaces) so it works as an HTTP Bearer token."
+ )
+ if candidate == SHIPPED_PLACEHOLDER_KEY:
+ raise ControlKeyValidationError(
+ "This value is the publicly shipped placeholder key and cannot be used."
+ )
+ return candidate
+
+
+def set_control_key(value: str) -> str:
+ """Persist a user-chosen key as the active control key and return it.
+
+ Validation is fail-closed (``ControlKeyValidationError``); persistence
+ mirrors :func:`rotate_control_key` — the old key stays active if neither
+ store accepts the new one.
+ """
+ return _replace_key_everywhere(validate_custom_control_key(value))
+
+
def verify_control_key(presented: str | None) -> bool:
"""Constant-time comparison of a presented key against the stored one."""
if not presented:
diff --git a/jarvis/ui/web/control_routes.py b/jarvis/ui/web/control_routes.py
index 62c490c4db..9a56492924 100644
--- a/jarvis/ui/web/control_routes.py
+++ b/jarvis/ui/web/control_routes.py
@@ -164,6 +164,11 @@ class RotateBody(BaseModel):
confirm: bool = Field(default=False)
+class SetKeyBody(BaseModel):
+ value: str = Field(..., min_length=1, description="The new user-chosen control key")
+ confirm: bool = Field(default=False)
+
+
# ----------------------------------------------------------------------
# Auth probe + discovery
# ----------------------------------------------------------------------
@@ -400,3 +405,38 @@ async def rotate_api_key(body: RotateBody) -> dict[str, Any]:
# Both stores rejected the new key — the old one is still active.
raise HTTPException(status_code=500, detail=str(exc)) from exc
return {"ok": True, "key": key, "masked": control_key.mask_control_key(key)}
+
+
+ "/api-key",
+ dependencies=[Depends(require_control_key_or_session)],
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def set_api_key(body: SetKeyBody, request: Request) -> dict[str, Any]:
+ """Replace the control key with a user-chosen value.
+
+ The caller already typed the value, so the response returns only the
+ masked form — the clear key never crosses the wire twice. An invalid
+ value (too short, unsafe characters, the shipped placeholder) is a 422
+ and leaves the current key untouched.
+ """
+ if not body.confirm:
+ raise HTTPException(
+ status_code=400,
+ detail="Setting a new key requires confirm=true; it invalidates the current key.",
+ )
+ try:
+ key = control_key.set_control_key(body.value)
+ except control_key.ControlKeyValidationError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
+ ) from exc
+ except RuntimeError as exc:
+ # Both stores rejected the new key — the old one is still active.
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+ client = getattr(request, "client", None)
+ log.info(
+ "control: API key replaced by a user-chosen value from %s",
+ getattr(client, "host", "unknown"),
+ )
+ return {"ok": True, "masked": control_key.mask_control_key(key)}
diff --git a/tests/integration/test_control_routes.py b/tests/integration/test_control_routes.py
index 21f54eba86..5492aaee28 100644
--- a/tests/integration/test_control_routes.py
+++ b/tests/integration/test_control_routes.py
@@ -203,6 +203,53 @@ def test_rotate_requires_confirm(client) -> None:
assert res.status_code == 200 and res.json()["key"] == "jctl_rotated_key"
+# --- user-chosen key (PUT /api/control/api-key) ---
+
+
[email protected]_auto_web_auth
+def test_set_custom_key_requires_auth(client) -> None:
+ # Opt out of the conftest auto-session: this asserts the raw boundary.
+ tc, _, _ = client
+ res = tc.put("/api/control/api-key", json={"value": "correct-horse-battery", "confirm": True})
+ assert res.status_code == 401
+
+
+def test_set_custom_key_requires_confirm(client) -> None:
+ tc, _, _ = client
+ res = tc.put("/api/control/api-key", json={"value": "correct-horse-battery"}, headers=AUTH)
+ assert res.status_code == 400
+
+
+def test_set_custom_key_rejects_weak_or_invalid_values(client) -> None:
+ tc, _, _ = client
+ too_short = tc.put(
+ "/api/control/api-key", json={"value": "short", "confirm": True}, headers=AUTH
+ )
+ assert too_short.status_code == 422
+ bad_chars = tc.put(
+ "/api/control/api-key",
+ json={"value": "has spaces in the key", "confirm": True},
+ headers=AUTH,
+ )
+ assert bad_chars.status_code == 422
+
+
+def test_set_custom_key_persists_and_returns_masked_only(client) -> None:
+ tc, _, secret_store = client
+ res = tc.put(
+ "/api/control/api-key",
+ json={"value": "correct-horse-battery", "confirm": True},
+ headers=AUTH,
+ )
+ assert res.status_code == 200
+ body = res.json()
+ assert body["ok"] is True
+ assert body["masked"] == "…tery"
+ # The caller typed the value — the clear key never crosses the wire twice.
+ assert "key" not in body
+ assert secret_store[control_key.KEYRING_SLOT] == "correct-horse-battery"
+
+
# --- providers (snapshot needs no live manager) ---
diff --git a/tests/unit/core/test_control_key.py b/tests/unit/core/test_control_key.py
index 1c56439f41..adc772e152 100644
--- a/tests/unit/core/test_control_key.py
+++ b/tests/unit/core/test_control_key.py
@@ -114,6 +114,42 @@ def test_env_seed_used_when_no_keyring_no_file(isolated, monkeypatch) -> None:
assert ck.KEYRING_SLOT not in isolated
+# --- user-chosen key (set_control_key) ---
+
+
+def test_validate_custom_key_rules() -> None:
+ with pytest.raises(ck.ControlKeyValidationError):
+ ck.validate_custom_control_key("short")
+ with pytest.raises(ck.ControlKeyValidationError):
+ ck.validate_custom_control_key("has spaces in the key")
+ with pytest.raises(ck.ControlKeyValidationError):
+ ck.validate_custom_control_key("x" * (ck.MAX_CUSTOM_KEY_LENGTH + 1))
+ # The publicly shipped placeholder passes length/charset but must be refused.
+ with pytest.raises(ck.ControlKeyValidationError):
+ ck.validate_custom_control_key(ck.SHIPPED_PLACEHOLDER_KEY)
+ assert ck.validate_custom_control_key(" correct-horse-battery ") == "correct-horse-battery"
+
+
+def test_set_control_key_replaces_and_verifies(isolated) -> None:
+ ck.ensure_control_key()
+ stored = ck.set_control_key("correct-horse-battery")
+ assert stored == "correct-horse-battery"
+ assert ck.get_control_key() == "correct-horse-battery"
+ assert ck.verify_control_key("correct-horse-battery") is True
+
+
+def test_set_control_key_invalid_value_keeps_old_key(isolated) -> None:
+ old = ck.ensure_control_key()
+ with pytest.raises(ck.ControlKeyValidationError):
+ ck.set_control_key("short")
+ assert ck.get_control_key() == old
+
+
+def test_mask_custom_key_has_no_generated_prefix() -> None:
+ # A user-chosen key must not be dressed up with the generated jctl_ prefix.
+ assert ck.mask_control_key("correct-horse-battery") == "…tery"
+
+
# --- shipped docker-compose.yml placeholder must never be accepted as real ---