AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
// (Shared with relay/, which uses the parts the app doesn't.)
|
|
|
|
|
#![allow(dead_code)]
|
|
|
|
|
// A very small HTTP/1.1 server (one thread per connection), shared by the phone page on this
|
|
|
|
|
// computer and by the relay (the thin backend). No keep-alive: every answer closes the connection.
|
|
|
|
|
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
use std::io::{Read, Write};
|
|
|
|
|
use std::net::{TcpListener, TcpStream};
|
|
|
|
|
use std::sync::Arc;
|
|
|
|
|
use std::time::Duration;
|
|
|
|
|
|
2026-11-11 08:19:06 +00:00
|
|
|
/// Answer a WebSocket upgrade: "101 Switching Protocols" (or 400/403). True when the
|
|
|
|
|
/// connection is now a WebSocket. Browser connections carry an `Origin` header, which must
|
|
|
|
|
/// match `Host` so another site (or a sandboxed page with `Origin: null`) cannot open a socket.
|
Remove what nothing uses and keep one copy of what was written several times
Unused (found by taking away the dead-code allowances; nothing else used them, tests aside):
computer::specs, quiet_button, the never-made Poke::Spin, ten icons and their SVGs, the
theme's chrome/bubble_agent colours, ImportRow.line, voice's multipart/transcribe/speak
wrappers, and the old keychain writers vault::save/remove/index_add with their live test
(the vault store replaced them; reading old keychain entries for the import stays).
One copy each: percent-encoding (httpd::url_encode, was four), tool arguments (tools::args_of,
was three), the WebSocket handshake (httpd::accept_websocket, was three), the read pacing
(wire::Pace, was two: relay and app), docker with input and a time limit (dk_with_input, was
two). Docs: FEATURES §看畫面 (VNC), protocol (v* frames, /screen, tickets), architecture.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:21:47 +00:00
|
|
|
pub fn accept_websocket(req: &Req, c: &mut TcpStream) -> bool {
|
2026-11-11 08:19:06 +00:00
|
|
|
let origin = req.header("origin");
|
|
|
|
|
if !origin.is_empty() {
|
|
|
|
|
let o_host = origin.strip_prefix("https://").or_else(|| origin.strip_prefix("http://")).unwrap_or("");
|
|
|
|
|
let host = req.header("host");
|
|
|
|
|
if o_host.is_empty() || host.is_empty() || !o_host.eq_ignore_ascii_case(host) {
|
|
|
|
|
write_response(c, &Resp::error(403, "forbidden origin"));
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
Remove what nothing uses and keep one copy of what was written several times
Unused (found by taking away the dead-code allowances; nothing else used them, tests aside):
computer::specs, quiet_button, the never-made Poke::Spin, ten icons and their SVGs, the
theme's chrome/bubble_agent colours, ImportRow.line, voice's multipart/transcribe/speak
wrappers, and the old keychain writers vault::save/remove/index_add with their live test
(the vault store replaced them; reading old keychain entries for the import stays).
One copy each: percent-encoding (httpd::url_encode, was four), tool arguments (tools::args_of,
was three), the WebSocket handshake (httpd::accept_websocket, was three), the read pacing
(wire::Pace, was two: relay and app), docker with input and a time limit (dk_with_input, was
two). Docs: FEATURES §看畫面 (VNC), protocol (v* frames, /screen, tickets), architecture.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:21:47 +00:00
|
|
|
let key = req.header("sec-websocket-key");
|
|
|
|
|
if key.is_empty() {
|
|
|
|
|
write_response(c, &Resp::error(400, "bad request"));
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
let accept = tungstenite::handshake::derive_accept_key(key.as_bytes());
|
|
|
|
|
let ok = c.write_all(format!("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {accept}\r\n\r\n").as_bytes()).is_ok();
|
|
|
|
|
let _ = c.set_nodelay(true);
|
|
|
|
|
ok
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Percent-encode a query value or form field (RFC 3986: letters, digits and -_.~ stay).
|
|
|
|
|
pub fn url_encode(s: &str) -> String {
|
|
|
|
|
s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect()
|
|
|
|
|
}
|
|
|
|
|
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
/// Largest request body accepted (a phone photo fits).
|
|
|
|
|
pub const MAX_BODY: usize = 30 * 1024 * 1024;
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug, Default)]
|
|
|
|
|
pub struct Req {
|
|
|
|
|
pub method: String,
|
|
|
|
|
pub path: String,
|
|
|
|
|
pub query: HashMap<String, String>,
|
|
|
|
|
/// Header names in lower case.
|
|
|
|
|
pub headers: HashMap<String, String>,
|
|
|
|
|
pub body: Vec<u8>,
|
|
|
|
|
pub peer: String,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Req {
|
|
|
|
|
pub fn header(&self, name: &str) -> &str {
|
|
|
|
|
self.headers.get(&name.to_ascii_lowercase()).map(|s| s.as_str()).unwrap_or("")
|
|
|
|
|
}
|
|
|
|
|
pub fn bearer(&self) -> String {
|
|
|
|
|
let a = self.header("authorization");
|
|
|
|
|
if let Some(t) = a.strip_prefix("Bearer ") {
|
|
|
|
|
return t.trim().to_string();
|
|
|
|
|
}
|
|
|
|
|
// EventSource / <img> can't send headers: a token in the query works too.
|
|
|
|
|
self.query.get("t").cloned().unwrap_or_default()
|
|
|
|
|
}
|
|
|
|
|
pub fn json(&self) -> serde_json::Value {
|
|
|
|
|
serde_json::from_slice(&self.body).unwrap_or(serde_json::Value::Null)
|
|
|
|
|
}
|
|
|
|
|
/// Path segments, e.g. "/api/bots/3/send" → ["api", "bots", "3", "send"].
|
|
|
|
|
pub fn parts(&self) -> Vec<&str> {
|
|
|
|
|
self.path.split('/').filter(|s| !s.is_empty()).collect()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
pub struct Resp {
|
|
|
|
|
pub status: u16,
|
|
|
|
|
pub ctype: String,
|
|
|
|
|
pub body: Vec<u8>,
|
|
|
|
|
pub headers: Vec<(String, String)>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Resp {
|
|
|
|
|
pub fn json(v: &serde_json::Value) -> Resp {
|
|
|
|
|
Resp { status: 200, ctype: "application/json; charset=utf-8".into(), body: v.to_string().into_bytes(), headers: vec![] }
|
|
|
|
|
}
|
|
|
|
|
pub fn bytes(ctype: &str, body: Vec<u8>) -> Resp {
|
|
|
|
|
Resp { status: 200, ctype: ctype.into(), body, headers: vec![] }
|
|
|
|
|
}
|
|
|
|
|
pub fn error(status: u16, msg: &str) -> Resp {
|
|
|
|
|
Resp { status, ..Resp::json(&serde_json::json!({ "error": msg })) }
|
|
|
|
|
}
|
|
|
|
|
pub fn empty(status: u16) -> Resp {
|
|
|
|
|
Resp { status, ctype: "text/plain".into(), body: vec![], headers: vec![] }
|
|
|
|
|
}
|
|
|
|
|
pub fn with_header(mut self, k: &str, v: &str) -> Resp {
|
|
|
|
|
self.headers.push((k.into(), v.into()));
|
|
|
|
|
self
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn reason(status: u16) -> &'static str {
|
|
|
|
|
match status {
|
|
|
|
|
200 => "OK",
|
|
|
|
|
204 => "No Content",
|
|
|
|
|
400 => "Bad Request",
|
|
|
|
|
401 => "Unauthorized",
|
|
|
|
|
403 => "Forbidden",
|
|
|
|
|
404 => "Not Found",
|
|
|
|
|
409 => "Conflict",
|
|
|
|
|
413 => "Payload Too Large",
|
|
|
|
|
429 => "Too Many Requests",
|
|
|
|
|
502 => "Bad Gateway",
|
|
|
|
|
503 => "Service Unavailable",
|
|
|
|
|
504 => "Gateway Timeout",
|
|
|
|
|
_ => "OK",
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn decode(s: &str) -> String {
|
2026-11-05 07:48:20 +00:00
|
|
|
// Work on bytes only: slicing the &str at byte offsets can land inside a multi-byte
|
|
|
|
|
// character and panic (an unauthenticated request like "/%)…" used to kill its thread).
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
let b = s.as_bytes();
|
|
|
|
|
let mut out = Vec::with_capacity(b.len());
|
2026-11-05 07:48:20 +00:00
|
|
|
let hex = |c: u8| -> Option<u8> {
|
|
|
|
|
match c {
|
|
|
|
|
b'0'..=b'9' => Some(c - b'0'),
|
|
|
|
|
b'a'..=b'f' => Some(c - b'a' + 10),
|
|
|
|
|
b'A'..=b'F' => Some(c - b'A' + 10),
|
|
|
|
|
_ => None,
|
|
|
|
|
}
|
|
|
|
|
};
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
let mut i = 0;
|
|
|
|
|
while i < b.len() {
|
|
|
|
|
match b[i] {
|
2026-11-05 07:48:20 +00:00
|
|
|
b'+' => {
|
|
|
|
|
out.push(b' ');
|
|
|
|
|
i += 1;
|
|
|
|
|
}
|
|
|
|
|
b'%' if i + 2 < b.len() && hex(b[i + 1]).is_some() && hex(b[i + 2]).is_some() => {
|
|
|
|
|
out.push(hex(b[i + 1]).unwrap() * 16 + hex(b[i + 2]).unwrap());
|
|
|
|
|
i += 3;
|
|
|
|
|
}
|
|
|
|
|
c => {
|
|
|
|
|
out.push(c);
|
|
|
|
|
i += 1;
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
String::from_utf8_lossy(&out).to_string()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn parse_query(q: &str) -> HashMap<String, String> {
|
|
|
|
|
q.split('&').filter(|p| !p.is_empty()).map(|p| {
|
|
|
|
|
let (k, v) = p.split_once('=').unwrap_or((p, ""));
|
|
|
|
|
(decode(k), decode(v))
|
|
|
|
|
}).collect()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Read one request (head, then exactly Content-Length bytes of body).
|
|
|
|
|
pub fn read_request(c: &mut TcpStream) -> Result<Req, u16> {
|
|
|
|
|
c.set_read_timeout(Some(Duration::from_secs(30))).ok();
|
|
|
|
|
let mut got: Vec<u8> = vec![];
|
|
|
|
|
let mut buf = [0u8; 16384];
|
|
|
|
|
let head_end = loop {
|
|
|
|
|
if let Some(p) = got.windows(4).position(|w| w == b"\r\n\r\n") {
|
|
|
|
|
break p;
|
|
|
|
|
}
|
|
|
|
|
if got.len() > 64 * 1024 {
|
|
|
|
|
return Err(400);
|
|
|
|
|
}
|
|
|
|
|
let n = c.read(&mut buf).map_err(|_| 400u16)?;
|
|
|
|
|
if n == 0 {
|
|
|
|
|
return Err(400);
|
|
|
|
|
}
|
|
|
|
|
got.extend_from_slice(&buf[..n]);
|
|
|
|
|
};
|
|
|
|
|
let head = String::from_utf8_lossy(&got[..head_end]).to_string();
|
|
|
|
|
let mut lines = head.split("\r\n");
|
|
|
|
|
let first = lines.next().unwrap_or("");
|
|
|
|
|
let mut fp = first.split_whitespace();
|
|
|
|
|
let method = fp.next().unwrap_or("").to_string();
|
|
|
|
|
let target = fp.next().unwrap_or("/").to_string();
|
|
|
|
|
let headers: HashMap<String, String> = lines.filter_map(|l| l.split_once(':')).map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_string())).collect();
|
2026-11-05 07:48:20 +00:00
|
|
|
let chunked = headers.get("transfer-encoding").map(|v| v.to_ascii_lowercase().contains("chunked")).unwrap_or(false);
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
let mut body = got[head_end + 4..].to_vec();
|
2026-11-05 07:48:20 +00:00
|
|
|
if chunked {
|
|
|
|
|
// Some phone browsers send POST bodies in chunks (no Content-Length): read chunks
|
|
|
|
|
// until the zero-size terminator, reassembling the body.
|
|
|
|
|
let mut out: Vec<u8> = vec![];
|
|
|
|
|
let mut pos = 0usize;
|
|
|
|
|
loop {
|
|
|
|
|
let size_end = loop {
|
|
|
|
|
if let Some(p) = body[pos..].windows(2).position(|w| w == b"\r\n") {
|
|
|
|
|
break pos + p;
|
|
|
|
|
}
|
|
|
|
|
if body.len() > MAX_BODY + 64 * 1024 {
|
|
|
|
|
return Err(413);
|
|
|
|
|
}
|
|
|
|
|
let n = c.read(&mut buf).map_err(|_| 400u16)?;
|
|
|
|
|
if n == 0 {
|
|
|
|
|
return Err(400);
|
|
|
|
|
}
|
|
|
|
|
body.extend_from_slice(&buf[..n]);
|
|
|
|
|
};
|
|
|
|
|
let hex = String::from_utf8_lossy(&body[pos..size_end]).split(';').next().unwrap_or("0").trim().to_string();
|
|
|
|
|
let size = usize::from_str_radix(&hex, 16).map_err(|_| 400u16)?;
|
|
|
|
|
if size == 0 {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
if out.len() + size > MAX_BODY {
|
|
|
|
|
return Err(413);
|
|
|
|
|
}
|
|
|
|
|
let end = size_end + 2 + size;
|
|
|
|
|
while body.len() < end + 2 {
|
|
|
|
|
let n = c.read(&mut buf).map_err(|_| 400u16)?;
|
|
|
|
|
if n == 0 {
|
|
|
|
|
return Err(400);
|
|
|
|
|
}
|
|
|
|
|
body.extend_from_slice(&buf[..n]);
|
|
|
|
|
}
|
|
|
|
|
out.extend_from_slice(&body[size_end + 2..end]);
|
|
|
|
|
pos = end + 2;
|
|
|
|
|
}
|
|
|
|
|
body = out;
|
|
|
|
|
} else {
|
|
|
|
|
let len: usize = headers.get("content-length").and_then(|v| v.parse().ok()).unwrap_or(0);
|
|
|
|
|
if len > MAX_BODY {
|
|
|
|
|
return Err(413);
|
|
|
|
|
}
|
|
|
|
|
while body.len() < len {
|
|
|
|
|
let n = c.read(&mut buf).map_err(|_| 400u16)?;
|
Bug sweep: gates, relay 2FA, Windows input, snapshots, encodings
Permissions and reach
- a file leaving a computer passes the same questions as reading it;
"looking" shell commands that do more than look ask first
- a symlink out of the work/sealed folder counts as outside it
(real paths, not just lexical ones); the search walk skips links
- web_fetch and skill_install read the public web only: localhost, the
LAN and cloud metadata are refused, at every redirect
- preview shows a file without running it; browser_upload may ask
- vault: logins no longer match across shared suffixes (pages.dev,
com.tw, ...); registrable_domain knows public suffixes
- axwrite: found elements are retained (use-after-free)
Relay
- replacing or turning off 2FA needs the current code (rate-limited);
new recovery codes only count once enrollment is verified
- a removed computer loses its socket and its `call` access
- a site name taken by another account answers 409
- RELAY_TRUST_PROXY: the login lock counts the caller's address, not
the proxy's (compose files and README)
- httpd: half a body is not a request
Desktop
- sign-in, join and restore work with 2FA on (code field; --serve reads
ANYBOT_ACCOUNT_CODE; the setup wizard points to a pairing code)
- Windows: text was typed twice; modifiers are held through click, drag
and scroll; horizontal scroll; screen control is no longer refused
- a recording that hits the limit is transcribed, not thrown away
- bot's computer: a new home volume restores the snapshot; a snapshot
is read through before the home is wiped; a failed volume removal
stops reset/restore
- events of a stopped turn no longer land in the next one; each channel
message gets a turn of its own
- saving a bot's settings keeps what it got meanwhile (three-way merge);
a save file that cannot be read is kept
- pages in Big5/GBK/Shift_JIS are read in their own encoding
(encoding_rs); osascript output past 64 KB no longer stalls
- pick_tab keeps a job's own non-http tab; pictures larger than the
texture limit are fitted; the auto-update time field takes typing
- skills live in <data>/skills; memories are unnumbered in the prompt;
the phone may skillify and skill_install
CI
- the test step fails when the tests fail (it piped into tail)
Tests: anybot 268 passed, 27 ignored; relay 16 passed; clippy unchanged.
Not run: Windows on a real machine (win.rs type-checked alone), the
Docker paths of the bot's computer, the live accessibility writes.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 03:46:17 +00:00
|
|
|
// The connection ended before the whole body came: not a request. (Half a body
|
|
|
|
|
// used to be handed on as the request: half an upload, saved over the whole one.)
|
2026-11-05 07:48:20 +00:00
|
|
|
if n == 0 {
|
Bug sweep: gates, relay 2FA, Windows input, snapshots, encodings
Permissions and reach
- a file leaving a computer passes the same questions as reading it;
"looking" shell commands that do more than look ask first
- a symlink out of the work/sealed folder counts as outside it
(real paths, not just lexical ones); the search walk skips links
- web_fetch and skill_install read the public web only: localhost, the
LAN and cloud metadata are refused, at every redirect
- preview shows a file without running it; browser_upload may ask
- vault: logins no longer match across shared suffixes (pages.dev,
com.tw, ...); registrable_domain knows public suffixes
- axwrite: found elements are retained (use-after-free)
Relay
- replacing or turning off 2FA needs the current code (rate-limited);
new recovery codes only count once enrollment is verified
- a removed computer loses its socket and its `call` access
- a site name taken by another account answers 409
- RELAY_TRUST_PROXY: the login lock counts the caller's address, not
the proxy's (compose files and README)
- httpd: half a body is not a request
Desktop
- sign-in, join and restore work with 2FA on (code field; --serve reads
ANYBOT_ACCOUNT_CODE; the setup wizard points to a pairing code)
- Windows: text was typed twice; modifiers are held through click, drag
and scroll; horizontal scroll; screen control is no longer refused
- a recording that hits the limit is transcribed, not thrown away
- bot's computer: a new home volume restores the snapshot; a snapshot
is read through before the home is wiped; a failed volume removal
stops reset/restore
- events of a stopped turn no longer land in the next one; each channel
message gets a turn of its own
- saving a bot's settings keeps what it got meanwhile (three-way merge);
a save file that cannot be read is kept
- pages in Big5/GBK/Shift_JIS are read in their own encoding
(encoding_rs); osascript output past 64 KB no longer stalls
- pick_tab keeps a job's own non-http tab; pictures larger than the
texture limit are fitted; the auto-update time field takes typing
- skills live in <data>/skills; memories are unnumbered in the prompt;
the phone may skillify and skill_install
CI
- the test step fails when the tests fail (it piped into tail)
Tests: anybot 268 passed, 27 ignored; relay 16 passed; clippy unchanged.
Not run: Windows on a real machine (win.rs type-checked alone), the
Docker paths of the bot's computer, the live accessibility writes.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 03:46:17 +00:00
|
|
|
return Err(400);
|
2026-11-05 07:48:20 +00:00
|
|
|
}
|
|
|
|
|
body.extend_from_slice(&buf[..n]);
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
}
|
2026-11-05 07:48:20 +00:00
|
|
|
body.truncate(len);
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
}
|
|
|
|
|
let (path, q) = target.split_once('?').unwrap_or((&target, ""));
|
|
|
|
|
Ok(Req { method, path: decode(path), query: parse_query(q), headers, body, peer: c.peer_addr().map(|a| a.ip().to_string()).unwrap_or_default() })
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn write_response(c: &mut TcpStream, r: &Resp) {
|
|
|
|
|
let mut head = format!(
|
|
|
|
|
"HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\n",
|
|
|
|
|
r.status,
|
|
|
|
|
reason(r.status),
|
|
|
|
|
r.ctype,
|
|
|
|
|
r.body.len()
|
|
|
|
|
);
|
|
|
|
|
for (k, v) in &r.headers {
|
|
|
|
|
head.push_str(&format!("{k}: {v}\r\n"));
|
|
|
|
|
}
|
|
|
|
|
head.push_str("\r\n");
|
|
|
|
|
let _ = c.write_all(head.as_bytes());
|
|
|
|
|
let _ = c.write_all(&r.body);
|
|
|
|
|
let _ = c.flush();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub type Handler = Arc<dyn Fn(Req) -> Resp + Send + Sync>;
|
2026-11-04 11:30:32 +00:00
|
|
|
/// Takes over a connection that asked to become a WebSocket (it answers the handshake itself).
|
|
|
|
|
pub type Upgrade = Arc<dyn Fn(Req, TcpStream) + Send + Sync>;
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
|
|
|
|
/// Answer every connection on this listener with `handler` (each on its own thread).
|
|
|
|
|
pub fn serve(listener: TcpListener, handler: Handler, alive: Arc<dyn Fn() -> bool + Send + Sync>) {
|
2026-11-04 11:30:32 +00:00
|
|
|
serve_upgrade(listener, handler, None, alive)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Like `serve`, and connections asking for a WebSocket go to `upgrade`.
|
|
|
|
|
pub fn serve_upgrade(listener: TcpListener, handler: Handler, upgrade: Option<Upgrade>, alive: Arc<dyn Fn() -> bool + Send + Sync>) {
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
listener.set_nonblocking(true).ok();
|
|
|
|
|
loop {
|
|
|
|
|
if !alive() {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
match listener.accept() {
|
|
|
|
|
Ok((mut c, _)) => {
|
|
|
|
|
c.set_nonblocking(false).ok();
|
|
|
|
|
let h = handler.clone();
|
2026-11-04 11:30:32 +00:00
|
|
|
let up = upgrade.clone();
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
std::thread::spawn(move || match read_request(&mut c) {
|
2026-11-04 11:30:32 +00:00
|
|
|
Ok(req) if req.header("upgrade").eq_ignore_ascii_case("websocket") && up.is_some() => {
|
|
|
|
|
if let Some(u) = up {
|
|
|
|
|
u(req, c)
|
|
|
|
|
}
|
|
|
|
|
}
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
Ok(req) => {
|
|
|
|
|
let resp = h(req);
|
|
|
|
|
write_response(&mut c, &resp);
|
|
|
|
|
}
|
|
|
|
|
Err(code) => write_response(&mut c, &Resp::error(code, "bad request")),
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
Err(_) => std::thread::sleep(Duration::from_millis(50)),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ---------- secrets ----------
|
|
|
|
|
|
|
|
|
|
pub fn random_hex(bytes: usize) -> String {
|
|
|
|
|
use ring::rand::SecureRandom;
|
|
|
|
|
let mut b = vec![0u8; bytes];
|
|
|
|
|
ring::rand::SystemRandom::new().fill(&mut b).expect("random");
|
|
|
|
|
b.iter().map(|x| format!("{x:02x}")).collect()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn sha256_hex(s: &str) -> String {
|
|
|
|
|
ring::digest::digest(&ring::digest::SHA256, s.as_bytes()).as_ref().iter().map(|x| format!("{x:02x}")).collect()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const PBKDF2_ROUNDS: u32 = 120_000;
|
|
|
|
|
|
|
|
|
|
/// A password stored as "salt$hash" (PBKDF2-HMAC-SHA256).
|
2026-11-09 09:52:42 +00:00
|
|
|
/// Password hashes: argon2id (memory-hard, OWASP parameters) in the form
|
|
|
|
|
/// `argon2id$<salt-hex>$<hash-hex>`. Old accounts keep their `salt$pbkdf2` string and are
|
|
|
|
|
/// checked with it (check_password reads the format from the stored string).
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
pub fn hash_password(pw: &str) -> String {
|
2026-11-09 09:52:42 +00:00
|
|
|
let salt = random_bytes(16);
|
|
|
|
|
let out = argon2_hash(pw, &salt);
|
|
|
|
|
format!("argon2id${}${}", hex_of(&salt), hex_of(&out))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn argon2_hash(pw: &str, salt: &[u8]) -> Vec<u8> {
|
|
|
|
|
use argon2::{Algorithm, Argon2, Params, Version};
|
|
|
|
|
// m=19 MiB, t=2, p=1 (OWASP's argon2id recommendation); 32-byte tag.
|
|
|
|
|
let params = Params::new(19_456, 2, 1, Some(32)).expect("params");
|
|
|
|
|
let a = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
|
|
|
|
|
let mut out = vec![0u8; 32];
|
|
|
|
|
a.hash_password_into(pw.as_bytes(), salt, &mut out).expect("argon2");
|
|
|
|
|
out
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn random_bytes(n: usize) -> Vec<u8> {
|
|
|
|
|
use ring::rand::SecureRandom;
|
|
|
|
|
let mut b = vec![0u8; n];
|
|
|
|
|
ring::rand::SystemRandom::new().fill(&mut b).expect("random");
|
|
|
|
|
b
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn hex_of(b: &[u8]) -> String {
|
|
|
|
|
b.iter().map(|x| format!("{x:02x}")).collect()
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn pbkdf2_hex(pw: &str, salt: &str) -> String {
|
|
|
|
|
let mut out = [0u8; 32];
|
|
|
|
|
ring::pbkdf2::derive(ring::pbkdf2::PBKDF2_HMAC_SHA256, std::num::NonZeroU32::new(PBKDF2_ROUNDS).unwrap(), salt.as_bytes(), pw.as_bytes(), &mut out);
|
|
|
|
|
out.iter().map(|x| format!("{x:02x}")).collect()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn check_password(pw: &str, stored: &str) -> bool {
|
2026-11-09 09:52:42 +00:00
|
|
|
if let Some(rest) = stored.strip_prefix("argon2id$") {
|
|
|
|
|
let Some((salt, hash)) = rest.split_once('$') else { return false };
|
|
|
|
|
let salt = hex_of(&hex_bytes(salt)); // normalise
|
|
|
|
|
let mine = hex_of(&argon2_hash(pw, &hex_bytes(&salt)));
|
|
|
|
|
return constant_time_eq(&mine, hash);
|
|
|
|
|
}
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
let Some((salt, hash)) = stored.split_once('$') else { return false };
|
|
|
|
|
let mine = pbkdf2_hex(pw, salt);
|
|
|
|
|
// Compare without stopping at the first difference.
|
2026-11-09 09:52:42 +00:00
|
|
|
constant_time_eq(&mine, hash)
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-11 08:19:06 +00:00
|
|
|
pub fn constant_time_eq(a: &str, b: &str) -> bool {
|
2026-11-09 09:52:42 +00:00
|
|
|
a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-11 08:19:06 +00:00
|
|
|
/// Restrict an existing file to its owner (`0600` on Unix).
|
|
|
|
|
pub fn tighten_permissions(path: &std::path::Path) {
|
|
|
|
|
#[cfg(unix)]
|
|
|
|
|
{
|
|
|
|
|
use std::os::unix::fs::PermissionsExt;
|
|
|
|
|
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
|
|
|
|
|
}
|
|
|
|
|
#[cfg(not(unix))]
|
|
|
|
|
let _ = path;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Atomically write a private file (`0600` from creation on Unix, synced before rename, no TOCTOU).
|
|
|
|
|
pub fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
|
|
|
|
|
if let Some(d) = path.parent() {
|
|
|
|
|
if !d.as_os_str().is_empty() {
|
|
|
|
|
let _ = std::fs::create_dir_all(d);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
let mut tmp_os = path.as_os_str().to_os_string();
|
|
|
|
|
tmp_os.push(".tmp");
|
|
|
|
|
let tmp = std::path::PathBuf::from(tmp_os);
|
|
|
|
|
let mut opts = std::fs::OpenOptions::new();
|
|
|
|
|
opts.write(true).create(true).truncate(true);
|
|
|
|
|
#[cfg(unix)]
|
|
|
|
|
{
|
|
|
|
|
use std::os::unix::fs::OpenOptionsExt;
|
|
|
|
|
opts.mode(0o600);
|
|
|
|
|
}
|
|
|
|
|
let mut f = opts.open(&tmp)?;
|
|
|
|
|
tighten_permissions(&tmp);
|
|
|
|
|
f.write_all(bytes)?;
|
|
|
|
|
f.sync_all()?;
|
|
|
|
|
drop(f);
|
|
|
|
|
std::fs::rename(&tmp, path)
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-09 09:52:42 +00:00
|
|
|
fn hex_bytes(s: &str) -> Vec<u8> {
|
|
|
|
|
(0..s.len() / 2).map(|i| u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).unwrap_or(0)).collect()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ── TOTP (RFC 6238, SHA-1, 30 s, 6 digits): the codes authenticator apps show. ──
|
|
|
|
|
|
|
|
|
|
const B32: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
|
|
|
|
|
|
|
|
pub fn base32_encode(b: &[u8]) -> String {
|
|
|
|
|
let mut out = String::new();
|
|
|
|
|
let mut acc = 0u32;
|
|
|
|
|
let mut bits = 0u32;
|
|
|
|
|
for x in b {
|
|
|
|
|
acc = (acc << 8) | *x as u32;
|
|
|
|
|
bits += 8;
|
|
|
|
|
while bits >= 5 {
|
|
|
|
|
bits -= 5;
|
|
|
|
|
out.push(B32[((acc >> bits) & 31) as usize] as char);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if bits > 0 {
|
|
|
|
|
out.push(B32[((acc << (5 - bits)) & 31) as usize] as char);
|
|
|
|
|
}
|
|
|
|
|
out
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn base32_decode(s: &str) -> Vec<u8> {
|
|
|
|
|
let mut out = Vec::new();
|
|
|
|
|
let (mut acc, mut bits) = (0u32, 0u32);
|
|
|
|
|
for c in s.to_uppercase().chars() {
|
|
|
|
|
if c == '=' || c == ' ' {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
let Some(v) = B32.iter().position(|&x| x as char == c) else { continue };
|
|
|
|
|
acc = (acc << 5) | v as u32;
|
|
|
|
|
bits += 5;
|
|
|
|
|
if bits >= 8 {
|
|
|
|
|
bits -= 8;
|
|
|
|
|
out.push((acc >> bits) as u8);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
out
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// A fresh shared secret (20 random bytes, the size authenticator apps expect).
|
|
|
|
|
pub fn totp_new_secret() -> String {
|
|
|
|
|
base32_encode(&random_bytes(20))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn totp_uri(secret: &str, user: &str) -> String {
|
|
|
|
|
format!("otpauth://totp/AnyBot:{user}?secret={secret}&issuer=AnyBot&period=30&digits=6")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn totp_code(secret: &str, step: u64) -> String {
|
|
|
|
|
use ring::hmac;
|
|
|
|
|
let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, &base32_decode(secret));
|
|
|
|
|
let tag = hmac::sign(&key, &step.to_be_bytes());
|
|
|
|
|
let t = tag.as_ref();
|
|
|
|
|
let off = (t[t.len() - 1] & 0x0F) as usize;
|
|
|
|
|
let n = (u32::from(t[off] & 0x7F) << 24) | (u32::from(t[off + 1]) << 16) | (u32::from(t[off + 2]) << 8) | u32::from(t[off + 3]);
|
|
|
|
|
format!("{:06}", n % 1_000_000)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// A code is good for its 30-second step and one step each way (clocks drift).
|
|
|
|
|
pub fn totp_check(secret: &str, code: &str) -> bool {
|
|
|
|
|
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() / 30).unwrap_or(0);
|
|
|
|
|
let code: String = code.chars().filter(|c| c.is_ascii_digit()).collect();
|
|
|
|
|
if code.len() != 6 {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
(now.saturating_sub(1)..=now + 1).any(|s| constant_time_eq(&totp_code(secret, s), &code))
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// A 256-bit key from a password (for the encrypted backup kept by the relay).
|
|
|
|
|
pub fn derive_key(pw: &str, user: &str) -> [u8; 32] {
|
|
|
|
|
let mut out = [0u8; 32];
|
|
|
|
|
ring::pbkdf2::derive(ring::pbkdf2::PBKDF2_HMAC_SHA256, std::num::NonZeroU32::new(PBKDF2_ROUNDS).unwrap(), format!("anybot-backup:{user}").as_bytes(), pw.as_bytes(), &mut out);
|
|
|
|
|
out
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// AES-256-GCM; the 12-byte nonce goes first.
|
|
|
|
|
pub fn seal(key: &[u8; 32], plain: &[u8]) -> Vec<u8> {
|
|
|
|
|
use ring::aead::*;
|
|
|
|
|
use ring::rand::SecureRandom;
|
|
|
|
|
let k = LessSafeKey::new(UnboundKey::new(&AES_256_GCM, key).expect("key"));
|
|
|
|
|
let mut nonce = [0u8; 12];
|
|
|
|
|
ring::rand::SystemRandom::new().fill(&mut nonce).expect("random");
|
|
|
|
|
let mut data = plain.to_vec();
|
|
|
|
|
k.seal_in_place_append_tag(Nonce::assume_unique_for_key(nonce), Aad::empty(), &mut data).expect("seal");
|
|
|
|
|
let mut out = nonce.to_vec();
|
|
|
|
|
out.extend(data);
|
|
|
|
|
out
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn open(key: &[u8; 32], sealed: &[u8]) -> Option<Vec<u8>> {
|
|
|
|
|
use ring::aead::*;
|
|
|
|
|
if sealed.len() < 12 + 16 {
|
|
|
|
|
return None;
|
|
|
|
|
}
|
|
|
|
|
let k = LessSafeKey::new(UnboundKey::new(&AES_256_GCM, key).ok()?);
|
|
|
|
|
let nonce = Nonce::try_assume_unique_for_key(&sealed[..12]).ok()?;
|
|
|
|
|
let mut data = sealed[12..].to_vec();
|
|
|
|
|
let plain = k.open_in_place(nonce, Aad::empty(), &mut data).ok()?;
|
|
|
|
|
Some(plain.to_vec())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod tests {
|
|
|
|
|
use super::*;
|
|
|
|
|
|
2026-11-09 09:52:42 +00:00
|
|
|
#[test]
|
|
|
|
|
fn totp_matches_the_rfc_6238_vectors() {
|
|
|
|
|
// RFC 6238's SHA-1 test secret, 8-digit codes; the last six of each.
|
|
|
|
|
let s = base32_encode(b"12345678901234567890");
|
|
|
|
|
assert_eq!(s, "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
|
|
|
|
|
assert_eq!(&totp_code(&s, 59 / 30), "287082");
|
|
|
|
|
assert_eq!(&totp_code(&s, 1_111_111_109 / 30), "081804");
|
|
|
|
|
assert_eq!(&totp_code(&s, 1_111_111_111 / 30), "050471");
|
|
|
|
|
assert_eq!(&totp_code(&s, 1_234_567_890 / 30), "005924");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn password_hashes_are_argon2_and_old_ones_still_sign_in() {
|
|
|
|
|
let h = hash_password(" hunter2 ");
|
|
|
|
|
assert!(h.starts_with("argon2id$"));
|
|
|
|
|
assert!(check_password(" hunter2 ", &h));
|
|
|
|
|
assert!(!check_password("hunter2", &h));
|
|
|
|
|
// A hash made with the old PBKDF2 format keeps working (no forced password reset).
|
|
|
|
|
let old = format!("{}${}", "abcd", pbkdf2_hex("hunter2", "abcd"));
|
|
|
|
|
assert!(check_password("hunter2", &old));
|
|
|
|
|
}
|
|
|
|
|
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
#[test]
|
|
|
|
|
fn passwords_and_sealing() {
|
|
|
|
|
let h = hash_password("貓咪 123");
|
|
|
|
|
assert!(check_password("貓咪 123", &h) && !check_password("貓咪 124", &h));
|
|
|
|
|
let k = derive_key("pw", "daniel");
|
|
|
|
|
let s = seal(&k, "秘密".as_bytes());
|
|
|
|
|
assert_eq!(open(&k, &s).unwrap(), "秘密".as_bytes());
|
|
|
|
|
assert!(open(&derive_key("pw2", "daniel"), &s).is_none());
|
|
|
|
|
assert_eq!(parse_query("a=1&b=%E4%BD%A0+x")["b"], "你 x");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn serves_a_request() {
|
|
|
|
|
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
|
|
|
let port = l.local_addr().unwrap().port();
|
|
|
|
|
let h: Handler = Arc::new(|r: Req| Resp::json(&serde_json::json!({"p": r.path, "n": r.body.len(), "q": r.query.get("x")})));
|
|
|
|
|
std::thread::spawn(move || serve(l, h, Arc::new(|| true)));
|
|
|
|
|
let body = vec![7u8; 100_000];
|
|
|
|
|
let mut resp = ureq::post(&format!("http://127.0.0.1:{port}/a/b?x=1")).send(&body[..]).unwrap();
|
|
|
|
|
let v: serde_json::Value = serde_json::from_str(&resp.body_mut().read_to_string().unwrap()).unwrap();
|
|
|
|
|
assert_eq!(v["n"], 100_000);
|
|
|
|
|
assert_eq!(v["p"], "/a/b");
|
|
|
|
|
}
|
Bug sweep: gates, relay 2FA, Windows input, snapshots, encodings
Permissions and reach
- a file leaving a computer passes the same questions as reading it;
"looking" shell commands that do more than look ask first
- a symlink out of the work/sealed folder counts as outside it
(real paths, not just lexical ones); the search walk skips links
- web_fetch and skill_install read the public web only: localhost, the
LAN and cloud metadata are refused, at every redirect
- preview shows a file without running it; browser_upload may ask
- vault: logins no longer match across shared suffixes (pages.dev,
com.tw, ...); registrable_domain knows public suffixes
- axwrite: found elements are retained (use-after-free)
Relay
- replacing or turning off 2FA needs the current code (rate-limited);
new recovery codes only count once enrollment is verified
- a removed computer loses its socket and its `call` access
- a site name taken by another account answers 409
- RELAY_TRUST_PROXY: the login lock counts the caller's address, not
the proxy's (compose files and README)
- httpd: half a body is not a request
Desktop
- sign-in, join and restore work with 2FA on (code field; --serve reads
ANYBOT_ACCOUNT_CODE; the setup wizard points to a pairing code)
- Windows: text was typed twice; modifiers are held through click, drag
and scroll; horizontal scroll; screen control is no longer refused
- a recording that hits the limit is transcribed, not thrown away
- bot's computer: a new home volume restores the snapshot; a snapshot
is read through before the home is wiped; a failed volume removal
stops reset/restore
- events of a stopped turn no longer land in the next one; each channel
message gets a turn of its own
- saving a bot's settings keeps what it got meanwhile (three-way merge);
a save file that cannot be read is kept
- pages in Big5/GBK/Shift_JIS are read in their own encoding
(encoding_rs); osascript output past 64 KB no longer stalls
- pick_tab keeps a job's own non-http tab; pictures larger than the
texture limit are fitted; the auto-update time field takes typing
- skills live in <data>/skills; memories are unnumbered in the prompt;
the phone may skillify and skill_install
CI
- the test step fails when the tests fail (it piped into tail)
Tests: anybot 268 passed, 27 ignored; relay 16 passed; clippy unchanged.
Not run: Windows on a real machine (win.rs type-checked alone), the
Docker paths of the bot's computer, the live accessibility writes.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 03:46:17 +00:00
|
|
|
|
|
|
|
|
/// An upload cut off on the way is no request (it used to be answered as a whole one).
|
|
|
|
|
#[test]
|
|
|
|
|
fn half_a_body_is_not_a_request() {
|
|
|
|
|
use std::io::Write;
|
|
|
|
|
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
|
|
|
let port = l.local_addr().unwrap().port();
|
|
|
|
|
let send = move |bytes: &'static [u8]| {
|
|
|
|
|
std::thread::spawn(move || {
|
|
|
|
|
let mut c = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
|
|
|
|
c.write_all(bytes).unwrap();
|
|
|
|
|
// (Closed here, before the rest of the body.)
|
|
|
|
|
})
|
|
|
|
|
};
|
|
|
|
|
let t = send(b"POST /backup HTTP/1.1\r\nContent-Length: 10\r\n\r\nabc");
|
|
|
|
|
let (mut c, _) = l.accept().unwrap();
|
|
|
|
|
assert_eq!(read_request(&mut c).err(), Some(400));
|
|
|
|
|
t.join().unwrap();
|
|
|
|
|
let t = send(b"POST /backup HTTP/1.1\r\nContent-Length: 10\r\n\r\n0123456789");
|
|
|
|
|
let (mut c, _) = l.accept().unwrap();
|
|
|
|
|
assert_eq!(read_request(&mut c).map(|r| r.body).ok(), Some(b"0123456789".to_vec()));
|
|
|
|
|
t.join().unwrap();
|
|
|
|
|
}
|
2026-11-11 08:19:06 +00:00
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn websocket_checks_origin_and_private_writes_are_owner_only() {
|
|
|
|
|
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
|
|
|
let port = l.local_addr().unwrap().port();
|
|
|
|
|
let try_ws = |origin: &str| -> bool {
|
|
|
|
|
let mut headers = HashMap::new();
|
|
|
|
|
headers.insert("host".into(), format!("127.0.0.1:{port}"));
|
|
|
|
|
headers.insert("sec-websocket-key".into(), "dGhlIHNhbXBsZSBub25jZQ==".into());
|
|
|
|
|
if !origin.is_empty() {
|
|
|
|
|
headers.insert("origin".into(), origin.into());
|
|
|
|
|
}
|
|
|
|
|
let req = Req { headers, ..Default::default() };
|
|
|
|
|
let t = std::thread::spawn(move || TcpStream::connect(("127.0.0.1", port)).unwrap());
|
|
|
|
|
let (mut srv, _) = l.accept().unwrap();
|
|
|
|
|
let _cli = t.join().unwrap();
|
|
|
|
|
accept_websocket(&req, &mut srv)
|
|
|
|
|
};
|
|
|
|
|
assert!(!try_ws("https://evil.example"));
|
|
|
|
|
assert!(!try_ws("null"));
|
|
|
|
|
assert!(try_ws(&format!("http://127.0.0.1:{port}")));
|
|
|
|
|
assert!(try_ws(""));
|
|
|
|
|
|
|
|
|
|
let f = std::env::temp_dir().join(format!("anybot-priv-{}.secret", random_hex(6)));
|
|
|
|
|
write_private(&f, b"top-secret").unwrap();
|
|
|
|
|
assert_eq!(std::fs::read(&f).unwrap(), b"top-secret");
|
|
|
|
|
#[cfg(unix)]
|
|
|
|
|
{
|
|
|
|
|
use std::os::unix::fs::PermissionsExt;
|
|
|
|
|
assert_eq!(std::fs::metadata(&f).unwrap().permissions().mode() & 0o777, 0o600);
|
|
|
|
|
}
|
|
|
|
|
let _ = std::fs::remove_file(&f);
|
|
|
|
|
}
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
}
|