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
@@ -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() }))),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user