Skip to main content

aios_cli/
android_bridge.rs

1use std::io::{Read, Write};
2use std::net::{Shutdown, TcpStream};
3use std::time::{Duration, SystemTime, UNIX_EPOCH};
4
5use anyhow::{bail, Context, Result};
6use serde_json::json;
7use sha2::{Digest, Sha256};
8
9const READ_TIMEOUT_MS: u64 = 5000;
10const MAX_RESPONSE_BYTES: usize = 4096;
11const ACTION_PAYLOAD_TTL_MS: i64 = 60_000;
12
13/// Send a ping/health-check message to the Android localhost action bridge.
14///
15/// The bridge is expected to reply with a JSON object containing at least
16/// `"status": "ok"`. This command intentionally does **not** dispatch any
17/// action; it only verifies reachability and token acceptance.
18pub fn send_ping(host: &str, port: u16, auth_token: &str) -> Result<()> {
19    let payload = json!({
20        "message_type": "ping",
21        "auth_token": auth_token,
22    })
23    .to_string();
24
25    let mut stream =
26        TcpStream::connect((host, port)).with_context(|| format!("connecting to {host}:{port}"))?;
27    stream
28        .set_read_timeout(Some(Duration::from_millis(READ_TIMEOUT_MS)))
29        .with_context(|| "setting read timeout")?;
30    stream
31        .write_all(payload.as_bytes())
32        .with_context(|| format!("writing ping to {host}:{port}"))?;
33    stream
34        .flush()
35        .with_context(|| format!("flushing ping to {host}:{port}"))?;
36
37    let mut buf = Vec::with_capacity(MAX_RESPONSE_BYTES);
38    let mut chunk = [0u8; 1024];
39    loop {
40        match stream.read(&mut chunk) {
41            Ok(0) => break,
42            Ok(n) => {
43                if buf.len() + n > MAX_RESPONSE_BYTES {
44                    bail!("bridge response exceeded {MAX_RESPONSE_BYTES} bytes");
45                }
46                buf.extend_from_slice(&chunk[..n]);
47                // If we already have a complete JSON value we can stop reading;
48                // the server may keep its half-open socket alive after sending.
49                if std::str::from_utf8(&buf)
50                    .ok()
51                    .and_then(|text| serde_json::from_str::<serde_json::Value>(text).ok())
52                    .is_some()
53                {
54                    break;
55                }
56            },
57            Err(e)
58                if e.kind() == std::io::ErrorKind::WouldBlock
59                    || e.kind() == std::io::ErrorKind::TimedOut =>
60            {
61                if buf.is_empty() {
62                    return Err(e).with_context(|| format!("reading pong from {host}:{port}"));
63                }
64                break;
65            },
66            Err(e) => {
67                return Err(e).with_context(|| format!("reading pong from {host}:{port}"));
68            },
69        }
70    }
71
72    let text = std::str::from_utf8(&buf).with_context(|| "bridge returned non-UTF-8 response")?;
73    let value: serde_json::Value =
74        serde_json::from_str(text).with_context(|| "bridge returned invalid JSON")?;
75
76    match value.get("status").and_then(|v| v.as_str()) {
77        Some("ok") => Ok(()),
78        Some(other) => bail!("bridge returned status '{other}'"),
79        None => bail!("bridge response missing status field"),
80    }
81}
82
83/// Send a real authorized action payload to the Android action bridge.
84///
85/// This constructs a payload that mirrors what `aios-action` produces
86/// when forwarding an `AuthorizedAction` to the Android bridge, including
87/// the length-prefixed canonical HMAC-SHA256 signature.
88pub fn send_action(
89    host: &str,
90    port: u16,
91    auth_token: &str,
92    action_type: &str,
93    target: &str,
94    urgency: &str,
95) -> Result<()> {
96    let issued_at_ms = SystemTime::now()
97        .duration_since(UNIX_EPOCH)
98        .context("system clock before epoch")?
99        .as_millis() as i64;
100    let expires_at_ms = issued_at_ms + ACTION_PAYLOAD_TTL_MS;
101    let signature = action_signature(
102        auth_token,
103        issued_at_ms,
104        expires_at_ms,
105        action_type,
106        target,
107        urgency,
108    );
109
110    let target_value: serde_json::Value = if target.is_empty() {
111        serde_json::Value::Null
112    } else {
113        serde_json::Value::String(target.to_string())
114    };
115
116    let payload = json!({
117        "intent_id": "cli-manual-action",
118        "coord": {
119            "window_ordinal": 0,
120            "intent_ordinal": 0,
121            "action_ordinal": 0,
122        },
123        "action": {
124            "action_type": action_type,
125            "target": target_value,
126            "urgency": urgency,
127        },
128        "effect": "PureRead",
129        "authorized_at_ms": issued_at_ms,
130        "auth_token": auth_token,
131        "issued_at_ms": issued_at_ms,
132        "expires_at_ms": expires_at_ms,
133        "action_signature": signature,
134    })
135    .to_string();
136
137    let mut stream =
138        TcpStream::connect((host, port)).with_context(|| format!("connecting to {host}:{port}"))?;
139    stream
140        .set_read_timeout(Some(Duration::from_millis(READ_TIMEOUT_MS)))
141        .with_context(|| "setting read timeout")?;
142    stream
143        .write_all(payload.as_bytes())
144        .with_context(|| format!("writing action payload to {host}:{port}"))?;
145    stream
146        .flush()
147        .with_context(|| format!("flushing action payload to {host}:{port}"))?;
148
149    stream
150        .shutdown(Shutdown::Write)
151        .with_context(|| format!("shutting down write side to {host}:{port}"))?;
152
153    let mut buf = Vec::with_capacity(MAX_RESPONSE_BYTES);
154    let mut chunk = [0u8; 1024];
155    loop {
156        match stream.read(&mut chunk) {
157            Ok(0) => break,
158            Ok(n) => {
159                if buf.len() + n > MAX_RESPONSE_BYTES {
160                    bail!("bridge response exceeded {MAX_RESPONSE_BYTES} bytes");
161                }
162                buf.extend_from_slice(&chunk[..n]);
163                if std::str::from_utf8(&buf)
164                    .ok()
165                    .and_then(|text| serde_json::from_str::<serde_json::Value>(text).ok())
166                    .is_some()
167                {
168                    break;
169                }
170            },
171            Err(e)
172                if e.kind() == std::io::ErrorKind::WouldBlock
173                    || e.kind() == std::io::ErrorKind::TimedOut =>
174            {
175                if !buf.is_empty() {
176                    break;
177                }
178                return Err(e)
179                    .with_context(|| format!("reading bridge response from {host}:{port}"));
180            },
181            Err(e) => {
182                return Err(e)
183                    .with_context(|| format!("reading bridge response from {host}:{port}"));
184            },
185        }
186    }
187
188    let text = std::str::from_utf8(&buf).with_context(|| "bridge returned non-UTF-8 response")?;
189    tracing::info!(response = %text, "action sent to Android bridge");
190    Ok(())
191}
192
193fn action_signature(
194    auth_token: &str,
195    issued_at_ms: i64,
196    expires_at_ms: i64,
197    action_type: &str,
198    target: &str,
199    urgency: &str,
200) -> String {
201    let canonical = format!(
202        "dipecs.android.action.v1\nissued_at_ms:{issued_at_ms}\nexpires_at_ms:{expires_at_ms}\naction_type:{}:{action_type}\ntarget:{}:{target}\nurgency:{}:{urgency}",
203        action_type.len(),
204        target.len(),
205        urgency.len(),
206    );
207    hmac_sha256_hex(auth_token.as_bytes(), canonical.as_bytes())
208}
209
210fn hmac_sha256_hex(key: &[u8], message: &[u8]) -> String {
211    const BLOCK_SIZE: usize = 64;
212    let mut key_block = [0u8; BLOCK_SIZE];
213    if key.len() > BLOCK_SIZE {
214        let digest = Sha256::digest(key);
215        key_block[..digest.len()].copy_from_slice(&digest);
216    } else {
217        key_block[..key.len()].copy_from_slice(key);
218    }
219
220    let mut outer_key_pad = [0x5cu8; BLOCK_SIZE];
221    let mut inner_key_pad = [0x36u8; BLOCK_SIZE];
222    for index in 0..BLOCK_SIZE {
223        outer_key_pad[index] ^= key_block[index];
224        inner_key_pad[index] ^= key_block[index];
225    }
226
227    let mut inner = Sha256::new();
228    inner.update(inner_key_pad);
229    inner.update(message);
230    let inner_digest = inner.finalize();
231
232    let mut outer = Sha256::new();
233    outer.update(outer_key_pad);
234    outer.update(inner_digest);
235    hex_encode(&outer.finalize())
236}
237
238fn hex_encode(bytes: &[u8]) -> String {
239    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
240}
241
242#[cfg(test)]
243mod tests;