Skip to main content

agentmux_srv/server/
http_viewer_computers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Another computer as a paired device (docs/specs/SPEC_REMOTE_PANES_WATCH_AND_DRIVE_AN_AGENT_ON_ANOTHER_COMPUTER_2026_11_20.md
5//! §5.1): it pairs on the same listener as a phone, as `device_kind: "computer"`, and is let in only while this
6//! computer's person allows computers (`viewer:allowcomputers`, off by default, a setting only the person changes).
7//! While it is off a computer can't pair, a paired one is refused at every route, and a feed it has open ends at its
8//! next event or heartbeat. Phones are not affected.
9
10use axum::http::StatusCode;
11use axum::response::{IntoResponse, Response};
12use axum::Json;
13use serde_json::json;
14
15use crate::backend::storage::viewer_devices::DeviceKind;
16use crate::server::AppState;
17
18/// The setting: whether other computers may pair with this one and watch its agents.
19pub(crate) const SETTING_ALLOW_COMPUTERS: &str = "viewer:allowcomputers";
20
21/// What a refused computer is told, as `reason`.
22pub(crate) const COMPUTERS_OFF: &str = "computers_off";
23
24/// The capability a host advertises in `hello` once it serves remote panes (§7, version mismatch).
25pub(crate) const REMOTE_PANES_VERSION: u32 = 1;
26
27/// Whether this computer's person lets other computers watch its agents.
28pub(crate) fn computers_allowed(state: &AppState) -> bool {
29    state
30        .config_watcher
31        .get_settings()
32        .extra
33        .get(SETTING_ALLOW_COMPUTERS)
34        .and_then(|v| v.as_bool())
35        .unwrap_or(false)
36}
37
38/// Whether a device of `kind` is let in now.
39pub(crate) fn kind_admitted(state: &AppState, kind: DeviceKind) -> bool {
40    kind == DeviceKind::Phone || computers_allowed(state)
41}
42
43/// Whether an open feed of the paired device `device_id` goes on: false only for a computer once its host's person
44/// stopped allowing computers. A device whose row is gone was revoked, and revoking closes its feeds itself, silently
45/// (`revoke_impl`); a read that fails now is not a reason to end a feed (the device's next request is refused by
46/// [`admit`] if the store still can't be read).
47pub(crate) fn device_admitted(state: &AppState, device_id: &str) -> bool {
48    match state.mstore.viewer_device_get(device_id) {
49        Ok(Some(device)) => kind_admitted(state, device.kind),
50        Ok(None) | Err(_) => true,
51    }
52}
53
54/// What a computer is told when it asks for a route of this computer that isn't an agent's, as `reason`.
55pub(crate) const NOT_FOR_COMPUTERS: &str = "not_for_computers";
56
57/// Whether a computer may ask for `path`: who this is and an agent's list, feed, history, attachments and input.
58/// Nothing else of this
59/// computer (its terminals, processes, panes or system figures) is reachable from a remote pane (§5.3).
60fn open_to_computers(path: &str) -> bool {
61    match path.strip_prefix("/agentmux/viewer/") {
62        Some("hello" | "agents") => true,
63        Some(rest) => rest
64            .strip_prefix("agents/")
65            .and_then(|r| r.split_once('/'))
66            .is_some_and(|(name, route)| {
67                let attachment = route.strip_prefix("attachments/").is_some_and(|id| !id.is_empty() && !id.contains('/'));
68                !name.is_empty() && (attachment || matches!(route, "feed" | "history" | "input"))
69            }),
70        None => false,
71    }
72}
73
74/// The answer, when the paired device `device_id` may not have `path` now: a computer while computers are
75/// not allowed, or a computer asking for a route that isn't an agent's. A device that can't be read is refused.
76pub(crate) fn admit(state: &AppState, device_id: &str, path: &str) -> Option<Response> {
77    let kind = match state.mstore.viewer_device_get(device_id) {
78        Ok(Some(device)) => device.kind,
79        _ => {
80            let body = json!({ "error": "the paired device could not be read; try again" });
81            return Some((StatusCode::SERVICE_UNAVAILABLE, Json(body)).into_response());
82        }
83    };
84    if !kind_admitted(state, kind) {
85        return Some(refused());
86    }
87    if kind == DeviceKind::Computer && !open_to_computers(path) {
88        let body = json!({ "error": "a computer may watch this computer's agents, nothing else", "reason": NOT_FOR_COMPUTERS });
89        return Some((StatusCode::FORBIDDEN, Json(body)).into_response());
90    }
91    None
92}
93
94fn refuse(status: StatusCode, reason: &str, error: &str) -> Option<Response> {
95    Some((status, Json(json!({ "error": error, "reason": reason }))).into_response())
96}
97
98/// The answer, when a read of the paired device `device_id` for `path` (a feed open, or a history page or an
99/// attachment with its query) is not signed as a computer's must be
100/// (§3: `signing::open_signed_text`, by the key the computer paired with, over this computer's certificate
101/// fingerprint, fresh, and with a nonce it hasn't used). A phone's open needs no signature, as before.
102pub(crate) fn refuse_unsigned_open(state: &AppState, device_id: &str, path: &str, headers: &axum::http::HeaderMap) -> Option<Response> {
103    use crate::backend::viewer::signing::{self, DeviceKey};
104    let device = match state.mstore.viewer_device_get(device_id) {
105        Ok(Some(device)) => device,
106        Ok(None) => return refuse(StatusCode::UNAUTHORIZED, "revoked", "this device is no longer paired"),
107        Err(_) => return refuse(StatusCode::SERVICE_UNAVAILABLE, "", "the paired device could not be read; try again"),
108    };
109    if device.kind != DeviceKind::Computer {
110        return None;
111    }
112    let Ok(key) = DeviceKey::parse(&device.device_key) else {
113        return refuse(StatusCode::FORBIDDEN, "pair_again", "this computer paired without a key: pair it again");
114    };
115    let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).map(str::trim);
116    let (Some(timestamp), Some(nonce), Some(signature)) =
117        (header(signing::TIMESTAMP_HEADER), header(signing::NONCE_HEADER), header(signing::SIGNATURE_HEADER))
118    else {
119        return refuse(StatusCode::FORBIDDEN, "bad_signature", "a computer's reads must be signed");
120    };
121    let (Ok(timestamp_ms), true) = (timestamp.parse::<i64>(), signing::nonce_shape_ok(nonce)) else {
122        return refuse(StatusCode::FORBIDDEN, "bad_signature", "the signing time or the nonce is malformed");
123    };
124    let Ok(tls) = state.viewer.tls() else {
125        return refuse(StatusCode::SERVICE_UNAVAILABLE, "", "this computer's certificate is not ready");
126    };
127    let signed = signing::open_signed_text("GET", path, timestamp_ms, nonce, &tls.fingerprint);
128    if !key.verifies(signed.as_bytes(), signature) {
129        tracing::warn!(device = %device_id, "viewer feed: a computer's open did not verify");
130        return refuse(StatusCode::FORBIDDEN, "bad_signature", "the signature does not verify");
131    }
132    let now = agentmux_common::time::now_ms();
133    if !signing::fresh(timestamp_ms, now) {
134        return refuse(StatusCode::FORBIDDEN, "stale_timestamp", "the two computers' clocks differ by more than a minute");
135    }
136    if !state.viewer.nonces.lock().first_use(device_id, nonce, now) {
137        tracing::warn!(device = %device_id, "viewer feed: a computer's open was replayed");
138        return refuse(StatusCode::FORBIDDEN, "replayed", "this signed open was already used");
139    }
140    None
141}
142
143/// The answer to a computer while computers are not allowed.
144pub(crate) fn refused() -> Response {
145    (
146        StatusCode::FORBIDDEN,
147        Json(json!({
148            "error": "this computer doesn't let other computers watch its agents; its person can allow it in Settings",
149            "reason": COMPUTERS_OFF,
150        })),
151    )
152        .into_response()
153}