ci / checks (push) Successful in 56s
ci / test (push) Successful in 1m1s
ci / chart (push) Successful in 6s
ci / web (push) Successful in 29s
ci / docker (push) Successful in 2m37s
ci / publish-edge-image (push) Successful in 11s
ci / publish-edge-chart (push) Successful in 4s
A chat line can carry up to four images, each capped at 5 MB and sniffed from its bytes. Uploads go to a room route first, the message references the ids, and the bytes are served back to members; an upload no message claims within an hour is swept on the next send. Images only make sense when the model can look at them, and the catalog's answer is tri-state, so the gate is a stored fact, not a guess: the provider listing remembers supports_vision per kind and model, the upload and send routes refuse when the room's effective model is not a known vision model, and the composer hides the attach button on the same fact, which rides the room payload. At turn time the fact goes to the host agent, which sends the blocks on a vision model and leaves a note where each image was on the rest.
276 lines
9.1 KiB
Rust
276 lines
9.1 KiB
Rust
//! Small helpers shared by the API and the turn runner.
|
|
|
|
use std::net::{IpAddr, Ipv4Addr};
|
|
|
|
use rand::RngCore;
|
|
|
|
/// Milliseconds since the Unix epoch.
|
|
pub fn now_ms() -> i64 {
|
|
std::time::SystemTime::now()
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
.map(|d| d.as_millis() as i64)
|
|
.unwrap_or(0)
|
|
}
|
|
|
|
/// Parses an IP literal, including a bracketed IPv6 address.
|
|
pub fn literal_ip(host: &str) -> Option<IpAddr> {
|
|
let host = host.trim().trim_start_matches('[').trim_end_matches(']');
|
|
host.parse().ok()
|
|
}
|
|
|
|
/// True when a target address is local. The list is the one a server
|
|
/// must not dial on behalf of a user: loopback, private, link-local,
|
|
/// multicast, unspecified, carrier-grade NAT, and the documentation
|
|
/// ranges. IPv4-mapped IPv6 follows its IPv4 part.
|
|
pub fn forbidden_target_ip(ip: IpAddr) -> bool {
|
|
match ip {
|
|
IpAddr::V4(v4) => forbidden_v4(v4),
|
|
IpAddr::V6(v6) => {
|
|
if let Some(v4) = v6.to_ipv4_mapped() {
|
|
return forbidden_v4(v4);
|
|
}
|
|
let s = v6.segments();
|
|
v6.is_loopback()
|
|
|| v6.is_unspecified()
|
|
|| v6.is_multicast()
|
|
|| (s[0] & 0xffc0) == 0xfe80
|
|
|| (s[0] & 0xfe00) == 0xfc00
|
|
|| (s[0] & 0xffc0) == 0xfec0
|
|
|| (s[0] == 0x2001 && s[1] == 0x0db8)
|
|
}
|
|
}
|
|
}
|
|
|
|
fn forbidden_v4(v4: Ipv4Addr) -> bool {
|
|
let o = v4.octets();
|
|
v4.is_loopback()
|
|
|| v4.is_private()
|
|
|| v4.is_link_local()
|
|
|| v4.is_broadcast()
|
|
|| v4.is_unspecified()
|
|
|| v4.is_multicast()
|
|
|| v4.is_documentation()
|
|
|| (o[0] == 100 && (o[1] & 0xc0) == 64)
|
|
}
|
|
|
|
/// Resolves a target and rejects it when any address is local. A
|
|
/// hostname that does not resolve is an error too: a target the server
|
|
/// cannot reach is not a target.
|
|
pub async fn check_target_address(host: &str, port: u16) -> Result<(), String> {
|
|
if let Some(ip) = literal_ip(host) {
|
|
return if forbidden_target_ip(ip) {
|
|
Err(format!(
|
|
"{host} is a local or private address; an operator can allow those with TOGETHER_ALLOW_PRIVATE_TARGETS=1"
|
|
))
|
|
} else {
|
|
Ok(())
|
|
};
|
|
}
|
|
let addrs = tokio::time::timeout(
|
|
std::time::Duration::from_secs(5),
|
|
tokio::net::lookup_host((host, port)),
|
|
)
|
|
.await
|
|
.map_err(|_| format!("could not resolve {host} in time"))?
|
|
.map_err(|err| format!("could not resolve {host}: {err}"))?
|
|
.collect::<Vec<_>>();
|
|
if addrs.is_empty() {
|
|
return Err(format!("{host} did not resolve to an address"));
|
|
}
|
|
for addr in addrs {
|
|
if forbidden_target_ip(addr.ip()) {
|
|
return Err(format!(
|
|
"{host} resolves to the local address {}; an operator can allow private targets with TOGETHER_ALLOW_PRIVATE_TARGETS=1",
|
|
addr.ip()
|
|
));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// A URL-safe random token of `bytes` entropy, no padding.
|
|
pub fn random_token(bytes: usize) -> String {
|
|
use base64::Engine;
|
|
let mut buf = vec![0u8; bytes];
|
|
rand::thread_rng().fill_bytes(&mut buf);
|
|
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf)
|
|
}
|
|
|
|
/// A short, lowercase, unguessable id: 12 characters over a 32-symbol
|
|
/// alphabet (60 bits).
|
|
pub fn random_id(len: usize) -> String {
|
|
const ALPHABET: &[u8] = b"0123456789abcdefghjkmnpqrstvwxyz";
|
|
let mut rng = rand::thread_rng();
|
|
(0..len)
|
|
.map(|_| ALPHABET[(rng.next_u32() % ALPHABET.len() as u32) as usize] as char)
|
|
.collect()
|
|
}
|
|
|
|
/// SHA-256 in lowercase hex.
|
|
pub fn sha256_hex(input: &[u8]) -> String {
|
|
use sha2::{Digest, Sha256};
|
|
hex::encode(Sha256::digest(input))
|
|
}
|
|
|
|
/// One of the member colors assigned when a member joins.
|
|
pub fn member_color(index: usize) -> &'static str {
|
|
const COLORS: &[&str] = &[
|
|
"#3f6f5a", "#8a5a2b", "#4f5f8f", "#8f4f5a", "#6a5a8f", "#2f6f6f", "#7a6a2f", "#5a6a3f",
|
|
];
|
|
COLORS[index % COLORS.len()]
|
|
}
|
|
|
|
/// A workspace-relative path with no escape. Empty names the root.
|
|
pub fn safe_rel_path(path: &str) -> Result<String, String> {
|
|
let trimmed = path.trim();
|
|
if trimmed.starts_with('/') {
|
|
return Err("path must be relative to the workspace".into());
|
|
}
|
|
let normalized = trimmed.trim_matches('/');
|
|
if normalized.split('/').any(|part| part == "..") {
|
|
return Err("path escapes the workspace".into());
|
|
}
|
|
Ok(if normalized.is_empty() {
|
|
".".to_owned()
|
|
} else {
|
|
normalized.to_owned()
|
|
})
|
|
}
|
|
|
|
/// The stored vision fact for one model id, when a listing carried it.
|
|
/// `None` is unknown: no row, or a row the last listing left blank.
|
|
pub fn model_supports_vision(conn: &rusqlite::Connection, kind: &str, model: &str) -> Option<bool> {
|
|
conn.query_row(
|
|
"SELECT supports_vision FROM model_facts WHERE kind = ?1 AND model_id = ?2",
|
|
rusqlite::params![kind, model],
|
|
|row| row.get::<_, Option<i64>>(0),
|
|
)
|
|
.ok()
|
|
.flatten()
|
|
.map(|value| value != 0)
|
|
}
|
|
|
|
/// The room's effective model vision: the stored fact for the room's
|
|
/// provider kind and its effective model, the room override or the
|
|
/// provider default. `None` when the room has no provider or no fact.
|
|
pub fn room_model_vision(conn: &rusqlite::Connection, room: &str) -> Option<bool> {
|
|
let (kind, model): (String, String) = conn
|
|
.query_row(
|
|
"SELECT p.kind, COALESCE(NULLIF(r.model, ''), p.model)
|
|
FROM rooms r JOIN provider_configs p ON p.id = r.provider_config_id
|
|
WHERE r.id = ?1",
|
|
rusqlite::params![room],
|
|
|row| Ok((row.get(0)?, row.get(1)?)),
|
|
)
|
|
.ok()?;
|
|
model_supports_vision(conn, &kind, &model)
|
|
}
|
|
|
|
/// `@rhema` in any case, as a whole word.
|
|
pub fn mentions_agent(text: &str) -> bool {
|
|
let lower = text.to_lowercase();
|
|
let needle = "@rhema";
|
|
let mut start = 0;
|
|
while let Some(pos) = lower[start..].find(needle) {
|
|
let at = start + pos;
|
|
let after = at + needle.len();
|
|
let boundary = lower[after..]
|
|
.chars()
|
|
.next()
|
|
.map(|c| !c.is_alphanumeric() && c != '_')
|
|
.unwrap_or(true);
|
|
if boundary {
|
|
return true;
|
|
}
|
|
start = after;
|
|
}
|
|
false
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn relative_paths_stay_under_the_workspace() {
|
|
assert_eq!(safe_rel_path("").unwrap(), ".");
|
|
assert_eq!(safe_rel_path("web/dist").unwrap(), "web/dist");
|
|
assert_eq!(
|
|
safe_rel_path("/web/dist/").unwrap_err(),
|
|
"path must be relative to the workspace"
|
|
);
|
|
assert_eq!(
|
|
safe_rel_path("web/../secret").unwrap_err(),
|
|
"path escapes the workspace"
|
|
);
|
|
assert_eq!(
|
|
safe_rel_path("..").unwrap_err(),
|
|
"path escapes the workspace"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn local_target_addresses_are_forbidden() {
|
|
for text in [
|
|
"127.0.0.1",
|
|
"10.0.0.1",
|
|
"172.16.0.1",
|
|
"192.168.1.1",
|
|
"169.254.169.254",
|
|
"100.64.0.1",
|
|
"0.0.0.0",
|
|
"224.0.0.1",
|
|
"::1",
|
|
"fe80::1",
|
|
"fc00::1",
|
|
"::ffff:127.0.0.1",
|
|
] {
|
|
let ip = literal_ip(text).unwrap();
|
|
assert!(forbidden_target_ip(ip), "{text} should be forbidden");
|
|
}
|
|
for text in ["1.1.1.1", "2606:4700:4700::1111", "::ffff:1.1.1.1"] {
|
|
let ip = literal_ip(text).unwrap();
|
|
assert!(!forbidden_target_ip(ip), "{text} should be allowed");
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_literal_loopback_target_is_rejected() {
|
|
assert!(check_target_address("127.0.0.1", 22).await.is_err());
|
|
assert!(check_target_address("[::1]", 22).await.is_err());
|
|
assert!(check_target_address("1.1.1.1", 22).await.is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn vision_facts_read_back_and_stay_unknown_when_absent() {
|
|
let conn = rusqlite::Connection::open_in_memory().unwrap();
|
|
conn.execute_batch(crate::db::SCHEMA).unwrap();
|
|
assert_eq!(model_supports_vision(&conn, "openai", "gpt-5"), None);
|
|
conn.execute(
|
|
"INSERT INTO model_facts (kind, model_id, supports_vision, updated_at)
|
|
VALUES ('openai', 'gpt-5', 1, 0), ('llama-cpp', 'qwen', NULL, 0)",
|
|
[],
|
|
)
|
|
.unwrap();
|
|
assert_eq!(model_supports_vision(&conn, "openai", "gpt-5"), Some(true));
|
|
assert_eq!(model_supports_vision(&conn, "llama-cpp", "qwen"), None);
|
|
assert_eq!(model_supports_vision(&conn, "openai", "other"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn a_room_without_a_provider_has_no_vision_fact() {
|
|
let conn = rusqlite::Connection::open_in_memory().unwrap();
|
|
conn.execute_batch(crate::db::SCHEMA).unwrap();
|
|
assert_eq!(room_model_vision(&conn, "room"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn mentions_need_a_word_boundary() {
|
|
assert!(mentions_agent("@rhema fix this"));
|
|
assert!(mentions_agent("hey @Rhema, look"));
|
|
assert!(mentions_agent("ping @rhema."));
|
|
assert!(!mentions_agent("@rhema2 go"));
|
|
assert!(!mentions_agent("rhema go"));
|
|
}
|
|
}
|