Skip to main content

tilo_actions/remote/
shell.rs

1//! The shell lane an app's own connection carries: a shell the device's shell runtime runs, with
2//! its terminal kept by the device and its bytes carried to the app.
3//!
4//! An app's process is sandboxed: it holds no socket of the shell runtime's and starts no program
5//! of the device's. An app whose signed manifest declares it may open shells (`shells`) asks the
6//! device for one on its connection ([`ShellOpen`]). The device opens it on its one connection to
7//! the runtime, in the workspace the app was started in and never another, keeps the terminal
8//! the runtime hands it, and from then on carries the session on this connection: what the app
9//! types ([`ShellBytes`] as `ShellInput`), the window's size, the shell's output back
10//! (`ShellOutput`) and, last, how the session ended (`ShellEnded`). Closing the shell
11//! (`ShellClose`) or the connection lets the session go.
12
13use serde::{Deserialize, Serialize};
14
15/// The most bytes one frame of a shell's input or output carries.
16pub const MAX_SHELL_BYTES: usize = 16 * 1024;
17
18/// A shell to open: where it runs and how it starts.
19#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(deny_unknown_fields)]
21pub struct ShellOpen {
22    /// Where it runs, as the shell runtime names a session's target (`{"kind": "environment",
23    /// "record": "work"}`, `{"kind": "host"}`).
24    pub target: serde_json::Value,
25    /// The window's size, in cells.
26    pub cols: u16,
27    pub rows: u16,
28    /// An agent asks for it, rather than the person.
29    #[serde(default)]
30    pub agent: bool,
31    /// The program to run instead of the shell, when one is named.
32    #[serde(default, skip_serializing_if = "Vec::is_empty")]
33    pub command: Vec<String>,
34    /// The hosted session to come back to.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub relay_session: Option<String>,
37    /// The Terminal session record the shell belongs to, in a workspace a server hosts.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub record: Option<String>,
40    /// The key the shell marks each command line it runs with, so the app sees where each
41    /// starts and ends in its output.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub commands: Option<String>,
44}
45
46/// An opened shell: what the app names it by on the connection, and what the runtime said of it.
47#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(deny_unknown_fields)]
49pub struct ShellOpened {
50    /// The shell's id on this connection.
51    pub shell: u64,
52    /// The program at its prompt (`ush`, `host`).
53    pub name: String,
54    /// The hosted session it is, to come back to.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub relay_session: Option<String>,
57    /// Whether the shell marks its command lines with the key the open named.
58    #[serde(default)]
59    pub commands: bool,
60}
61
62/// Bytes of one shell's input or output.
63#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(deny_unknown_fields)]
65pub struct ShellBytes {
66    pub shell: u64,
67    /// The bytes, as hex digits.
68    #[serde(with = "hex_bytes")]
69    pub bytes: Vec<u8>,
70}
71
72/// How a shell's session ended: the runtime's own report (`{"ended": "lost", "reason": ...}`),
73/// empty when the shell exited and nothing more was said.
74#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(deny_unknown_fields)]
76pub struct ShellEnded {
77    pub shell: u64,
78    #[serde(default)]
79    pub report: String,
80}
81
82/// The report of a session whose connection to the device was lost: the device's word for
83/// `ShellEnded` when it can no longer say anything itself.
84#[must_use]
85pub fn lost_report(reason: &str) -> String {
86    serde_json::json!({ "ended": "lost", "reason": reason }).to_string()
87}
88
89mod hex_bytes {
90    use serde::{Deserialize as _, Deserializer, Serializer};
91
92    pub fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
93        serializer.serialize_str(&hex::encode(bytes))
94    }
95
96    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
97        let digits = String::deserialize(deserializer)?;
98        if digits.len() > super::MAX_SHELL_BYTES * 2 {
99            return Err(serde::de::Error::custom("a shell frame over its bound"));
100        }
101        hex::decode(digits).map_err(serde::de::Error::custom)
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[test]
110    fn a_shells_bytes_travel_as_hex_and_an_oversized_frame_is_refused() {
111        let frame = ShellBytes {
112            shell: 3,
113            bytes: b"echo hi\r".to_vec(),
114        };
115        let text = serde_json::to_string(&frame).unwrap();
116        assert_eq!(text, r#"{"shell":3,"bytes":"6563686f2068690d"}"#);
117        assert_eq!(serde_json::from_str::<ShellBytes>(&text).unwrap(), frame);
118        let over = format!(
119            r#"{{"shell":3,"bytes":"{}"}}"#,
120            "00".repeat(MAX_SHELL_BYTES + 1)
121        );
122        assert!(serde_json::from_str::<ShellBytes>(&over).is_err());
123    }
124}