feat: add static previews to the room pane

The preview tool could only name a port, so a static build needed a
server the terminal had to keep alive. `preview` now accepts a path:
the app reads the file or folder over the room's ssh sandbox and serves
it from a signed host, with `..` and dotfiles refused and a 16 MiB cap.

The target is stored with the room and replayed as a durable event. The
pane shows a static path with a reload control and keeps the port field
as a local fallback.
This commit is contained in:
vhaudiquet committed 2026-11-28 11:24:57 +01:00
1 parent 5be17cf4ef
commit 36de0aace7
20 files changed
+1046 -145

No files matched your search

+2 -15
View File
@@ -18,6 +18,7 @@ use crate::error::{AppError, AppResult};
use crate::models::FileEntry;
use crate::room::agent;
use crate::state::Shared;
use crate::util::safe_rel_path;
use super::rooms::member_of;
@@ -35,21 +36,7 @@ fn room_workspace(state: &Shared, room: &str) -> AppResult<(String, agent::Targe
/// 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()
})
safe_rel_path(path).map_err(AppError::bad_request)
}
async fn run(
+19 -7
View File
@@ -273,9 +273,11 @@ pub async fn detail(
let membership = member_of(&state, &id, &user.user.id)?;
let room = load_room(&state, &id)?;
let members = load_members(&state, &id)?;
let preview = crate::preview::load_target(&state, &id)?;
Ok(Json(json!({
"room": room,
"members": members,
"preview": preview,
"me": {
"id": membership.id,
"display_name": membership.display_name,
@@ -375,7 +377,8 @@ pub struct PreviewQuery {
pub port: Option<u16>,
}
/// The signed iframe URL for one port inside this room's sandbox.
/// The signed iframe URL for the room's preview, or for one port when
/// the caller names one.
pub async fn preview(
user: AuthUser,
State(state): State<Shared>,
@@ -383,12 +386,21 @@ pub async fn preview(
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 })))
let target = match query.port {
Some(0) => {
return Err(AppError::bad_request("port must be between 1 and 65535"));
}
Some(port) => crate::models::PreviewTarget::Port { port },
None => crate::preview::load_target(&state, &room)?
.ok_or_else(|| AppError::bad_request("the room has no preview yet"))?,
};
let url = match &target {
crate::models::PreviewTarget::Port { port } => {
crate::preview::url(&state.config, &state.secrets, &room, *port)?
}
_ => crate::preview::url_for_target(&state.config, &state.secrets, &room, &target)?,
};
Ok(Json(json!({ "url": url, "target": target })))
}
/// Removes a member. The owner cannot be removed.
+10
View File
@@ -120,6 +120,16 @@ CREATE TABLE IF NOT EXISTS rooms (
archived_at INTEGER
) STRICT;
CREATE TABLE IF NOT EXISTS room_previews (
room_id TEXT PRIMARY KEY REFERENCES rooms(id) ON DELETE CASCADE,
kind TEXT NOT NULL,
port INTEGER,
path TEXT,
root TEXT,
entry TEXT,
updated_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS members (
id TEXT PRIMARY KEY,
room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
+19
View File
@@ -67,6 +67,25 @@ pub struct User {
pub avatar_updated_at: Option<i64>,
}
/// What the room's preview pane shows: a port inside the sandbox, or
/// a static file or folder served by the app.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum PreviewTarget {
/// A listener inside the sandbox.
Port { port: u16 },
/// A file, or a folder with an `index.html`, read over ssh and
/// served from the signed preview host.
Static {
/// The workspace-relative path the agent named.
path: String,
/// The workspace-relative directory the URL paths resolve in.
root: String,
/// The workspace-relative file a request for `/` serves.
entry: String,
},
}
/// One server-sent event. Durable events are also rows in `events`;
/// deltas are live only.
#[derive(Debug, Clone, Serialize, Deserialize)]
+600 -43
View File
@@ -1,24 +1,33 @@
//! The preview proxy: a room's dev server, served under a signed
//! subdomain of the preview origin.
//! The preview proxy: a room's dev server or static build, 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.
//! `r<room>-p<port>-<expiry>-<sig>.<preview host>` routes to
//! 127.0.0.1:<port> inside the room's sandbox over the same ssh connection
//! settings the agent uses. `r<room>-s<hash>-<expiry>-<sig>.<preview host>`
//! serves a file or folder with `index.html` read over ssh. Paths and the
//! origin stay stable, so absolute asset URLs keep working.
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use axum::body::Body;
use axum::http::{HeaderMap, HeaderName, HeaderValue, Request, StatusCode, Uri, header};
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode, Uri, header};
use axum::response::{IntoResponse, Response};
use hyper_util::rt::TokioIo;
use percent_encoding::percent_decode_str;
use rhema_sandbox::Sandbox;
use rhema_sandbox::exec_util::shquote;
use rusqlite::OptionalExtension;
use crate::config::Config;
use crate::crypto::Secrets;
use crate::error::AppResult;
use crate::room::agent;
use crate::error::{AppError, AppResult};
use crate::models::PreviewTarget;
use crate::room::agent::{self, TargetRow};
use crate::state::Shared;
use crate::util::safe_rel_path;
/// One ssh connection per sandbox, opened lazily by the first preview
/// request and reused by the channels after it.
@@ -81,13 +90,25 @@ const PREVIEW_TTL_SECONDS: i64 = 24 * 60 * 60;
/// The signed URL for one room and port.
pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResult<String> {
url_for_target(config, secrets, room, &PreviewTarget::Port { port })
}
/// The signed URL for the room's current target.
pub fn url_for_target(
config: &Config,
secrets: &Secrets,
room: &str,
target: &PreviewTarget,
) -> AppResult<String> {
let Some((scheme, domain)) = domain(config) else {
return Err(crate::error::AppError::bad_request(
"the preview proxy is not configured",
));
return Err(AppError::bad_request("the preview proxy is not configured"));
};
let expires = crate::util::now_ms() / 1000 + PREVIEW_TTL_SECONDS;
let signature = secrets.sign(&format!("{room}:{port}:{expires}"));
let (kind, value) = match target {
PreviewTarget::Port { port } => ('p', port.to_string()),
PreviewTarget::Static { root, entry, .. } => ('s', static_key(root, entry)),
};
let signature = secrets.sign(&signature_text(room, kind, &value, expires));
let port_part = config
.preview_origin
.split_once("://")
@@ -98,25 +119,248 @@ pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResu
.map(|(_, value)| format!(":{value}"))
.unwrap_or_default();
Ok(format!(
"{scheme}://r{room}-p{port}-{expires}-{signature}.{domain}{port_part}/"
"{scheme}://r{room}-{kind}{value}-{expires}-{signature}.{domain}{port_part}/"
))
}
/// Splits `r<room>-p<port>-<expiry>-<sig>` from the Host header.
fn target_of_host(config: &Config, host: &str) -> Option<(String, u16, i64, String)> {
/// A short identity for a static target. The signed link names it, so a
/// link minted for one path stops matching after the agent points the
/// preview somewhere else.
fn static_key(root: &str, entry: &str) -> String {
crate::util::sha256_hex(format!("{root}\n{entry}").as_bytes())[..12].to_owned()
}
/// What a preview host label names.
#[derive(Debug, Clone, PartialEq, Eq)]
enum HostTarget {
Port(u16),
Static(String),
}
/// One parsed preview host label.
struct HostClaim {
room: String,
target: HostTarget,
expires: i64,
signature: String,
}
/// Splits `r<room>-p<port>-<expiry>-<sig>` or
/// `r<room>-s<hash>-<expiry>-<sig>` from the Host header.
fn target_of_host(config: &Config, host: &str) -> Option<HostClaim> {
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, rest) = rest.rsplit_once("-p")?;
let mut fields = rest.split('-');
let port: u16 = fields.next()?.parse().ok()?;
let expires: i64 = fields.next()?.parse().ok()?;
let signature = fields.next()?;
if room.is_empty() || signature.is_empty() || fields.next().is_some() {
let (room, rest) = rest.split_once('-')?;
let (target, rest) = rest.split_once('-')?;
let (expires, signature) = rest.split_once('-')?;
if room.is_empty()
|| signature.is_empty()
|| signature.contains('-')
|| !expires.chars().all(|c| c.is_ascii_digit())
{
return None;
}
Some((room.to_owned(), port, expires, signature.to_owned()))
let expires: i64 = expires.parse().ok()?;
let kind = target.chars().next()?;
let value = &target[kind.len_utf8()..];
if value.is_empty() {
return None;
}
let target = match kind {
'p' => HostTarget::Port(value.parse().ok()?),
's' if value.chars().all(|c| c.is_ascii_hexdigit()) => HostTarget::Static(value.to_owned()),
_ => return None,
};
Some(HostClaim {
room: room.to_owned(),
target,
expires,
signature: signature.to_owned(),
})
}
fn signature_text(room: &str, kind: char, value: &str, expires: i64) -> String {
match kind {
'p' => format!("{room}:{value}:{expires}"),
_ => format!("{room}:static:{value}:{expires}"),
}
}
/// The stored columns of one preview row.
type PreviewRow = (
String,
Option<i64>,
Option<String>,
Option<String>,
Option<String>,
);
/// The room's current preview target, if one is set.
pub fn load_target(state: &Shared, room: &str) -> AppResult<Option<PreviewTarget>> {
let row: Option<PreviewRow> = state
.db
.conn()
.query_row(
"SELECT kind, port, path, root, entry FROM room_previews WHERE room_id = ?1",
rusqlite::params![room],
|row| {
Ok((
row.get(0)?,
row.get(1)?,
row.get(2)?,
row.get(3)?,
row.get(4)?,
))
},
)
.optional()?;
let Some((kind, port, path, root, entry)) = row else {
return Ok(None);
};
let target = match kind.as_str() {
"port" => PreviewTarget::Port {
port: u16::try_from(port.unwrap_or(0))
.map_err(|_| AppError::internal("the saved preview port is invalid"))?,
},
"static" => PreviewTarget::Static {
path: path.ok_or_else(|| AppError::internal("the saved preview has no path"))?,
root: root.ok_or_else(|| AppError::internal("the saved preview has no root"))?,
entry: entry.ok_or_else(|| AppError::internal("the saved preview has no entry"))?,
},
_ => return Err(AppError::internal("the saved preview kind is unknown")),
};
Ok(Some(target))
}
/// Stores a target without announcing it.
pub fn store_target(state: &Shared, room: &str, target: &PreviewTarget) -> AppResult<()> {
let (kind, port, path, root, entry) = match target {
PreviewTarget::Port { port } => ("port", Some(i64::from(*port)), None, None, None),
PreviewTarget::Static { path, root, entry } => (
"static",
None,
Some(path.as_str()),
Some(root.as_str()),
Some(entry.as_str()),
),
};
state.db.conn().execute(
"INSERT INTO room_previews (room_id, kind, port, path, root, entry, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
ON CONFLICT(room_id) DO UPDATE SET
kind = excluded.kind,
port = excluded.port,
path = excluded.path,
root = excluded.root,
entry = excluded.entry,
updated_at = excluded.updated_at",
rusqlite::params![room, kind, port, path, root, entry, crate::util::now_ms()],
)?;
Ok(())
}
/// Stores a target and adds it to the room log, so every open pane and
/// every later reconnect learns about it.
pub fn publish(state: &Shared, room: &str, target: &PreviewTarget) -> AppResult<()> {
store_target(state, room, target)?;
state
.hub
.durable(&state.db, room, "preview", serde_json::to_value(target)?)?;
Ok(())
}
/// Validates a workspace path for the static preview and answers the
/// target to store. A folder must have an `index.html`; a file is served
/// as itself and its parent becomes the asset root.
pub async fn static_target(
state: &Shared,
workspace: &str,
sandbox_target: &TargetRow,
path: &str,
) -> Result<PreviewTarget, String> {
let rel = visible_rel_path(path)?;
let abs = workspace_path(workspace, &rel);
let index = if rel == "." {
format!("{}/index.html", workspace.trim_end_matches('/'))
} else {
format!("{}/{rel}/index.html", workspace.trim_end_matches('/'))
};
let command = format!(
"if [ -d {p} ]; then \
if [ -f {i} ]; then printf 'dir'; else printf 'noindex'; fi; \
elif [ -f {p} ]; then printf 'file'; else printf 'missing'; fi",
p = shquote(&abs),
i = shquote(&index)
);
let sandbox = agent::sandbox_for(state, workspace, sandbox_target).map_err(|e| e.message)?;
let cancelled = AtomicBool::new(false);
let mut progress = rhema_sandbox::OutputOnly(|_| {});
let outcome = sandbox
.run(
rhema_sandbox::RunRequest {
command,
cwd: workspace.into(),
timeout: Duration::from_secs(15),
env: Default::default(),
},
&cancelled,
&mut progress,
)
.await
.map_err(|err| err.to_string())?;
let kind = String::from_utf8_lossy(&outcome.stdout).trim().to_owned();
match kind.as_str() {
"dir" => {
let entry = if rel == "." {
"index.html".to_owned()
} else {
format!("{rel}/index.html")
};
Ok(PreviewTarget::Static {
path: rel.clone(),
root: rel,
entry,
})
}
"file" => {
let root = rel
.rsplit_once('/')
.map(|(parent, _)| parent.to_owned())
.unwrap_or_else(|| ".".to_owned());
Ok(PreviewTarget::Static {
path: rel.clone(),
root,
entry: rel,
})
}
"noindex" => Err(format!("{rel} has no index.html to serve")),
"missing" => Err(format!("{rel} does not exist in the workspace")),
_ => Err(format!("could not inspect {rel} in the workspace")),
}
}
/// A static target must not name a hidden file or folder. The request
/// side refuses dotfiles too, but checking here stops a model from
/// publishing `.env` or `.git` as the entry.
fn visible_rel_path(path: &str) -> Result<String, String> {
let rel = safe_rel_path(path)?;
if rel
.split('/')
.any(|part| part != "." && part.starts_with('.') && part != ".well-known")
{
return Err("the preview cannot point at a hidden file or folder".into());
}
Ok(rel)
}
fn workspace_path(workspace: &str, rel: &str) -> String {
if rel == "." {
workspace.trim_end_matches('/').to_owned()
} else {
format!("{}/{}", workspace.trim_end_matches('/'), rel)
}
}
fn signatures_match(a: &str, b: &str) -> bool {
@@ -130,6 +374,18 @@ fn signatures_match(a: &str, b: &str) -> bool {
diff == 0
}
fn frame_ancestors(config: &Config, mut response: Response) -> Response {
if let Ok(value) = HeaderValue::from_str(&format!(
"frame-ancestors {}",
config.public_url.trim_end_matches('/')
)) {
response
.headers_mut()
.insert(header::CONTENT_SECURITY_POLICY, value);
}
response
}
fn no_referrer(mut response: Response) -> Response {
response.headers_mut().insert(
header::REFERRER_POLICY,
@@ -138,8 +394,8 @@ fn no_referrer(mut response: Response) -> Response {
response
}
/// Verifies the signature in the Host header against the room and port
/// it names, then proxies the request.
/// Verifies the signed label against the target it names, then serves
/// that target.
pub async fn proxy(state: Shared, request: Request<Body>) -> Response {
let host = request
.headers()
@@ -147,25 +403,37 @@ pub async fn proxy(state: Shared, request: Request<Body>) -> Response {
.and_then(|value| value.to_str().ok())
.unwrap_or("")
.to_owned();
let Some((room, port, expires, signature)) = target_of_host(&state.config, &host) else {
let Some(claim) = target_of_host(&state.config, &host) else {
return (StatusCode::NOT_FOUND, "not a preview host").into_response();
};
if expires < crate::util::now_ms() / 1000 {
if claim.expires < crate::util::now_ms() / 1000 {
return (StatusCode::NOT_FOUND, "this preview link has expired").into_response();
}
let expected = state.secrets.sign(&format!("{room}:{port}:{expires}"));
if !signatures_match(&signature, &expected) {
let (kind, value) = match &claim.target {
HostTarget::Port(port) => ('p', port.to_string()),
HostTarget::Static(key) => ('s', key.clone()),
};
let expected = state
.secrets
.sign(&signature_text(&claim.room, kind, &value, claim.expires));
if !signatures_match(&claim.signature, &expected) {
return (StatusCode::NOT_FOUND, "not a preview host").into_response();
}
match try_proxy(&state, &room, port, request).await {
Ok(response) => no_referrer(response),
Err(message) => no_referrer(
(
StatusCode::BAD_GATEWAY,
format!("the preview did not answer: {message}"),
)
.into_response(),
),
match claim.target {
HostTarget::Port(port) => match try_proxy(&state, &claim.room, port, request).await {
Ok(response) => no_referrer(frame_ancestors(&state.config, response)),
Err(message) => no_referrer(
(
StatusCode::BAD_GATEWAY,
format!("the preview did not answer: {message}"),
)
.into_response(),
),
},
HostTarget::Static(key) => match try_static(&state, &claim.room, &key, request).await {
Ok(response) => no_referrer(response),
Err((status, message)) => no_referrer((status, message).into_response()),
},
}
}
@@ -246,6 +514,187 @@ async fn try_proxy(
Ok(no_referrer(out))
}
/// The largest static file the preview serves. The sandbox read caps at
/// 32 MiB; this leaves room for the status line and keeps one request
/// from holding a whole build artifact in memory.
const STATIC_MAX_BYTES: usize = 16 * 1024 * 1024;
/// Serves one request from a static target over the room's ssh sandbox.
async fn try_static(
state: &Shared,
room: &str,
key: &str,
request: Request<Body>,
) -> Result<Response, (StatusCode, String)> {
let target = load_target(state, room)
.map_err(|err| (StatusCode::BAD_GATEWAY, err.message))?
.ok_or_else(|| (StatusCode::NOT_FOUND, "this room has no preview".to_owned()))?;
let PreviewTarget::Static { root, entry, .. } = target else {
return Err((
StatusCode::NOT_FOUND,
"this preview link no longer matches the room".to_owned(),
));
};
if static_key(&root, &entry) != key {
return Err((
StatusCode::NOT_FOUND,
"this preview link no longer matches the room".to_owned(),
));
}
let method = request.method();
if method != Method::GET && method != Method::HEAD {
return Err((
StatusCode::METHOD_NOT_ALLOWED,
"the static preview only answers GET and HEAD".to_owned(),
));
}
let rel = static_request_path(request.uri(), &root, &entry)?;
let (workspace, sandbox_target) = agent::load_room_target(state, room)
.map_err(|err| (StatusCode::BAD_GATEWAY, err.message))?;
let abs = workspace_path(&workspace, &rel);
let sandbox = agent::sandbox_for(state, &workspace, &sandbox_target)
.map_err(|err| (StatusCode::BAD_GATEWAY, err.message))?;
let cancelled = AtomicBool::new(false);
let mut progress = rhema_sandbox::OutputOnly(|_| {});
let outcome = sandbox
.run(
rhema_sandbox::RunRequest {
command: static_read_command(&abs),
cwd: workspace.into(),
timeout: Duration::from_secs(20),
env: Default::default(),
},
&cancelled,
&mut progress,
)
.await
.map_err(|err| (StatusCode::BAD_GATEWAY, err.to_string()))?;
let read = parse_static_output(outcome.stdout).ok_or_else(|| {
(
StatusCode::BAD_GATEWAY,
"the static preview returned no status".to_owned(),
)
})?;
let body = match read {
StaticRead::Body(body) => body,
StaticRead::Missing => {
return Err((StatusCode::NOT_FOUND, "file not found".to_owned()));
}
StaticRead::Large => {
return Err((
StatusCode::PAYLOAD_TOO_LARGE,
"this file is too large for the static preview".to_owned(),
));
}
};
let length = body.len();
let body = if method == Method::HEAD {
Body::empty()
} else {
Body::from(body)
};
let frame_ancestors = format!(
"frame-ancestors {}",
state.config.public_url.trim_end_matches('/')
);
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, content_type(&rel))
.header(header::CONTENT_LENGTH, length)
.header(header::CACHE_CONTROL, "no-store")
.header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
.header(header::CONTENT_SECURITY_POLICY, frame_ancestors)
.body(body)
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))
}
/// Maps a request path onto the static root, refusing escapes and
/// dotfiles. A trailing slash asks for that directory's `index.html`.
fn static_request_path(uri: &Uri, root: &str, entry: &str) -> Result<String, (StatusCode, String)> {
let decoded = percent_decode_str(uri.path())
.decode_utf8()
.map_err(|_| (StatusCode::NOT_FOUND, "file not found".to_owned()))?;
let raw = decoded.trim_start_matches('/');
if raw.is_empty() {
return Ok(entry.to_owned());
}
if raw.contains('\0') {
return Err((StatusCode::NOT_FOUND, "file not found".to_owned()));
}
let trailing = raw.ends_with('/');
let mut parts = Vec::new();
for part in raw.split('/') {
if part.is_empty() || part == "." {
continue;
}
if part == ".." {
return Err((StatusCode::NOT_FOUND, "file not found".to_owned()));
}
if part.starts_with('.') && part != ".well-known" {
return Err((StatusCode::NOT_FOUND, "file not found".to_owned()));
}
parts.push(part);
}
if trailing {
parts.push("index.html");
}
let rel = parts.join("/");
if rel.is_empty() {
return Ok(entry.to_owned());
}
Ok(if root == "." {
rel
} else {
format!("{root}/{rel}")
})
}
fn static_read_command(path: &str) -> String {
format!(
"p={q}; if [ ! -f \"$p\" ]; then printf 'missing'; exit 0; fi; \
s=$(stat -c %s -- \"$p\" 2>/dev/null) || {{ printf 'missing'; exit 0; }}; \
if [ \"$s\" -gt {max} ]; then printf 'large'; exit 0; fi; \
printf 'ok\\n'; cat -- \"$p\"",
q = shquote(path),
max = STATIC_MAX_BYTES
)
}
enum StaticRead {
Body(Vec<u8>),
Missing,
Large,
}
fn parse_static_output(stdout: Vec<u8>) -> Option<StaticRead> {
let boundary = stdout.iter().position(|byte| *byte == b'\n');
let (head, body) = match boundary {
Some(index) => (&stdout[..index], stdout[index + 1..].to_vec()),
None => (&stdout[..], Vec::new()),
};
match head {
b"ok" => Some(StaticRead::Body(body)),
b"missing" => Some(StaticRead::Missing),
b"large" => Some(StaticRead::Large),
_ => None,
}
}
fn content_type(path: &str) -> HeaderValue {
let mime = mime_guess::from_path(path).first_or_octet_stream();
let mut value = mime.to_string();
if value.starts_with("text/")
|| matches!(
value.as_str(),
"application/javascript" | "application/json" | "application/xml" | "image/svg+xml"
)
{
value.push_str("; charset=utf-8");
}
HeaderValue::from_str(&value)
.unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"))
}
fn strip_hop_by_hop(headers: &mut HeaderMap) {
for name in [
header::CONNECTION,
@@ -288,11 +737,56 @@ mod tests {
.split('/')
.next()
.expect("host");
let (room, port, expires, signature) = target_of_host(&config, host).expect("parsed host");
assert_eq!(room, "room123");
assert_eq!(port, 5173);
assert!(expires >= crate::util::now_ms() / 1000);
assert_eq!(signature, secrets.sign(&format!("room123:5173:{expires}")));
let claim = target_of_host(&config, host).expect("parsed host");
assert_eq!(claim.room, "room123");
assert_eq!(claim.target, HostTarget::Port(5173));
assert!(claim.expires >= crate::util::now_ms() / 1000);
assert_eq!(
claim.signature,
secrets.sign(&format!("room123:5173:{}", claim.expires))
);
let _ = std::fs::remove_file(path);
}
#[test]
fn a_static_target_refuses_hidden_paths() {
assert!(visible_rel_path(".env").is_err());
assert!(visible_rel_path(".git/config").is_err());
assert!(visible_rel_path("dist/../.env").is_err());
assert_eq!(visible_rel_path("dist").unwrap(), "dist");
assert_eq!(visible_rel_path(".").unwrap(), ".");
assert_eq!(visible_rel_path(".well-known").unwrap(), ".well-known");
}
#[test]
fn a_static_host_carries_the_target_and_signature() {
let config = Config {
preview_origin: "https://preview.example.com".into(),
..Default::default()
};
let (secrets, path) = secrets();
let target = PreviewTarget::Static {
path: "web/dist".into(),
root: "web/dist".into(),
entry: "web/dist/index.html".into(),
};
let url = url_for_target(&config, &secrets, "room123", &target).expect("url");
let host = url
.trim_start_matches("https://")
.split('/')
.next()
.expect("host");
let claim = target_of_host(&config, host).expect("parsed host");
assert_eq!(claim.room, "room123");
assert_eq!(
claim.signature,
secrets.sign(&format!(
"room123:static:{}:{}",
static_key("web/dist", "web/dist/index.html"),
claim.expires
))
);
assert!(matches!(claim.target, HostTarget::Static(_)));
let _ = std::fs::remove_file(path);
}
@@ -311,6 +805,69 @@ mod tests {
);
}
#[test]
fn static_paths_stay_inside_the_root() {
let uri: Uri = "/assets/app.js?version=2".parse().unwrap();
assert_eq!(
static_request_path(&uri, "dist", "dist/index.html").unwrap(),
"dist/assets/app.js"
);
let uri: Uri = "/".parse().unwrap();
assert_eq!(
static_request_path(&uri, "dist", "dist/index.html").unwrap(),
"dist/index.html"
);
let uri: Uri = "/docs/".parse().unwrap();
assert_eq!(
static_request_path(&uri, "dist", "dist/index.html").unwrap(),
"dist/docs/index.html"
);
let uri: Uri = "/../secret".parse().unwrap();
assert!(static_request_path(&uri, "dist", "dist/index.html").is_err());
let uri: Uri = "/%2e%2e/secret".parse().unwrap();
assert!(static_request_path(&uri, "dist", "dist/index.html").is_err());
let uri: Uri = "/.env".parse().unwrap();
assert!(static_request_path(&uri, "dist", "dist/index.html").is_err());
}
#[test]
fn a_single_file_uses_its_parent_as_the_root() {
let uri: Uri = "/".parse().unwrap();
assert_eq!(
static_request_path(&uri, ".", "index.html").unwrap(),
"index.html"
);
let uri: Uri = "/style.css".parse().unwrap();
assert_eq!(
static_request_path(&uri, ".", "index.html").unwrap(),
"style.css"
);
}
#[test]
fn static_reads_split_the_status_from_the_body() {
assert!(matches!(
parse_static_output(b"ok\n<html></html>".to_vec()),
Some(StaticRead::Body(body)) if body == b"<html></html>"
));
assert!(matches!(
parse_static_output(b"missing".to_vec()),
Some(StaticRead::Missing)
));
assert!(matches!(
parse_static_output(b"large".to_vec()),
Some(StaticRead::Large)
));
assert!(parse_static_output(Vec::new()).is_none());
}
#[test]
fn text_types_get_a_charset() {
assert_eq!(content_type("index.html"), "text/html; charset=utf-8");
assert_eq!(content_type("app.js"), "text/javascript; charset=utf-8");
assert_eq!(content_type("logo.png"), "image/png");
}
#[test]
fn signatures_compare_by_value() {
assert!(signatures_match("abcd", "abcd"));
+6 -2
View File
@@ -8,7 +8,7 @@ use std::sync::Arc;
use base64::Engine;
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::request::ThinkingEffort;
use rhema_core::{Session, ToolResolver};
use rhema_core::{Overlay, Session, ToolResolver};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_sandbox::WorkspaceSeed;
use rhema_sandbox::{Sandbox, ShellSandbox};
@@ -18,6 +18,7 @@ use crate::error::{AppError, AppResult};
use crate::state::Shared;
use super::message_tool::MessageTool;
use super::preview_tool::PreviewTool;
/// The room and its configuration, read fresh for every turn.
pub struct TurnConfig {
@@ -310,6 +311,9 @@ pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> App
.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 preview_tool: Arc<dyn ToolResolver> =
Arc::new(PreviewTool::new(state.clone(), config.room_id.clone()));
let extra_tools: Arc<dyn ToolResolver> = Arc::new(Overlay::new(message_tool, preview_tool));
let max_turn_steps =
NonZeroU32::new(config.max_turn_steps).unwrap_or(NonZeroU32::new(48).unwrap());
let mut sections = BTreeMap::new();
@@ -330,7 +334,7 @@ pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> App
max_turn_steps,
thinking: ThinkingEffort::Default,
tools: Some(shell),
extra_resolver: Some(message_tool),
extra_resolver: Some(extra_tools),
shell_env: Default::default(),
transcript: Some(Default::default()),
summary_worker: None,
+1
View File
@@ -79,4 +79,5 @@ impl RoomRunner {
pub mod agent;
pub mod message_tool;
pub mod preview_tool;
pub mod runner;
+110
View File
@@ -0,0 +1,110 @@
//! The `preview` tool: point the room's pane at a port or a static build.
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::models::PreviewTarget;
use crate::state::Shared;
use super::agent;
/// The resolver handed to the agent beside `message`.
pub struct PreviewTool {
state: Shared,
room: String,
}
impl PreviewTool {
/// A tool pointing `room`'s preview.
pub fn new(state: Shared, room: String) -> Self {
Self { state, room }
}
}
#[async_trait]
impl ToolResolver for PreviewTool {
fn specs(&self) -> Vec<ToolSpec> {
vec![ToolSpec::new(
"preview",
"Point the room's preview pane at what you changed. Use `path` for a \
static page (an HTML file, or a folder with index.html): the app reads \
it over ssh and serves it, no server needed. Use `port` for a dev server \
already listening in the sandbox. Set exactly one. Point a static preview \
at a build folder, not the repository root, unless the whole tree is meant \
to be public.",
json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "A workspace-relative HTML file or folder with index.html."
},
"port": {
"type": "integer",
"minimum": 1,
"maximum": 65535,
"description": "A port listening on 127.0.0.1 inside the sandbox."
}
}
}),
)]
}
fn replay_safety(&self, _name: &str) -> ReplaySafety {
ReplaySafety::Unsafe
}
async fn resolve(&self, call: ToolCall, _ctx: &ToolContext) -> ToolResult {
let port = match call.args.get("port") {
None | Some(serde_json::Value::Null) => None,
Some(value) => match value.as_u64().and_then(|port| u16::try_from(port).ok()) {
Some(port) if port > 0 => Some(port),
_ => return ToolResult::failure(call.id, "`port` must be between 1 and 65535"),
},
};
let path = match call.args.get("path") {
None | Some(serde_json::Value::Null) => None,
Some(value) => match value.as_str() {
Some(text) if !text.trim().is_empty() => Some(text.trim().to_owned()),
_ => return ToolResult::failure(call.id, "`path` must be a non-empty string"),
},
};
let target = match (port, path) {
(Some(port), None) => PreviewTarget::Port { port },
(None, Some(path)) => {
let (workspace, sandbox_target) =
match agent::load_room_target(&self.state, &self.room) {
Ok(found) => found,
Err(err) => return ToolResult::failure(call.id, err.message),
};
match crate::preview::static_target(&self.state, &workspace, &sandbox_target, &path)
.await
{
Ok(target) => target,
Err(message) => return ToolResult::failure(call.id, message),
}
}
(Some(_), Some(_)) => {
return ToolResult::failure(call.id, "set `path` or `port`, not both");
}
(None, None) => {
return ToolResult::failure(call.id, "set `path` or `port`");
}
};
if let Err(err) = crate::preview::publish(&self.state, &self.room, &target) {
return ToolResult::failure(
call.id,
format!("could not open the preview: {}", err.message),
);
}
let answer = match &target {
PreviewTarget::Port { port } => format!("The room preview now shows port {port}."),
PreviewTarget::Static { path, .. } => {
format!("The room preview now serves {path}.")
}
};
ToolResult::success(call.id, answer)
}
}
+13
View File
@@ -27,6 +27,19 @@ 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.
## Preview
When what you changed is visible, point the room at it with the `preview`
tool. Use `path` for a static page: an HTML file, or a folder with an
`index.html`. The app reads it over ssh and serves it, so there is no server
to start and nothing to keep alive. Point at a build folder, not the whole
repository, unless every file in the tree is meant to be readable through the
preview link.
Use `port` for a dev server that is already listening on 127.0.0.1 in the
sandbox. Set one of `path` or `port`, never both. The pane opens it for
everyone in the room.
{% if tools %}
## Tools
+35
View File
@@ -42,6 +42,23 @@ pub fn member_color(index: usize) -> &'static str {
COLORS[index % COLORS.len()]
}
/// A workspace-relative path with no escape. Empty names the root.
pub fn safe_rel_path(path: &str) -> Result<String, String> {
let trimmed = path.trim();
if trimmed.starts_with('/') {
return Err("path must be relative to the workspace".into());
}
let normalized = trimmed.trim_matches('/');
if normalized.split('/').any(|part| part == "..") {
return Err("path escapes the workspace".into());
}
Ok(if normalized.is_empty() {
".".to_owned()
} else {
normalized.to_owned()
})
}
/// `@rhema` in any case, as a whole word.
pub fn mentions_agent(text: &str) -> bool {
let lower = text.to_lowercase();
@@ -67,6 +84,24 @@ pub fn mentions_agent(text: &str) -> bool {
mod tests {
use super::*;
#[test]
fn relative_paths_stay_under_the_workspace() {
assert_eq!(safe_rel_path("").unwrap(), ".");
assert_eq!(safe_rel_path("web/dist").unwrap(), "web/dist");
assert_eq!(
safe_rel_path("/web/dist/").unwrap_err(),
"path must be relative to the workspace"
);
assert_eq!(
safe_rel_path("web/../secret").unwrap_err(),
"path escapes the workspace"
);
assert_eq!(
safe_rel_path("..").unwrap_err(),
"path escapes the workspace"
);
}
#[test]
fn mentions_need_a_word_boundary() {
assert!(mentions_agent("@rhema fix this"));