Skip to main content

agentmux_srv_core/backend/viewer/
audit.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Audit's rows for what a paired device does on this computer
5//! (docs/specs/SPEC_REMOTE_PANES_WATCH_AND_DRIVE_AN_AGENT_ON_ANOTHER_COMPUTER_2026_11_20.md ยง5.5, "Audit rows").
6//!
7//! Each is an action row (`log_fleet_action_audit`): the actor is the device, the target the agent it acted on,
8//! the outcome `viewer.<act>`, and the reason says what kind of device it is, how this computer knows the device
9//! did it, and, for a computer, that the person's name is the computer's own claim.
10//!
11//! - The actor is `<user>@<computer>` for a computer that names its person, else `<name> (computer)` or
12//!   `<name> (phone)`. Each always holds an `@` or a space, so the Audit never takes it for an agent, the
13//!   operator or the person (`audit_query`), and a `:` in a name is shown as `-`, so no name reads as `agent:<id>`.
14//! - A message a device sent is recorded when its line is stored, with the line's position
15//!   ([`note_landed`]), never its text: the text is in the conversation, as for any message.
16//!
17//! What the host's own person does to a device (a grant, a revoke, stopping its viewing, a setting) is recorded
18//! as their call, like any other (`rpc::action_commands`).
19
20use std::sync::atomic::{AtomicUsize, Ordering};
21use std::sync::OnceLock;
22use std::time::Instant;
23
24use crate::backend::mps::StreamPos;
25use crate::backend::storage::viewer_devices::{DeviceKind, ViewerDevice};
26
27/// The longest name part kept in a row.
28const MAX_NAME: usize = 64;
29
30/// How this computer knows the device did it.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Proof {
33    /// The pairing code shown on this screen (a device pairing; its name and kind are its own words).
34    Code,
35    /// Its viewer token (a phone's reads).
36    Token,
37    /// Its token, and the request signed by the key it paired with.
38    Signed,
39}
40
41impl Proof {
42    fn as_str(self) -> &'static str {
43        match self {
44            Proof::Code => "the pairing code shown on this computer",
45            Proof::Token => "its viewer token",
46            Proof::Signed => "signed by its paired key",
47        }
48    }
49}
50
51/// A paired device, as its rows name it.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct ViewerActor {
54    pub device_id: String,
55    pub name: String,
56    pub kind: DeviceKind,
57    /// The person on a computer, as that computer says: a claim, never proven here.
58    pub user: Option<String>,
59}
60
61/// `text` without control characters, trimmed, at most [`MAX_NAME`] characters.
62fn tidy(text: &str) -> String {
63    let kept: String = text.chars().filter(|c| !c.is_control()).collect();
64    kept.trim().chars().take(MAX_NAME).collect::<String>().trim_end().to_string()
65}
66
67/// A name part of a row's actor: [`tidy`], with a `:` shown as `-`.
68fn clean(text: &str) -> String {
69    let kept = tidy(text).replace(':', "-");
70    if kept.is_empty() { "unnamed".to_string() } else { kept }
71}
72
73impl ViewerActor {
74    /// `device`, with the person its request named (`user`), kept only for a computer, tidied (it is stored beside
75    /// the message too, `amx.user`).
76    pub fn of(device: &ViewerDevice, user: Option<&str>) -> Self {
77        let user = user.filter(|_| device.kind == DeviceKind::Computer).map(tidy).filter(|u| !u.is_empty());
78        Self { device_id: device.device_id.clone(), name: device.device_name.clone(), kind: device.kind, user }
79    }
80
81    /// The row's actor: `<user>@<computer>`, `<name> (computer)` or `<name> (phone)`.
82    pub fn label(&self) -> String {
83        match (&self.user, self.kind) {
84            (Some(user), _) => format!("{}@{}", clean(user).replace('@', "-"), clean(&self.name)),
85            (None, kind) => format!("{} ({})", clean(&self.name), kind.as_str()),
86        }
87    }
88
89    fn reason(&self, proof: Proof, detail: Option<&str>) -> String {
90        let mut reason = format!("paired {} {}; {}", self.kind.as_str(), self.device_id, proof.as_str());
91        if self.user.is_some() {
92            reason.push_str("; the person's name is claimed by the paired computer");
93        }
94        if let Some(detail) = detail.filter(|d| !d.is_empty()) {
95            reason.push_str("; ");
96            reason.push_str(detail);
97        }
98        reason
99    }
100}
101
102/// One row: `actor` did `act` (`viewer.<act>`) to `agent` (empty for none), proven by `proof`. `refused` says
103/// why it was not done.
104pub fn record(actor: &ViewerActor, act: &str, agent: &str, proof: Proof, detail: Option<&str>, refused: Option<&str>) {
105    let reason = actor.reason(proof, detail);
106    crate::backend::reactive::get_global_handler().log_fleet_action_audit(
107        Some(&actor.label()),
108        agent,
109        "",
110        &format!("viewer.{act}"),
111        refused.is_none(),
112        refused,
113        "",
114        Some(&reason),
115    );
116}
117
118/// A device answered the code this computer shows with a wrong one. Nothing about it is proven: its name and kind
119/// are its own words.
120pub fn wrong_pairing_code(name: &str, kind: DeviceKind) {
121    let label = format!("{} ({})", clean(name), kind.as_str());
122    let reason = "an unpaired device answered the pairing code shown on this computer with a wrong one; its name and kind are its own words";
123    crate::backend::reactive::get_global_handler().log_fleet_action_audit(
124        Some(&label),
125        "",
126        "",
127        "viewer.pair",
128        false,
129        Some("a wrong pairing code"),
130        "",
131        Some(reason),
132    );
133}
134
135/// Records the feed's opening now and its closing when the lease drops.
136pub fn feed_opened(actor: ViewerActor, agent: &str, proof: Proof, lease: super::FeedLease) -> super::FeedLease {
137    record(&actor, "feed-open", agent, proof, None, None);
138    let agent = agent.to_string();
139    lease.on_close(move || record(&actor, "feed-close", &agent, proof, None, None))
140}
141
142/// A device's message whose record was stored with its sender (`origin::stamp`) and waits for its position.
143struct Landing {
144    block_id: String,
145    /// The device's name, as stored in the line's `amx`.
146    device: String,
147    message_id: String,
148    actor: ViewerActor,
149    agent: String,
150    at: Instant,
151}
152
153static LANDING: OnceLock<parking_lot::Mutex<Vec<Landing>>> = OnceLock::new();
154/// Entries waiting, read without the lock so storing a line costs nothing while no device is sending.
155static WAITING: AtomicUsize = AtomicUsize::new(0);
156
157fn landing() -> &'static parking_lot::Mutex<Vec<Landing>> {
158    LANDING.get_or_init(|| parking_lot::Mutex::new(Vec::new()))
159}
160
161/// The record of `message_id`, sent by `actor` (stored as `device`) to `agent` in `block_id`, is about to be stored:
162/// its row is written once the line lands ([`note_landed`]).
163pub(super) fn expect_landing(block_id: &str, device: &str, message_id: &str, actor: ViewerActor, agent: &str) {
164    let mut list = landing().lock();
165    let now = Instant::now();
166    list.retain(|l| now.duration_since(l.at) < super::origin::KEEP);
167    let landing = Landing {
168        block_id: block_id.to_string(),
169        device: device.to_string(),
170        message_id: message_id.to_string(),
171        actor,
172        agent: agent.to_string(),
173        at: now,
174    };
175    list.push(landing);
176    WAITING.store(list.len(), Ordering::Release);
177}
178
179/// Where line `n` of a run that starts at `pos` sits: the agent's zone when it was written there, else the block's.
180fn position(pos: &[StreamPos], n: u64) -> Option<String> {
181    let p = pos.iter().find(|p| p.stream.starts_with("g:")).or_else(|| pos.first())?;
182    Some(format!("line {}:{} of {}", p.gen, p.line + n, p.stream))
183}
184
185/// The sender srv stored with line `line` (`amx`: device and message id), if a device sent it.
186fn sent_by(line: &[u8]) -> Option<(String, String)> {
187    // Cheap first: only a line that names a viewer is parsed.
188    find(line, b"\"via\":\"viewer\"")?;
189    let record: serde_json::Value = serde_json::from_slice(line).ok()?;
190    let amx = record.get("amx")?;
191    (amx.get("via")?.as_str()? == "viewer").then_some(())?;
192    Some((amx.get("device")?.as_str()?.to_string(), amx.get("message_id")?.as_str()?.to_string()))
193}
194
195/// `records` (complete NDJSON lines) of `block_id` were handed to the transcript: `stored` says whether any copy was
196/// written, `pos` where the counted ones landed (empty when none is counted). A device's message among them gets
197/// its row, naming the line's position, never its text; one stored nowhere is recorded as not stored. A line is
198/// matched to its send by block, device and message id: an id is the device's own, so two devices may use the
199/// same one.
200pub fn note_landed(block_id: &str, records: &[u8], pos: &[StreamPos], stored: bool) {
201    if WAITING.load(Ordering::Acquire) == 0 {
202        return;
203    }
204    let mut landed = Vec::new();
205    {
206        let mut list = landing().lock();
207        for (n, line) in records.split(|b| *b == b'\n').enumerate() {
208            let Some((device, message_id)) = sent_by(line) else { continue };
209            let Some(at) = list.iter().position(|l| l.block_id == block_id && l.device == device && l.message_id == message_id) else {
210                continue;
211            };
212            let l = list.remove(at);
213            landed.push((l.actor, l.agent, position(pos, n as u64)));
214        }
215        WAITING.store(list.len(), Ordering::Release);
216    }
217    for (actor, agent, at) in landed {
218        match at {
219            Some(at) => record(&actor, "send", &agent, Proof::Signed, Some(&at), None),
220            None if stored => record(&actor, "send", &agent, Proof::Signed, Some("its line's position is not known"), None),
221            None => record(&actor, "send", &agent, Proof::Signed, None, Some("delivered, but its line was not stored")),
222        }
223    }
224}
225
226fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
227    haystack.windows(needle.len()).position(|w| w == needle)
228}
229
230#[cfg(test)]
231#[path = "audit_tests.rs"]
232mod tests;