aboutsummaryrefslogtreecommitdiff
path: root/crates/chat-server/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/chat-server/src')
-rw-r--r--crates/chat-server/src/http.rs20
-rw-r--r--crates/chat-server/src/main.rs54
-rw-r--r--crates/chat-server/src/maintenance.rs61
-rw-r--r--crates/chat-server/src/store.rs13
4 files changed, 126 insertions, 22 deletions
diff --git a/crates/chat-server/src/http.rs b/crates/chat-server/src/http.rs
index bb618d9..1c7286f 100644
--- a/crates/chat-server/src/http.rs
+++ b/crates/chat-server/src/http.rs
@@ -33,6 +33,7 @@ struct App {
permits: Arc<Semaphore>,
root: PathBuf,
origin: String,
+ public: std::collections::BTreeMap<String, String>,
}
fn secured(mut response: Response) -> Response {
@@ -129,22 +130,33 @@ async fn asset(State(app): State<App>, uri: axum::http::Uri) -> Response {
"/LICENSE" => ("LICENSE", "text/plain; charset=utf-8"),
_ => return secured(StatusCode::NOT_FOUND.into_response()),
};
- tokio::fs::read(app.root.join(path)).await.map_or_else(
- |_| secured(StatusCode::NOT_FOUND.into_response()),
- |bytes| secured(([("content-type", mime)], bytes).into_response()),
- )
+ let Ok(bytes) = tokio::fs::read(app.root.join(path)).await else {
+ return secured(StatusCode::NOT_FOUND.into_response());
+ };
+ if matches!(uri.path(), "/" | "/javascript.html") {
+ let rendered = String::from_utf8(bytes)
+ .map_err(anyhow::Error::from)
+ .and_then(|source| stack_config::render(&source, &app.public));
+ return rendered.map_or_else(
+ |_| secured(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
+ |html| secured(([("content-type", mime)], html).into_response()),
+ );
+ }
+ secured(([("content-type", mime)], bytes).into_response())
}
pub(crate) async fn serve(
listener: tokio::net::TcpListener,
service: Service,
root: &Path,
+ public: std::collections::BTreeMap<String, String>,
) -> Result<()> {
let app = App {
origin: service.origin.clone(),
service: Arc::new(Mutex::new(service)),
permits: Arc::new(Semaphore::new(4)),
root: root.to_path_buf(),
+ public,
};
let routes = Router::new()
.route("/api", post(api))
diff --git a/crates/chat-server/src/main.rs b/crates/chat-server/src/main.rs
index 6c7f4e1..cfd3e7a 100644
--- a/crates/chat-server/src/main.rs
+++ b/crates/chat-server/src/main.rs
@@ -16,6 +16,7 @@
#![doc = "Local experimental chat server with ciphertext-only durable storage."]
mod http;
+mod maintenance;
mod service;
mod store;
@@ -31,10 +32,18 @@ use std::process::ExitCode;
struct Arguments {
#[arg(long, default_value = ".")]
root: PathBuf,
- #[arg(long, default_value = "127.0.0.1:9080")]
- bind: SocketAddr,
#[arg(long)]
+ bind: Option<SocketAddr>,
+ #[arg(long, conflicts_with_all = ["reset_owner", "owner_fingerprint", "snapshot"])]
init: bool,
+ #[arg(long, value_name = "FINGERPRINT", conflicts_with_all = ["owner_fingerprint", "snapshot"], help = "Permanently clear the matching owner registration and all chat history after key loss")]
+ reset_owner: Option<String>,
+ #[arg(
+ long,
+ conflicts_with = "snapshot",
+ help = "Print the registered owner's public fingerprint"
+ )]
+ owner_fingerprint: bool,
#[arg(long)]
snapshot: Option<PathBuf>,
}
@@ -64,7 +73,7 @@ fn initialize(root: &std::path::Path) -> Result<()> {
{
writeln!(file, "CHAT_ORIGIN=http://127.0.0.1:9080")?;
}
- Ok(())
+ stack_config::initialize_public(root)
}
async fn run(arguments: Arguments) -> Result<()> {
@@ -72,15 +81,28 @@ async fn run(arguments: Arguments) -> Result<()> {
if arguments.init {
return initialize(&root);
}
+ let configuration = stack_config::Config::load(&root)?;
+ let bind = arguments.bind.unwrap_or(configuration.chat_bind()?);
let data = root.join("var/data/chat");
std::fs::create_dir_all(&data)?;
std::fs::set_permissions(&data, std::os::unix::fs::PermissionsExt::from_mode(0o700))?;
let database = data.join("chat.sqlite");
- let store = store::Store::open(&database)?;
+ let _server_lock = if arguments.snapshot.is_none() && !arguments.owner_fingerprint {
+ Some(maintenance::lock(&data)?)
+ } else {
+ None
+ };
+ let mut store = store::Store::open(&database)?;
std::fs::set_permissions(
&database,
std::os::unix::fs::PermissionsExt::from_mode(0o600),
)?;
+ if arguments.owner_fingerprint {
+ return maintenance::fingerprint(&store);
+ }
+ if let Some(expected) = arguments.reset_owner {
+ return maintenance::reset(&mut store, &expected, bind);
+ }
if let Some(destination) = arguments.snapshot {
store.snapshot(&destination)?;
std::fs::set_permissions(
@@ -90,28 +112,24 @@ async fn run(arguments: Arguments) -> Result<()> {
return Ok(());
}
ensure!(
- arguments.bind.ip().is_loopback(),
+ bind.ip().is_loopback(),
"Experimental server must bind to loopback"
);
- let settings = dotenvy::from_path_iter(root.join(".env"))?
- .collect::<std::result::Result<std::collections::HashMap<_, _>, _>>()?;
- let origin = settings
- .get("CHAT_ORIGIN")
- .context("Run --init to configure chat")?;
+ let origin = configuration.value("CHAT_ORIGIN")?;
ensure!(
- origin == &format!("http://{}", arguments.bind),
- "This development server requires CHAT_ORIGIN to match its loopback bind address"
+ origin == format!("http://{bind}"),
+ "CHAT_ORIGIN must match the loopback CHAT_BIND or --bind address"
);
- let setup = settings
- .get("CHAT_SETUP_TOKEN")
- .context("Missing CHAT_SETUP_TOKEN")?;
- let state = service::Service::new(store, origin.clone(), setup.clone());
- let listener = tokio::net::TcpListener::bind(arguments.bind).await?;
+ let setup = configuration
+ .value("CHAT_SETUP_TOKEN")
+ .context("Run --init to configure chat")?;
+ let state = service::Service::new(store, origin.to_owned(), setup.to_owned());
+ let listener = tokio::net::TcpListener::bind(bind).await?;
writeln!(
std::io::stdout().lock(),
"Experimental chat: {origin} (owner setup: /#setup)"
)?;
- http::serve(listener, state, &root).await
+ http::serve(listener, state, &root, configuration.public_values(None)?).await
}
#[tokio::main]
diff --git a/crates/chat-server/src/maintenance.rs b/crates/chat-server/src/maintenance.rs
new file mode 100644
index 0000000..eac689d
--- /dev/null
+++ b/crates/chat-server/src/maintenance.rs
@@ -0,0 +1,61 @@
+// Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+use crate::store::Store;
+use anyhow::{Context, Result, ensure};
+use std::fs::{File, OpenOptions};
+use std::io::Write;
+use std::net::{SocketAddr, TcpListener};
+use std::os::unix::fs::OpenOptionsExt;
+use std::path::Path;
+
+pub(crate) fn lock(directory: &Path) -> Result<File> {
+ let file = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .mode(0o600)
+ .open(directory.join("server.lock"))?;
+ file.try_lock().context(
+ "Chat is already running. Stop it before starting another server or resetting the owner.",
+ )?;
+ Ok(file)
+}
+
+pub(crate) fn fingerprint(store: &Store) -> Result<()> {
+ let certificate = store.owner()?.context("No owner identity is registered")?;
+ writeln!(
+ std::io::stdout().lock(),
+ "{}",
+ stack_chat_crypto::public_identity(&certificate)?
+ )?;
+ Ok(())
+}
+
+pub(crate) fn reset(store: &mut Store, expected: &str, address: SocketAddr) -> Result<()> {
+ ensure!(
+ address.ip().is_loopback(),
+ "Reset must use the local chat address"
+ );
+ let _port =
+ TcpListener::bind(address).context("Stop the chat server before resetting its owner")?;
+ store.reset_owner(expected)?;
+ writeln!(
+ std::io::stdout().lock(),
+ "Owner registration and chat history cleared. Restart chat and use OWNER SETUP to create a new owner file. Existing backup archives were not changed."
+ )?;
+ Ok(())
+}
diff --git a/crates/chat-server/src/store.rs b/crates/chat-server/src/store.rs
index fce3bb3..0e09de7 100644
--- a/crates/chat-server/src/store.rs
+++ b/crates/chat-server/src/store.rs
@@ -45,6 +45,19 @@ impl Store {
Ok(())
}
+ pub(crate) fn reset_owner(&mut self, expected: &str) -> Result<()> {
+ let owner = self.owner()?.context("No owner identity is registered")?;
+ let fingerprint = stack_chat_crypto::public_identity(&owner)?;
+ ensure!(
+ expected.len() == 64 && expected.eq_ignore_ascii_case(&fingerprint),
+ "Owner fingerprint does not match; no data was cleared"
+ );
+ let transaction = self.connection.transaction()?;
+ transaction.execute_batch("DELETE FROM messages; DELETE FROM conversations; DELETE FROM metadata WHERE key='owner'; DELETE FROM sqlite_sequence WHERE name='messages';")?;
+ transaction.commit()?;
+ Ok(())
+ }
+
pub(crate) fn register(&self, id: &str, cert: &str) -> Result<()> {
if self.connection.query_row(
"SELECT EXISTS(SELECT 1 FROM conversations WHERE id=?1)",