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
+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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user