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