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(computers): provider catalog, own SSH keys and try-before-save

rubenluetke10-beepe1e9e9fcaf4a
diff --git a/jarvis/computers/cloud.py b/jarvis/computers/cloud.py
index cde3701a82..048c1a6bf9 100644
--- a/jarvis/computers/cloud.py
+++ b/jarvis/computers/cloud.py
@@ -22,7 +22,7 @@ from jarvis.core.http_pool import HttpClientPool
log = logging.getLogger(__name__)
-CloudProviderId = Literal["hostinger", "hetzner", "digitalocean"]
+CloudProviderId = Literal["hostinger", "hetzner", "digitalocean", "vultr", "linode"]
_POOL = HttpClientPool(timeout_s=20.0)
_MAX_PAGES = 20
@@ -39,6 +39,8 @@ class CloudProvider:
#: True when Jarvis can put its key on an EXISTING server through the API.
attaches_keys: bool
base_url: str
+ #: What the provider calls the credential, as its own panel names it.
+ credential_label: str = "API token"
PROVIDERS: Final[dict[CloudProviderId, CloudProvider]] = {
@@ -71,6 +73,29 @@ PROVIDERS: Final[dict[CloudProviderId, CloudProvider]] = {
setup_hint="Control panel -> API -> Tokens (scope droplet:read)",
attaches_keys=False,
base_url="https://api.digitalocean.com",
+ credential_label="Personal access token",
+ ),
+ "vultr": CloudProvider(
+ id="vultr",
+ name="Vultr",
+ keyring_slot="vultr_api_token",
+ env_var="VULTR_API_KEY",
+ console_url="https://my.vultr.com/settings/#settingsapi",
+ setup_hint="Account -> API -> Enable API, then allow your IP (or all IPv4)",
+ attaches_keys=False,
+ base_url="https://api.vultr.com",
+ credential_label="API key",
+ ),
+ "linode": CloudProvider(
+ id="linode",
+ name="Akamai Cloud (Linode)",
+ keyring_slot="linode_api_token",
+ env_var="LINODE_TOKEN",
+ console_url="https://cloud.linode.com/profile/tokens",
+ setup_hint="Profile -> API Tokens -> Create a Personal Access Token (Linodes: Read Only)",
+ attaches_keys=False,
+ base_url="https://api.linode.com",
+ credential_label="Personal access token",
),
}
@@ -286,6 +311,81 @@ def parse_digitalocean(payload: Any) -> list[CloudServer]:
return servers
+def parse_vultr(payload: Any) -> list[CloudServer]:
+ servers: list[CloudServer] = []
+ for row in (payload or {}).get("instances", []) if isinstance(payload, dict) else []:
+ if not isinstance(row, dict) or not row.get("id"):
+ continue
+ ip = row.get("main_ip")
+ status = str(row.get("power_status") or row.get("status") or "unknown")
+ servers.append(
+ CloudServer(
+ id=str(row["id"]),
+ name=str(row.get("label") or row.get("hostname") or row["id"]),
+ host=ip if ip and ip != "0.0.0.0" else None, # noqa: S104 — Vultr's "no IP yet"
+ status=status,
+ running=status == "running" and row.get("status") == "active",
+ os=row.get("os") or None,
+ plan=row.get("plan") or None,
+ region=row.get("region") or None,
+ cpus=_as_int(row.get("vcpu_count")),
+ memory_mb=_as_int(row.get("ram")),
+ disk_gb=float(row["disk"]) if row.get("disk") is not None else None,
+ )
+ )
+ return servers
+
+
+def parse_linode(payload: Any) -> list[CloudServer]:
+ servers: list[CloudServer] = []
+ for row in (payload or {}).get("data", []) if isinstance(payload, dict) else []:
+ if not isinstance(row, dict) or row.get("id") is None:
+ continue
+ ipv4 = [ip for ip in row.get("ipv4") or [] if isinstance(ip, str)]
+ public = next((ip for ip in ipv4 if not _is_private(ip)), None)
+ specs = row.get("specs") or {}
+ disk_mb = _as_int(specs.get("disk"))
+ image = str(row.get("image") or "")
+ status = str(row.get("status") or "unknown")
+ servers.append(
+ CloudServer(
+ id=str(row["id"]),
+ name=str(row.get("label") or row["id"]),
+ host=public,
+ status=status,
+ running=status == "running",
+ os=image.split("/", 1)[-1] if image else None,
+ plan=row.get("type") or None,
+ region=row.get("region") or None,
+ cpus=_as_int(specs.get("vcpus")),
+ memory_mb=_as_int(specs.get("memory")),
+ disk_gb=round(disk_mb / 1024, 1) if disk_mb else None,
+ )
+ )
+ return servers
+
+
+_INTERNAL_NETS = (
+ "10.0.0.0/8",
+ "172.16.0.0/12",
+ "192.168.0.0/16",
+ "100.64.0.0/10",
+ "127.0.0.0/8",
+ "169.254.0.0/16",
+)
+
+
+def _is_private(ip: str) -> bool:
+ """A provider-internal address (not reachable from here), by RFC 1918 & co."""
+ import ipaddress
+
+ try:
+ address = ipaddress.ip_address(ip)
+ except ValueError: # not an IP at all: never offer it as the address
+ return True
+ return any(address in ipaddress.ip_network(net) for net in _INTERNAL_NETS)
+
+
# -- listing -----------------------------------------------------------------
@@ -328,6 +428,39 @@ async def list_servers(provider_id: str, *, client: Any | None = None) -> list[C
page = _as_int(pagination.get("next_page"))
return servers
+ if spec.id == "vultr":
+ servers = []
+ cursor: str | None = ""
+ for _ in range(_MAX_PAGES):
+ params: dict[str, Any] = {"per_page": 100}
+ if cursor:
+ params["cursor"] = cursor
+ payload = await _request(
+ spec, api_token, "GET", "/v2/instances", params=params, client=client
+ )
+ servers.extend(parse_vultr(payload))
+ links = ((payload or {}).get("meta") or {}).get("links") or {}
+ cursor = links.get("next") or None
+ if not cursor:
+ break
+ return servers
+
+ if spec.id == "linode":
+ servers = []
+ for page_no in range(1, _MAX_PAGES + 1):
+ payload = await _request(
+ spec,
+ api_token,
+ "GET",
+ "/v4/linode/instances",
+ params={"page": page_no, "page_size": 100},
+ client=client,
+ )
+ servers.extend(parse_linode(payload))
+ if page_no >= (_as_int((payload or {}).get("pages")) or 1):
+ break
+ return servers
+
servers = []
page = 1
while page and page <= _MAX_PAGES:
diff --git a/jarvis/computers/models.py b/jarvis/computers/models.py
index 6271f84910..d1f0d063a9 100644
--- a/jarvis/computers/models.py
+++ b/jarvis/computers/models.py
@@ -15,12 +15,16 @@ from pydantic import BaseModel, ConfigDict, Field
#: A rented or self-hosted machine reached over the network, or a VM on this box.
ComputerKind = Literal["server", "local_vm"]
-#: Where the machine came from. ``generic`` is any SSH host typed in by hand.
-ProviderId = Literal["generic", "hostinger", "hetzner", "digitalocean", "multipass"]
+#: Where the machine came from: an id from :mod:`jarvis.computers.providers`
+#: (``generic`` for any SSH host typed in by hand, ``multipass`` for a local
+#: VM). A plain string so the catalog can grow without a schema change; the
+#: service validates it against the catalog on every write.
+ProviderId = str
#: How Jarvis logs in. ``key`` is Jarvis's own key pair (the default and the
-#: recommended path); ``password`` keeps a password in the OS keyring.
-AuthMethod = Literal["key", "password"]
+#: 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"]
#: 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/providers.py b/jarvis/computers/providers.py
new file mode 100644
index 0000000000..31101ed42a
--- /dev/null
+++ b/jarvis/computers/providers.py
@@ -0,0 +1,282 @@
+"""The provider catalog: where a computer can come from, and how to reach it.
+
+One entry per place a user might rent or own a machine. Every entry carries
+the SSH facts a first-time user needs (which login the provider gives you,
+where the IP is shown, where a public SSH key goes, where the root password
+arrives); the few providers whose account API Jarvis can read also point at
+:mod:`jarvis.computers.cloud` for a server list and token setup.
+
+The catalog is data, ordered for display. Adding a provider is one entry here;
+an API integration additionally needs its parser in ``cloud.py``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Final, Literal
+
+from jarvis.computers import cloud
+
+Category = Literal["cloud", "hosting", "home", "other"]
+
+
+@dataclass(frozen=True)
+class SshGuide:
+ default_username: str
+ ip_hint: str
+ key_hint: str
+ key_url: str | None
+ #: Where the first login (root password) comes from.
+ login_hint: str
+
+
+@dataclass(frozen=True)
+class CatalogEntry:
+ id: str
+ name: str
+ category: Category
+ ssh: SshGuide
+ #: The id in ``cloud.PROVIDERS`` when Jarvis can read this account's API.
+ api: str | None = None
+
+
+CATALOG: Final[tuple[CatalogEntry, ...]] = (
+ CatalogEntry(
+ id="hostinger",
+ name="Hostinger",
+ category="hosting",
+ api="hostinger",
+ ssh=SshGuide(
+ default_username="root",
+ ip_hint="hPanel -> VPS -> your server -> Overview shows the IP address.",
+ key_hint="hPanel -> VPS -> Settings -> SSH keys -> Add SSH key.",
+ key_url="https://hpanel.hostinger.com/vps",
+ login_hint="You set the root password when creating the VPS; "
+ "change it under VPS -> Settings -> Root password.",
+ ),
+ ),
+ CatalogEntry(
+ id="hetzner",
+ name="Hetzner Cloud",
+ category="cloud",
+ api="hetzner",
+ ssh=SshGuide(
+ default_username="root",
+ ip_hint="Cloud Console -> your project -> Servers lists the public IPv4.",
+ key_hint="Cloud Console -> Security -> SSH keys. Keys are added when a server "
+ "is created or rebuilt.",
+ key_url="https://console.hetzner.cloud/",
+ login_hint="Without an SSH key, Hetzner emails the root password "
+ "when the server is created.",
+ ),
+ ),
+ CatalogEntry(
+ id="digitalocean",
+ name="DigitalOcean",
+ category="cloud",
+ api="digitalocean",
+ ssh=SshGuide(
+ default_username="root",
+ ip_hint="Control panel -> Droplets shows the ipv4 address next to each droplet.",
+ key_hint="Settings -> Security -> SSH keys. Keys are added when a droplet is created.",
+ key_url="https://cloud.digitalocean.com/account/security",
+ login_hint="With password login chosen, you set the root password "
+ "while creating the droplet.",
+ ),
+ ),
+ CatalogEntry(
+ id="vultr",
+ name="Vultr",
+ category="cloud",
+ api="vultr",
+ ssh=SshGuide(
+ default_username="root",
+ ip_hint="Products -> your instance -> Overview shows the IP address.",
+ key_hint="Account -> SSH keys. Keys are added when an instance is deployed.",
+ key_url="https://my.vultr.com/sshkeys/",
+ login_hint="The root password is on the instance's Overview page (click the eye icon).",
+ ),
+ ),
+ CatalogEntry(
+ id="linode",
+ name="Akamai Cloud (Linode)",
+ category="cloud",
+ api="linode",
+ ssh=SshGuide(
+ default_username="root",
+ ip_hint="Cloud Manager -> Linodes shows the public IPv4 address.",
+ key_hint="Profile -> SSH keys. Keys are added when a Linode is created or rebuilt.",
+ key_url="https://cloud.linode.com/profile/keys",
+ login_hint="You set the root password while creating the Linode.",
+ ),
+ ),
+ CatalogEntry(
+ id="aws_lightsail",
+ name="AWS Lightsail",
+ category="cloud",
+ ssh=SshGuide(
+ default_username="ubuntu",
+ ip_hint="Lightsail -> Instances shows the public IP under each instance "
+ "(attach a static IP so it never changes).",
+ key_hint="Download the instance's key pair from Account -> SSH keys and "
+ "use it as your own key.",
+ key_url="https://lightsail.aws.amazon.com/ls/webapp/account/keys",
+ login_hint="Lightsail has no password login; use its SSH key.",
+ ),
+ ),
+ CatalogEntry(
+ id="contabo",
+ name="Contabo",
+ category="hosting",
+ ssh=SshGuide(
+ default_username="root",
+ ip_hint="Customer Control Panel -> Your services shows the IP address.",
+ key_hint="Add the key when installing or reinstalling the server in the control panel.",
+ key_url="https://my.contabo.com/",
+ login_hint="You set the root password at order time; reset it in the control panel.",
+ ),
+ ),
+ CatalogEntry(
+ id="ionos",
+ name="IONOS",
+ category="hosting",
+ ssh=SshGuide(
+ default_username="root",
+ ip_hint="Cloud Panel -> Servers & Cloud -> your server shows the IP.",
+ key_hint="Cloud Panel -> Network -> SSH keys; choose the key when "
+ "setting the server up.",
+ key_url="https://my.ionos.com/",
+ login_hint="The initial root password is shown under the server's access data.",
+ ),
+ ),
+ CatalogEntry(
+ id="strato",
+ name="Strato",
+ category="hosting",
+ ssh=SshGuide(
+ default_username="root",
+ ip_hint="Customer login -> Server -> your server's overview shows the IP.",
+ key_hint="Paste the key into ~/.ssh/authorized_keys once logged in, "
+ "or let Jarvis do it with the password.",
+ key_url=None,
+ login_hint="The root password is in the server's access data in the customer login.",
+ ),
+ ),
+ CatalogEntry(
+ id="ovhcloud",
+ name="OVHcloud",
+ category="hosting",
+ ssh=SshGuide(
+ default_username="ubuntu",
+ ip_hint="Control Panel -> Bare Metal Cloud -> VPS -> your VPS shows the IPv4.",
+ key_hint="Add the key when installing the OS, or let Jarvis add it with the password.",
+ key_url="https://www.ovh.com/manager/",
+ login_hint="OVHcloud emails the login and password after installation.",
+ ),
+ ),
+ CatalogEntry(
+ id="oracle_cloud",
+ name="Oracle Cloud",
+ category="cloud",
+ ssh=SshGuide(
+ default_username="ubuntu",
+ ip_hint="Compute -> Instances -> your instance shows the public IP address "
+ "(the default user is opc on Oracle Linux).",
+ key_hint="Paste or upload the public key in 'Add SSH keys' while creating "
+ "the instance.",
+ key_url="https://cloud.oracle.com/compute/instances",
+ login_hint="Oracle Cloud has no password login; use the key you gave the instance.",
+ ),
+ ),
+ CatalogEntry(
+ id="raspberry_pi",
+ name="Raspberry Pi",
+ category="home",
+ ssh=SshGuide(
+ default_username="pi",
+ ip_hint="Your router's device list shows it, or run hostname -I on the Pi.",
+ key_hint="Turn on SSH in Raspberry Pi Imager or raspi-config; Jarvis adds "
+ "its key with the password.",
+ key_url=None,
+ login_hint="The user and password you chose in Raspberry Pi Imager.",
+ ),
+ ),
+ CatalogEntry(
+ id="home_server",
+ name="Home server or NAS",
+ category="home",
+ ssh=SshGuide(
+ default_username="root",
+ ip_hint="Your router's device list shows the local IP address.",
+ key_hint="Enable SSH in its settings; Jarvis adds its key with the password.",
+ key_url=None,
+ login_hint="The account you log in to the machine with.",
+ ),
+ ),
+ CatalogEntry(
+ id="generic",
+ name="Other server",
+ category="other",
+ ssh=SshGuide(
+ default_username="root",
+ ip_hint="Your provider's panel or welcome email shows the IP address.",
+ key_hint="Paste the public key into ~/.ssh/authorized_keys on the server.",
+ key_url=None,
+ login_hint="The login your provider gave you, usually in the welcome email.",
+ ),
+ ),
+)
+
+#: Ids that are valid on a record but never offered in the add flow.
+INTERNAL_IDS: Final[frozenset[str]] = frozenset({"multipass"})
+
+_BY_ID: Final[dict[str, CatalogEntry]] = {entry.id: entry for entry in CATALOG}
+
+
+def entry(provider_id: str) -> CatalogEntry | None:
+ return _BY_ID.get(provider_id)
+
+
+def is_known(provider_id: str) -> bool:
+ return provider_id in _BY_ID or provider_id in INTERNAL_IDS
+
+
+def display_name(provider_id: str) -> str:
+ found = _BY_ID.get(provider_id)
+ if found is not None:
+ return found.name
+ if provider_id == "multipass":
+ return "Local VM"
+ return "Other server"
+
+
+def catalog_rows() -> list[dict[str, Any]]:
+ """The catalog as the REST route answers it (``GET /api/computers/providers``)."""
+ rows: list[dict[str, Any]] = []
+ for item in CATALOG:
+ api: dict[str, Any] | None = None
+ if item.api is not None:
+ spec = cloud.PROVIDERS[item.api] # type: ignore[index]
+ api = {
+ "connected": bool(cloud.token(item.api)),
+ "console_url": spec.console_url,
+ "setup_hint": spec.setup_hint,
+ "attaches_keys": spec.attaches_keys,
+ "token_label": spec.credential_label,
+ }
+ rows.append(
+ {
+ "id": item.id,
+ "name": item.name,
+ "category": item.category,
+ "api": api,
+ "ssh": {
+ "default_username": item.ssh.default_username,
+ "ip_hint": item.ssh.ip_hint,
+ "key_hint": item.ssh.key_hint,
+ "key_url": item.ssh.key_url,
+ "password_hint": item.ssh.login_hint,
+ },
+ }
+ )
+ return rows
diff --git a/jarvis/computers/service.py b/jarvis/computers/service.py
index ba29d54cc4..3d6de137db 100644
--- a/jarvis/computers/service.py
+++ b/jarvis/computers/service.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import asyncio
import contextlib
+import dataclasses
import logging
import re
import secrets
@@ -26,7 +27,7 @@ import time
from collections.abc import AsyncIterator
from typing import Any
-from jarvis.computers import cloud, identity, local_vm
+from jarvis.computers import cloud, identity, local_vm, providers
from jarvis.computers.models import (
AuthMethod,
Computer,
@@ -69,6 +70,68 @@ def _password_slot(computer_id: str) -> str:
return f"computer_password_{computer_id}"
+def _private_key_slot(computer_id: str) -> str:
+ return f"computer_private_key_{computer_id}"
+
+
+def _passphrase_slot(computer_id: str) -> str:
+ return f"computer_key_passphrase_{computer_id}"
+
+
+def _forget_secrets(computer_id: str, *, keep: str | None = None) -> None:
+ """Drop every stored credential of a computer except the ``keep`` kind."""
+ if keep != "password":
+ delete_secret(_password_slot(computer_id))
+ if keep != "private_key":
+ delete_secret(_private_key_slot(computer_id))
+ delete_secret(_passphrase_slot(computer_id))
+
+
+def import_private_key(pem: str | None, passphrase: str | None) -> Any:
+ """The user's own SSH key as an asyncssh key; a 400 sentence when unusable."""
+ import asyncssh
+
+ text = (pem or "").strip()
+ if not text:
+ raise ComputerError("Paste your private SSH key.", kind="bad_key")
+ if text.startswith(("ssh-", "ecdsa-")):
+ raise ComputerError(
+ "That is a public key. Paste the PRIVATE key (it starts with -----BEGIN).",
+ kind="bad_key",
+ )
+ try:
+ return asyncssh.import_private_key(text + "\n", passphrase or None)
+ except asyncssh.KeyEncryptionError as exc:
+ raise ComputerError(
+ "The passphrase does not unlock this key."
+ if passphrase
+ else "This key is protected. Enter its passphrase.",
+ kind="bad_key",
+ ) from exc
+ except (asyncssh.KeyImportError, ValueError) as exc:
+ raise ComputerError(
+ "This does not look like a private SSH key (OpenSSH or PEM format).",
+ kind="bad_key",
+ ) from exc
+
+
+def _check_provider(provider_id: str) -> str:
+ if not providers.is_known(provider_id):
+ raise ComputerError(f"Unknown provider: {provider_id}.")
+ return provider_id
+
+
+def _test_result(ok: bool, kind: str | None, message: str | None) -> dict[str, Any]:
+ return {
+ "ok": ok,
+ "kind": kind,
+ "message": message,
+ "host_fingerprint": None,
+ "facts": None,
+ "latency_ms": None,
+ }
+
+
def _new_id() -> str:
return f"c_{secrets.token_hex(6)}"
@@ -134,6 +197,20 @@ class ComputerService:
host_key=computer.host_key,
password=password,
)
+ if computer.auth == "private_key":
+ pem = get_secret(_private_key_slot(computer.id), env_fallback="")
+ if not pem:
+ raise ComputerError(
+ "The saved SSH key is missing. Paste it again.", status=409, kind="auth"
+ )
+ phrase = get_secret(_passphrase_slot(computer.id), env_fallback="")
+ return SshTarget(
+ host=computer.host,
+ port=computer.port,
+ username=computer.username,
+ host_key=computer.host_key,
+ client_key=import_private_key(pem, phrase),
+ )
if computer.auth == "password":
stored = get_secret(_password_slot(computer.id), env_fallback="")
if not stored:
@@ -326,6 +403,8 @@ class ComputerService:
auth: AuthMethod = "key",
password: str | None = None,
keep_password: bool = False,
+ private_key: str | None = None,
+ passphrase: str | None = None,
provider: ProviderId = "generic",
provider_ref: str | None = None,
region: str | None = None,
@@ -336,7 +415,7 @@ class ComputerService:
id=_new_id(),
name=_clean_name(name),
kind="server",
- provider=provider,
+ provider=_check_provider(provider),
host=_check_host(host),
port=port,
username=_check_user(username),
@@ -361,9 +440,105 @@ class ComputerService:
computer = computer.model_copy(
update={"host_key": proof.host_key, "host_fingerprint": proof.host_fingerprint}
)
+ elif auth == "private_key":
+ import_private_key(private_key, passphrase)
+ self._save_private_key(computer.id, private_key or "", passphrase)
+ computer = computer.model_copy(update={"auth": "private_key"})
self._store.add(computer)
return await self.check(computer.id)
+ def _save_private_key(self, computer_id: str, pem: str, passphrase: str | None) -> None:
+ if not set_secret(_private_key_slot(computer_id), pem.strip()):
+ raise ComputerError("The SSH key could not be saved to the keyring.", status=500)
+ if passphrase:
+ if not set_secret(_passphrase_slot(computer_id), passphrase):
+ raise ComputerError("The passphrase could not be saved to the keyring.", status=500)
+ else:
+ delete_secret(_passphrase_slot(computer_id))
+
+ async def test_connection(
+ self,
+ *,
+ host: str,
+ port: int = 22,
+ username: str = "root",
+ auth: AuthMethod = "key",
+ password: str | None = None,
+ private_key: str | None = None,
+ passphrase: str | None = None,
+ ) -> dict[str, Any]:
+ """Try a login WITHOUT saving anything; nothing is planted on the server."""
+ try:
+ base = SshTarget(host=_check_host(host), port=port, username=_check_user(username))
+ if auth == "password":
+ if not password:
+ raise ComputerError("Enter the password for this login.", kind="auth")
+ target = dataclasses.replace(base, password=password)
+ elif auth == "private_key":
+ key = import_private_key(private_key, passphrase)
+ target = dataclasses.replace(base, client_key=key)
+ else:
+ target = dataclasses.replace(base, client_key=identity.private_key())
+ except ComputerError as exc: # the answer IS the result: shown in the form
+ return _test_result(False, exc.kind or "protocol", exc.message)
+ except identity.IdentityError as exc: # reported in the result, not raised
+ return _test_result(False, "protocol", str(exc))
+ try:
+ opened = await open_session(target)
+ except SshError as exc: # a failed login is the test's answer, not an error
+ message = exc.message
+ if exc.kind == "auth" and auth == "key":
+ message = (
+ "The server does not accept the app's key yet. Add the public key on "
+ "the server, or log in once with the password."
+ )
+ return _test_result(False, exc.kind, message)
+ facts: dict[str, Any] | None = None
+ try:
+ probe = await run_command(opened, PROBE_SCRIPT, timeout_s=_PROBE_TIMEOUT_S)
+ facts = parse_probe(probe.stdout).facts.model_dump(mode="json")
+ except SshError as exc:
+ log.info("computers: test probe failed after login: %s", exc.message)
+ finally:
+ close(opened)
+ return {
+ "ok": True,
+ "kind": None,
+ "message": None,
+ "host_fingerprint": opened.host_fingerprint,
+ "facts": facts,
+ "latency_ms": opened.latency_ms,
+ }
+
+ async def set_credentials(
+ self,
+ computer_id: str,
+ *,
+ auth: AuthMethod,
+ password: str | None = None,
+ keep_password: bool = False,
+ private_key: str | None = None,
+ passphrase: str | None = None,
+ ) -> Computer:
+ """Switch how the app logs in to an existing computer."""
+ self.get(computer_id)
+ if auth == "password":
+ if not password:
+ raise ComputerError("Enter the password for this login.")
+ if not keep_password:
+ return await self.install_key(computer_id, password)
+ if not set_secret(_password_slot(computer_id), password):
+ raise ComputerError("The password could not be saved to the keyring.", status=500)
+ _forget_secrets(computer_id, keep="password")
+ elif auth == "private_key":
+ import_private_key(private_key, passphrase)
+ self._save_private_key(computer_id, private_key or "", passphrase)
+ _forget_secrets(computer_id, keep="private_key")
+ else:
+ _forget_secrets(computer_id)
+ self._store.update(computer_id, lambda row: row.model_copy(update={"auth": auth}))
+ return await self.check(computer_id)
+
async def install_key(self, computer_id: str, password: str) -> Computer:
"""Plant Jarvis's key with a one-time password; switch to key login."""
computer = self.get(computer_id)
@@ -371,7 +546,7 @@ class ComputerService:
raise ComputerError("Enter the password for this login.")
proof = await self._plant_key(self._target(computer, password=password))
close(proof)
- delete_secret(_password_slot(computer_id))
+ _forget_secrets(computer_id)
self._store.update(
computer_id,
lambda row: row.model_copy(
@@ -424,7 +599,7 @@ class ComputerService:
await local_vm.delete(computer.provider_ref)
except local_vm.LocalVmError as exc:
raise ComputerError(exc.message, status=502) from exc
- delete_secret(_password_slot(computer_id))
+ _forget_secrets(computer_id)
return self._store.remove(computer_id)
# -- cloud import ---------------------------------------------------------
diff --git a/jarvis/computers/toolbox.py b/jarvis/computers/toolbox.py
index d74bd2d045..f043b1e85a 100644
--- a/jarvis/computers/toolbox.py
+++ b/jarvis/computers/toolbox.py
@@ -250,7 +250,7 @@ async def _run_install(current: InstallJob, script: str) -> None:
else:
current.state = "failed"
current.message = f"The installation stopped (exit {code}). See the log."
- except ComputerError as exc:
+ except ComputerError as exc: # recorded on the job the UI polls
current.state = "failed"
current.message = exc.message
except Exception as exc: # noqa: BLE001 — reported in the job, logged here
diff --git a/jarvis/ui/web/computers_routes.py b/jarvis/ui/web/computers_routes.py
index 45df16de6e..5d8e7f69c7 100644
--- a/jarvis/ui/web/computers_routes.py
+++ b/jarvis/ui/web/computers_routes.py
@@ -4,6 +4,9 @@
POST /api/computers add an SSH server
POST /api/computers/check-all check every computer
GET /api/computers/identity Jarvis's public key + fingerprint
+ GET /api/computers/providers provider catalog (SSH guides, API)
+ POST /api/computers/test try a login without saving
+ PUT /api/computers/{id}/credentials switch the login method
GET /api/computers/cloud hosting providers + token state
PUT /api/computers/cloud/{provider}/token save an API token (keyring)
DELETE /api/computers/cloud/{provider}/token forget it
@@ -39,7 +42,7 @@ from typing import Any, Literal
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
-from jarvis.computers import cloud, identity, local_vm, toolbox
+from jarvis.computers import cloud, identity, local_vm, providers, toolbox
from jarvis.computers.models import Computer
from jarvis.computers.service import ComputerError, get_service
@@ -55,20 +58,48 @@ def _fail(exc: ComputerError) -> HTTPException:
def _row(computer: Computer) -> dict[str, Any]:
data = computer.model_dump(mode="json")
data["busy"] = get_service().is_busy(computer.id)
+ data["provider_name"] = providers.display_name(computer.provider)
return data
# -- request bodies ----------------------------------------------------------
+AuthLiteral = Literal["key", "password", "private_key"]
+
+
class AddServerBody(BaseModel):
name: str = Field(min_length=1, max_length=120)
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: Literal["key", "password"] = "key"
+ auth: AuthLiteral = "key"
+ password: str | None = Field(default=None, max_length=1024)
+ keep_password: bool = False
+ private_key: str | None = Field(default=None, max_length=32_000)
+ passphrase: str | None = Field(default=None, max_length=1024)
+ provider: str = Field(default="generic", max_length=40)
+
+
+class TestBody(BaseModel):
+ name: str | None = Field(default=None, max_length=120)
+ 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"
+ password: str | None = Field(default=None, max_length=1024)
+ keep_password: bool = False
+ private_key: str | None = Field(default=None, max_length=32_000)
+ passphrase: str | None = Field(default=None, max_length=1024)
+ provider: str = Field(default="generic", max_length=40)
+
+
+class CredentialsBody(BaseModel):
+ auth: AuthLiteral
password: str | None = Field(default=None, max_length=1024)
keep_password: bool = False
+ private_key: str | None = Field(default=None, max_length=32_000)
+ passphrase: str | None = Field(default=None, max_length=1024)
class UpdateBody(BaseModel):
@@ -137,12 +168,35 @@ async def add_computer(body: AddServerBody) -> dict[str, Any]:
auth=body.auth,
password=body.password,
keep_password=body.keep_password,
+ private_key=body.private_key,
+ passphrase=body.passphrase,
+ provider=body.provider,
)
except ComputerError as exc:
raise _fail(exc) from exc
return _row(computer)
+async def test_computer(body: TestBody) -> dict[str, Any]:
+ """Try the login a form describes, saving nothing and planting nothing."""
+ return await get_service().test_connection(
+ host=body.host,
+ port=body.port,
+ username=body.username,
+ auth=body.auth,
+ password=body.password,
+ private_key=body.private_key,
+ passphrase=body.passphrase,
+ )
+
+
[email protected]("/providers")
+def list_providers() -> dict[str, Any]:
+ """Every place a computer can come from, with how to reach it there."""
+ return {"providers": providers.catalog_rows()}
+
+
@router.post("/check-all")
async def check_all() -> dict[str, Any]:
computers = await get_service().check_all()
@@ -170,6 +224,7 @@ def list_cloud_providers() -> dict[str, Any]:
"name": spec.name,
"connected": bool(cloud.token(spec.id)),
"console_url": spec.console_url,
+ "token_label": spec.credential_label,
"setup_hint": spec.setup_hint,
"attaches_keys": spec.attaches_keys,
}
@@ -318,6 +373,23 @@ async def run_on_computer(computer_id: str, body: RunBody) -> dict[str, Any]:
}
[email protected]("/{computer_id}/credentials")
+async def set_credentials(computer_id: str, body: CredentialsBody) -> dict[str, Any]:
+ """Switch the login method (a password alone plants the app's key once)."""
+ try:
+ computer = await get_service().set_credentials(
+ computer_id,
+ auth=body.auth,
+ password=body.password,
+ keep_password=body.keep_password,
+ private_key=body.private_key,
+ passphrase=body.passphrase,
+ )
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+ return _row(computer)
+
+
@router.post("/{computer_id}/install-key")
async def install_key(computer_id: str, body: PasswordBody) -> dict[str, Any]:
try:
diff --git a/tests/unit/computers/test_cloud_and_routes.py b/tests/unit/computers/test_cloud_and_routes.py
index c9dbf390c7..9cfc98720c 100644
--- a/tests/unit/computers/test_cloud_and_routes.py
+++ b/tests/unit/computers/test_cloud_and_routes.py
@@ -81,7 +81,7 @@ def test_routes_list_identity_and_providers(client: TestClient) -> None:
assert client.get("/api/computers/identity").json()["public_key"] == ident["public_key"]
providers = {p["id"]: p for p in client.get("/api/computers/cloud").json()["providers"]}
- assert set(providers) == {"hostinger", "hetzner", "digitalocean"}
+ assert set(providers) == {"hostinger", "hetzner", "digitalocean", "vultr", "linode"}
assert providers["hostinger"]["attaches_keys"] is True
assert providers["hostinger"]["connected"] is False
diff --git a/tests/unit/computers/test_overhaul.py b/tests/unit/computers/test_overhaul.py
new file mode 100644
index 0000000000..691f46be5b
--- /dev/null
+++ b/tests/unit/computers/test_overhaul.py
@@ -0,0 +1,296 @@
+"""Provider catalog, the user's own SSH key, try-before-save, and switching logins."""
+
+from __future__ import annotations
+
+import asyncssh
+import httpx
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.computers import cloud, identity, providers
+from jarvis.computers.service import ComputerError, ComputerService
+from jarvis.ui.web import computers_routes
+from tests.fakes.fake_ssh_server import TEST_PASSWORD, FakeSshServer
+
+
+async def ssh_server(): # noqa: ANN201
+ server = FakeSshServer()
+ await server.start()
+ try:
+ yield server
+ finally:
+ await server.stop()
+
+
+def own_key() -> asyncssh.SSHKey:
+ return asyncssh.generate_private_key("ssh-ed25519", comment="me@laptop")
+
+
+def _pem(key: asyncssh.SSHKey, passphrase: str | None = None) -> str:
+ return key.export_private_key("openssh", passphrase=passphrase).decode()
+
+
+def _public(key: asyncssh.SSHKey) -> str:
+ return key.export_public_key("openssh").decode().strip()
+
+
+# -- catalog -------------------------------------------------------------------
+
+
+def test_catalog_has_the_promised_providers_and_shape(secret_box) -> None: # noqa: ANN001
+ rows = providers.catalog_rows()
+ ids = [row["id"] for row in rows]
+ for wanted in (
+ "hostinger",
+ "hetzner",
+ "digitalocean",
+ "vultr",
+ "linode",
+ "aws_lightsail",
+ "contabo",
+ "ionos",
+ "strato",
+ "ovhcloud",
+ "oracle_cloud",
+ "raspberry_pi",
+ "home_server",
+ "generic",
+ ):
+ assert wanted in ids
+ assert ids[-1] == "generic"
+ with_api = {row["id"] for row in rows if row["api"] is not None}
+ assert with_api == {"hostinger", "hetzner", "digitalocean", "vultr", "linode"}
+ pi = next(row for row in rows if row["id"] == "raspberry_pi")
+ assert pi["category"] == "home" and pi["ssh"]["default_username"] == "pi"
+ for row in rows:
+ assert set(row["ssh"]) == {
+ "default_username",
+ "ip_hint",
+ "key_hint",
+ "key_url",
+ "password_hint",
+ }
+ if row["api"]:
+ assert set(row["api"]) == {
+ "connected",
+ "console_url",
+ "setup_hint",
+ "attaches_keys",
+ "token_label",
+ }
+
+
+# -- the user's own key ------------------------------------------------------------
+
+
+async def test_add_with_own_private_key_logs_in_and_keeps_the_key_out_of_json(
+ computer_service: ComputerService,
+ ssh_server: FakeSshServer,
+ own_key,
+ secret_box, # noqa: ANN001
+) -> None:
+ ssh_server.state.authorized.add(_public(own_key))
+
+ computer = await computer_service.add_server(
+ name="lightsail",
+ host="127.0.0.1",
+ port=ssh_server.port,
+ auth="private_key",
+ private_key=_pem(own_key, "pw1"),
+ passphrase="pw1", # noqa: S106 — test key
+ provider="aws_lightsail",
+ )
+
+ assert computer.auth == "private_key" and computer.provider == "aws_lightsail"
+ assert computer.health.status == "online", computer.health.message
+ assert secret_box.values[f"computer_private_key_{computer.id}"].startswith("-----BEGIN")
+ assert "BEGIN" not in computer.model_dump_json()
+
+ await computer_service.remove(computer.id)
+ assert not any(k.endswith(computer.id) for k in secret_box.values)
+
+
+async def test_bad_key_and_wrong_passphrase_are_sentences(
+ computer_service: ComputerService,
+ own_key, # noqa: ANN001
+) -> None:
+ for pem, phrase in (
+ ("nonsense", None),
+ (_pem(own_key, "right"), "wrong"),
+ (_pem(own_key, "right"), None),
+ (_public(own_key), None),
+ ):
+ with pytest.raises(ComputerError) as caught:
+ await computer_service.add_server(
+ name="x",
+ host="127.0.0.1",
+ port=1,
+ auth="private_key",
+ private_key=pem,
+ passphrase=phrase,
+ )
+ assert caught.value.kind == "bad_key" and caught.value.status == 400
+ assert computer_service.all() == []
+
+
+async def test_unknown_provider_is_refused(computer_service: ComputerService) -> None:
+ with pytest.raises(ComputerError):
+ await computer_service.add_server(name="x", host="127.0.0.1", provider="nope")
+
+
+# -- try before save ------------------------------------------------------------------
+
+
+async def test_test_connection_for_all_three_logins(
+ computer_service: ComputerService,
+ ssh_server: FakeSshServer,
+ own_key, # noqa: ANN001
+) -> None:
+ common = {"host": "127.0.0.1", "port": ssh_server.port, "username": "root"}
+
+ by_password = await computer_service.test_connection(
+ **common, auth="password", password=TEST_PASSWORD
+ )
+ assert by_password["ok"] and by_password["facts"]["os_id"] == "ubuntu"
+ assert by_password["host_fingerprint"].startswith("SHA256:")
+ assert not ssh_server.state.authorized, "a test plants nothing"
+
+ jarvis_key = await computer_service.test_connection(**common, auth="key")
+ assert jarvis_key["ok"] is False and jarvis_key["kind"] == "auth"
+ ssh_server.state.authorized.add(identity.public_key_line())
+ assert (await computer_service.test_connection(**common, auth="key"))["ok"]
+
+ ssh_server.state.authorized.add(_public(own_key))
+ mine = await computer_service.test_connection(
+ **common, auth="private_key", private_key=_pem(own_key)
+ )
+ assert mine["ok"] and mine["latency_ms"] is not None
+
+ broken = await computer_service.test_connection(
+ **common, auth="private_key", private_key="not a key"
+ )
+ assert broken == {**broken, "ok": False, "kind": "bad_key"}
+ assert computer_service.all() == [], "nothing was saved"
+
+
+# -- switching logins -------------------------------------------------------------------
+
+
+async def test_switch_from_jarvis_key_to_own_key_and_to_kept_password(
+ computer_service: ComputerService,
+ ssh_server: FakeSshServer,
+ own_key,
+ secret_box, # noqa: ANN001
+) -> None:
+ ssh_server.state.authorized.add(identity.public_key_line())
+ computer = await computer_service.add_server(name="box", host="127.0.0.1", port=ssh_server.port)
+ ssh_server.state.authorized.add(_public(own_key))
+
+ switched = await computer_service.set_credentials(
+ computer.id, auth="private_key", private_key=_pem(own_key)
+ )
+ assert switched.auth == "private_key" and switched.health.status == "online"
+
+ kept = await computer_service.set_credentials(
+ computer.id, auth="password", password=TEST_PASSWORD, keep_password=True
+ )
+ assert kept.auth == "password" and kept.health.status == "online"
+ assert f"computer_private_key_{computer.id}" not in secret_box.values
+
+ planted = await computer_service.set_credentials(
+ computer.id, auth="password", password=TEST_PASSWORD
+ )
+ assert planted.auth == "key" and f"computer_password_{computer.id}" not in secret_box.values
+
+
+# -- routes -------------------------------------------------------------------------------
+
+
+def client(computer_service: ComputerService, monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ monkeypatch.setattr(computers_routes, "get_service", lambda: computer_service)
+ app = FastAPI()
+ app.include_router(computers_routes.router)
+ return TestClient(app)
+
+
+def test_routes_providers_test_and_bad_key(client: TestClient) -> None:
+ body = client.get("/api/computers/providers").json()
+ assert body["providers"][0]["id"] == "hostinger"
+
+ tried = client.post(
+ "/api/computers/test", json={"host": "127.0.0.1", "port": 1, "auth": "key"}
+ ).json()
+ assert tried["ok"] is False and tried["kind"] in {"unreachable", "timeout"}
+
+ refused = client.post(
+ "/api/computers",
+ json={"name": "x", "host": "127.0.0.1", "auth": "private_key", "private_key": "junk"},
+ )
+ assert refused.status_code == 400 and refused.json()["detail"]["kind"] == "bad_key"
+
+ listed = client.post(
+ "/api/computers", json={"name": "y", "host": "127.0.0.1", "port": 1, "provider": "strato"}
+ ).json()
+ assert listed["provider_name"] == "Strato"
+
+
+# -- Vultr and Linode --------------------------------------------------------------------
+
+
+async def test_vultr_follows_the_cursor(secret_box) -> None: # noqa: ANN001
+ secret_box.set("vultr_api_token", "vultr-token")
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url.path == "/v2/instances"
+ first = "cursor" not in request.url.params
+ instance = {
+ "id": "a1" if first else "b2",
+ "label": "web" if first else "db",
+ "main_ip": "198.51.100.7" if first else "0.0.0.0", # noqa: S104
+ "status": "active",
+ "power_status": "running",
+ "os": "Ubuntu 24.04 LTS x64",
+ "plan": "vc2-1c-1gb",
+ "region": "fra",
+ "vcpu_count": 1,
+ "ram": 1024,
+ "disk": 25,
+ }
+ meta = {"total": 2, "links": {"next": "abc" if first else "", "prev": ""}}
+ return httpx.Response(200, json={"instances": [instance], "meta": meta})
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
+ servers = await cloud.list_servers("vultr", client=http)
+
+ assert [s.name for s in servers] == ["web", "db"]
+ assert servers[0].host == "198.51.100.7" and servers[0].running
+ assert servers[1].host is None, "0.0.0.0 means no IP yet"
+ assert servers[0].memory_mb == 1024 and servers[0].disk_gb == 25.0
+
+
+async def test_linode_pages_and_public_ip(secret_box) -> None: # noqa: ANN001
+ secret_box.set("linode_api_token", "linode-token")
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ page = int(request.url.params["page"])
+ row = {
+ "id": page,
+ "label": f"li{page}",
+ "status": "running",
+ "ipv4": ["192.168.130.2", f"203.0.113.{page}"],
+ "type": "g6-standard-1",
+ "region": "eu-central",
+ "image": "linode/ubuntu24.04",
+ "specs": {"vcpus": 1, "memory": 2048, "disk": 51200},
+ }
+ return httpx.Response(200, json={"data": [row], "page": page, "pages": 2, "results": 2})
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
+ servers = await cloud.list_servers("linode", client=http)
+
+ assert [s.host for s in servers] == ["203.0.113.1", "203.0.113.2"]
+ assert servers[0].os == "ubuntu24.04" and servers[0].disk_gb == 50.0