forked from vhaudiquet/rhema-together
feat: add the multiplayer room server and client
A room is one conversation, one ssh sandbox, and one agent. Accounts create rooms; friends join through a single-use invite link and a display name; the agent speaks only through the message tool. The server is Axum and SQLite. It serves the built Nuxt client, streams room events over SSE, and runs one serialized turn loop per room with turn-level steering copied from rhema-code. The client has the chat, preview iframe, read-only file pane, xterm terminal, and presence. Preview URLs are signed wildcard hosts, and the proxy tunnels HTTP over ssh direct-tcpip. HostAgent::step remains deferred in the framework.
This commit is contained in:
1 parent
04dd63c4ca
commit
0035f4e031
69 files changed
+22501
-48
No files matched your search
+250
@@ -0,0 +1,250 @@
|
||||
//! Setup, login, registration, logout, and the bootstrap probe.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::HeaderMap;
|
||||
use axum_extra::extract::CookieJar;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::auth::{
|
||||
self, AuthUser, clean_display_name, hash_password, valid_handle, verify_password,
|
||||
};
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::models::User;
|
||||
use crate::state::Shared;
|
||||
use crate::util::sha256_hex;
|
||||
|
||||
/// The client's first request: who is signed in, and whether the server
|
||||
/// still needs its owner.
|
||||
pub async fn bootstrap(State(state): State<Shared>, headers: HeaderMap) -> Json<Value> {
|
||||
let needs_setup: i64 = state
|
||||
.db
|
||||
.scalar("SELECT COUNT(*) FROM accounts", rusqlite::params![])
|
||||
.unwrap_or(0);
|
||||
let user = auth::user_from_headers(&state, &headers);
|
||||
Json(json!({
|
||||
"needs_setup": needs_setup == 0,
|
||||
"user": user,
|
||||
"allow_registration": state.config.allow_registration,
|
||||
"public_url": state.config.public_url,
|
||||
"preview_origin": state.config.preview_origin,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The signed-in account.
|
||||
pub async fn me(user: AuthUser) -> Json<User> {
|
||||
Json(user.user)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SetupBody {
|
||||
pub token: String,
|
||||
pub handle: String,
|
||||
pub display_name: String,
|
||||
pub password: String,
|
||||
#[serde(default)]
|
||||
pub email: Option<String>,
|
||||
}
|
||||
|
||||
/// Creates the first account. Allowed only while the server has none.
|
||||
pub async fn setup(
|
||||
State(state): State<Shared>,
|
||||
Json(body): Json<SetupBody>,
|
||||
) -> AppResult<(CookieJar, Json<User>)> {
|
||||
let count: i64 = state
|
||||
.db
|
||||
.scalar("SELECT COUNT(*) FROM accounts", rusqlite::params![])?;
|
||||
if count > 0 {
|
||||
return Err(AppError::conflict("this server already has an owner"));
|
||||
}
|
||||
let expected: Option<String> = state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT value FROM meta WHERE key = 'setup_token'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.ok();
|
||||
match expected {
|
||||
Some(expected) if expected == body.token => {}
|
||||
Some(_) => return Err(AppError::forbidden("wrong setup token")),
|
||||
None => return Err(AppError::forbidden("setup is closed")),
|
||||
}
|
||||
let handle = body.handle.trim().to_lowercase();
|
||||
if !valid_handle(&handle) {
|
||||
return Err(AppError::bad_request(
|
||||
"handle must be 3 to 32 lowercase letters, digits, _ or -",
|
||||
));
|
||||
}
|
||||
if body.password.chars().count() < 8 {
|
||||
return Err(AppError::bad_request(
|
||||
"password must be at least 8 characters",
|
||||
));
|
||||
}
|
||||
let display_name = clean_display_name(&body.display_name)?;
|
||||
let password_hash = hash_password(&body.password)?;
|
||||
let email = body
|
||||
.email
|
||||
.map(|email| email.trim().to_lowercase())
|
||||
.filter(|email| !email.is_empty());
|
||||
let id = crate::util::random_id(16);
|
||||
{
|
||||
let conn = state.db.conn();
|
||||
conn.execute(
|
||||
"INSERT INTO accounts (id, handle, display_name, email, password_hash, kind, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, 'user', ?6)",
|
||||
rusqlite::params![id, handle, display_name, email, password_hash, crate::util::now_ms()],
|
||||
)?;
|
||||
conn.execute("DELETE FROM meta WHERE key = 'setup_token'", [])?;
|
||||
}
|
||||
let token = auth::create_session(&state, &id)?;
|
||||
let csrf = auth::new_csrf();
|
||||
let cookies = auth::session_cookies(&state.config, &token, &csrf);
|
||||
Ok((
|
||||
cookies,
|
||||
Json(User {
|
||||
id,
|
||||
handle,
|
||||
display_name,
|
||||
kind: "user".into(),
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RegisterBody {
|
||||
pub handle: String,
|
||||
pub display_name: String,
|
||||
pub password: String,
|
||||
#[serde(default)]
|
||||
pub email: Option<String>,
|
||||
}
|
||||
|
||||
/// Creates an ordinary account, when registration is open.
|
||||
pub async fn register(
|
||||
State(state): State<Shared>,
|
||||
Json(body): Json<RegisterBody>,
|
||||
) -> AppResult<(CookieJar, Json<User>)> {
|
||||
if !state.config.allow_registration {
|
||||
return Err(AppError::forbidden("registration is closed"));
|
||||
}
|
||||
let handle = body.handle.trim().to_lowercase();
|
||||
if !valid_handle(&handle) {
|
||||
return Err(AppError::bad_request(
|
||||
"handle must be 3 to 32 lowercase letters, digits, _ or -",
|
||||
));
|
||||
}
|
||||
if body.password.chars().count() < 8 {
|
||||
return Err(AppError::bad_request(
|
||||
"password must be at least 8 characters",
|
||||
));
|
||||
}
|
||||
let display_name = clean_display_name(&body.display_name)?;
|
||||
let password_hash = hash_password(&body.password)?;
|
||||
let email = body
|
||||
.email
|
||||
.map(|email| email.trim().to_lowercase())
|
||||
.filter(|email| !email.is_empty());
|
||||
let id = crate::util::random_id(16);
|
||||
let inserted = state.db.conn().execute(
|
||||
"INSERT INTO accounts (id, handle, display_name, email, password_hash, kind, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, 'user', ?6)",
|
||||
rusqlite::params![
|
||||
id,
|
||||
handle,
|
||||
display_name,
|
||||
email,
|
||||
password_hash,
|
||||
crate::util::now_ms()
|
||||
],
|
||||
);
|
||||
if let Err(rusqlite::Error::SqliteFailure(err, _)) = &inserted
|
||||
&& err.code == rusqlite::ErrorCode::ConstraintViolation
|
||||
{
|
||||
return Err(AppError::conflict("that handle is taken"));
|
||||
}
|
||||
inserted?;
|
||||
let token = auth::create_session(&state, &id)?;
|
||||
let csrf = auth::new_csrf();
|
||||
let cookies = auth::session_cookies(&state.config, &token, &csrf);
|
||||
Ok((
|
||||
cookies,
|
||||
Json(User {
|
||||
id,
|
||||
handle,
|
||||
display_name,
|
||||
kind: "user".into(),
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct LoginBody {
|
||||
pub identifier: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
/// Signs an account in by handle or email.
|
||||
pub async fn login(
|
||||
State(state): State<Shared>,
|
||||
Json(body): Json<LoginBody>,
|
||||
) -> AppResult<(CookieJar, Json<User>)> {
|
||||
let identifier = body.identifier.trim().to_lowercase();
|
||||
let row = state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT id, handle, display_name, kind, password_hash FROM accounts
|
||||
WHERE handle = ?1 OR (email IS NOT NULL AND email = ?1)
|
||||
LIMIT 1",
|
||||
rusqlite::params![identifier],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, String>(1)?,
|
||||
row.get::<_, String>(2)?,
|
||||
row.get::<_, String>(3)?,
|
||||
row.get::<_, Option<String>>(4)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.ok();
|
||||
let Some((id, handle, display_name, kind, Some(password_hash))) = row else {
|
||||
return Err(AppError::unauthorized("wrong handle or password"));
|
||||
};
|
||||
if !verify_password(&password_hash, &body.password) {
|
||||
return Err(AppError::unauthorized("wrong handle or password"));
|
||||
}
|
||||
let token = auth::create_session(&state, &id)?;
|
||||
let csrf = auth::new_csrf();
|
||||
let cookies = auth::session_cookies(&state.config, &token, &csrf);
|
||||
Ok((
|
||||
cookies,
|
||||
Json(User {
|
||||
id,
|
||||
handle,
|
||||
display_name,
|
||||
kind,
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
/// Ends the current session.
|
||||
pub async fn logout(
|
||||
State(state): State<Shared>,
|
||||
headers: HeaderMap,
|
||||
) -> AppResult<(CookieJar, Json<Value>)> {
|
||||
let jar = CookieJar::from_headers(&headers);
|
||||
if let Some(token) = jar.get(auth::SESSION_COOKIE) {
|
||||
let _ = state.db.conn().execute(
|
||||
"DELETE FROM auth_sessions WHERE token_hash = ?1",
|
||||
rusqlite::params![sha256_hex(token.value().as_bytes())],
|
||||
);
|
||||
}
|
||||
Ok((
|
||||
auth::cleared_cookies(&state.config),
|
||||
Json(json!({ "ok": true })),
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
//! Read-only file browsing, a git summary, and the web terminal.
|
||||
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::ws::WebSocketUpgrade;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::response::Response;
|
||||
use rhema_sandbox::Sandbox;
|
||||
use rhema_sandbox::exec_util::shquote;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::auth::AuthUser;
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::models::FileEntry;
|
||||
use crate::room::agent;
|
||||
use crate::state::Shared;
|
||||
|
||||
use super::rooms::member_of;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PathQuery {
|
||||
#[serde(default)]
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// The workspace and target of a room, without needing a provider.
|
||||
fn room_workspace(state: &Shared, room: &str) -> AppResult<(String, agent::TargetRow)> {
|
||||
let (workspace, target) = agent::load_room_target(state, room)?;
|
||||
Ok((workspace, target))
|
||||
}
|
||||
|
||||
/// Validates a workspace-relative path.
|
||||
fn safe_rel(path: &str) -> AppResult<String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.starts_with('/') {
|
||||
return Err(AppError::bad_request(
|
||||
"path must be relative to the workspace",
|
||||
));
|
||||
}
|
||||
let normalized = trimmed.trim_matches('/');
|
||||
if normalized.split('/').any(|part| part == "..") {
|
||||
return Err(AppError::bad_request("path escapes the workspace"));
|
||||
}
|
||||
Ok(if normalized.is_empty() {
|
||||
".".to_owned()
|
||||
} else {
|
||||
normalized.to_owned()
|
||||
})
|
||||
}
|
||||
|
||||
async fn run(
|
||||
state: &Shared,
|
||||
workspace: &str,
|
||||
target: &agent::TargetRow,
|
||||
command: String,
|
||||
timeout: Duration,
|
||||
) -> AppResult<rhema_sandbox::RunOutcome> {
|
||||
let sandbox = agent::sandbox_for(state, workspace, target)?;
|
||||
let cancelled = AtomicBool::new(false);
|
||||
let mut progress = rhema_sandbox::OutputOnly(|_| {});
|
||||
sandbox
|
||||
.run(
|
||||
rhema_sandbox::RunRequest {
|
||||
command,
|
||||
cwd: workspace.into(),
|
||||
timeout,
|
||||
env: Default::default(),
|
||||
},
|
||||
&cancelled,
|
||||
&mut progress,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| AppError::new(axum::http::StatusCode::BAD_GATEWAY, err.to_string()))
|
||||
}
|
||||
|
||||
/// One directory.
|
||||
pub async fn list(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(room): Path<String>,
|
||||
Query(query): Query<PathQuery>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
member_of(&state, &room, &user.user.id)?;
|
||||
let (workspace, target) = room_workspace(&state, &room)?;
|
||||
let rel = safe_rel(&query.path)?;
|
||||
let abs = if rel == "." {
|
||||
workspace.clone()
|
||||
} else {
|
||||
format!("{}/{rel}", workspace.trim_end_matches('/'))
|
||||
};
|
||||
let command = format!(
|
||||
"find {} -mindepth 1 -maxdepth 1 -printf '%y\\t%s\\t%f\\0' 2>/dev/null | head -c 400000",
|
||||
shquote(&abs)
|
||||
);
|
||||
let outcome = run(
|
||||
&state,
|
||||
&workspace,
|
||||
&target,
|
||||
command,
|
||||
Duration::from_secs(15),
|
||||
)
|
||||
.await?;
|
||||
let mut entries = Vec::new();
|
||||
for record in outcome.stdout.split(|byte| *byte == 0) {
|
||||
if record.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let text = String::from_utf8_lossy(record);
|
||||
let mut parts = text.splitn(3, '\t');
|
||||
let kind = parts.next().unwrap_or("f");
|
||||
let size = parts
|
||||
.next()
|
||||
.and_then(|value| value.parse::<i64>().ok())
|
||||
.unwrap_or(0);
|
||||
let name = parts.next().unwrap_or("");
|
||||
if name.is_empty() || name == ".git" {
|
||||
continue;
|
||||
}
|
||||
let child = if rel == "." {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("{rel}/{name}")
|
||||
};
|
||||
let kind = match kind {
|
||||
"d" => "dir",
|
||||
"l" => "link",
|
||||
_ => "file",
|
||||
};
|
||||
entries.push(FileEntry {
|
||||
name: name.to_owned(),
|
||||
path: child,
|
||||
kind: kind.into(),
|
||||
size,
|
||||
});
|
||||
}
|
||||
entries.sort_by(|a, b| {
|
||||
(a.kind != "dir")
|
||||
.cmp(&(b.kind != "dir"))
|
||||
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
|
||||
});
|
||||
Ok(Json(json!({ "path": rel, "entries": entries })))
|
||||
}
|
||||
|
||||
/// One file, capped at 400 KB.
|
||||
pub async fn read(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(room): Path<String>,
|
||||
Query(query): Query<PathQuery>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
member_of(&state, &room, &user.user.id)?;
|
||||
let (workspace, target) = room_workspace(&state, &room)?;
|
||||
let rel = safe_rel(&query.path)?;
|
||||
if rel == "." {
|
||||
return Err(AppError::bad_request("path names a directory"));
|
||||
}
|
||||
let abs = format!("{}/{rel}", workspace.trim_end_matches('/'));
|
||||
let size_command = format!("stat -c %s -- {} 2>/dev/null", shquote(&abs));
|
||||
let size_out = run(
|
||||
&state,
|
||||
&workspace,
|
||||
&target,
|
||||
size_command,
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await?;
|
||||
let size = String::from_utf8_lossy(&size_out.stdout)
|
||||
.trim()
|
||||
.parse::<i64>()
|
||||
.unwrap_or(0);
|
||||
if size == 0 && size_out.code != Some(0) {
|
||||
return Err(AppError::not_found("file not found"));
|
||||
}
|
||||
let read_command = format!("head -c 400000 -- {} 2>/dev/null", shquote(&abs));
|
||||
let outcome = run(
|
||||
&state,
|
||||
&workspace,
|
||||
&target,
|
||||
read_command,
|
||||
Duration::from_secs(20),
|
||||
)
|
||||
.await?;
|
||||
let binary = outcome.stdout.iter().take(8000).any(|byte| *byte == 0);
|
||||
let content = if binary {
|
||||
String::new()
|
||||
} else {
|
||||
String::from_utf8_lossy(&outcome.stdout).into_owned()
|
||||
};
|
||||
Ok(Json(json!({
|
||||
"path": rel,
|
||||
"content": content,
|
||||
"binary": binary,
|
||||
"size": size,
|
||||
"truncated": size > outcome.stdout.len() as i64,
|
||||
})))
|
||||
}
|
||||
|
||||
/// Branch, short status, and the diff stat.
|
||||
pub async fn git(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(room): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
member_of(&state, &room, &user.user.id)?;
|
||||
let (workspace, target) = room_workspace(&state, &room)?;
|
||||
let command = format!(
|
||||
"cd {} 2>/dev/null || {{ echo 'workspace not created yet'; exit 0; }}; \
|
||||
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || {{ echo 'not a git checkout'; exit 0; }}; \
|
||||
git status --short --branch 2>&1 | head -80; echo '---'; \
|
||||
git diff --stat 2>&1 | tail -40",
|
||||
shquote(&workspace)
|
||||
);
|
||||
let outcome = run(
|
||||
&state,
|
||||
&workspace,
|
||||
&target,
|
||||
command,
|
||||
Duration::from_secs(20),
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(json!({
|
||||
"text": String::from_utf8_lossy(&outcome.stdout),
|
||||
"code": outcome.code,
|
||||
})))
|
||||
}
|
||||
|
||||
/// The web terminal upgrade. The ssh connection is opened only after
|
||||
/// the socket is accepted, with the same target and key as the agent.
|
||||
pub async fn terminal(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(room): Path<String>,
|
||||
ws: WebSocketUpgrade,
|
||||
) -> AppResult<Response> {
|
||||
member_of(&state, &room, &user.user.id)?;
|
||||
let (workspace, target) = room_workspace(&state, &room)?;
|
||||
Ok(ws.on_upgrade(move |socket| crate::ssh::terminal(socket, state, workspace, target)))
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! Chat lines, the event feed, and presence.
|
||||
|
||||
use std::convert::Infallible;
|
||||
use std::pin::Pin;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade};
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::response::Response;
|
||||
use axum::response::sse::{Event as SseEvent, KeepAlive, KeepAliveStream, Sse};
|
||||
use futures::{SinkExt, Stream, StreamExt};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::auth::AuthUser;
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::models::{Envelope, Message};
|
||||
use crate::presence::Peer;
|
||||
use crate::state::Shared;
|
||||
use crate::util::{mentions_agent, now_ms, random_id};
|
||||
|
||||
use super::rooms::{Membership, member_of};
|
||||
|
||||
/// The SSE item type: never fails, errors travel as data.
|
||||
pub type EventStream = Pin<Box<dyn Stream<Item = Result<SseEvent, Infallible>> + Send>>;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SendBody {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Posts one human line and wakes the agent when it mentions `@rhema`.
|
||||
pub async fn send(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(room): Path<String>,
|
||||
Json(body): Json<SendBody>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let member = member_of(&state, &room, &user.user.id)?;
|
||||
let text = body.text.trim();
|
||||
if text.is_empty() {
|
||||
return Err(AppError::bad_request("the message is empty"));
|
||||
}
|
||||
if text.chars().count() > 16_000 {
|
||||
return Err(AppError::bad_request("the message is too long"));
|
||||
}
|
||||
let mentions = mentions_agent(text);
|
||||
let seq = state.hub.next_seq(&state.db, &room);
|
||||
let message = Message {
|
||||
seq,
|
||||
id: random_id(16),
|
||||
author_id: Some(member.id.clone()),
|
||||
author_name: member.display_name.clone(),
|
||||
author_kind: "human".into(),
|
||||
text: text.to_owned(),
|
||||
mentions,
|
||||
created_at: now_ms(),
|
||||
};
|
||||
let data = serde_json::to_value(&message)?;
|
||||
state.hub.insert(&state.db, &room, seq, "message", &data)?;
|
||||
state.hub.broadcast(
|
||||
&room,
|
||||
Envelope {
|
||||
seq,
|
||||
kind: "message".into(),
|
||||
data,
|
||||
},
|
||||
);
|
||||
state.rooms.wake(
|
||||
&state,
|
||||
&room,
|
||||
if mentions {
|
||||
crate::room::Wake::Mention
|
||||
} else {
|
||||
crate::room::Wake::Chat
|
||||
},
|
||||
);
|
||||
Ok(Json(json!({ "message": message })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Page {
|
||||
pub before: Option<u64>,
|
||||
pub limit: Option<u32>,
|
||||
}
|
||||
|
||||
/// A page of chat lines, newest page first in storage, oldest first on
|
||||
/// the wire.
|
||||
pub async fn list(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(room): Path<String>,
|
||||
Query(page): Query<Page>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
member_of(&state, &room, &user.user.id)?;
|
||||
let limit = page.limit.unwrap_or(60).clamp(1, 200) as i64;
|
||||
let before = page.before.unwrap_or(i64::MAX as u64).min(i64::MAX as u64) as i64;
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT data FROM events
|
||||
WHERE room_id = ?1 AND kind = 'message' AND seq < ?2
|
||||
ORDER BY seq DESC LIMIT ?3",
|
||||
)?;
|
||||
let rows = stmt.query_map(rusqlite::params![room, before, limit + 1], |row| {
|
||||
row.get::<_, String>(0)
|
||||
})?;
|
||||
let mut messages: Vec<Message> = rows
|
||||
.filter_map(Result::ok)
|
||||
.filter_map(|data| serde_json::from_str::<Message>(&data).ok())
|
||||
.collect();
|
||||
let has_more = messages.len() as i64 > limit;
|
||||
if has_more {
|
||||
messages.pop();
|
||||
}
|
||||
messages.reverse();
|
||||
Ok(Json(json!({ "messages": messages, "has_more": has_more })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Since {
|
||||
pub since: Option<u64>,
|
||||
}
|
||||
|
||||
/// The live event feed, with the durable backlog first.
|
||||
pub async fn events(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(room): Path<String>,
|
||||
Query(query): Query<Since>,
|
||||
) -> AppResult<Sse<KeepAliveStream<EventStream>>> {
|
||||
member_of(&state, &room, &user.user.id)?;
|
||||
let since = query.since.unwrap_or(0) as i64;
|
||||
// Subscribe before reading the backlog: an event that lands between
|
||||
// the two is then either in the backlog or on the feed, never lost.
|
||||
let mut rx = state.hub.subscribe(&state.db, &room);
|
||||
let backlog: Vec<Envelope> = {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT seq, kind, data FROM events
|
||||
WHERE room_id = ?1 AND seq > ?2 ORDER BY seq ASC LIMIT 2000",
|
||||
)?;
|
||||
let rows = stmt.query_map(rusqlite::params![room, since], |row| {
|
||||
let seq: i64 = row.get(0)?;
|
||||
let kind: String = row.get(1)?;
|
||||
let data: String = row.get(2)?;
|
||||
Ok(Envelope {
|
||||
seq: seq as u64,
|
||||
kind,
|
||||
data: serde_json::from_str(&data).unwrap_or(Value::Null),
|
||||
})
|
||||
})?;
|
||||
rows.filter_map(Result::ok).collect()
|
||||
};
|
||||
let mut last = backlog
|
||||
.last()
|
||||
.map(|envelope| envelope.seq)
|
||||
.unwrap_or(query.since.unwrap_or(0));
|
||||
let stream = async_stream::stream! {
|
||||
for envelope in backlog {
|
||||
let data = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".into());
|
||||
yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data));
|
||||
}
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(envelope) => {
|
||||
if envelope.seq <= last {
|
||||
continue;
|
||||
}
|
||||
last = envelope.seq;
|
||||
let data = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".into());
|
||||
yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data));
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
|
||||
let data = json!({ "seq": last, "kind": "lag", "data": {} }).to_string();
|
||||
yield Ok(SseEvent::default().event("lag").data(data));
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
|
||||
}
|
||||
}
|
||||
};
|
||||
let stream: EventStream = Box::pin(stream);
|
||||
Ok(Sse::new(stream).keep_alive(
|
||||
KeepAlive::new()
|
||||
.interval(Duration::from_secs(15))
|
||||
.text("keep-alive"),
|
||||
))
|
||||
}
|
||||
|
||||
/// The presence socket: who is here and what they have open.
|
||||
pub async fn presence(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(room): Path<String>,
|
||||
ws: WebSocketUpgrade,
|
||||
) -> AppResult<Response> {
|
||||
let member = member_of(&state, &room, &user.user.id)?;
|
||||
Ok(ws.on_upgrade(move |socket| presence_loop(socket, state, room, member)))
|
||||
}
|
||||
|
||||
async fn presence_loop(socket: WebSocket, state: Shared, room: String, member: Membership) {
|
||||
let (mut sink, mut source) = socket.split();
|
||||
let peer = Peer {
|
||||
member_id: member.id.clone(),
|
||||
display_name: member.display_name.clone(),
|
||||
color: member.color.clone(),
|
||||
state: Value::Null,
|
||||
};
|
||||
let (id, snapshot, mut updates) = state.presence.join(&room, peer);
|
||||
let _ = send_presence(&mut sink, &snapshot).await;
|
||||
let mut ping = tokio::time::interval(Duration::from_secs(25));
|
||||
loop {
|
||||
tokio::select! {
|
||||
message = source.next() => {
|
||||
match message {
|
||||
Some(Ok(WsMessage::Text(text))) => {
|
||||
if let Ok(value) = serde_json::from_str::<Value>(&text) {
|
||||
let state_value = value.get("state").cloned().unwrap_or(Value::Null);
|
||||
state.presence.update(&room, id, state_value);
|
||||
}
|
||||
}
|
||||
Some(Ok(WsMessage::Close(_))) | None => break,
|
||||
Some(Ok(_)) => {}
|
||||
Some(Err(_)) => break,
|
||||
}
|
||||
}
|
||||
update = updates.recv() => {
|
||||
if let Ok(peers) = update {
|
||||
let _ = send_presence(&mut sink, &peers).await;
|
||||
}
|
||||
}
|
||||
_ = ping.tick() => {
|
||||
if sink.send(WsMessage::Ping(Vec::new().into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
state.presence.leave(&room, id);
|
||||
}
|
||||
|
||||
async fn send_presence<S>(sink: &mut S, peers: &[Peer]) -> Result<(), axum::Error>
|
||||
where
|
||||
S: futures::Sink<WsMessage, Error = axum::Error> + Unpin,
|
||||
{
|
||||
let text = json!({ "type": "presence", "peers": peers }).to_string();
|
||||
sink.send(WsMessage::Text(text.into())).await
|
||||
}
|
||||
|
||||
/// Stops the running turn in a room. The logged notice stays in the log.
|
||||
pub async fn interrupt(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(room): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let member = member_of(&state, &room, &user.user.id)?;
|
||||
let stopped = state.rooms.interrupt(&room);
|
||||
if stopped {
|
||||
let text = format!("{} stopped the agent.", member.display_name);
|
||||
let seq = state.hub.next_seq(&state.db, &room);
|
||||
let message = Message {
|
||||
seq,
|
||||
id: random_id(16),
|
||||
author_id: None,
|
||||
author_name: "room".into(),
|
||||
author_kind: "system".into(),
|
||||
text,
|
||||
mentions: false,
|
||||
created_at: now_ms(),
|
||||
};
|
||||
let data = serde_json::to_value(&message)?;
|
||||
state.hub.insert(&state.db, &room, seq, "message", &data)?;
|
||||
state.hub.broadcast(
|
||||
&room,
|
||||
Envelope {
|
||||
seq,
|
||||
kind: "message".into(),
|
||||
data,
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(Json(json!({ "stopped": stopped })))
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
//! HTTP routes: the JSON API, the event feed, the presence socket, and
|
||||
//! the built client.
|
||||
|
||||
pub mod auth;
|
||||
pub mod files;
|
||||
pub mod messages;
|
||||
pub mod rooms;
|
||||
pub mod settings;
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::Body;
|
||||
use axum::extract::{Request, State};
|
||||
use axum::http::{HeaderValue, StatusCode, Uri, header};
|
||||
use axum::middleware::{self, Next};
|
||||
use axum::response::{Html, IntoResponse, Response};
|
||||
use axum::routing::{delete, get, post};
|
||||
use axum_extra::extract::CookieJar;
|
||||
|
||||
use crate::auth::require_csrf;
|
||||
use crate::state::Shared;
|
||||
|
||||
/// The whole application router.
|
||||
pub fn router(state: Shared) -> Router {
|
||||
let api = Router::new()
|
||||
.route("/bootstrap", get(auth::bootstrap))
|
||||
.route("/me", get(auth::me))
|
||||
.route("/setup", post(auth::setup))
|
||||
.route("/register", post(auth::register))
|
||||
.route("/login", post(auth::login))
|
||||
.route("/logout", post(auth::logout))
|
||||
.route(
|
||||
"/provider-configs",
|
||||
get(settings::list_providers).post(settings::create_provider),
|
||||
)
|
||||
.route("/provider-configs/{id}", delete(settings::delete_provider))
|
||||
.route(
|
||||
"/sandbox-targets",
|
||||
get(settings::list_targets).post(settings::create_target),
|
||||
)
|
||||
.route("/sandbox-targets/{id}", delete(settings::delete_target))
|
||||
.route("/sandbox-targets/{id}/test", post(settings::test_target))
|
||||
.route("/rooms", get(rooms::list).post(rooms::create))
|
||||
.route(
|
||||
"/rooms/{id}",
|
||||
get(rooms::detail)
|
||||
.patch(rooms::update)
|
||||
.delete(rooms::archive),
|
||||
)
|
||||
.route("/rooms/{id}/members/{member}", delete(rooms::remove_member))
|
||||
.route("/rooms/{id}/invites", post(rooms::create_invite))
|
||||
.route(
|
||||
"/invites/{token}",
|
||||
get(rooms::invite_preview).post(rooms::join),
|
||||
)
|
||||
.route(
|
||||
"/rooms/{id}/messages",
|
||||
get(messages::list).post(messages::send),
|
||||
)
|
||||
.route("/rooms/{id}/events", get(messages::events))
|
||||
.route("/rooms/{id}/presence", get(messages::presence))
|
||||
.route("/rooms/{id}/files", get(files::list))
|
||||
.route("/rooms/{id}/preview", get(rooms::preview))
|
||||
.route("/rooms/{id}/file", get(files::read))
|
||||
.route("/rooms/{id}/git", get(files::git))
|
||||
.route("/rooms/{id}/interrupt", post(messages::interrupt))
|
||||
.route("/rooms/{id}/terminal", get(files::terminal));
|
||||
Router::new()
|
||||
.nest("/api", api)
|
||||
.fallback(fallback)
|
||||
.layer(middleware::from_fn_with_state(state.clone(), csrf))
|
||||
.layer(middleware::from_fn_with_state(state.clone(), headers))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// Rejects a mutating API request without the matching CSRF header.
|
||||
/// Setup, login, registration, and joining with an invite happen before
|
||||
/// the client has a CSRF cookie.
|
||||
async fn csrf(State(_state): State<Shared>, request: Request, next: Next) -> Response {
|
||||
let method = request.method().clone();
|
||||
let path = request.uri().path().to_owned();
|
||||
let exempt = path == "/api/setup"
|
||||
|| path == "/api/login"
|
||||
|| path == "/api/register"
|
||||
|| (path.starts_with("/api/invites/") && method == axum::http::Method::POST);
|
||||
let mutating = matches!(
|
||||
method,
|
||||
axum::http::Method::POST
|
||||
| axum::http::Method::PATCH
|
||||
| axum::http::Method::PUT
|
||||
| axum::http::Method::DELETE
|
||||
);
|
||||
if mutating && path.starts_with("/api") && !exempt {
|
||||
let jar = CookieJar::from_headers(request.headers());
|
||||
if let Err(err) = require_csrf(request.headers(), &jar) {
|
||||
return err.into_response();
|
||||
}
|
||||
}
|
||||
next.run(request).await
|
||||
}
|
||||
|
||||
/// Security headers, including the CSP that names the preview origin.
|
||||
async fn headers(State(state): State<Shared>, request: Request, next: Next) -> Response {
|
||||
let host = request
|
||||
.headers()
|
||||
.get(header::HOST)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let is_preview = crate::preview::is_preview_host(&state.config, &host);
|
||||
let mut response = next.run(request).await;
|
||||
if is_preview {
|
||||
// The previewed app owns its own headers, including frame policy.
|
||||
return response;
|
||||
}
|
||||
let h = response.headers_mut();
|
||||
h.insert(
|
||||
header::X_CONTENT_TYPE_OPTIONS,
|
||||
HeaderValue::from_static("nosniff"),
|
||||
);
|
||||
h.insert(
|
||||
header::REFERRER_POLICY,
|
||||
HeaderValue::from_static("strict-origin-when-cross-origin"),
|
||||
);
|
||||
h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
|
||||
let frame_src = match state.config.preview_frame_source() {
|
||||
Some(source) => format!("'self' {source}"),
|
||||
None => "'self'".to_owned(),
|
||||
};
|
||||
let csp = format!(
|
||||
"default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; \
|
||||
script-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:; frame-src {frame_src}; \
|
||||
frame-ancestors 'self'; base-uri 'self'; form-action 'self'"
|
||||
);
|
||||
if let Ok(value) = HeaderValue::from_str(&csp) {
|
||||
h.insert(header::CONTENT_SECURITY_POLICY, value);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// Sends preview hosts to the proxy and everything else to the client.
|
||||
async fn fallback(State(state): State<Shared>, request: Request) -> Response {
|
||||
let host = request
|
||||
.headers()
|
||||
.get(header::HOST)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
if crate::preview::is_preview_host(&state.config, &host) {
|
||||
return crate::preview::proxy(state, request).await;
|
||||
}
|
||||
let uri = request.uri().clone();
|
||||
spa(State(state), uri).await
|
||||
}
|
||||
|
||||
/// Serves the built Nuxt app, falling back to its index for client-side
|
||||
/// routes. A missing build gets a page that says how to make one.
|
||||
async fn spa(State(state): State<Shared>, uri: Uri) -> Response {
|
||||
let requested = uri.path().trim_start_matches('/');
|
||||
if requested.contains("..") {
|
||||
return (StatusCode::NOT_FOUND, "not found").into_response();
|
||||
}
|
||||
let root = &state.config.web_dir;
|
||||
let mut file = if requested.is_empty() {
|
||||
root.join("index.html")
|
||||
} else {
|
||||
root.join(requested)
|
||||
};
|
||||
if !file.is_file() {
|
||||
file = root.join("index.html");
|
||||
}
|
||||
if !file.is_file() {
|
||||
return (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Html(
|
||||
"<!doctype html><meta charset=utf-8><title>rhema-together</title>\
|
||||
<body style=\"font:16px system-ui;max-width:38rem;margin:4rem auto;line-height:1.5\">\
|
||||
<h1>No client build</h1>\
|
||||
<p>The server is running, but the Nuxt build is missing. Run \
|
||||
<code>pnpm install && pnpm build</code> in <code>web/</code>, then reload.</p>",
|
||||
),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let bytes = match tokio::fs::read(&file).await {
|
||||
Ok(bytes) => bytes,
|
||||
Err(_) => return (StatusCode::NOT_FOUND, "not found").into_response(),
|
||||
};
|
||||
let mime = mime_guess::from_path(&file).first_or_octet_stream();
|
||||
let cache = if file.ends_with("index.html") {
|
||||
"no-cache"
|
||||
} else {
|
||||
"public, max-age=3600"
|
||||
};
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, mime.as_ref())
|
||||
.header(header::CACHE_CONTROL, cache)
|
||||
.body(Body::from(bytes))
|
||||
.unwrap_or_else(|_| (StatusCode::INTERNAL_SERVER_ERROR, "error").into_response())
|
||||
}
|
||||
@@ -0,0 +1,580 @@
|
||||
//! Rooms, members, and invite links.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::HeaderMap;
|
||||
use axum_extra::extract::CookieJar;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::auth::{self, AuthUser, clean_display_name};
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::models::{Member, Room, RoomSummary, User};
|
||||
use crate::state::Shared;
|
||||
use crate::util::{member_color, now_ms, random_id, random_token, sha256_hex};
|
||||
|
||||
/// A caller's membership in one room.
|
||||
pub struct Membership {
|
||||
pub id: String,
|
||||
pub display_name: String,
|
||||
pub role: String,
|
||||
pub color: String,
|
||||
pub owner_id: String,
|
||||
}
|
||||
|
||||
/// Looks up the caller's member row, refusing non-members.
|
||||
pub fn member_of(state: &Shared, room: &str, account: &str) -> AppResult<Membership> {
|
||||
state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT m.id, m.display_name, m.role, m.color, r.owner_id
|
||||
FROM members m JOIN rooms r ON r.id = m.room_id
|
||||
WHERE m.room_id = ?1 AND m.account_id = ?2 AND r.archived_at IS NULL",
|
||||
rusqlite::params![room, account],
|
||||
|row| {
|
||||
Ok(Membership {
|
||||
id: row.get(0)?,
|
||||
display_name: row.get(1)?,
|
||||
role: row.get(2)?,
|
||||
color: row.get(3)?,
|
||||
owner_id: row.get(4)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.map_err(|_| AppError::not_found("room not found"))
|
||||
}
|
||||
|
||||
/// The caller's membership, requiring the owner role.
|
||||
pub fn owner_of(state: &Shared, room: &str, account: &str) -> AppResult<Membership> {
|
||||
let member = member_of(state, room, account)?;
|
||||
if member.owner_id != account {
|
||||
return Err(AppError::forbidden("only the room owner can do that"));
|
||||
}
|
||||
Ok(member)
|
||||
}
|
||||
|
||||
fn room_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Room> {
|
||||
Ok(Room {
|
||||
id: row.get("id")?,
|
||||
name: row.get("name")?,
|
||||
owner_id: row.get("owner_id")?,
|
||||
provider_config_id: row.get("provider_config_id")?,
|
||||
sandbox_target_id: row.get("sandbox_target_id")?,
|
||||
workspace: row.get("workspace")?,
|
||||
repo_url: row.get("repo_url")?,
|
||||
model: row.get("model")?,
|
||||
max_turn_steps: row.get("max_turn_steps")?,
|
||||
created_at: row.get("created_at")?,
|
||||
archived_at: row.get("archived_at")?,
|
||||
})
|
||||
}
|
||||
|
||||
fn load_room(state: &Shared, id: &str) -> AppResult<Room> {
|
||||
state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT id, name, owner_id, provider_config_id, sandbox_target_id, workspace,
|
||||
repo_url, model, max_turn_steps, created_at, archived_at
|
||||
FROM rooms WHERE id = ?1",
|
||||
rusqlite::params![id],
|
||||
room_from_row,
|
||||
)
|
||||
.map_err(|_| AppError::not_found("room not found"))
|
||||
}
|
||||
|
||||
fn load_members(state: &Shared, room: &str) -> AppResult<Vec<Member>> {
|
||||
let online = state.presence.online(room);
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, account_id, display_name, role, color FROM members
|
||||
WHERE room_id = ?1 ORDER BY created_at ASC",
|
||||
)?;
|
||||
let rows = stmt.query_map(rusqlite::params![room], |row| {
|
||||
Ok(Member {
|
||||
id: row.get(0)?,
|
||||
account_id: row.get(1)?,
|
||||
display_name: row.get(2)?,
|
||||
role: row.get(3)?,
|
||||
color: row.get(4)?,
|
||||
online: false,
|
||||
})
|
||||
})?;
|
||||
let mut members = rows.collect::<Result<Vec<_>, _>>()?;
|
||||
for member in &mut members {
|
||||
member.online = online.contains(&member.id);
|
||||
}
|
||||
Ok(members)
|
||||
}
|
||||
|
||||
/// Every room the caller belongs to.
|
||||
pub async fn list(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<Value>> {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT r.id, r.name, m.role,
|
||||
(SELECT COUNT(*) FROM members x WHERE x.room_id = r.id),
|
||||
(SELECT MAX(e.created_at) FROM events e WHERE e.room_id = r.id AND e.kind = 'message'),
|
||||
(SELECT e.data FROM events e WHERE e.room_id = r.id AND e.kind = 'message'
|
||||
ORDER BY e.seq DESC LIMIT 1)
|
||||
FROM rooms r JOIN members m ON m.room_id = r.id
|
||||
WHERE m.account_id = ?1 AND r.archived_at IS NULL
|
||||
ORDER BY COALESCE((SELECT MAX(e.created_at) FROM events e WHERE e.room_id = r.id), r.created_at) DESC",
|
||||
)?;
|
||||
let rows = stmt.query_map(rusqlite::params![user.user.id], |row| {
|
||||
let last: Option<String> = row.get(5)?;
|
||||
let last_text = last
|
||||
.and_then(|data| serde_json::from_str::<crate::models::Message>(&data).ok())
|
||||
.map(|message| {
|
||||
let mut text = message.text.replace('\n', " ");
|
||||
if text.chars().count() > 90 {
|
||||
text = text.chars().take(90).collect::<String>() + "...";
|
||||
}
|
||||
text
|
||||
});
|
||||
Ok(RoomSummary {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
role: row.get(2)?,
|
||||
member_count: row.get(3)?,
|
||||
last_at: row.get(4)?,
|
||||
last_text,
|
||||
})
|
||||
})?;
|
||||
let rooms = rows.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(Json(json!({ "rooms": rooms })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateRoom {
|
||||
pub name: String,
|
||||
pub provider_config_id: String,
|
||||
pub sandbox_target_id: String,
|
||||
#[serde(default)]
|
||||
pub workspace: Option<String>,
|
||||
#[serde(default)]
|
||||
pub repo_url: Option<String>,
|
||||
#[serde(default)]
|
||||
pub model: Option<String>,
|
||||
}
|
||||
|
||||
/// Creates a room and makes the caller its owner.
|
||||
pub async fn create(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Json(body): Json<CreateRoom>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
if user.user.kind != "user" {
|
||||
return Err(AppError::forbidden(
|
||||
"create an account to start your own room",
|
||||
));
|
||||
}
|
||||
let name = body.name.trim();
|
||||
if name.is_empty() || name.chars().count() > 60 {
|
||||
return Err(AppError::bad_request(
|
||||
"room name must be 1 to 60 characters",
|
||||
));
|
||||
}
|
||||
let (provider_model, provider_owner) = state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT model, account_id FROM provider_configs WHERE id = ?1",
|
||||
rusqlite::params![body.provider_config_id],
|
||||
|row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
|
||||
)
|
||||
.map_err(|_| AppError::bad_request("provider configuration not found"))?;
|
||||
if provider_owner != user.user.id {
|
||||
return Err(AppError::forbidden(
|
||||
"that provider belongs to another account",
|
||||
));
|
||||
}
|
||||
let (workspace_root, target_owner) = state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT workspace_root, account_id FROM sandbox_targets WHERE id = ?1",
|
||||
rusqlite::params![body.sandbox_target_id],
|
||||
|row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
|
||||
)
|
||||
.map_err(|_| AppError::bad_request("sandbox target not found"))?;
|
||||
if target_owner != user.user.id {
|
||||
return Err(AppError::forbidden(
|
||||
"that sandbox belongs to another account",
|
||||
));
|
||||
}
|
||||
let id = random_id(12);
|
||||
let workspace = match body.workspace.as_deref().map(str::trim) {
|
||||
Some(path) if !path.is_empty() => {
|
||||
if !path.starts_with('/') || path.split('/').any(|part| part == "..") {
|
||||
return Err(AppError::bad_request(
|
||||
"workspace must be an absolute path without ..",
|
||||
));
|
||||
}
|
||||
path.trim_end_matches('/').to_owned()
|
||||
}
|
||||
_ => format!("{}/{}", workspace_root.trim_end_matches('/'), id),
|
||||
};
|
||||
let repo_url = body
|
||||
.repo_url
|
||||
.map(|url| url.trim().to_owned())
|
||||
.filter(|url| !url.is_empty());
|
||||
let model = body
|
||||
.model
|
||||
.map(|model| model.trim().to_owned())
|
||||
.filter(|model| !model.is_empty())
|
||||
.unwrap_or_else(|| provider_model.clone());
|
||||
let now = now_ms();
|
||||
{
|
||||
let conn = state.db.conn();
|
||||
conn.execute(
|
||||
"INSERT INTO rooms (id, name, owner_id, provider_config_id, sandbox_target_id,
|
||||
workspace, repo_url, model, max_turn_steps, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
rusqlite::params![
|
||||
id,
|
||||
name,
|
||||
user.user.id,
|
||||
body.provider_config_id,
|
||||
body.sandbox_target_id,
|
||||
workspace,
|
||||
repo_url,
|
||||
model,
|
||||
state.config.max_turn_steps,
|
||||
now
|
||||
],
|
||||
)?;
|
||||
conn.execute(
|
||||
"INSERT INTO members (id, room_id, account_id, display_name, role, color, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, 'owner', ?5, ?6)",
|
||||
rusqlite::params![
|
||||
random_id(12),
|
||||
id,
|
||||
user.user.id,
|
||||
user.user.display_name,
|
||||
member_color(0),
|
||||
now
|
||||
],
|
||||
)?;
|
||||
}
|
||||
let room = load_room(&state, &id)?;
|
||||
Ok(Json(json!({ "room": room })))
|
||||
}
|
||||
|
||||
/// One room with its people.
|
||||
pub async fn detail(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let membership = member_of(&state, &id, &user.user.id)?;
|
||||
let room = load_room(&state, &id)?;
|
||||
let members = load_members(&state, &id)?;
|
||||
Ok(Json(json!({
|
||||
"room": room,
|
||||
"members": members,
|
||||
"me": {
|
||||
"id": membership.id,
|
||||
"display_name": membership.display_name,
|
||||
"role": membership.role,
|
||||
"color": membership.color,
|
||||
}
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct UpdateRoom {
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub provider_config_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub model: Option<String>,
|
||||
#[serde(default)]
|
||||
pub max_turn_steps: Option<u32>,
|
||||
}
|
||||
|
||||
/// Owner edits: name, provider, model, step budget.
|
||||
pub async fn update(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
Json(body): Json<UpdateRoom>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
owner_of(&state, &id, &user.user.id)?;
|
||||
if let Some(name) = body.name.as_deref() {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || name.chars().count() > 60 {
|
||||
return Err(AppError::bad_request(
|
||||
"room name must be 1 to 60 characters",
|
||||
));
|
||||
}
|
||||
state.db.conn().execute(
|
||||
"UPDATE rooms SET name = ?1 WHERE id = ?2",
|
||||
rusqlite::params![name, id],
|
||||
)?;
|
||||
}
|
||||
if let Some(provider_id) = body.provider_config_id.as_deref() {
|
||||
let owner: Option<String> = state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT account_id FROM provider_configs WHERE id = ?1",
|
||||
rusqlite::params![provider_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.ok();
|
||||
if owner.as_deref() != Some(user.user.id.as_str()) {
|
||||
return Err(AppError::forbidden(
|
||||
"that provider belongs to another account",
|
||||
));
|
||||
}
|
||||
state.db.conn().execute(
|
||||
"UPDATE rooms SET provider_config_id = ?1 WHERE id = ?2",
|
||||
rusqlite::params![provider_id, id],
|
||||
)?;
|
||||
}
|
||||
if let Some(model) = body.model.as_deref() {
|
||||
let model = model.trim();
|
||||
if !model.is_empty() {
|
||||
state.db.conn().execute(
|
||||
"UPDATE rooms SET model = ?1 WHERE id = ?2",
|
||||
rusqlite::params![model, id],
|
||||
)?;
|
||||
}
|
||||
}
|
||||
if let Some(steps) = body.max_turn_steps {
|
||||
state.db.conn().execute(
|
||||
"UPDATE rooms SET max_turn_steps = ?1 WHERE id = ?2",
|
||||
rusqlite::params![steps.clamp(1, 500) as i64, id],
|
||||
)?;
|
||||
}
|
||||
Ok(Json(json!({ "room": load_room(&state, &id)? })))
|
||||
}
|
||||
|
||||
/// Archives a room. The log and the session stay on disk.
|
||||
pub async fn archive(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
owner_of(&state, &id, &user.user.id)?;
|
||||
state.db.conn().execute(
|
||||
"UPDATE rooms SET archived_at = ?1 WHERE id = ?2",
|
||||
rusqlite::params![now_ms(), id],
|
||||
)?;
|
||||
Ok(Json(json!({ "ok": true })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PreviewQuery {
|
||||
#[serde(default)]
|
||||
pub port: Option<u16>,
|
||||
}
|
||||
|
||||
/// The signed iframe URL for one port inside this room's sandbox.
|
||||
pub async fn preview(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(room): Path<String>,
|
||||
axum::extract::Query(query): axum::extract::Query<PreviewQuery>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
member_of(&state, &room, &user.user.id)?;
|
||||
let port = query.port.unwrap_or(3000);
|
||||
if port == 0 {
|
||||
return Err(AppError::bad_request("port must be between 1 and 65535"));
|
||||
}
|
||||
let url = crate::preview::url(&state.config, &state.secrets, &room, port)?;
|
||||
Ok(Json(json!({ "url": url, "port": port })))
|
||||
}
|
||||
|
||||
/// Removes a member. The owner cannot be removed.
|
||||
pub async fn remove_member(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path((room, member)): Path<(String, String)>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let me = owner_of(&state, &room, &user.user.id)?;
|
||||
if member == me.id {
|
||||
return Err(AppError::bad_request("the owner cannot be removed"));
|
||||
}
|
||||
state.db.conn().execute(
|
||||
"DELETE FROM members WHERE id = ?1 AND room_id = ?2",
|
||||
rusqlite::params![member, room],
|
||||
)?;
|
||||
Ok(Json(json!({ "ok": true })))
|
||||
}
|
||||
|
||||
/// Creates a single-use invite link.
|
||||
pub async fn create_invite(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(room): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
member_of(&state, &room, &user.user.id)?;
|
||||
let token = random_token(24);
|
||||
let now = now_ms();
|
||||
let expires = now + 7 * 86_400_000;
|
||||
state.db.conn().execute(
|
||||
"INSERT INTO invites (token_hash, room_id, role, created_by, created_at, expires_at)
|
||||
VALUES (?1, ?2, 'guest', ?3, ?4, ?5)",
|
||||
rusqlite::params![
|
||||
sha256_hex(token.as_bytes()),
|
||||
room,
|
||||
user.user.id,
|
||||
now,
|
||||
expires
|
||||
],
|
||||
)?;
|
||||
let url = format!("{}/join/{}", state.config.public_url, token);
|
||||
Ok(Json(
|
||||
json!({ "token": token, "url": url, "expires_at": expires }),
|
||||
))
|
||||
}
|
||||
|
||||
fn invite_row(
|
||||
state: &Shared,
|
||||
token: &str,
|
||||
) -> AppResult<(String, String, i64, Option<i64>, String)> {
|
||||
state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT i.room_id, i.role, i.expires_at, i.used_at, r.name
|
||||
FROM invites i JOIN rooms r ON r.id = i.room_id
|
||||
WHERE i.token_hash = ?1 AND r.archived_at IS NULL",
|
||||
rusqlite::params![sha256_hex(token.as_bytes())],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get(0)?,
|
||||
row.get(1)?,
|
||||
row.get(2)?,
|
||||
row.get(3)?,
|
||||
row.get(4)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.map_err(|_| AppError::not_found("this invite link is not valid"))
|
||||
}
|
||||
|
||||
/// The public view of an invite.
|
||||
pub async fn invite_preview(
|
||||
State(state): State<Shared>,
|
||||
Path(token): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let (room_id, role, expires_at, used_at, room_name) = invite_row(&state, &token)?;
|
||||
if used_at.is_some() {
|
||||
return Err(AppError::gone("this invite was already used"));
|
||||
}
|
||||
if expires_at < now_ms() {
|
||||
return Err(AppError::gone("this invite has expired"));
|
||||
}
|
||||
let owner: String = state.db.conn().query_row(
|
||||
"SELECT a.display_name FROM rooms r JOIN accounts a ON a.id = r.owner_id WHERE r.id = ?1",
|
||||
rusqlite::params![room_id],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(Json(json!({
|
||||
"room_id": room_id,
|
||||
"room_name": room_name,
|
||||
"owner": owner,
|
||||
"role": role,
|
||||
"expires_at": expires_at,
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct JoinBody {
|
||||
pub display_name: String,
|
||||
}
|
||||
|
||||
/// Redeems an invite: creates a guest account, or adds the signed-in
|
||||
/// account, then signs the visitor in.
|
||||
pub async fn join(
|
||||
State(state): State<Shared>,
|
||||
Path(token): Path<String>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<JoinBody>,
|
||||
) -> AppResult<(CookieJar, Json<Value>)> {
|
||||
let (room_id, role, expires_at, used_at, _) = invite_row(&state, &token)?;
|
||||
if used_at.is_some() {
|
||||
return Err(AppError::gone("this invite was already used"));
|
||||
}
|
||||
if expires_at < now_ms() {
|
||||
return Err(AppError::gone("this invite has expired"));
|
||||
}
|
||||
let display_name = clean_display_name(&body.display_name)?;
|
||||
let existing = auth::user_from_headers(&state, &headers);
|
||||
let mut new_session = false;
|
||||
let account = match existing {
|
||||
Some(user) => user,
|
||||
None => {
|
||||
let id = random_id(16);
|
||||
let handle = format!("guest-{}", random_id(8));
|
||||
state.db.conn().execute(
|
||||
"INSERT INTO accounts (id, handle, display_name, password_hash, kind, created_at)
|
||||
VALUES (?1, ?2, ?3, NULL, 'guest', ?4)",
|
||||
rusqlite::params![id, handle, display_name, now_ms()],
|
||||
)?;
|
||||
new_session = true;
|
||||
User {
|
||||
id,
|
||||
handle,
|
||||
display_name,
|
||||
kind: "guest".into(),
|
||||
}
|
||||
}
|
||||
};
|
||||
let already: Option<(String, String)> = state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT id, role FROM members WHERE room_id = ?1 AND account_id = ?2",
|
||||
rusqlite::params![room_id, account.id],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.ok();
|
||||
let member = match already {
|
||||
Some((id, role)) => (id, role),
|
||||
None => {
|
||||
let count: i64 = state.db.scalar(
|
||||
"SELECT COUNT(*) FROM members WHERE room_id = ?1",
|
||||
rusqlite::params![room_id],
|
||||
)?;
|
||||
let id = random_id(12);
|
||||
state.db.conn().execute(
|
||||
"INSERT INTO members (id, room_id, account_id, display_name, role, color, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
|
||||
rusqlite::params![
|
||||
id,
|
||||
room_id,
|
||||
account.id,
|
||||
account.display_name,
|
||||
role,
|
||||
member_color(count as usize),
|
||||
now_ms()
|
||||
],
|
||||
)?;
|
||||
(id, role)
|
||||
}
|
||||
};
|
||||
state.db.conn().execute(
|
||||
"UPDATE invites SET used_at = ?1, used_by = ?2 WHERE token_hash = ?3",
|
||||
rusqlite::params![now_ms(), account.id, sha256_hex(token.as_bytes())],
|
||||
)?;
|
||||
let cookies = if new_session {
|
||||
let raw = auth::create_session(&state, &account.id)?;
|
||||
let csrf = auth::new_csrf();
|
||||
auth::session_cookies(&state.config, &raw, &csrf)
|
||||
} else {
|
||||
CookieJar::new()
|
||||
};
|
||||
Ok((
|
||||
cookies,
|
||||
Json(json!({
|
||||
"user": account,
|
||||
"room_id": room_id,
|
||||
"member": { "id": member.0, "role": member.1 }
|
||||
})),
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
//! Provider configurations and ssh sandbox targets.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use rhema_sandbox::Sandbox;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use ssh_key::{Algorithm, LineEnding, PrivateKey};
|
||||
|
||||
use crate::auth::AuthUser;
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::models::{ProviderConfig, SandboxTarget};
|
||||
use crate::state::Shared;
|
||||
use crate::util::random_id;
|
||||
|
||||
const KINDS: &[&str] = &[
|
||||
"anthropic",
|
||||
"openai",
|
||||
"openrouter",
|
||||
"google",
|
||||
"deepseek",
|
||||
"zai",
|
||||
"mistral",
|
||||
"mistral-vibe",
|
||||
"opencode",
|
||||
"llama-cpp",
|
||||
];
|
||||
|
||||
/// The caller's provider configurations.
|
||||
pub async fn list_providers(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<Value>> {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, name, kind, model, base_url FROM provider_configs
|
||||
WHERE account_id = ?1 ORDER BY created_at ASC",
|
||||
)?;
|
||||
let rows = stmt.query_map(rusqlite::params![user.user.id], |row| {
|
||||
Ok(ProviderConfig {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
kind: row.get(2)?,
|
||||
model: row.get(3)?,
|
||||
base_url: row.get(4)?,
|
||||
})
|
||||
})?;
|
||||
let configs = rows.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(Json(json!({ "providers": configs, "kinds": KINDS })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateProvider {
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
pub model: String,
|
||||
#[serde(default)]
|
||||
pub base_url: Option<String>,
|
||||
#[serde(default)]
|
||||
pub api_key: String,
|
||||
}
|
||||
|
||||
/// Stores a provider configuration. The key is sealed before it reaches
|
||||
/// the database and never leaves the server again.
|
||||
pub async fn create_provider(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Json(body): Json<CreateProvider>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
if user.user.kind != "user" {
|
||||
return Err(AppError::forbidden("create an account to add a provider"));
|
||||
}
|
||||
let name = body.name.trim();
|
||||
if name.is_empty() || name.chars().count() > 60 {
|
||||
return Err(AppError::bad_request("name must be 1 to 60 characters"));
|
||||
}
|
||||
if !KINDS.contains(&body.kind.as_str()) {
|
||||
return Err(AppError::bad_request("unknown provider kind"));
|
||||
}
|
||||
let model = body.model.trim();
|
||||
if model.is_empty() {
|
||||
return Err(AppError::bad_request("a model id is required"));
|
||||
}
|
||||
let base_url = body
|
||||
.base_url
|
||||
.map(|url| url.trim().to_owned())
|
||||
.filter(|url| !url.is_empty());
|
||||
if body.kind == "llama-cpp" && base_url.is_none() {
|
||||
return Err(AppError::bad_request("llama.cpp needs a server url"));
|
||||
}
|
||||
if body.kind != "llama-cpp" && body.api_key.trim().is_empty() {
|
||||
return Err(AppError::bad_request("an api key is required"));
|
||||
}
|
||||
let sealed = state.secrets.seal_str(body.api_key.trim())?;
|
||||
let id = random_id(12);
|
||||
state.db.conn().execute(
|
||||
"INSERT INTO provider_configs (id, account_id, name, kind, model, base_url,
|
||||
api_key_ciphertext, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
|
||||
rusqlite::params![
|
||||
id,
|
||||
user.user.id,
|
||||
name,
|
||||
body.kind,
|
||||
model,
|
||||
base_url,
|
||||
sealed,
|
||||
crate::util::now_ms()
|
||||
],
|
||||
)?;
|
||||
Ok(Json(json!({ "id": id })))
|
||||
}
|
||||
|
||||
/// Removes a provider configuration. Rooms that used it are left with
|
||||
/// no provider until the owner picks another.
|
||||
pub async fn delete_provider(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
state.db.conn().execute(
|
||||
"DELETE FROM provider_configs WHERE id = ?1 AND account_id = ?2",
|
||||
rusqlite::params![id, user.user.id],
|
||||
)?;
|
||||
Ok(Json(json!({ "ok": true })))
|
||||
}
|
||||
|
||||
/// The caller's ssh targets.
|
||||
pub async fn list_targets(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<Value>> {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, name, host, port, user_name, workspace_root, public_key, host_fingerprint
|
||||
FROM sandbox_targets WHERE account_id = ?1 ORDER BY created_at ASC",
|
||||
)?;
|
||||
let rows = stmt.query_map(rusqlite::params![user.user.id], |row| {
|
||||
Ok(SandboxTarget {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
host: row.get(2)?,
|
||||
port: row.get(3)?,
|
||||
user_name: row.get(4)?,
|
||||
workspace_root: row.get(5)?,
|
||||
public_key: row.get(6)?,
|
||||
host_fingerprint: row.get(7)?,
|
||||
})
|
||||
})?;
|
||||
let targets = rows.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(Json(json!({ "targets": targets })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateTarget {
|
||||
pub name: String,
|
||||
pub host: String,
|
||||
#[serde(default)]
|
||||
pub port: Option<u16>,
|
||||
#[serde(default)]
|
||||
pub user_name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub workspace_root: Option<String>,
|
||||
#[serde(default)]
|
||||
pub private_key: String,
|
||||
}
|
||||
|
||||
/// Creates an ssh target, generating an ed25519 key when none is given.
|
||||
pub async fn create_target(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Json(body): Json<CreateTarget>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
if user.user.kind != "user" {
|
||||
return Err(AppError::forbidden("create an account to add a sandbox"));
|
||||
}
|
||||
let name = body.name.trim();
|
||||
if name.is_empty() || name.chars().count() > 60 {
|
||||
return Err(AppError::bad_request("name must be 1 to 60 characters"));
|
||||
}
|
||||
let host = body.host.trim();
|
||||
if host.is_empty() || host.contains(char::is_whitespace) {
|
||||
return Err(AppError::bad_request("host must be a hostname or address"));
|
||||
}
|
||||
let port = body.port.unwrap_or(22);
|
||||
let user_name = body
|
||||
.user_name
|
||||
.map(|value| value.trim().to_owned())
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or_else(|| "root".into());
|
||||
if user_name.contains(char::is_whitespace) || user_name.contains('@') {
|
||||
return Err(AppError::bad_request("invalid ssh user"));
|
||||
}
|
||||
let workspace_root = body
|
||||
.workspace_root
|
||||
.map(|value| value.trim().to_owned())
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or_else(|| "/root".into());
|
||||
if !workspace_root.starts_with('/') || workspace_root.split('/').any(|part| part == "..") {
|
||||
return Err(AppError::bad_request(
|
||||
"workspace root must be an absolute path",
|
||||
));
|
||||
}
|
||||
let (private_key, public_key) = if body.private_key.trim().is_empty() {
|
||||
generate_key()?
|
||||
} else {
|
||||
let key = PrivateKey::from_openssh(body.private_key.trim()).map_err(|err| {
|
||||
AppError::bad_request(format!("the private key does not parse: {err}"))
|
||||
})?;
|
||||
let public = key
|
||||
.public_key()
|
||||
.to_openssh()
|
||||
.map_err(|err| AppError::bad_request(format!("the key has no public half: {err}")))?;
|
||||
(body.private_key.trim().to_owned(), public)
|
||||
};
|
||||
let sealed = state.secrets.seal_str(&private_key)?;
|
||||
let id = random_id(12);
|
||||
state.db.conn().execute(
|
||||
"INSERT INTO sandbox_targets (id, account_id, name, host, port, user_name,
|
||||
workspace_root, private_key_ciphertext, public_key, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
rusqlite::params![
|
||||
id,
|
||||
user.user.id,
|
||||
name,
|
||||
host,
|
||||
port,
|
||||
user_name,
|
||||
workspace_root.trim_end_matches('/'),
|
||||
sealed,
|
||||
public_key,
|
||||
crate::util::now_ms()
|
||||
],
|
||||
)?;
|
||||
Ok(Json(json!({ "id": id, "public_key": public_key })))
|
||||
}
|
||||
|
||||
fn generate_key() -> AppResult<(String, String)> {
|
||||
let key = PrivateKey::random(&mut rand::rngs::OsRng, Algorithm::Ed25519)
|
||||
.map_err(|err| AppError::internal(format!("could not generate a key: {err}")))?;
|
||||
let private = key
|
||||
.to_openssh(LineEnding::LF)
|
||||
.map_err(|err| AppError::internal(format!("could not encode a key: {err}")))?
|
||||
.to_string();
|
||||
let public = key
|
||||
.public_key()
|
||||
.to_openssh()
|
||||
.map_err(|err| AppError::internal(format!("could not encode a key: {err}")))?;
|
||||
Ok((private, public))
|
||||
}
|
||||
|
||||
/// Deletes a target.
|
||||
pub async fn delete_target(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
state.db.conn().execute(
|
||||
"DELETE FROM sandbox_targets WHERE id = ?1 AND account_id = ?2",
|
||||
rusqlite::params![id, user.user.id],
|
||||
)?;
|
||||
Ok(Json(json!({ "ok": true })))
|
||||
}
|
||||
|
||||
/// Opens an ssh connection and runs `printf ok` at `/`. This proves the
|
||||
/// key, the host key, and the login, without touching the room's files.
|
||||
pub async fn test_target(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let row = state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT host, port, user_name, private_key_ciphertext FROM sandbox_targets
|
||||
WHERE id = ?1 AND account_id = ?2",
|
||||
rusqlite::params![id, user.user.id],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, i64>(1)?,
|
||||
row.get::<_, String>(2)?,
|
||||
row.get::<_, String>(3)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.map_err(|_| AppError::not_found("sandbox target not found"))?;
|
||||
let key = state.secrets.open_str(&row.3)?;
|
||||
let sandbox = rhema_sandbox_ssh::SshSandbox::new(format!("{}@{}:{}", row.2, row.0, row.1))
|
||||
.with_workspace("/")
|
||||
.with_private_key(key);
|
||||
let cancelled = Arc::new(AtomicBool::new(false));
|
||||
let mut progress = rhema_sandbox::OutputOnly(|_| {});
|
||||
let request = rhema_sandbox::RunRequest {
|
||||
command: "printf ok".into(),
|
||||
cwd: "/".into(),
|
||||
timeout: Duration::from_secs(20),
|
||||
env: Default::default(),
|
||||
};
|
||||
let result = sandbox.run(request, &cancelled, &mut progress).await;
|
||||
match result {
|
||||
Ok(outcome) if String::from_utf8_lossy(&outcome.stdout).trim() == "ok" => Ok(Json(json!({
|
||||
"ok": true,
|
||||
"detail": format!("connected to {}@{}:{}", row.2, row.0, row.1),
|
||||
}))),
|
||||
Ok(outcome) => Ok(Json(json!({
|
||||
"ok": false,
|
||||
"detail": format!(
|
||||
"connected, but the probe returned {}: stdout {:?}, stderr {:?}",
|
||||
outcome.code.map(|code| code.to_string()).unwrap_or_else(|| "no exit code".into()),
|
||||
String::from_utf8_lossy(&outcome.stdout),
|
||||
String::from_utf8_lossy(&outcome.stderr).trim()
|
||||
),
|
||||
}))),
|
||||
Err(err) => Ok(Json(json!({ "ok": false, "detail": err.to_string() }))),
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
//! Accounts, sessions, cookies, and the request extractor.
|
||||
|
||||
use argon2::Argon2;
|
||||
use argon2::PasswordHasher;
|
||||
use argon2::password_hash::PasswordHash;
|
||||
use argon2::password_hash::PasswordVerifier;
|
||||
use argon2::password_hash::SaltString;
|
||||
use argon2::password_hash::rand_core::OsRng as SaltRng;
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::http::request::Parts;
|
||||
use axum_extra::extract::CookieJar;
|
||||
use axum_extra::extract::cookie::{Cookie, SameSite};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::models::User;
|
||||
use crate::state::Shared;
|
||||
use crate::util::{now_ms, random_token, sha256_hex};
|
||||
|
||||
/// The login cookie.
|
||||
pub const SESSION_COOKIE: &str = "together_session";
|
||||
/// The double-submit CSRF cookie, readable by the client.
|
||||
pub const CSRF_COOKIE: &str = "together_csrf";
|
||||
/// How long a login lasts.
|
||||
pub const SESSION_DAYS: i64 = 30;
|
||||
|
||||
/// The signed-in account taken from the request cookie.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AuthUser {
|
||||
pub user: User,
|
||||
}
|
||||
|
||||
impl FromRequestParts<Shared> for AuthUser {
|
||||
type Rejection = AppError;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut Parts,
|
||||
state: &Shared,
|
||||
) -> Result<Self, Self::Rejection> {
|
||||
let jar = CookieJar::from_headers(&parts.headers);
|
||||
let token = jar
|
||||
.get(SESSION_COOKIE)
|
||||
.map(|cookie| cookie.value().to_owned())
|
||||
.ok_or_else(|| AppError::unauthorized("sign in first"))?;
|
||||
let token_hash = sha256_hex(token.as_bytes());
|
||||
let user = user_from_token(state, &token_hash)
|
||||
.ok_or_else(|| AppError::unauthorized("session expired"))?;
|
||||
Ok(Self { user })
|
||||
}
|
||||
}
|
||||
|
||||
/// Looks up a live session by its token hash and refreshes its
|
||||
/// `last_seen`.
|
||||
pub fn user_from_token(state: &Shared, token_hash: &str) -> Option<User> {
|
||||
let now = now_ms();
|
||||
let row = state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT a.id, a.handle, a.display_name, a.kind, s.expires_at
|
||||
FROM auth_sessions s JOIN accounts a ON a.id = s.account_id
|
||||
WHERE s.token_hash = ?1",
|
||||
rusqlite::params![token_hash],
|
||||
|row| {
|
||||
Ok((
|
||||
User {
|
||||
id: row.get(0)?,
|
||||
handle: row.get(1)?,
|
||||
display_name: row.get(2)?,
|
||||
kind: row.get(3)?,
|
||||
},
|
||||
row.get::<_, i64>(4)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.ok()?;
|
||||
if row.1 < now {
|
||||
let _ = state.db.conn().execute(
|
||||
"DELETE FROM auth_sessions WHERE token_hash = ?1",
|
||||
rusqlite::params![token_hash],
|
||||
);
|
||||
return None;
|
||||
}
|
||||
let _ = state.db.conn().execute(
|
||||
"UPDATE auth_sessions SET last_seen = ?1 WHERE token_hash = ?2",
|
||||
rusqlite::params![now, token_hash],
|
||||
);
|
||||
Some(row.0)
|
||||
}
|
||||
|
||||
/// The user behind the request cookies, if any.
|
||||
pub fn user_from_headers(state: &Shared, headers: &HeaderMap) -> Option<User> {
|
||||
let jar = CookieJar::from_headers(headers);
|
||||
let token = jar.get(SESSION_COOKIE)?.value().to_owned();
|
||||
user_from_token(state, &sha256_hex(token.as_bytes()))
|
||||
}
|
||||
|
||||
/// Hashes a password with argon2id and a fresh salt.
|
||||
pub fn hash_password(password: &str) -> AppResult<String> {
|
||||
let salt = SaltString::generate(&mut SaltRng);
|
||||
Argon2::default()
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map(|hash| hash.to_string())
|
||||
.map_err(|_| AppError::internal("could not hash the password"))
|
||||
}
|
||||
|
||||
/// Verifies a password against a stored argon2 hash.
|
||||
pub fn verify_password(stored: &str, password: &str) -> bool {
|
||||
let Ok(hash) = PasswordHash::new(stored) else {
|
||||
return false;
|
||||
};
|
||||
Argon2::default()
|
||||
.verify_password(password.as_bytes(), &hash)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Creates a login session row and returns the raw token.
|
||||
pub fn create_session(state: &Shared, account_id: &str) -> AppResult<String> {
|
||||
let token = random_token(32);
|
||||
let now = now_ms();
|
||||
state.db.conn().execute(
|
||||
"INSERT INTO auth_sessions (token_hash, account_id, created_at, expires_at, last_seen)
|
||||
VALUES (?1, ?2, ?3, ?4, ?3)",
|
||||
rusqlite::params![
|
||||
sha256_hex(token.as_bytes()),
|
||||
account_id,
|
||||
now,
|
||||
now + SESSION_DAYS * 86_400_000
|
||||
],
|
||||
)?;
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// A fresh CSRF token, not stored: the cookie and the header carry the
|
||||
/// same value, which is enough for a same-origin client.
|
||||
pub fn new_csrf() -> String {
|
||||
random_token(24)
|
||||
}
|
||||
|
||||
/// The cookies a successful login sets.
|
||||
pub fn session_cookies(config: &Config, token: &str, csrf: &str) -> CookieJar {
|
||||
let mut session = Cookie::new(SESSION_COOKIE, token.to_owned());
|
||||
session.set_http_only(true);
|
||||
session.set_same_site(SameSite::Lax);
|
||||
session.set_path("/");
|
||||
session.set_secure(config.secure_cookies());
|
||||
session.set_max_age(time::Duration::days(SESSION_DAYS));
|
||||
let mut csrf_cookie = Cookie::new(CSRF_COOKIE, csrf.to_owned());
|
||||
csrf_cookie.set_http_only(false);
|
||||
csrf_cookie.set_same_site(SameSite::Lax);
|
||||
csrf_cookie.set_path("/");
|
||||
csrf_cookie.set_secure(config.secure_cookies());
|
||||
csrf_cookie.set_max_age(time::Duration::days(SESSION_DAYS));
|
||||
CookieJar::new().add(session).add(csrf_cookie)
|
||||
}
|
||||
|
||||
/// The cookies a logout clears.
|
||||
pub fn cleared_cookies(config: &Config) -> CookieJar {
|
||||
let mut session = Cookie::new(SESSION_COOKIE, String::new());
|
||||
session.set_path("/");
|
||||
session.set_max_age(time::Duration::seconds(0));
|
||||
session.set_secure(config.secure_cookies());
|
||||
let mut csrf = Cookie::new(CSRF_COOKIE, String::new());
|
||||
csrf.set_path("/");
|
||||
csrf.set_max_age(time::Duration::seconds(0));
|
||||
csrf.set_secure(config.secure_cookies());
|
||||
CookieJar::new().add(session).add(csrf)
|
||||
}
|
||||
|
||||
/// Requires the `X-CSRF-Token` header to match the CSRF cookie.
|
||||
pub fn require_csrf(headers: &HeaderMap, jar: &CookieJar) -> AppResult<()> {
|
||||
let cookie = jar
|
||||
.get(CSRF_COOKIE)
|
||||
.map(|cookie| cookie.value().to_owned())
|
||||
.ok_or_else(|| AppError::forbidden("missing CSRF cookie"))?;
|
||||
let header = headers
|
||||
.get("x-csrf-token")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.ok_or_else(|| AppError::forbidden("missing CSRF header"))?;
|
||||
if cookie != header {
|
||||
return Err(AppError::forbidden("CSRF token mismatch"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validates a handle: 3 to 32 lowercase letters, digits, `_` or `-`.
|
||||
pub fn valid_handle(handle: &str) -> bool {
|
||||
let len = handle.len();
|
||||
(3..=32).contains(&len)
|
||||
&& handle
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-')
|
||||
}
|
||||
|
||||
/// Normalizes a display name: trimmed, 1 to 48 characters.
|
||||
pub fn clean_display_name(name: &str) -> AppResult<String> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || name.chars().count() > 48 {
|
||||
return Err(AppError::bad_request(
|
||||
"display name must be 1 to 48 characters",
|
||||
));
|
||||
}
|
||||
Ok(name.to_owned())
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
//! Process configuration: one YAML file, environment overrides.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The server's settings. Every field has a default that works from the
|
||||
/// repository root, so `cargo run` starts without a config file.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Config {
|
||||
/// Address the HTTP server binds.
|
||||
pub listen: String,
|
||||
/// The URL browsers use. Cookies and invite links are built from it.
|
||||
pub public_url: String,
|
||||
/// The origin previews are served from. Empty disables the preview
|
||||
/// proxy.
|
||||
#[serde(default)]
|
||||
pub preview_origin: String,
|
||||
/// SQLite file.
|
||||
pub database: PathBuf,
|
||||
/// The 32-byte symmetric key protecting stored provider keys and ssh
|
||||
/// keys, base64 or raw. Created on first start when missing.
|
||||
pub secret_key_file: PathBuf,
|
||||
/// The built Nuxt client.
|
||||
pub web_dir: PathBuf,
|
||||
/// Cap on agent steps in one turn.
|
||||
#[serde(default = "default_steps")]
|
||||
pub max_turn_steps: u32,
|
||||
/// Extra origins allowed to frame the app. Empty is none.
|
||||
#[serde(default)]
|
||||
pub allowed_frame_ancestors: Vec<String>,
|
||||
/// Whether anyone may create an account. Off leaves setup and
|
||||
/// invites as the only doors.
|
||||
#[serde(default = "default_true")]
|
||||
pub allow_registration: bool,
|
||||
}
|
||||
|
||||
fn default_steps() -> u32 {
|
||||
48
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
listen: "127.0.0.1:7800".into(),
|
||||
public_url: "http://localhost:7800".into(),
|
||||
preview_origin: "http://preview.localhost:7800".into(),
|
||||
database: PathBuf::from("data/together.db"),
|
||||
secret_key_file: PathBuf::from("data/secret.key"),
|
||||
web_dir: PathBuf::from("web/.output/public"),
|
||||
max_turn_steps: default_steps(),
|
||||
allowed_frame_ancestors: Vec::new(),
|
||||
allow_registration: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Reads `path` when it exists, then applies the `TOGETHER_*`
|
||||
/// environment variables. A missing file is the defaults.
|
||||
pub fn load(path: &std::path::Path) -> anyhow::Result<Self> {
|
||||
let mut config = if path.exists() {
|
||||
let text = std::fs::read_to_string(path)?;
|
||||
serde_yaml::from_str(&text)?
|
||||
} else {
|
||||
Self::default()
|
||||
};
|
||||
if let Ok(value) = std::env::var("TOGETHER_LISTEN") {
|
||||
config.listen = value;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_PUBLIC_URL") {
|
||||
config.public_url = value;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_PREVIEW_ORIGIN") {
|
||||
config.preview_origin = value;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_DATABASE") {
|
||||
config.database = value.into();
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_SECRET_KEY_FILE") {
|
||||
config.secret_key_file = value.into();
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_WEB_DIR") {
|
||||
config.web_dir = value.into();
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_MAX_TURN_STEPS") {
|
||||
config.max_turn_steps = value.parse()?;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_ALLOW_REGISTRATION") {
|
||||
config.allow_registration = matches!(value.as_str(), "1" | "true" | "yes");
|
||||
}
|
||||
config.public_url = config.public_url.trim_end_matches('/').to_owned();
|
||||
config.preview_origin = config.preview_origin.trim_end_matches('/').to_owned();
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Whether cookies should carry `Secure`.
|
||||
pub fn secure_cookies(&self) -> bool {
|
||||
self.public_url.starts_with("https://")
|
||||
}
|
||||
|
||||
/// `scheme://*.<preview host>`, for the CSP that lets the app frame
|
||||
/// any room's preview. `None` when previews are off.
|
||||
pub fn preview_frame_source(&self) -> Option<String> {
|
||||
let (scheme, rest) = self.preview_origin.split_once("://")?;
|
||||
let host = rest.split('/').next()?;
|
||||
let (name, port) = match host.rsplit_once(':') {
|
||||
Some((name, port)) if port.chars().all(|c| c.is_ascii_digit()) => {
|
||||
(name, format!(":{port}"))
|
||||
}
|
||||
_ => (host, String::new()),
|
||||
};
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{scheme}://*.{name}{port}"))
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
//! Symmetric protection for the credentials the server stores: provider
|
||||
//! API keys and ssh private keys. The key comes from a 0600 file.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use base64::Engine;
|
||||
use chacha20poly1305::aead::{Aead, KeyInit};
|
||||
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
/// The server's secret box.
|
||||
#[derive(Clone)]
|
||||
pub struct Secrets {
|
||||
cipher: ChaCha20Poly1305,
|
||||
sign_key: [u8; 32],
|
||||
}
|
||||
|
||||
impl Secrets {
|
||||
/// Loads the key at `path`, creating a 32-byte key with mode 0600
|
||||
/// when the file does not exist. A key file that is neither 32 raw
|
||||
/// bytes nor base64 for 32 bytes is refused.
|
||||
pub fn load_or_create(path: &Path) -> anyhow::Result<Self> {
|
||||
let key = if path.exists() {
|
||||
let raw = std::fs::read(path)?;
|
||||
decode_key(&raw)?
|
||||
} else {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
use rand::RngCore;
|
||||
let mut key = [0u8; 32];
|
||||
rand::rngs::OsRng.fill_bytes(&mut key);
|
||||
std::fs::write(path, key)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
|
||||
}
|
||||
key
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut derive = Sha256::new();
|
||||
derive.update(key);
|
||||
derive.update(b"rhema-together preview signatures");
|
||||
let sign_key: [u8; 32] = derive.finalize().into();
|
||||
Ok(Self {
|
||||
cipher: ChaCha20Poly1305::new(Key::from_slice(&key)),
|
||||
sign_key,
|
||||
})
|
||||
}
|
||||
|
||||
/// A short, stable signature over `message`. Used to sign preview
|
||||
/// hosts so a preview URL cannot be guessed from a room id alone.
|
||||
pub fn sign(&self, message: &str) -> String {
|
||||
use hmac::{Hmac, Mac};
|
||||
let mut mac = <Hmac<sha2::Sha256> as Mac>::new_from_slice(&self.sign_key)
|
||||
.expect("hmac accepts any key length");
|
||||
mac.update(message.as_bytes());
|
||||
hex::encode(mac.finalize().into_bytes())[..24].to_owned()
|
||||
}
|
||||
|
||||
/// Encrypts `plaintext` into `base64(nonce || ciphertext)`.
|
||||
pub fn seal(&self, plaintext: &[u8]) -> Result<String, AppError> {
|
||||
use rand::RngCore;
|
||||
let mut nonce = [0u8; 12];
|
||||
rand::rngs::OsRng.fill_bytes(&mut nonce);
|
||||
let ciphertext = self
|
||||
.cipher
|
||||
.encrypt(Nonce::from_slice(&nonce), plaintext)
|
||||
.map_err(|_| AppError::internal("could not encrypt a secret"))?;
|
||||
let mut out = nonce.to_vec();
|
||||
out.extend_from_slice(&ciphertext);
|
||||
Ok(base64::engine::general_purpose::STANDARD.encode(out))
|
||||
}
|
||||
|
||||
/// The inverse of [`Secrets::seal`].
|
||||
pub fn open(&self, sealed: &str) -> Result<Vec<u8>, AppError> {
|
||||
let raw = base64::engine::general_purpose::STANDARD
|
||||
.decode(sealed)
|
||||
.map_err(|_| AppError::internal("stored secret is not valid base64"))?;
|
||||
if raw.len() < 13 {
|
||||
return Err(AppError::internal("stored secret is truncated"));
|
||||
}
|
||||
let (nonce, ciphertext) = raw.split_at(12);
|
||||
self.cipher
|
||||
.decrypt(Nonce::from_slice(nonce), ciphertext)
|
||||
.map_err(|_| AppError::internal("stored secret could not be decrypted"))
|
||||
}
|
||||
|
||||
/// Seals a string.
|
||||
pub fn seal_str(&self, plaintext: &str) -> Result<String, AppError> {
|
||||
self.seal(plaintext.as_bytes())
|
||||
}
|
||||
|
||||
/// Opens a sealed string as UTF-8.
|
||||
pub fn open_str(&self, sealed: &str) -> Result<String, AppError> {
|
||||
String::from_utf8(self.open(sealed)?)
|
||||
.map_err(|_| AppError::internal("stored secret is not UTF-8"))
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_key(raw: &[u8]) -> anyhow::Result<[u8; 32]> {
|
||||
if raw.len() == 32 {
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(raw);
|
||||
return Ok(key);
|
||||
}
|
||||
let text = String::from_utf8_lossy(raw);
|
||||
let decoded = base64::engine::general_purpose::STANDARD
|
||||
.decode(text.trim())
|
||||
.map_err(|_| anyhow::anyhow!("secret key file is neither 32 bytes nor base64"))?;
|
||||
if decoded.len() != 32 {
|
||||
anyhow::bail!("secret key must be 32 bytes, found {}", decoded.len());
|
||||
}
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(&decoded);
|
||||
Ok(key)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! The SQLite store: one file, WAL, foreign keys on.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
use rusqlite::Connection;
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
/// A cloneable handle to the one connection. Every query is short; the
|
||||
/// mutex keeps the single connection honest.
|
||||
#[derive(Clone)]
|
||||
pub struct Db {
|
||||
conn: Arc<Mutex<Connection>>,
|
||||
}
|
||||
|
||||
impl Db {
|
||||
/// Opens the database, creating the schema on first use.
|
||||
pub fn open(path: &Path) -> anyhow::Result<Self> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let conn = Connection::open(path)?;
|
||||
conn.pragma_update(None, "journal_mode", "WAL")?;
|
||||
conn.pragma_update(None, "synchronous", "FULL")?;
|
||||
conn.pragma_update(None, "foreign_keys", "ON")?;
|
||||
conn.busy_timeout(std::time::Duration::from_secs(5))?;
|
||||
conn.execute_batch(SCHEMA)?;
|
||||
Ok(Self {
|
||||
conn: Arc::new(Mutex::new(conn)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The connection, locked.
|
||||
pub fn conn(&self) -> MutexGuard<'_, Connection> {
|
||||
self.conn.lock().unwrap_or_else(|err| err.into_inner())
|
||||
}
|
||||
|
||||
/// One scalar value.
|
||||
pub fn scalar<T: rusqlite::types::FromSql>(
|
||||
&self,
|
||||
sql: &str,
|
||||
params: impl rusqlite::Params,
|
||||
) -> Result<T, AppError> {
|
||||
let value = self.conn().query_row(sql, params, |row| row.get(0))?;
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
const SCHEMA: &str = r#"
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id TEXT PRIMARY KEY,
|
||||
handle TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
email TEXT,
|
||||
password_hash TEXT,
|
||||
kind TEXT NOT NULL DEFAULT 'user',
|
||||
created_at INTEGER NOT NULL
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
last_seen INTEGER NOT NULL
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS provider_configs (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
base_url TEXT,
|
||||
api_key_ciphertext TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sandbox_targets (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
host TEXT NOT NULL,
|
||||
port INTEGER NOT NULL DEFAULT 22,
|
||||
user_name TEXT NOT NULL,
|
||||
workspace_root TEXT NOT NULL,
|
||||
private_key_ciphertext TEXT NOT NULL,
|
||||
public_key TEXT NOT NULL,
|
||||
host_fingerprint TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS rooms (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
owner_id TEXT NOT NULL REFERENCES accounts(id),
|
||||
provider_config_id TEXT REFERENCES provider_configs(id) ON DELETE SET NULL,
|
||||
sandbox_target_id TEXT REFERENCES sandbox_targets(id) ON DELETE SET NULL,
|
||||
workspace TEXT NOT NULL,
|
||||
repo_url TEXT,
|
||||
model TEXT,
|
||||
max_turn_steps INTEGER NOT NULL DEFAULT 48,
|
||||
session_json TEXT,
|
||||
absorbed_seq INTEGER NOT NULL DEFAULT 0,
|
||||
seeded INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
archived_at INTEGER
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS members (
|
||||
id TEXT PRIMARY KEY,
|
||||
room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
display_name TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
color TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE(room_id, account_id)
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS invites (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
|
||||
role TEXT NOT NULL DEFAULT 'guest',
|
||||
created_by TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
used_at INTEGER,
|
||||
used_by TEXT
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
|
||||
seq INTEGER NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (room_id, seq)
|
||||
) STRICT;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS members_room ON members(room_id);
|
||||
CREATE INDEX IF NOT EXISTS events_room_seq ON events(room_id, seq);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_account ON auth_sessions(account_id);
|
||||
"#;
|
||||
@@ -0,0 +1,88 @@
|
||||
//! The one error shape the HTTP layer returns.
|
||||
|
||||
use axum::Json;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use serde_json::json;
|
||||
|
||||
/// An API failure: a status and a message safe to show a user.
|
||||
#[derive(Debug)]
|
||||
pub struct AppError {
|
||||
pub status: StatusCode,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl AppError {
|
||||
pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bad_request(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::BAD_REQUEST, message)
|
||||
}
|
||||
|
||||
pub fn unauthorized(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::UNAUTHORIZED, message)
|
||||
}
|
||||
|
||||
pub fn forbidden(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::FORBIDDEN, message)
|
||||
}
|
||||
|
||||
pub fn not_found(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::NOT_FOUND, message)
|
||||
}
|
||||
|
||||
pub fn conflict(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::CONFLICT, message)
|
||||
}
|
||||
|
||||
pub fn gone(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::GONE, message)
|
||||
}
|
||||
|
||||
pub fn internal(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::INTERNAL_SERVER_ERROR, message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for AppError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AppError {}
|
||||
|
||||
impl From<rusqlite::Error> for AppError {
|
||||
fn from(err: rusqlite::Error) -> Self {
|
||||
tracing::error!(error = %err, "database");
|
||||
Self::internal("database error")
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::Error> for AppError {
|
||||
fn from(err: serde_json::Error) -> Self {
|
||||
tracing::error!(error = %err, "json");
|
||||
Self::internal("serialization error")
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for AppError {
|
||||
fn from(err: std::io::Error) -> Self {
|
||||
tracing::error!(error = %err, "io");
|
||||
Self::internal("io error")
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
(self.status, Json(json!({ "error": self.message }))).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// The handler result alias.
|
||||
pub type AppResult<T> = Result<T, AppError>;
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
mod api;
|
||||
mod auth;
|
||||
mod config;
|
||||
mod crypto;
|
||||
mod db;
|
||||
mod error;
|
||||
mod models;
|
||||
mod presence;
|
||||
mod preview;
|
||||
mod room;
|
||||
mod ssh;
|
||||
mod state;
|
||||
mod util;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tower_http::trace::TraceLayer;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::crypto::Secrets;
|
||||
use crate::db::Db;
|
||||
use crate::state::{AppState, Hub};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| "rhema_together=info,tower_http=warn".into()),
|
||||
)
|
||||
.init();
|
||||
let config_path = std::env::args()
|
||||
.nth(1)
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| std::path::PathBuf::from("together.yaml"));
|
||||
let config = Config::load(&config_path)?;
|
||||
let db = Db::open(&config.database)?;
|
||||
let secrets = Secrets::load_or_create(&config.secret_key_file)?;
|
||||
print_setup_token(&db, &config);
|
||||
let state = Arc::new(AppState {
|
||||
config: config.clone(),
|
||||
db,
|
||||
secrets,
|
||||
hub: Hub::default(),
|
||||
rooms: Default::default(),
|
||||
previews: Default::default(),
|
||||
presence: Default::default(),
|
||||
});
|
||||
let app = api::router(state).layer(TraceLayer::new_for_http());
|
||||
let listener = tokio::net::TcpListener::bind(&config.listen).await?;
|
||||
tracing::info!(listen = %config.listen, "rhema-together");
|
||||
axum::serve(listener, app).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// On a server with no accounts, keeps a first-run token and prints it.
|
||||
/// The token survives restarts, so the banner stays valid.
|
||||
fn print_setup_token(db: &Db, config: &Config) {
|
||||
let accounts: i64 = db
|
||||
.scalar("SELECT COUNT(*) FROM accounts", rusqlite::params![])
|
||||
.unwrap_or(0);
|
||||
if accounts > 0 {
|
||||
return;
|
||||
}
|
||||
let existing: Option<String> = db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT value FROM meta WHERE key = 'setup_token'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.ok();
|
||||
let token = match existing {
|
||||
Some(token) => token,
|
||||
None => {
|
||||
let token = crate::util::random_token(18);
|
||||
let _ = db.conn().execute(
|
||||
"INSERT OR REPLACE INTO meta (key, value) VALUES ('setup_token', ?1)",
|
||||
rusqlite::params![token],
|
||||
);
|
||||
token
|
||||
}
|
||||
};
|
||||
eprintln!();
|
||||
eprintln!(
|
||||
" First run. Open {}/setup and enter this token:",
|
||||
config.public_url
|
||||
);
|
||||
eprintln!();
|
||||
eprintln!(" {token}");
|
||||
eprintln!();
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
//! Rows and wire types shared by the API and the room.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// One chat line. The sequence number orders it in the room log.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Message {
|
||||
pub seq: u64,
|
||||
pub id: String,
|
||||
/// The member id for a human, `None` for the agent and system lines.
|
||||
pub author_id: Option<String>,
|
||||
pub author_name: String,
|
||||
/// `human`, `agent`, or `system`.
|
||||
pub author_kind: String,
|
||||
pub text: String,
|
||||
pub mentions: bool,
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
/// A room as the sidebar needs it.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct RoomSummary {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub role: String,
|
||||
pub member_count: i64,
|
||||
pub last_at: Option<i64>,
|
||||
pub last_text: Option<String>,
|
||||
}
|
||||
|
||||
/// A full room.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Room {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub owner_id: String,
|
||||
pub provider_config_id: Option<String>,
|
||||
pub sandbox_target_id: Option<String>,
|
||||
pub workspace: String,
|
||||
pub repo_url: Option<String>,
|
||||
pub model: Option<String>,
|
||||
pub max_turn_steps: i64,
|
||||
pub created_at: i64,
|
||||
pub archived_at: Option<i64>,
|
||||
}
|
||||
|
||||
/// A member row.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Member {
|
||||
pub id: String,
|
||||
pub account_id: String,
|
||||
pub display_name: String,
|
||||
pub role: String,
|
||||
pub color: String,
|
||||
pub online: bool,
|
||||
}
|
||||
|
||||
/// The account as the client sees it.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct User {
|
||||
pub id: String,
|
||||
pub handle: String,
|
||||
pub display_name: String,
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
/// One server-sent event. Durable events are also rows in `events`;
|
||||
/// deltas are live only.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Envelope {
|
||||
pub seq: u64,
|
||||
pub kind: String,
|
||||
pub data: serde_json::Value,
|
||||
}
|
||||
|
||||
/// A provider configuration without its key.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ProviderConfig {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
pub model: String,
|
||||
pub base_url: Option<String>,
|
||||
}
|
||||
|
||||
/// A sandbox target without its private key.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct SandboxTarget {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub host: String,
|
||||
pub port: i64,
|
||||
pub user_name: String,
|
||||
pub workspace_root: String,
|
||||
pub public_key: String,
|
||||
pub host_fingerprint: Option<String>,
|
||||
}
|
||||
|
||||
/// A directory entry in the read-only file pane.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct FileEntry {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub kind: String,
|
||||
pub size: i64,
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Who has a room open right now. Presence is ephemeral: it never enters
|
||||
//! the room log or the model's history.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
/// What one connection reports. The server relays it to the others.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Peer {
|
||||
pub member_id: String,
|
||||
pub display_name: String,
|
||||
pub color: String,
|
||||
/// Free-form client state: typing, open file, active pane.
|
||||
#[serde(default)]
|
||||
pub state: serde_json::Value,
|
||||
}
|
||||
|
||||
struct Room {
|
||||
next: u64,
|
||||
peers: HashMap<u64, Peer>,
|
||||
tx: broadcast::Sender<Vec<Peer>>,
|
||||
}
|
||||
|
||||
/// The per-room presence registry.
|
||||
#[derive(Default)]
|
||||
pub struct Presence {
|
||||
rooms: Mutex<HashMap<String, Room>>,
|
||||
}
|
||||
|
||||
impl Presence {
|
||||
/// Registers a connection and returns its id, the current peer list,
|
||||
/// and a subscription to changes.
|
||||
pub fn join(&self, room: &str, peer: Peer) -> (u64, Vec<Peer>, broadcast::Receiver<Vec<Peer>>) {
|
||||
let mut rooms = self.rooms.lock().unwrap_or_else(|err| err.into_inner());
|
||||
let entry = rooms.entry(room.to_owned()).or_insert_with(|| {
|
||||
let (tx, _) = broadcast::channel(128);
|
||||
Room {
|
||||
next: 0,
|
||||
peers: HashMap::new(),
|
||||
tx,
|
||||
}
|
||||
});
|
||||
entry.next += 1;
|
||||
let id = entry.next;
|
||||
entry.peers.insert(id, peer);
|
||||
let snapshot = entry.peers.values().cloned().collect();
|
||||
let rx = entry.tx.subscribe();
|
||||
(id, snapshot, rx)
|
||||
}
|
||||
|
||||
/// Replaces a connection's state and broadcasts the new list.
|
||||
pub fn update(&self, room: &str, id: u64, state: serde_json::Value) {
|
||||
let mut rooms = self.rooms.lock().unwrap_or_else(|err| err.into_inner());
|
||||
let Some(entry) = rooms.get_mut(room) else {
|
||||
return;
|
||||
};
|
||||
if let Some(peer) = entry.peers.get_mut(&id) {
|
||||
peer.state = state;
|
||||
}
|
||||
let snapshot: Vec<Peer> = entry.peers.values().cloned().collect();
|
||||
let _ = entry.tx.send(snapshot);
|
||||
}
|
||||
|
||||
/// Removes a connection and broadcasts the new list.
|
||||
pub fn leave(&self, room: &str, id: u64) {
|
||||
let mut rooms = self.rooms.lock().unwrap_or_else(|err| err.into_inner());
|
||||
let Some(entry) = rooms.get_mut(room) else {
|
||||
return;
|
||||
};
|
||||
entry.peers.remove(&id);
|
||||
let snapshot: Vec<Peer> = entry.peers.values().cloned().collect();
|
||||
let _ = entry.tx.send(snapshot);
|
||||
}
|
||||
|
||||
/// The online member ids in a room.
|
||||
pub fn online(&self, room: &str) -> Vec<String> {
|
||||
let rooms = self.rooms.lock().unwrap_or_else(|err| err.into_inner());
|
||||
rooms
|
||||
.get(room)
|
||||
.map(|entry| {
|
||||
entry
|
||||
.peers
|
||||
.values()
|
||||
.map(|peer| peer.member_id.clone())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
//! The preview proxy: a room's dev server, served under a signed
|
||||
//! subdomain of the preview origin.
|
||||
//!
|
||||
//! `r<room>-p<port>-<sig>.<preview host>` routes to 127.0.0.1:<port>
|
||||
//! inside the room's sandbox over the same ssh connection settings the
|
||||
//! agent uses. Paths and the origin stay stable, so a dev server's
|
||||
//! absolute asset URLs keep working; the host is per room and port.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{HeaderMap, HeaderName, HeaderValue, Request, StatusCode, Uri, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use hyper_util::rt::TokioIo;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::crypto::Secrets;
|
||||
use crate::error::AppResult;
|
||||
use crate::room::agent;
|
||||
use crate::state::Shared;
|
||||
|
||||
/// One ssh connection per sandbox, opened lazily by the first preview
|
||||
/// request and reused by the channels after it.
|
||||
#[derive(Default)]
|
||||
pub struct PreviewTunnels {
|
||||
handles: Mutex<HashMap<String, Arc<russh::client::Handle<crate::ssh::HostKey>>>>,
|
||||
}
|
||||
|
||||
impl PreviewTunnels {
|
||||
fn get(&self, target: &str) -> Option<Arc<russh::client::Handle<crate::ssh::HostKey>>> {
|
||||
self.handles
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.get(target)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn put(&self, target: &str, handle: Arc<russh::client::Handle<crate::ssh::HostKey>>) {
|
||||
self.handles
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.insert(target.to_owned(), handle);
|
||||
}
|
||||
|
||||
fn forget(&self, target: &str) {
|
||||
self.handles
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.remove(target);
|
||||
}
|
||||
}
|
||||
|
||||
/// The preview scheme and host for this configuration, if previews
|
||||
/// are on.
|
||||
fn domain(config: &Config) -> Option<(&str, &str)> {
|
||||
let origin = config.preview_origin.trim_end_matches('/');
|
||||
let (scheme, rest) = origin.split_once("://")?;
|
||||
let (host, _port) = match rest.rsplit_once(':') {
|
||||
Some((host, port)) if port.chars().all(|c| c.is_ascii_digit()) => (host, Some(port)),
|
||||
_ => (rest, None),
|
||||
};
|
||||
if host.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((scheme, host))
|
||||
}
|
||||
|
||||
/// Whether a Host header belongs to the preview listener.
|
||||
pub fn is_preview_host(config: &Config, host: &str) -> bool {
|
||||
let Some((_, domain)) = domain(config) else {
|
||||
return false;
|
||||
};
|
||||
let name = host.split(':').next().unwrap_or(host);
|
||||
name.ends_with(&format!(".{domain}"))
|
||||
}
|
||||
|
||||
/// The signed URL for one room and port.
|
||||
pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResult<String> {
|
||||
let Some((scheme, domain)) = domain(config) else {
|
||||
return Err(crate::error::AppError::bad_request(
|
||||
"the preview proxy is not configured",
|
||||
));
|
||||
};
|
||||
let signature = secrets.sign(&format!("{room}:{port}"));
|
||||
let port_part = config
|
||||
.preview_origin
|
||||
.split_once("://")
|
||||
.map(|(_, rest)| rest)
|
||||
.unwrap_or("")
|
||||
.rsplit_once(':')
|
||||
.filter(|(_, value)| value.chars().all(|c| c.is_ascii_digit()))
|
||||
.map(|(_, value)| format!(":{value}"))
|
||||
.unwrap_or_default();
|
||||
Ok(format!(
|
||||
"{scheme}://r{room}-p{port}-{signature}.{domain}{port_part}/"
|
||||
))
|
||||
}
|
||||
|
||||
/// Splits `r<room>-p<port>-<sig>` from the Host header.
|
||||
fn target_of_host(config: &Config, host: &str) -> Option<(String, u16, String)> {
|
||||
let (_, domain) = domain(config)?;
|
||||
let name = host.split(':').next().unwrap_or(host);
|
||||
let label = name.strip_suffix(&format!(".{domain}"))?;
|
||||
let rest = label.strip_prefix('r')?;
|
||||
let (room, port) = rest.rsplit_once("-p")?;
|
||||
let (port, signature) = port.rsplit_once('-')?;
|
||||
if room.is_empty() || signature.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let port: u16 = port.parse().ok()?;
|
||||
Some((room.to_owned(), port, signature.to_owned()))
|
||||
}
|
||||
|
||||
/// Verifies the signature in the Host header against the room and port
|
||||
/// it names, then proxies the request.
|
||||
pub async fn proxy(state: Shared, request: Request<Body>) -> Response {
|
||||
let host = request
|
||||
.headers()
|
||||
.get(header::HOST)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let Some((room, port, signature)) = target_of_host(&state.config, &host) else {
|
||||
return (StatusCode::NOT_FOUND, "not a preview host").into_response();
|
||||
};
|
||||
let expected = state.secrets.sign(&format!("{room}:{port}"));
|
||||
if signature != expected {
|
||||
return (StatusCode::NOT_FOUND, "not a preview host").into_response();
|
||||
}
|
||||
match try_proxy(&state, &room, port, request).await {
|
||||
Ok(response) => response,
|
||||
Err(message) => (
|
||||
StatusCode::BAD_GATEWAY,
|
||||
format!("the preview did not answer: {message}"),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn try_proxy(
|
||||
state: &Shared,
|
||||
room: &str,
|
||||
port: u16,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response, String> {
|
||||
let (workspace, target) = agent::load_room_target(state, room).map_err(|err| err.message)?;
|
||||
let _ = workspace;
|
||||
let key = state
|
||||
.secrets
|
||||
.open_str(&target.private_key_ciphertext)
|
||||
.map_err(|err| err.message)?;
|
||||
let handle = match state.previews.get(&target.id) {
|
||||
Some(handle) => handle,
|
||||
None => {
|
||||
let handle = Arc::new(crate::ssh::connect_handle(&target, &key).await?);
|
||||
state.previews.put(&target.id, handle.clone());
|
||||
handle
|
||||
}
|
||||
};
|
||||
let channel = match handle
|
||||
.channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0)
|
||||
.await
|
||||
{
|
||||
Ok(channel) => channel,
|
||||
Err(_) => {
|
||||
state.previews.forget(&target.id);
|
||||
let handle = Arc::new(crate::ssh::connect_handle(&target, &key).await?);
|
||||
state.previews.put(&target.id, handle.clone());
|
||||
handle
|
||||
.channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0)
|
||||
.await
|
||||
.map_err(|err| format!("the sandbox refused port {port}: {err}"))?
|
||||
}
|
||||
};
|
||||
let stream = channel.into_stream();
|
||||
let io = TokioIo::new(stream);
|
||||
let (mut sender, connection) = hyper::client::conn::http1::handshake(io)
|
||||
.await
|
||||
.map_err(|err| format!("http handshake failed: {err}"))?;
|
||||
tokio::spawn(async move {
|
||||
let _ = connection.await;
|
||||
});
|
||||
let path = request
|
||||
.uri()
|
||||
.path_and_query()
|
||||
.map(|value| value.as_str())
|
||||
.unwrap_or("/");
|
||||
let uri: Uri = path.parse().map_err(|err| format!("bad path: {err}"))?;
|
||||
let (parts, body) = request.into_parts();
|
||||
let mut outbound = Request::builder()
|
||||
.method(parts.method)
|
||||
.uri(uri)
|
||||
.body(body)
|
||||
.map_err(|err| format!("could not build the request: {err}"))?;
|
||||
*outbound.headers_mut() = parts.headers;
|
||||
strip_hop_by_hop(outbound.headers_mut());
|
||||
outbound.headers_mut().insert(
|
||||
header::HOST,
|
||||
HeaderValue::from_str(&format!("127.0.0.1:{port}")).unwrap(),
|
||||
);
|
||||
let response = sender
|
||||
.send_request(outbound)
|
||||
.await
|
||||
.map_err(|err| format!("the preview did not answer: {err}"))?;
|
||||
let (parts, body) = response.into_parts();
|
||||
let mut out = Response::new(Body::new(body));
|
||||
*out.status_mut() = parts.status;
|
||||
*out.headers_mut() = parts.headers;
|
||||
strip_hop_by_hop(out.headers_mut());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn strip_hop_by_hop(headers: &mut HeaderMap) {
|
||||
for name in [
|
||||
header::CONNECTION,
|
||||
HeaderName::from_static("keep-alive"),
|
||||
HeaderName::from_static("proxy-authenticate"),
|
||||
HeaderName::from_static("proxy-authorization"),
|
||||
header::TE,
|
||||
header::TRAILER,
|
||||
header::TRANSFER_ENCODING,
|
||||
header::UPGRADE,
|
||||
] {
|
||||
headers.remove(name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
//! Building one turn: rows, the ssh sandbox, the provider, and the
|
||||
//! host agent over a stored session.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::num::NonZeroU32;
|
||||
use std::sync::Arc;
|
||||
|
||||
use base64::Engine;
|
||||
use rhema_bash::{AllowAll, ShellTools};
|
||||
use rhema_core::request::ThinkingEffort;
|
||||
use rhema_core::{Session, ToolResolver};
|
||||
use rhema_host_agent::{HostAgent, HostAgentConfig};
|
||||
use rhema_sandbox::WorkspaceSeed;
|
||||
use rhema_sandbox::{Sandbox, ShellSandbox};
|
||||
use rhema_sandbox_ssh::SshSandbox;
|
||||
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::state::Shared;
|
||||
|
||||
use super::message_tool::MessageTool;
|
||||
|
||||
/// The room and its configuration, read fresh for every turn.
|
||||
pub struct TurnConfig {
|
||||
pub room_id: String,
|
||||
pub room_name: String,
|
||||
pub workspace: String,
|
||||
pub repo_url: Option<String>,
|
||||
pub model: String,
|
||||
pub max_turn_steps: u32,
|
||||
pub absorbed_seq: i64,
|
||||
pub seeded: bool,
|
||||
pub owner_name: String,
|
||||
pub members: Vec<String>,
|
||||
pub provider: ProviderRow,
|
||||
pub target: TargetRow,
|
||||
}
|
||||
|
||||
/// The provider row, ciphertext included.
|
||||
pub struct ProviderRow {
|
||||
pub kind: String,
|
||||
pub base_url: Option<String>,
|
||||
pub api_key_ciphertext: String,
|
||||
}
|
||||
|
||||
/// The sandbox row, ciphertext included.
|
||||
pub struct TargetRow {
|
||||
pub id: String,
|
||||
pub host: String,
|
||||
pub port: i64,
|
||||
pub user_name: String,
|
||||
pub private_key_ciphertext: String,
|
||||
pub host_fingerprint: Option<String>,
|
||||
}
|
||||
|
||||
/// Reads everything a turn needs.
|
||||
pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig> {
|
||||
let conn = state.db.conn();
|
||||
let row = conn
|
||||
.query_row(
|
||||
"SELECT name, provider_config_id, sandbox_target_id, workspace, repo_url, model,
|
||||
max_turn_steps, absorbed_seq, seeded
|
||||
FROM rooms WHERE id = ?1 AND archived_at IS NULL",
|
||||
rusqlite::params![room_id],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, Option<String>>(1)?,
|
||||
row.get::<_, Option<String>>(2)?,
|
||||
row.get::<_, String>(3)?,
|
||||
row.get::<_, Option<String>>(4)?,
|
||||
row.get::<_, Option<String>>(5)?,
|
||||
row.get::<_, i64>(6)?,
|
||||
row.get::<_, i64>(7)?,
|
||||
row.get::<_, i64>(8)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.map_err(|_| AppError::not_found("room not found"))?;
|
||||
let (
|
||||
name,
|
||||
provider_id,
|
||||
target_id,
|
||||
workspace,
|
||||
repo_url,
|
||||
room_model,
|
||||
max_steps,
|
||||
absorbed,
|
||||
seeded,
|
||||
) = row;
|
||||
let provider_id =
|
||||
provider_id.ok_or_else(|| AppError::bad_request("room has no provider configured"))?;
|
||||
let target_id =
|
||||
target_id.ok_or_else(|| AppError::bad_request("room has no sandbox configured"))?;
|
||||
let (kind, provider_model, base_url, key) = conn.query_row(
|
||||
"SELECT kind, model, base_url, api_key_ciphertext FROM provider_configs WHERE id = ?1",
|
||||
rusqlite::params![provider_id],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, String>(1)?,
|
||||
row.get::<_, Option<String>>(2)?,
|
||||
row.get::<_, String>(3)?,
|
||||
))
|
||||
},
|
||||
)?;
|
||||
let target = conn.query_row(
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint
|
||||
FROM sandbox_targets WHERE id = ?1",
|
||||
rusqlite::params![target_id],
|
||||
|row| {
|
||||
Ok(TargetRow {
|
||||
id: row.get(0)?,
|
||||
host: row.get(1)?,
|
||||
port: row.get(2)?,
|
||||
user_name: row.get(3)?,
|
||||
private_key_ciphertext: row.get(4)?,
|
||||
host_fingerprint: row.get(5)?,
|
||||
})
|
||||
},
|
||||
)?;
|
||||
let owner_name: String = conn.query_row(
|
||||
"SELECT display_name FROM accounts WHERE id = (SELECT owner_id FROM rooms WHERE id = ?1)",
|
||||
rusqlite::params![room_id],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT display_name FROM members WHERE room_id = ?1 ORDER BY created_at")?;
|
||||
let members = stmt
|
||||
.query_map(rusqlite::params![room_id], |row| row.get::<_, String>(0))?
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(TurnConfig {
|
||||
room_id: room_id.to_owned(),
|
||||
room_name: name,
|
||||
workspace,
|
||||
repo_url,
|
||||
model: room_model.unwrap_or_else(|| provider_model.clone()),
|
||||
max_turn_steps: max_steps.max(1) as u32,
|
||||
absorbed_seq: absorbed,
|
||||
seeded: seeded != 0,
|
||||
owner_name,
|
||||
members,
|
||||
provider: ProviderRow {
|
||||
kind,
|
||||
base_url,
|
||||
api_key_ciphertext: key,
|
||||
},
|
||||
target,
|
||||
})
|
||||
}
|
||||
|
||||
/// The ssh destination in the form the backend resolves.
|
||||
fn destination(target: &TargetRow) -> String {
|
||||
format!("{}@{}:{}", target.user_name, target.host, target.port)
|
||||
}
|
||||
|
||||
/// A sandbox handle for this room.
|
||||
pub fn build_sandbox(state: &Shared, config: &TurnConfig) -> AppResult<SshSandbox> {
|
||||
sandbox_for(state, &config.workspace, &config.target)
|
||||
}
|
||||
|
||||
/// A sandbox handle from a workspace and a target row.
|
||||
pub fn sandbox_for(state: &Shared, workspace: &str, target: &TargetRow) -> AppResult<SshSandbox> {
|
||||
let key = state.secrets.open_str(&target.private_key_ciphertext)?;
|
||||
Ok(SshSandbox::new(destination(target))
|
||||
.with_workspace(workspace.to_owned())
|
||||
.with_private_key(key))
|
||||
}
|
||||
|
||||
/// The room's workspace and target, for routes that do not need the
|
||||
/// provider.
|
||||
pub fn load_room_target(state: &Shared, room: &str) -> AppResult<(String, TargetRow)> {
|
||||
let conn = state.db.conn();
|
||||
let (workspace, target_id): (String, Option<String>) = conn
|
||||
.query_row(
|
||||
"SELECT workspace, sandbox_target_id FROM rooms WHERE id = ?1 AND archived_at IS NULL",
|
||||
rusqlite::params![room],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.map_err(|_| AppError::not_found("room not found"))?;
|
||||
let target_id =
|
||||
target_id.ok_or_else(|| AppError::bad_request("room has no sandbox configured"))?;
|
||||
let target = conn.query_row(
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint
|
||||
FROM sandbox_targets WHERE id = ?1",
|
||||
rusqlite::params![target_id],
|
||||
|row| {
|
||||
Ok(TargetRow {
|
||||
id: row.get(0)?,
|
||||
host: row.get(1)?,
|
||||
port: row.get(2)?,
|
||||
user_name: row.get(3)?,
|
||||
private_key_ciphertext: row.get(4)?,
|
||||
host_fingerprint: row.get(5)?,
|
||||
})
|
||||
},
|
||||
)?;
|
||||
Ok((workspace, target))
|
||||
}
|
||||
|
||||
/// Creates the remote workspace on the first turn: a clone when the
|
||||
/// room names a repository, an empty directory otherwise.
|
||||
pub async fn ensure_workspace(state: &Shared, config: &TurnConfig) -> AppResult<()> {
|
||||
if config.seeded {
|
||||
return Ok(());
|
||||
}
|
||||
let sandbox = build_sandbox(state, config)?;
|
||||
let seed = match config.repo_url.as_deref().map(str::trim) {
|
||||
Some(url) if !url.is_empty() => WorkspaceSeed::GitClone(url.to_owned()),
|
||||
_ => WorkspaceSeed::Tarball {
|
||||
name: "room-seed".into(),
|
||||
tar_gz_base64: seed_tarball(config)?,
|
||||
},
|
||||
};
|
||||
sandbox
|
||||
.seed(&seed)
|
||||
.await
|
||||
.map_err(|err| AppError::internal(format!("could not prepare the workspace: {err}")))?;
|
||||
state.db.conn().execute(
|
||||
"UPDATE rooms SET seeded = 1 WHERE id = ?1",
|
||||
rusqlite::params![config.room_id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn seed_tarball(config: &TurnConfig) -> AppResult<String> {
|
||||
let readme = format!(
|
||||
"# {}\n\nThis workspace belongs to the Rhema room \"{}\".\n\n\
|
||||
The agent works here with the same sandbox and key as the web terminal.\n\
|
||||
Open a terminal in the room to add a project, or create the room with a\n\
|
||||
repository URL to clone one.\n",
|
||||
config
|
||||
.workspace
|
||||
.trim_end_matches('/')
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or("workspace"),
|
||||
config.room_name
|
||||
);
|
||||
let ignore = "node_modules/\ntarget/\n.env\n.DS_Store\n";
|
||||
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
{
|
||||
let mut builder = tar::Builder::new(&mut gz);
|
||||
for (name, body) in [("README.md", readme.as_str()), (".gitignore", ignore)] {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_path(name).map_err(|err| {
|
||||
AppError::internal(format!("could not build the room seed: {err}"))
|
||||
})?;
|
||||
header.set_mode(0o644);
|
||||
header.set_size(body.len() as u64);
|
||||
header.set_mtime(
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|value| value.as_secs())
|
||||
.unwrap_or(0),
|
||||
);
|
||||
header.set_cksum();
|
||||
builder.append(&header, body.as_bytes()).map_err(|err| {
|
||||
AppError::internal(format!("could not build the room seed: {err}"))
|
||||
})?;
|
||||
}
|
||||
builder
|
||||
.finish()
|
||||
.map_err(|err| AppError::internal(format!("could not build the room seed: {err}")))?;
|
||||
}
|
||||
let bytes = gz
|
||||
.finish()
|
||||
.map_err(|err| AppError::internal(format!("could not build the room seed: {err}")))?;
|
||||
Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
|
||||
}
|
||||
|
||||
/// The turn's room section, rendered into the system prompt.
|
||||
fn room_section(config: &TurnConfig) -> String {
|
||||
let mut people = config.members.join(", ");
|
||||
if people.is_empty() {
|
||||
people = config.owner_name.clone();
|
||||
}
|
||||
format!(
|
||||
"Room \"{}\". Workspace {}. Sandbox {}@{}. Model {}.\n\
|
||||
People here: {}.",
|
||||
config.room_name,
|
||||
config.workspace,
|
||||
config.target.user_name,
|
||||
config.target.host,
|
||||
config.model,
|
||||
people
|
||||
)
|
||||
}
|
||||
|
||||
/// Assembles the host agent over `session`.
|
||||
pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> AppResult<HostAgent> {
|
||||
let sandbox = build_sandbox(state, config)?;
|
||||
let executor = Arc::new(ShellSandbox::new(Arc::new(sandbox)));
|
||||
let shell = Arc::new(ShellTools::with_executor(
|
||||
config.workspace.clone(),
|
||||
executor,
|
||||
));
|
||||
let api_key = state
|
||||
.secrets
|
||||
.open_str(&config.provider.api_key_ciphertext)?;
|
||||
let llama_url = (config.provider.kind == "llama-cpp")
|
||||
.then_some(config.provider.base_url.as_deref())
|
||||
.flatten();
|
||||
let built = rhema_provider_registry::build(
|
||||
&config.provider.kind,
|
||||
Some(&api_key),
|
||||
llama_url,
|
||||
config.provider.base_url.as_deref(),
|
||||
None,
|
||||
)
|
||||
.map_err(|err| AppError::bad_request(format!("provider: {err}")))?;
|
||||
let message_tool: Arc<dyn ToolResolver> =
|
||||
Arc::new(MessageTool::new(state.clone(), config.room_id.clone()));
|
||||
let max_turn_steps =
|
||||
NonZeroU32::new(config.max_turn_steps).unwrap_or(NonZeroU32::new(48).unwrap());
|
||||
let mut sections = BTreeMap::new();
|
||||
sections.insert("room".to_owned(), serde_json::json!(room_section(config)));
|
||||
let agent_config = HostAgentConfig {
|
||||
provider: built.provider,
|
||||
approval: Arc::new(AllowAll),
|
||||
model: config.model.clone(),
|
||||
system: None,
|
||||
base_system: Some(include_str!("prompt.md").to_owned()),
|
||||
workspace: config.workspace.clone().into(),
|
||||
skills: Some(Vec::new()),
|
||||
disabled_skills: Default::default(),
|
||||
mcp: None,
|
||||
disabled_subagents: Default::default(),
|
||||
subagent_providers: None,
|
||||
session_id: Some(config.room_id.clone()),
|
||||
max_turn_steps,
|
||||
thinking: ThinkingEffort::Default,
|
||||
tools: Some(shell),
|
||||
extra_resolver: Some(message_tool),
|
||||
shell_env: Default::default(),
|
||||
transcript: Some(Default::default()),
|
||||
summary_worker: None,
|
||||
steering: None,
|
||||
home: None,
|
||||
environment: Some(rhema_host_agent::remote_notice(
|
||||
"ssh",
|
||||
&config.workspace,
|
||||
&config.model,
|
||||
concat!("rhema-together ", env!("CARGO_PKG_VERSION")),
|
||||
)),
|
||||
user_preferences: None,
|
||||
supports_vision: None,
|
||||
vision: None,
|
||||
jobs: None,
|
||||
websearch: None,
|
||||
decision: None,
|
||||
sections,
|
||||
};
|
||||
let mut agent = HostAgent::from_session(agent_config, session)
|
||||
.map_err(|err| AppError::internal(format!("could not build the agent: {err}")))?;
|
||||
let db = state.db.clone();
|
||||
let room = config.room_id.clone();
|
||||
agent.set_commit_hook(Some(Box::new(move |session| {
|
||||
let json = serde_json::to_string(session)
|
||||
.map_err(|err| rhema_core::CommitError(err.to_string()))?;
|
||||
db.conn()
|
||||
.execute(
|
||||
"UPDATE rooms SET session_json = ?1 WHERE id = ?2",
|
||||
rusqlite::params![json, room],
|
||||
)
|
||||
.map_err(|err| rhema_core::CommitError(err.to_string()))?;
|
||||
Ok(())
|
||||
})));
|
||||
Ok(agent)
|
||||
}
|
||||
|
||||
/// Reads the saved session, or an empty one.
|
||||
pub fn load_session(state: &Shared, room: &str) -> AppResult<Session> {
|
||||
let json: Option<String> = state.db.conn().query_row(
|
||||
"SELECT session_json FROM rooms WHERE id = ?1",
|
||||
rusqlite::params![room],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
match json {
|
||||
Some(json) if !json.trim().is_empty() => serde_json::from_str(&json)
|
||||
.map_err(|err| AppError::internal(format!("saved session is corrupt: {err}"))),
|
||||
_ => Ok(Session::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Persists a session outside the commit hook (the end of a turn).
|
||||
pub fn save_session(state: &Shared, room: &str, session: &Session) -> AppResult<()> {
|
||||
let json = serde_json::to_string(session)?;
|
||||
state.db.conn().execute(
|
||||
"UPDATE rooms SET session_json = ?1 WHERE id = ?2",
|
||||
rusqlite::params![json, room],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! The `message` tool: the agent's only way into the room.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use rhema_core::request::ToolSpec;
|
||||
use rhema_core::tool::{ReplaySafety, ToolCall, ToolContext, ToolResolver, ToolResult};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::error::AppResult;
|
||||
use crate::models::Message;
|
||||
use crate::state::Shared;
|
||||
use crate::util::{mentions_agent, now_ms, random_id};
|
||||
|
||||
/// Posts an agent message into the room log.
|
||||
pub fn post_agent_message(state: &Shared, room: &str, text: &str) -> AppResult<Message> {
|
||||
let text = text.trim();
|
||||
let seq = state.hub.next_seq(&state.db, room);
|
||||
let message = Message {
|
||||
seq,
|
||||
id: random_id(16),
|
||||
author_id: None,
|
||||
author_name: "rhema".into(),
|
||||
author_kind: "agent".into(),
|
||||
text: text.to_owned(),
|
||||
mentions: mentions_agent(text),
|
||||
created_at: now_ms(),
|
||||
};
|
||||
let data = serde_json::to_value(&message)?;
|
||||
state.hub.insert(&state.db, room, seq, "message", &data)?;
|
||||
state.hub.broadcast(
|
||||
room,
|
||||
crate::models::Envelope {
|
||||
seq,
|
||||
kind: "message".into(),
|
||||
data,
|
||||
},
|
||||
);
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
/// The resolver handed to the agent as an extra tool.
|
||||
pub struct MessageTool {
|
||||
state: Shared,
|
||||
room: String,
|
||||
}
|
||||
|
||||
impl MessageTool {
|
||||
/// A tool posting into `room`.
|
||||
pub fn new(state: Shared, room: String) -> Self {
|
||||
Self { state, room }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ToolResolver for MessageTool {
|
||||
fn specs(&self) -> Vec<ToolSpec> {
|
||||
vec![ToolSpec::new(
|
||||
"message",
|
||||
"Send a message to the people in the room. This is the only way you \
|
||||
speak: text outside this tool is not shown. One short message per \
|
||||
update. Always send one before the turn ends.",
|
||||
json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "The message, in plain language. Address people by name."
|
||||
}
|
||||
},
|
||||
"required": ["text"]
|
||||
}),
|
||||
)]
|
||||
}
|
||||
|
||||
fn replay_safety(&self, _name: &str) -> ReplaySafety {
|
||||
// Posting twice would duplicate a line in the room. A resume
|
||||
// reports the call interrupted instead of re-running it.
|
||||
ReplaySafety::Unsafe
|
||||
}
|
||||
|
||||
async fn resolve(&self, call: ToolCall, _ctx: &ToolContext) -> ToolResult {
|
||||
let Some(text) = call.args.get("text").and_then(|value| value.as_str()) else {
|
||||
return ToolResult::failure(call.id, "`text` must be a string");
|
||||
};
|
||||
if text.trim().is_empty() {
|
||||
return ToolResult::failure(call.id, "the message is empty");
|
||||
}
|
||||
match post_agent_message(&self.state, &self.room, text) {
|
||||
Ok(_) => ToolResult::success(call.id, "sent"),
|
||||
Err(err) => ToolResult::failure(call.id, format!("could not post: {}", err.message)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
//! The room turn runner. Filled in below.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::state::Shared;
|
||||
|
||||
/// A wake signal for a room's turn task.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Wake {
|
||||
/// A message was posted without mentioning the agent.
|
||||
Chat,
|
||||
/// A message mentioned the agent.
|
||||
Mention,
|
||||
}
|
||||
|
||||
struct Handle {
|
||||
tx: mpsc::UnboundedSender<Wake>,
|
||||
}
|
||||
|
||||
/// The live turn tasks, one per room.
|
||||
#[derive(Default)]
|
||||
pub struct RoomRunner {
|
||||
handles: Mutex<HashMap<String, Handle>>,
|
||||
current: Mutex<HashMap<String, Arc<AtomicBool>>>,
|
||||
}
|
||||
|
||||
impl RoomRunner {
|
||||
/// Notifies the room's task that new work may be pending, spawning
|
||||
/// the task on first use.
|
||||
pub fn wake(&self, state: &Shared, room: &str, wake: Wake) {
|
||||
let mut handles = self.handles.lock().unwrap_or_else(|err| err.into_inner());
|
||||
if let Some(handle) = handles.get(room) {
|
||||
let _ = handle.tx.send(wake);
|
||||
return;
|
||||
}
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let _ = tx.send(wake);
|
||||
handles.insert(room.to_owned(), Handle { tx });
|
||||
let room = room.to_owned();
|
||||
let weak = std::sync::Arc::downgrade(state);
|
||||
tokio::spawn(async move {
|
||||
let Some(state) = weak.upgrade() else { return };
|
||||
crate::room::runner::run(state, room, rx).await;
|
||||
});
|
||||
}
|
||||
|
||||
/// Records the cancel flag of the turn now running in `room`.
|
||||
pub fn set_current(&self, room: &str, cancel: Arc<AtomicBool>) {
|
||||
self.current
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.insert(room.to_owned(), cancel);
|
||||
}
|
||||
|
||||
/// Forgets the running turn.
|
||||
pub fn clear_current(&self, room: &str) {
|
||||
self.current
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.remove(room);
|
||||
}
|
||||
|
||||
/// Flips the running turn's cancel flag. False when nothing runs.
|
||||
pub fn interrupt(&self, room: &str) -> bool {
|
||||
let current = self.current.lock().unwrap_or_else(|err| err.into_inner());
|
||||
match current.get(room) {
|
||||
Some(flag) => {
|
||||
flag.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod agent;
|
||||
pub mod message_tool;
|
||||
pub mod runner;
|
||||
@@ -0,0 +1,42 @@
|
||||
You are @rhema, the coding agent in a shared room.
|
||||
|
||||
{{ room }}
|
||||
|
||||
## Talking to the room
|
||||
|
||||
Every human line in the conversation starts with the speaker's name. People
|
||||
also talk to each other. Messages that mention @rhema ask you to act. The
|
||||
rest is context.
|
||||
|
||||
Your only way to speak is the `message` tool. Text you write outside that
|
||||
tool is not shown to anyone.
|
||||
|
||||
- Send one short message when you have something to say.
|
||||
- Always send one before the turn ends. A short "Ack." is enough for a small
|
||||
change.
|
||||
- Report a decision, a result, a blocker, or a question. Do not narrate every
|
||||
command.
|
||||
- When a decision belongs to the people in the room, ask in a message and
|
||||
stop.
|
||||
- Address people by name when you answer someone in particular.
|
||||
|
||||
## Work
|
||||
|
||||
The workspace is {{ workspace }}. Inspect before you edit. Use `bash` for
|
||||
reading, searching, editing, and running tests. Leave the tree in a state
|
||||
someone else can pick up. When you finish, say which files changed and which
|
||||
checks you ran.
|
||||
|
||||
{% if tools %}
|
||||
## Tools
|
||||
|
||||
You have the following tools: each entry is its name and arguments, then what
|
||||
it is for. The arguments are the JSON schema a call must satisfy.
|
||||
{% for tool in tools %}
|
||||
|
||||
|
||||
- {{ tool.name }} | {{ tool.parameters | json }}
|
||||
|
||||
{{ tool.description | indent(2, true) }}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
@@ -0,0 +1,395 @@
|
||||
//! The per-room turn loop. One task per room, one turn at a time.
|
||||
//!
|
||||
//! Steering is turn level for now: a new mention drops the running turn
|
||||
//! future and starts a fresh turn over the committed session, the shape
|
||||
//! `rhema-code` uses. The step-level hook (`HostAgent::step`) is
|
||||
//! deferred; see the spec's framework section.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use rhema_core::event::Event;
|
||||
use rhema_core::{EventSink, Message, Role, Session, Usage};
|
||||
use serde_json::json;
|
||||
use tokio::sync::mpsc::UnboundedReceiver;
|
||||
|
||||
use crate::error::AppResult;
|
||||
use crate::models::Message as RoomMessage;
|
||||
use crate::state::Shared;
|
||||
use crate::util::{now_ms, random_id};
|
||||
|
||||
use super::Wake;
|
||||
use super::agent::{self, TurnConfig};
|
||||
|
||||
/// Runs the room until the process stops.
|
||||
pub async fn run(state: Shared, room: String, mut rx: UnboundedReceiver<Wake>) {
|
||||
let mut pending_mention = false;
|
||||
loop {
|
||||
let Some(wake) = rx.recv().await else { break };
|
||||
if matches!(wake, Wake::Mention) {
|
||||
pending_mention = true;
|
||||
}
|
||||
if !pending_mention {
|
||||
continue;
|
||||
}
|
||||
loop {
|
||||
let config = match agent::load_turn_config(&state, &room) {
|
||||
Ok(config) => config,
|
||||
Err(err) => {
|
||||
notice(&state, &room, "error", err.message);
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
};
|
||||
let pending = match pending_messages(&state, &room, config.absorbed_seq) {
|
||||
Ok(pending) => pending,
|
||||
Err(err) => {
|
||||
notice(&state, &room, "error", err.message);
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
};
|
||||
if !pending.iter().any(|message| message.mentions) {
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
if let Err(err) = agent::ensure_workspace(&state, &config).await {
|
||||
notice(&state, &room, "error", err.message);
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
let mut session = match agent::load_session(&state, &room) {
|
||||
Ok(session) => session,
|
||||
Err(err) => {
|
||||
notice(&state, &room, "error", err.message);
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
};
|
||||
for message in &pending {
|
||||
session.history.push(Message::text(
|
||||
Role::User,
|
||||
format!("{}: {}", message.author_name, message.text),
|
||||
));
|
||||
}
|
||||
if let Err(err) = agent::save_session(&state, &room, &session) {
|
||||
notice(&state, &room, "error", err.message);
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
let last = pending.last().map(|message| message.seq).unwrap_or(0);
|
||||
let _ = state.db.conn().execute(
|
||||
"UPDATE rooms SET absorbed_seq = ?1 WHERE id = ?2",
|
||||
rusqlite::params![last as i64, room],
|
||||
);
|
||||
pending_mention = false;
|
||||
let trigger = pending
|
||||
.iter()
|
||||
.find(|message| message.mentions)
|
||||
.map(|message| message.author_name.clone())
|
||||
.unwrap_or_else(|| "someone".into());
|
||||
run_turn(
|
||||
&state,
|
||||
&room,
|
||||
&config,
|
||||
session,
|
||||
&trigger,
|
||||
&mut rx,
|
||||
&mut pending_mention,
|
||||
)
|
||||
.await;
|
||||
if !pending_mention {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_turn(
|
||||
state: &Shared,
|
||||
room: &str,
|
||||
config: &TurnConfig,
|
||||
session: Session,
|
||||
trigger: &str,
|
||||
rx: &mut UnboundedReceiver<Wake>,
|
||||
pending_mention: &mut bool,
|
||||
) {
|
||||
let mut agent = match agent::build_agent(state, config, session) {
|
||||
Ok(agent) => agent,
|
||||
Err(err) => {
|
||||
notice(state, room, "error", err.message);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let turn_id = random_id(12);
|
||||
let started = state.hub.durable(
|
||||
&state.db,
|
||||
room,
|
||||
"turn_start",
|
||||
json!({
|
||||
"turn_id": turn_id,
|
||||
"by": trigger,
|
||||
"model": config.model,
|
||||
"at": now_ms(),
|
||||
}),
|
||||
);
|
||||
if let Err(err) = started {
|
||||
notice(state, room, "error", err.message);
|
||||
return;
|
||||
}
|
||||
let mut sink = RoomSink::new(state.clone(), room.to_owned(), turn_id.clone());
|
||||
let cancelled = Arc::new(AtomicBool::new(false));
|
||||
state.rooms.set_current(room, cancelled.clone());
|
||||
let mut turn = Box::pin(agent.retry_turn_with_cancel(&mut sink, cancelled));
|
||||
let outcome = loop {
|
||||
tokio::select! {
|
||||
result = &mut turn => break Some(result),
|
||||
wake = rx.recv() => match wake {
|
||||
Some(Wake::Mention) => {
|
||||
*pending_mention = true;
|
||||
break None;
|
||||
}
|
||||
Some(Wake::Chat) => continue,
|
||||
None => break None,
|
||||
},
|
||||
}
|
||||
};
|
||||
drop(turn);
|
||||
state.rooms.clear_current(room);
|
||||
let session = agent.session().clone();
|
||||
if let Err(err) = agent::save_session(state, room, &session) {
|
||||
notice(state, room, "error", err.message);
|
||||
}
|
||||
let data = match outcome {
|
||||
Some(Ok(output)) => {
|
||||
let reason = match &output.stop_reason {
|
||||
rhema_core::StopReason::EndTurn => "done",
|
||||
rhema_core::StopReason::ToolUse => "step_limit",
|
||||
rhema_core::StopReason::MaxTokens => "max_tokens",
|
||||
_ => "done",
|
||||
};
|
||||
json!({
|
||||
"turn_id": turn_id,
|
||||
"status": reason,
|
||||
"usage": sink.usage_json(),
|
||||
"steps": sink.steps,
|
||||
})
|
||||
}
|
||||
Some(Err(err)) => json!({
|
||||
"turn_id": turn_id,
|
||||
"status": "error",
|
||||
"error": err.to_string(),
|
||||
"usage": sink.usage_json(),
|
||||
"steps": sink.steps,
|
||||
}),
|
||||
None => json!({
|
||||
"turn_id": turn_id,
|
||||
"status": "interrupted",
|
||||
"usage": sink.usage_json(),
|
||||
"steps": sink.steps,
|
||||
}),
|
||||
};
|
||||
if let Err(err) = state.hub.durable(&state.db, room, "turn_end", data) {
|
||||
notice(state, room, "error", err.message);
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_messages(state: &Shared, room: &str, absorbed: i64) -> AppResult<Vec<RoomMessage>> {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT data FROM events WHERE room_id = ?1 AND kind = 'message' AND seq > ?2
|
||||
ORDER BY seq ASC LIMIT 500",
|
||||
)?;
|
||||
let rows = stmt.query_map(rusqlite::params![room, absorbed], |row| {
|
||||
row.get::<_, String>(0)
|
||||
})?;
|
||||
let mut messages = Vec::new();
|
||||
for row in rows {
|
||||
let text = row?;
|
||||
if let Ok(message) = serde_json::from_str::<RoomMessage>(&text)
|
||||
&& message.author_kind == "human"
|
||||
{
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
fn notice(state: &Shared, room: &str, level: &str, text: impl Into<String>) {
|
||||
let _ = state.hub.durable(
|
||||
&state.db,
|
||||
room,
|
||||
"notice",
|
||||
json!({ "level": level, "text": text.into(), "at": now_ms() }),
|
||||
);
|
||||
}
|
||||
|
||||
/// The sink that turns the engine's events into room events.
|
||||
struct RoomSink {
|
||||
state: Shared,
|
||||
room: String,
|
||||
turn_id: String,
|
||||
names: HashMap<String, String>,
|
||||
args: HashMap<String, String>,
|
||||
usage: Usage,
|
||||
steps: u32,
|
||||
}
|
||||
|
||||
impl RoomSink {
|
||||
fn new(state: Shared, room: String, turn_id: String) -> Self {
|
||||
Self {
|
||||
state,
|
||||
room,
|
||||
turn_id,
|
||||
names: HashMap::new(),
|
||||
args: HashMap::new(),
|
||||
usage: Usage::default(),
|
||||
steps: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn live(&self, kind: &str, data: serde_json::Value) {
|
||||
self.state.hub.live(&self.state.db, &self.room, kind, data);
|
||||
}
|
||||
|
||||
fn usage_json(&self) -> serde_json::Value {
|
||||
json!({
|
||||
"input_tokens": self.usage.input_tokens,
|
||||
"output_tokens": self.usage.output_tokens,
|
||||
"cached_input_tokens": self.usage.cached_input_tokens,
|
||||
"cost_usd": self.usage.cost_usd,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl EventSink for RoomSink {
|
||||
fn emit(&mut self, event: Event<'_>) {
|
||||
let turn = self.turn_id.clone();
|
||||
match event {
|
||||
Event::StepStart { iteration } => {
|
||||
self.live(
|
||||
"step_start",
|
||||
json!({ "turn_id": turn, "iteration": iteration }),
|
||||
);
|
||||
}
|
||||
Event::TextDelta(delta) => {
|
||||
self.live("text_delta", json!({ "turn_id": turn, "delta": delta }));
|
||||
}
|
||||
Event::ThinkingDelta(delta) => {
|
||||
self.live("thinking_delta", json!({ "turn_id": turn, "delta": delta }));
|
||||
}
|
||||
Event::ToolCallStart { id, name } => {
|
||||
self.names.insert(id.to_owned(), name.to_owned());
|
||||
self.live(
|
||||
"tool_start",
|
||||
json!({ "turn_id": turn, "call_id": id, "name": name }),
|
||||
);
|
||||
}
|
||||
Event::ToolCallArgsDelta { id, delta } => {
|
||||
self.args.entry(id.to_owned()).or_default().push_str(delta);
|
||||
self.live(
|
||||
"tool_args",
|
||||
json!({ "turn_id": turn, "call_id": id, "delta": delta }),
|
||||
);
|
||||
}
|
||||
Event::ToolOutputDelta { id, chunk } => {
|
||||
self.live(
|
||||
"tool_output",
|
||||
json!({ "turn_id": turn, "call_id": id, "chunk": chunk }),
|
||||
);
|
||||
}
|
||||
Event::ToolResult {
|
||||
id,
|
||||
content,
|
||||
is_error,
|
||||
code,
|
||||
} => {
|
||||
let name = self.names.remove(id).unwrap_or_default();
|
||||
let args = self.args.remove(id).unwrap_or_default();
|
||||
let data = json!({
|
||||
"turn_id": turn,
|
||||
"call_id": id,
|
||||
"name": name,
|
||||
"args": args,
|
||||
"content": truncate(content, 32_000),
|
||||
"is_error": is_error,
|
||||
"code": code,
|
||||
});
|
||||
let _ = self
|
||||
.state
|
||||
.hub
|
||||
.durable(&self.state.db, &self.room, "tool_result", data);
|
||||
}
|
||||
Event::Usage(usage) => {
|
||||
self.usage.input_tokens += usage.input_tokens;
|
||||
self.usage.output_tokens += usage.output_tokens;
|
||||
self.usage.cached_input_tokens += usage.cached_input_tokens;
|
||||
if let Some(cost) = usage.cost_usd {
|
||||
self.usage.cost_usd = Some(self.usage.cost_usd.unwrap_or(0.0) + cost);
|
||||
}
|
||||
self.live(
|
||||
"usage",
|
||||
json!({
|
||||
"turn_id": turn,
|
||||
"input_tokens": usage.input_tokens,
|
||||
"output_tokens": usage.output_tokens,
|
||||
"cached_input_tokens": usage.cached_input_tokens,
|
||||
"cost_usd": usage.cost_usd,
|
||||
}),
|
||||
);
|
||||
}
|
||||
Event::StepEnd { usage, stop_reason } => {
|
||||
self.steps += 1;
|
||||
self.live(
|
||||
"step_end",
|
||||
json!({
|
||||
"turn_id": turn,
|
||||
"usage": {
|
||||
"input_tokens": usage.input_tokens,
|
||||
"output_tokens": usage.output_tokens,
|
||||
"cached_input_tokens": usage.cached_input_tokens,
|
||||
"cost_usd": usage.cost_usd,
|
||||
},
|
||||
"stop_reason": format!("{stop_reason:?}"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
Event::ToolStatus { id, status } => {
|
||||
self.live(
|
||||
"tool_status",
|
||||
json!({ "turn_id": turn, "call_id": id, "status": format!("{status:?}") }),
|
||||
);
|
||||
}
|
||||
Event::RetryWait {
|
||||
error,
|
||||
delay,
|
||||
attempt,
|
||||
total,
|
||||
} => {
|
||||
self.live(
|
||||
"retry_wait",
|
||||
json!({
|
||||
"turn_id": turn,
|
||||
"error": error,
|
||||
"delay_ms": delay.as_millis() as u64,
|
||||
"attempt": attempt,
|
||||
"total": total,
|
||||
}),
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate(text: &str, max: usize) -> String {
|
||||
if text.len() <= max {
|
||||
return text.to_owned();
|
||||
}
|
||||
let mut end = max;
|
||||
while !text.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
format!("{}\n[truncated]", &text[..end])
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
//! The web terminal: a real pty on the far side, over the same ssh
|
||||
//! target and key the agent's commands use.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::extract::ws::{Message as WsMessage, WebSocket};
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use russh::client::{self, Handle};
|
||||
use russh::keys::{PrivateKeyWithHashAlg, PublicKeyOrCertificate, decode_secret_key};
|
||||
use russh::{ChannelMsg, Error as SshError};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::room::agent::TargetRow;
|
||||
use crate::state::Shared;
|
||||
use crate::util::sha256_hex;
|
||||
|
||||
/// The host-key policy: learn the key on first contact, refuse a change.
|
||||
pub(crate) struct HostKey {
|
||||
expected: Option<String>,
|
||||
learned: Arc<Mutex<Option<String>>>,
|
||||
}
|
||||
|
||||
impl client::Handler for HostKey {
|
||||
type Error = SshError;
|
||||
|
||||
async fn check_server_key(
|
||||
&mut self,
|
||||
key: &PublicKeyOrCertificate,
|
||||
) -> Result<bool, Self::Error> {
|
||||
let PublicKeyOrCertificate::PublicKey { key, .. } = key else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Ok(line) = key.to_openssh() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let fingerprint = sha256_hex(line.as_bytes());
|
||||
match &self.expected {
|
||||
Some(expected) => Ok(expected == &fingerprint),
|
||||
None => {
|
||||
if let Ok(mut slot) = self.learned.lock() {
|
||||
*slot = Some(fingerprint);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a connection for the preview proxy.
|
||||
pub(crate) async fn connect_handle(
|
||||
target: &TargetRow,
|
||||
private_key: &str,
|
||||
) -> Result<Handle<HostKey>, String> {
|
||||
let (handle, _fingerprint) = connect(target, private_key).await?;
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
async fn connect(
|
||||
target: &TargetRow,
|
||||
private_key: &str,
|
||||
) -> Result<(Handle<HostKey>, Option<String>), String> {
|
||||
let learned = Arc::new(Mutex::new(None));
|
||||
let handler = HostKey {
|
||||
expected: target.host_fingerprint.clone(),
|
||||
learned: learned.clone(),
|
||||
};
|
||||
let config = Arc::new(client::Config::default());
|
||||
let port = u16::try_from(target.port).unwrap_or(22);
|
||||
let mut connection = client::connect(config, (target.host.as_str(), port), handler)
|
||||
.await
|
||||
.map_err(|err| format!("could not reach {}:{}: {err}", target.host, target.port))?;
|
||||
let hash = connection
|
||||
.best_supported_rsa_hash()
|
||||
.await
|
||||
.map_err(|err| format!("ssh negotiation failed: {err}"))?
|
||||
.flatten();
|
||||
let key = decode_secret_key(private_key, None)
|
||||
.map_err(|err| format!("the stored private key does not decode: {err}"))?;
|
||||
let answer = connection
|
||||
.authenticate_publickey(
|
||||
target.user_name.clone(),
|
||||
PrivateKeyWithHashAlg::new(Arc::new(key), hash),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| format!("ssh authentication failed: {err}"))?;
|
||||
if !answer.success() {
|
||||
return Err(format!(
|
||||
"{} refused the stored key for {}",
|
||||
target.host, target.user_name
|
||||
));
|
||||
}
|
||||
let fingerprint = learned.lock().ok().and_then(|slot| slot.clone());
|
||||
Ok((connection, fingerprint))
|
||||
}
|
||||
|
||||
/// Attaches a browser socket to an interactive shell in the room's
|
||||
/// sandbox.
|
||||
pub async fn terminal(socket: WebSocket, state: Shared, workspace: String, target: TargetRow) {
|
||||
let (mut sink, mut source) = socket.split();
|
||||
let key = match state.secrets.open_str(&target.private_key_ciphertext) {
|
||||
Ok(key) => key,
|
||||
Err(err) => {
|
||||
let _ = sink
|
||||
.send(WsMessage::Text(
|
||||
json!({ "type": "error", "message": err.message })
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let (connection, learned) = match connect(&target, &key).await {
|
||||
Ok(connection) => connection,
|
||||
Err(message) => {
|
||||
let _ = sink
|
||||
.send(WsMessage::Text(
|
||||
json!({ "type": "error", "message": message })
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
// Learn the host key once the login succeeded, not before: a
|
||||
// server that refuses us should not become known.
|
||||
if target.host_fingerprint.is_none()
|
||||
&& let Some(fingerprint) = learned
|
||||
{
|
||||
let _ = state.db.conn().execute(
|
||||
"UPDATE sandbox_targets SET host_fingerprint = ?1 WHERE id = ?2",
|
||||
rusqlite::params![fingerprint, target.id],
|
||||
);
|
||||
}
|
||||
let mut channel = match connection.channel_open_session().await {
|
||||
Ok(channel) => channel,
|
||||
Err(err) => {
|
||||
send_error(&mut sink, format!("the far end refused a session: {err}")).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let cwd = format!(
|
||||
"cd {} 2>/dev/null || cd ~; exec bash -l",
|
||||
rhema_sandbox::exec_util::shquote(&workspace)
|
||||
);
|
||||
if let Err(err) = channel
|
||||
.request_pty(true, "xterm-256color", 100, 30, 0, 0, &[])
|
||||
.await
|
||||
{
|
||||
send_error(&mut sink, format!("the far end refused a pty: {err}")).await;
|
||||
return;
|
||||
}
|
||||
if let Err(err) = channel.exec(true, cwd).await {
|
||||
send_error(&mut sink, format!("the far end refused the shell: {err}")).await;
|
||||
return;
|
||||
}
|
||||
let _ = sink
|
||||
.send(WsMessage::Text(
|
||||
json!({ "type": "ready" }).to_string().into(),
|
||||
))
|
||||
.await;
|
||||
loop {
|
||||
tokio::select! {
|
||||
message = channel.wait() => {
|
||||
match message {
|
||||
Some(ChannelMsg::Data { data }) => {
|
||||
if sink.send(WsMessage::Binary(data.to_vec().into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some(ChannelMsg::ExtendedData { data, .. }) => {
|
||||
if sink.send(WsMessage::Binary(data.to_vec().into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some(ChannelMsg::ExitStatus { exit_status }) => {
|
||||
let _ = sink
|
||||
.send(WsMessage::Text(
|
||||
json!({ "type": "exit", "code": exit_status }).to_string().into(),
|
||||
))
|
||||
.await;
|
||||
break;
|
||||
}
|
||||
Some(ChannelMsg::Eof) | Some(ChannelMsg::Close) | None => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
message = source.next() => {
|
||||
match message {
|
||||
Some(Ok(WsMessage::Binary(data))) => {
|
||||
if channel.data(&data[..]).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some(Ok(WsMessage::Text(text))) => {
|
||||
match serde_json::from_str::<serde_json::Value>(&text) {
|
||||
Ok(value) => {
|
||||
if value.get("type").and_then(|kind| kind.as_str()) == Some("resize") {
|
||||
let cols = value.get("cols").and_then(|v| v.as_u64()).unwrap_or(100) as u32;
|
||||
let rows = value.get("rows").and_then(|v| v.as_u64()).unwrap_or(30) as u32;
|
||||
let _ = channel.window_change(cols, rows, 0, 0).await;
|
||||
} else if let Some(data) = value.get("data").and_then(|v| v.as_str()) {
|
||||
let _ = channel.data(data.as_bytes()).await;
|
||||
}
|
||||
}
|
||||
// A plain text frame is keystrokes, for simple
|
||||
// clients that do not speak the control format.
|
||||
Err(_) => {
|
||||
let _ = channel.data(text.as_bytes()).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Ok(WsMessage::Close(_))) | None => break,
|
||||
Some(Ok(_)) => {}
|
||||
Some(Err(_)) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = channel.close().await;
|
||||
drop(connection);
|
||||
}
|
||||
|
||||
async fn send_error<S>(sink: &mut S, message: String)
|
||||
where
|
||||
S: futures::Sink<WsMessage, Error = axum::Error> + Unpin,
|
||||
{
|
||||
let _ = sink
|
||||
.send(WsMessage::Text(
|
||||
json!({ "type": "error", "message": message })
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await;
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
//! Process state: the database, the secret box, the per-room event buses,
|
||||
//! and the turn runners.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::crypto::Secrets;
|
||||
use crate::db::Db;
|
||||
use crate::error::AppResult;
|
||||
use crate::models::Envelope;
|
||||
use crate::preview::PreviewTunnels;
|
||||
use crate::room::RoomRunner;
|
||||
|
||||
/// One room's live feed and sequence allocator.
|
||||
pub struct Bus {
|
||||
pub tx: broadcast::Sender<Envelope>,
|
||||
pub seq: AtomicU64,
|
||||
}
|
||||
|
||||
/// Every room's bus, created on demand.
|
||||
#[derive(Default)]
|
||||
pub struct Hub {
|
||||
buses: Mutex<HashMap<String, Arc<Bus>>>,
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
/// The bus for `room`, its sequence seeded from the database the
|
||||
/// first time the room is seen in this process.
|
||||
pub fn bus(&self, db: &Db, room: &str) -> Arc<Bus> {
|
||||
let mut buses = self.buses.lock().unwrap_or_else(|err| err.into_inner());
|
||||
if let Some(bus) = buses.get(room) {
|
||||
return bus.clone();
|
||||
}
|
||||
let next: u64 = db
|
||||
.scalar(
|
||||
"SELECT COALESCE(MAX(seq), 0) FROM events WHERE room_id = ?1",
|
||||
rusqlite::params![room],
|
||||
)
|
||||
.unwrap_or(0);
|
||||
let (tx, _) = broadcast::channel(1024);
|
||||
let bus = Arc::new(Bus {
|
||||
tx,
|
||||
seq: AtomicU64::new(next),
|
||||
});
|
||||
buses.insert(room.to_owned(), bus.clone());
|
||||
bus
|
||||
}
|
||||
|
||||
/// Allocates the next sequence number.
|
||||
pub fn next_seq(&self, db: &Db, room: &str) -> u64 {
|
||||
self.bus(db, room).seq.fetch_add(1, Ordering::SeqCst) + 1
|
||||
}
|
||||
|
||||
/// Writes a durable event and broadcasts it.
|
||||
pub fn durable(
|
||||
&self,
|
||||
db: &Db,
|
||||
room: &str,
|
||||
kind: &str,
|
||||
data: serde_json::Value,
|
||||
) -> AppResult<Envelope> {
|
||||
let seq = self.next_seq(db, room);
|
||||
self.insert(db, room, seq, kind, &data)?;
|
||||
let envelope = Envelope {
|
||||
seq,
|
||||
kind: kind.to_owned(),
|
||||
data,
|
||||
};
|
||||
self.broadcast(room, envelope.clone());
|
||||
Ok(envelope)
|
||||
}
|
||||
|
||||
/// Writes one durable event at an already allocated sequence.
|
||||
pub fn insert(
|
||||
&self,
|
||||
db: &Db,
|
||||
room: &str,
|
||||
seq: u64,
|
||||
kind: &str,
|
||||
data: &serde_json::Value,
|
||||
) -> AppResult<()> {
|
||||
db.conn().execute(
|
||||
"INSERT INTO events (room_id, seq, kind, data, created_at) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
rusqlite::params![room, seq, kind, data.to_string(), crate::util::now_ms()],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sends an envelope to every subscriber of `room`.
|
||||
pub fn broadcast(&self, room: &str, envelope: Envelope) {
|
||||
let buses = self.buses.lock().unwrap_or_else(|err| err.into_inner());
|
||||
if let Some(bus) = buses.get(room) {
|
||||
let _ = bus.tx.send(envelope);
|
||||
}
|
||||
}
|
||||
|
||||
/// Broadcasts a live-only event (a delta). Its sequence is allocated
|
||||
/// but never written; on reconnect the client refetches durable
|
||||
/// events and the gap is harmless.
|
||||
pub fn live(&self, db: &Db, room: &str, kind: &str, data: serde_json::Value) -> u64 {
|
||||
let bus = self.bus(db, room);
|
||||
let seq = bus.seq.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
let _ = bus.tx.send(Envelope {
|
||||
seq,
|
||||
kind: kind.to_owned(),
|
||||
data,
|
||||
});
|
||||
seq
|
||||
}
|
||||
|
||||
/// Subscribes to a room's feed.
|
||||
pub fn subscribe(&self, db: &Db, room: &str) -> broadcast::Receiver<Envelope> {
|
||||
self.bus(db, room).tx.subscribe()
|
||||
}
|
||||
}
|
||||
|
||||
/// The single application state every handler receives.
|
||||
pub struct AppState {
|
||||
pub config: Config,
|
||||
pub db: Db,
|
||||
pub secrets: Secrets,
|
||||
pub hub: Hub,
|
||||
pub rooms: RoomRunner,
|
||||
pub previews: PreviewTunnels,
|
||||
pub presence: crate::presence::Presence,
|
||||
}
|
||||
|
||||
/// The state behind an `Arc`.
|
||||
pub type Shared = Arc<AppState>;
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
//! Small helpers shared by the API and the turn runner.
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
/// 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()]
|
||||
}
|
||||
|
||||
/// `@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 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"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user