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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(computers): connect a server from just its address
rubenluetke10-beep3e8e563f8fc2
diff --git a/jarvis/computers/identity.py b/jarvis/computers/identity.pyindex 80bd8e4111..f5e88a72c7 100644--- a/jarvis/computers/identity.py+++ b/jarvis/computers/identity.py@@ -66,9 +66,15 @@ def public_key_line() -> str:def describe() -> dict[str, Any]:"""Public key plus fingerprint for the UI; creates the key when missing."""+ from jarvis.computers.ssh import authorize_key_command+key = private_key()+ public = key.export_public_key("openssh").decode("utf-8").strip()return {- "public_key": key.export_public_key("openssh").decode("utf-8").strip(),+ "public_key": public,"fingerprint": key.get_fingerprint("sha256"),"algorithm": key.get_algorithm(),+ # Run once on the server (hosting web console or any SSH session) for+ # a server that lets in known keys only.+ "install_command": authorize_key_command(public),}diff --git a/jarvis/computers/models.py b/jarvis/computers/models.pyindex d1f0d063a9..ae4f10fd7c 100644--- a/jarvis/computers/models.py+++ b/jarvis/computers/models.py@@ -25,6 +25,9 @@ ProviderId = str#: recommended path); ``password`` keeps a password in the OS keyring;#: ``private_key`` is the user's own SSH key, kept in the OS keyring.AuthMethod = Literal["key", "password", "private_key"]+#: How a form asks to log in. ``auto`` is not stored: it tries the app's key+#: and this PC's own SSH keys, then plants the app's key (auth becomes "key").+LoginMode = Literal["key", "password", "private_key", "auto"]#: The state a check leaves behind. ``provisioning`` belongs to a local VM that#: is still being created; ``stopped`` to a local VM that is powered off.diff --git a/jarvis/computers/service.py b/jarvis/computers/service.pyindex 932008df05..7edfd6181c 100644--- a/jarvis/computers/service.py+++ b/jarvis/computers/service.py@@ -33,6 +33,7 @@ from jarvis.computers.models import (AuthMethod,Computer,ComputerHealth,+ LoginMode,ProviderId,)from jarvis.computers.probe import PROBE_SCRIPT, parse_probe@@ -188,6 +189,25 @@ _ERROR_STATUS = {}+def _login_error(exc: SshError, target: SshTarget) -> ComputerError:+ """A refused login as the sentence (and kind) the connect form acts on."""+ if exc.kind == "auth" and target.use_this_pc:+ if exc.password_offered:+ return ComputerError(+ "None of this PC's SSH keys opens this server. Enter its password once: "+ "the app then sets up its own key and forgets the password.",+ status=502,+ kind="needs_password",+ )+ return ComputerError(+ "This server only accepts keys it already knows. Add the app's key there "+ "once (one line, shown below), then try again.",+ status=502,+ kind="key_only",+ )+ return ComputerError(exc.message, status=502, kind=exc.kind)++class ComputerService:def __init__(self, store: ComputerStore | None = None) -> None:self._store = store or ComputerStore()@@ -383,11 +403,11 @@ class ComputerService:# -- adding -------------------------------------------------------------async def _plant_key(self, target: SshTarget) -> Session:- """Log in with the password, add Jarvis's key, prove the key works."""+ """Log in (password or this PC's keys), add Jarvis's key, prove it works."""try:opened = await open_session(target)except SshError as exc:- raise ComputerError(exc.message, status=502, kind=exc.kind) from exc+ raise _login_error(exc, target) from exctry:result = await run_command(opened, authorize_key_command(identity.public_key_line()), timeout_s=20@@ -428,7 +448,7 @@ class ComputerService:host: str,port: int = 22,username: str = "root",- auth: AuthMethod = "key",+ auth: LoginMode = "key",password: str | None = None,keep_password: bool = False,private_key: str | None = None,@@ -438,7 +458,14 @@ class ComputerService:region: str | None = None,plan: str | None = None,) -> Computer:- """Register a server. With a password, plant the key first (default)."""+ """Register a server. With a password, plant the key first (default).++ ``auth="auto"`` needs nothing but the address: the app's own key or any+ key this PC's ``ssh`` uses logs in once, the app's key is planted, and+ the computer is stored with key login. When none opens the server the+ error says whether a password would (``needs_password``) or only a key+ (``key_only``).+ """computer = Computer(id=_new_id(),name=_clean_name(name),@@ -472,6 +499,12 @@ class ComputerService:import_private_key(private_key, passphrase)self._save_private_key(computer.id, private_key or "", passphrase)computer = computer.model_copy(update={"auth": "private_key"})+ elif auth == "auto":+ proof = await self._plant_key(self._this_pc_target(computer))+ close(proof)+ computer = computer.model_copy(+ update={"host_key": proof.host_key, "host_fingerprint": proof.host_fingerprint}+ )self._store.add(computer)return await self.check(computer.id)@@ -484,13 +517,28 @@ class ComputerService:else:delete_secret(_passphrase_slot(computer_id))+ def _this_pc_target(self, computer: Computer) -> SshTarget:+ """The app's key plus this PC's own SSH keys, for one planting login."""+ try:+ key = identity.private_key()+ except identity.IdentityError as exc:+ raise ComputerError(str(exc), status=500) from exc+ return SshTarget(+ host=computer.host,+ port=computer.port,+ username=computer.username,+ host_key=computer.host_key,+ client_key=key,+ use_this_pc=True,+ )+async def test_connection(self,*,host: str,port: int = 22,username: str = "root",- auth: AuthMethod = "key",+ auth: LoginMode = "key",password: str | None = None,private_key: str | None = None,passphrase: str | None = None,@@ -513,6 +561,10 @@ class ComputerService:elif auth == "private_key":key = import_private_key(private_key, passphrase)target = dataclasses.replace(base, client_key=key)+ elif auth == "auto":+ target = dataclasses.replace(+ base, client_key=identity.private_key(), use_this_pc=True+ )else:target = dataclasses.replace(base, client_key=identity.private_key())except ComputerError as exc: # the answer IS the result: shown in the form@@ -522,6 +574,9 @@ class ComputerService:try:opened = await open_session(target)except SshError as exc: # a failed login is the test's answer, not an error+ if target.use_this_pc:+ refused = _login_error(exc, target)+ return _test_result(False, refused.kind or exc.kind, refused.message)message = exc.messageif exc.kind == "auth" and auth == "key":message = (diff --git a/jarvis/computers/ssh.py b/jarvis/computers/ssh.pyindex cd0de229da..acc0415dc4 100644--- a/jarvis/computers/ssh.py+++ b/jarvis/computers/ssh.py@@ -44,6 +44,9 @@ class SshError(Exception):super().__init__(message)self.kind: SshErrorKind = kindself.message = message+ #: Set on a refused login that tried this PC's keys: did the server+ #: offer a password (or keyboard-interactive) login as well?+ self.password_offered: bool | None = None@dataclass(frozen=True)@@ -56,6 +59,10 @@ class SshTarget:#: Pinned OpenSSH host-key line; ``None`` on first contact (TOFU).host_key: str | None = Nonepassword: str | None = None+ #: Also offer the keys this PC's own ``ssh`` would use: the default files+ #: in ``~/.ssh`` (encrypted ones skipped) and the running SSH agent. Used+ #: once, to plant the app's own key; never stored.+ use_this_pc: bool = Falseclient_key: asyncssh.SSHKey | None = None@@ -78,6 +85,34 @@ class Session:latency_ms: int+#: The agent for ``use_this_pc``: ``()`` finds it the way ``ssh`` does+#: (SSH_AUTH_SOCK, else Pageant or the Windows OpenSSH agent). Tests set None.+THIS_PC_AGENT: Any = ()+++def this_pc_keys() -> list[Any]:+ """The key files this PC's ``ssh`` would offer (``~/.ssh`` defaults)."""+ from asyncssh.public_key import load_default_keypairs++ return list(load_default_keypairs())+++def _password_probe(offered: list[bool]) -> Any:+ """An SSH client that notes whether the server would take a password."""+ import asyncssh++ class _Probe(asyncssh.SSHClient):+ def password_auth_requested(self) -> None:+ offered.append(True)+ return None++ def kbdint_auth_requested(self) -> None:+ offered.append(True)+ return None++ return _Probe++def _classify(exc: BaseException) -> SshError:import asyncssh@@ -144,6 +179,14 @@ async def open_session(target: SshTarget, *, timeout_s: float = CONNECT_TIMEOUT_}if target.client_key is None:options["preferred_auth"] = "password,keyboard-interactive"+ offered: list[bool] = []+ if target.use_this_pc:+ own = [target.client_key] if target.client_key is not None else []+ options["client_keys"] = [*own, *this_pc_keys()] or ()+ options["agent_path"] = THIS_PC_AGENT+ # Keys only; a password offer is noted, never answered.+ options["preferred_auth"] = "publickey,keyboard-interactive,password"+ options["client_factory"] = _password_probe(offered)started = time.perf_counter()try:conn = await asyncssh.connect(target.host, **options)@@ -151,6 +194,8 @@ async def open_session(target: SshTarget, *, timeout_s: float = CONNECT_TIMEOUT_if isinstance(exc, asyncio.CancelledError):raiseerror = _classify(exc)+ if target.use_this_pc:+ error.password_offered = bool(offered)log.info("computers: ssh %s@%s:%s failed (%s)",target.username,diff --git a/jarvis/ui/web/computers_routes.py b/jarvis/ui/web/computers_routes.pyindex 9d5997c48c..b8a0871ca9 100644--- a/jarvis/ui/web/computers_routes.py+++ b/jarvis/ui/web/computers_routes.py@@ -66,6 +66,8 @@ def _row(computer: Computer) -> dict[str, Any]:AuthLiteral = Literal["key", "password", "private_key"]+#: What a connect form may ask for; "auto" tries this PC's own SSH keys.+LoginLiteral = Literal["key", "password", "private_key", "auto"]class AddServerBody(BaseModel):@@ -73,7 +75,7 @@ class AddServerBody(BaseModel):host: str = Field(min_length=1, max_length=253)port: int = Field(default=22, ge=1, le=65535)username: str = Field(default="root", min_length=1, max_length=64)- auth: AuthLiteral = "key"+ auth: LoginLiteral = "key"password: str | None = Field(default=None, max_length=1024)keep_password: bool = Falseprivate_key: str | None = Field(default=None, max_length=32_000)@@ -86,7 +88,7 @@ class TestBody(BaseModel):host: str = Field(min_length=1, max_length=253)port: int = Field(default=22, ge=1, le=65535)username: str = Field(default="root", min_length=1, max_length=64)- auth: AuthLiteral = "key"+ auth: LoginLiteral = "key"password: str | None = Field(default=None, max_length=1024)keep_password: bool = Falseprivate_key: str | None = Field(default=None, max_length=32_000)diff --git a/tests/fakes/fake_ssh_server.py b/tests/fakes/fake_ssh_server.pyindex 52cfbcd4b5..28bfa98465 100644--- a/tests/fakes/fake_ssh_server.py+++ b/tests/fakes/fake_ssh_server.py@@ -54,6 +54,8 @@ _KEY_RE = re.compile(r"'?(ssh-[a-z0-9-]+ [A-Za-z0-9+/=]+(?: [^'\s]+)?)'?")class FakeSshState:password: str = TEST_PASSWORDusername: str = "root"+ #: False plays a server with ``PasswordAuthentication no`` (keys only).+ password_login: bool = Trueauthorized: set[str] = field(default_factory=set)commands: list[str] = field(default_factory=list)#: Optional scripted command handler: return True when it answered the@@ -74,7 +76,10 @@ class _Server(asyncssh.SSHServer):return Truedef password_auth_supported(self) -> bool:- return True+ return self._state.password_login++ def kbdint_auth_supported(self) -> bool:+ return self._state.password_logindef validate_password(self, username: str, password: str) -> bool:return username == self._state.username and password == self._state.passworddiff --git a/tests/unit/computers/test_connect_auto.py b/tests/unit/computers/test_connect_auto.pynew file mode 100644index 0000000000..6a522204be--- /dev/null+++ b/tests/unit/computers/test_connect_auto.py@@ -0,0 +1,129 @@+"""Connecting with nothing but an address.++"auto" first offers the app's own key and the keys this PC's ``ssh`` already+uses; one that opens the server is used ONCE to plant the app's key. When none+does, the answer says what would: the password (``needs_password``) or a key+the server already knows (``key_only``) — so the form asks for exactly that.+"""++from __future__ import annotations++from typing import Any++import asyncssh+import pytest++from jarvis.computers import identity, ssh+from jarvis.computers.service import ComputerError, ComputerService+from tests.fakes.fake_ssh_server import FakeSshServer+++async def ssh_server(): # noqa: ANN201+ server = FakeSshServer()+ await server.start()+ try:+ yield server+ finally:+ await server.stop()+++def pc_keys(monkeypatch: pytest.MonkeyPatch) -> list[Any]:+ """This PC's own SSH keys, in memory; no real agent or ~/.ssh is touched."""+ keys: list[Any] = []+ monkeypatch.setattr(ssh, "this_pc_keys", lambda: list(keys))+ monkeypatch.setattr(ssh, "THIS_PC_AGENT", None)+ return keys+++def _public(key: Any) -> str:+ return key.export_public_key("openssh").decode().strip()+++async def test_a_key_this_pc_already_uses_connects_and_plants_the_apps_key(+ computer_service: ComputerService, ssh_server: FakeSshServer, pc_keys: list[Any]+) -> None:+ mine = asyncssh.generate_private_key("ssh-ed25519")+ pc_keys.append(mine)+ ssh_server.state.authorized.add(_public(mine))++ test = await computer_service.test_connection(+ host="127.0.0.1", port=ssh_server.port, auth="auto"+ )+ computer = await computer_service.add_server(+ name="vps", host="127.0.0.1", port=ssh_server.port, auth="auto"+ )++ assert test["ok"] is True+ assert computer.auth == "key", "stored as the app's own key, not the PC's"+ assert computer.health.status == "online"+ assert any(identity.public_key_line().split()[1] in k for k in ssh_server.state.authorized)+++async def test_the_apps_key_alone_is_enough_when_it_is_already_there(+ computer_service: ComputerService, ssh_server: FakeSshServer, pc_keys: list[Any]+) -> None:+ ssh_server.state.authorized.add(identity.public_key_line())++ computer = await computer_service.add_server(+ name="vps", host="127.0.0.1", port=ssh_server.port, auth="auto"+ )++ assert computer.auth == "key" and computer.health.status == "online"+++async def test_without_a_working_key_it_asks_for_the_password(+ computer_service: ComputerService, ssh_server: FakeSshServer, pc_keys: list[Any]+) -> None:+ pc_keys.append(asyncssh.generate_private_key("ssh-ed25519")) # not on the server++ test = await computer_service.test_connection(+ host="127.0.0.1", port=ssh_server.port, auth="auto"+ )+ with pytest.raises(ComputerError) as refused:+ await computer_service.add_server(+ name="vps", host="127.0.0.1", port=ssh_server.port, auth="auto"+ )++ assert test["ok"] is False and test["kind"] == "needs_password"+ assert "password" in test["message"]+ assert refused.value.kind == "needs_password"+ assert computer_service.all() == [], "nothing is saved on a refused login"+++async def test_a_keys_only_server_says_which_line_to_run(+ computer_service: ComputerService, ssh_server: FakeSshServer, pc_keys: list[Any]+) -> None:+ ssh_server.state.password_login = False++ test = await computer_service.test_connection(+ host="127.0.0.1", port=ssh_server.port, auth="auto"+ )++ assert test["ok"] is False and test["kind"] == "key_only"+ command = identity.describe()["install_command"]+ assert identity.public_key_line().split()[1] in command+ assert "authorized_keys" in command+++def test_this_pc_keys_reads_the_default_files_and_skips_encrypted_ones(+ tmp_path: Any, monkeypatch: pytest.MonkeyPatch+) -> None:+ home = tmp_path / "home"+ (home / ".ssh").mkdir(parents=True)+ plain = asyncssh.generate_private_key("ssh-ed25519")+ plain.write_private_key(str(home / ".ssh" / "id_ed25519"))+ locked = asyncssh.generate_private_key("ecdsa-sha2-nistp256")+ locked.write_private_key( # a passphrase-protected key: needs a person, so skipped+ str(home / ".ssh" / "id_ecdsa"),+ format_name="pkcs8-pem",+ passphrase="fixture-only", # noqa: S106 - a fixture, not a credential+ cipher_name="aes256-cbc",+ )+ monkeypatch.setenv("HOME", str(home))+ monkeypatch.setenv("USERPROFILE", str(home))++ found = ssh.this_pc_keys()++ assert [k.public_data for k in found] == [plain.public_data]