feat: add account avatars and a deployable image

Accounts get a profile page with an uploaded picture, shown in the
sidebar, the room bar, and every human message. Pictures live in the
SQLite database and are served through an authenticated route.

Hardening from the security audit: preview hosts expire after 24 hours
and carry no-referrer; removing a member or archiving a room ends their
event feed, presence socket, and terminal within seconds; previews and
the terminal pin the SSH host key; invites are claimed atomically;
missing accounts spend the same argon2 time as wrong passwords;
registration is closed by default; WebSockets check the origin; and the
master key is created with mode 0600.

The Dockerfile builds one image with the static client and the server.
The Helm chart runs a single replica with a SQLite volume, a wildcard
preview ingress, and the proxy settings the event feed and uploads
need. It refuses more than one replica because state is in process.
This commit is contained in:
vhaudiquet committed 2026-11-28 02:07:26 +01:00
1 parent 7e7a1d2bb6
commit 3b82719d56
38 files changed
+1307 -106

No files matched your search

+111 -22
View File
@@ -43,7 +43,7 @@ impl PreviewTunnels {
.insert(target.to_owned(), handle);
}
fn forget(&self, target: &str) {
pub(crate) fn forget(&self, target: &str) {
self.handles
.lock()
.unwrap_or_else(|err| err.into_inner())
@@ -75,6 +75,10 @@ pub fn is_preview_host(config: &Config, host: &str) -> bool {
name.ends_with(&format!(".{domain}"))
}
/// How long a preview host stays valid. The browser keeps using the
/// host it was given; a reload of the room mints a fresh one.
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> {
let Some((scheme, domain)) = domain(config) else {
@@ -82,7 +86,8 @@ pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResu
"the preview proxy is not configured",
));
};
let signature = secrets.sign(&format!("{room}:{port}"));
let expires = crate::util::now_ms() / 1000 + PREVIEW_TTL_SECONDS;
let signature = secrets.sign(&format!("{room}:{port}:{expires}"));
let port_part = config
.preview_origin
.split_once("://")
@@ -93,23 +98,44 @@ 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}-{signature}.{domain}{port_part}/"
"{scheme}://r{room}-p{port}-{expires}-{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)> {
/// Splits `r<room>-p<port>-<expiry>-<sig>` from the Host header.
fn target_of_host(config: &Config, host: &str) -> Option<(String, u16, i64, 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() {
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() {
return None;
}
let port: u16 = port.parse().ok()?;
Some((room.to_owned(), port, signature.to_owned()))
Some((room.to_owned(), port, expires, signature.to_owned()))
}
fn signatures_match(a: &str, b: &str) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (left, right) in a.as_bytes().iter().zip(b.as_bytes()) {
diff |= left ^ right;
}
diff == 0
}
fn no_referrer(mut response: Response) -> Response {
response.headers_mut().insert(
header::REFERRER_POLICY,
HeaderValue::from_static("no-referrer"),
);
response
}
/// Verifies the signature in the Host header against the room and port
@@ -121,20 +147,25 @@ 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, signature)) = target_of_host(&state.config, &host) else {
let Some((room, port, expires, 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 {
if 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) {
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(),
Ok(response) => no_referrer(response),
Err(message) => no_referrer(
(
StatusCode::BAD_GATEWAY,
format!("the preview did not answer: {message}"),
)
.into_response(),
),
}
}
@@ -153,7 +184,9 @@ async fn try_proxy(
let handle = match state.previews.get(&target.id) {
Some(handle) => handle,
None => {
let handle = Arc::new(crate::ssh::connect_handle(&target, &key).await?);
let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?;
crate::ssh::remember_host_key(state, &target, learned);
let handle = Arc::new(handle);
state.previews.put(&target.id, handle.clone());
handle
}
@@ -165,7 +198,9 @@ async fn try_proxy(
Ok(channel) => channel,
Err(_) => {
state.previews.forget(&target.id);
let handle = Arc::new(crate::ssh::connect_handle(&target, &key).await?);
let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?;
crate::ssh::remember_host_key(state, &target, learned);
let handle = Arc::new(handle);
state.previews.put(&target.id, handle.clone());
handle
.channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0)
@@ -208,7 +243,7 @@ async fn try_proxy(
*out.status_mut() = parts.status;
*out.headers_mut() = parts.headers;
strip_hop_by_hop(out.headers_mut());
Ok(out)
Ok(no_referrer(out))
}
fn strip_hop_by_hop(headers: &mut HeaderMap) {
@@ -225,3 +260,57 @@ fn strip_hop_by_hop(headers: &mut HeaderMap) {
headers.remove(name);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
fn secrets() -> (Secrets, std::path::PathBuf) {
let path = std::env::temp_dir().join(format!(
"rhema-together-preview-test-{}.key",
crate::util::random_id(10)
));
let secrets = Secrets::load_or_create(&path).expect("test key");
(secrets, path)
}
#[test]
fn a_preview_host_carries_room_port_expiry_and_signature() {
let mut config = Config::default();
config.preview_origin = "https://preview.example.com".into();
let (secrets, path) = secrets();
let url = url(&config, &secrets, "room123", 5173).expect("url");
let host = url
.trim_start_matches("https://")
.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 _ = std::fs::remove_file(path);
}
#[test]
fn the_old_host_shape_is_not_accepted() {
let mut config = Config::default();
config.preview_origin = "https://preview.example.com".into();
assert!(
target_of_host(
&config,
"rroom123-p5173-0123456789abcdef01234567.preview.example.com"
)
.is_none()
);
}
#[test]
fn signatures_compare_by_value() {
assert!(signatures_match("abcd", "abcd"));
assert!(!signatures_match("abcd", "abce"));
assert!(!signatures_match("abcd", "abc"));
}
}