diff --git a/.env.example b/.env.example
index 133e6cb..9028c4d 100644
--- a/.env.example
+++ b/.env.example
@@ -96,11 +96,14 @@
# Enable drawing canvas in submission form. Drawings are stored as PNG files in DATA_DIR/drawings/.
# BOOK_ENABLE_DRAWINGS=false
-# Label for the drawing canvas.
-# BOOK_LABEL_DRAWING=Draw (optional):
-
# Drawing canvas width in pixels.
# BOOK_CANVAS_WIDTH=400
# Drawing canvas height in pixels.
# BOOK_CANVAS_HEIGHT=200
+
+# Enable voice note recording in submission form. Voice notes are stored as WebM files in DATA_DIR/voice_notes/.
+# BOOK_ENABLE_VOICE_NOTES=false
+
+# Maximum voice note duration in seconds. Max file size is derived as duration * 10KB.
+# BOOK_VOICE_NOTE_MAX_DURATION=20
diff --git a/Cargo.lock b/Cargo.lock
index 83157cc..9bcad99 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -458,7 +458,7 @@ dependencies = [
[[package]]
name = "guestbook"
-version = "0.2.2"
+version = "0.2.3"
dependencies = [
"axum",
"base64 0.22.1",
diff --git a/Cargo.toml b/Cargo.toml
index bb6d3a1..a6d96a5 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,8 +1,8 @@
[package]
name = "guestbook"
-version = "0.2.2"
+version = "0.2.3"
edition = "2021"
-description = "A configurable web guestbook made to be easy to use, with entries in plain text files, an optional drawing canvas, honeypots and captchas to deter spam, and moderation via Telegram bot."
+description = "A standalone guestbook to let visitors to your site leave behind written messages, drawings, and voice notes, with spam-prevention and moderation via Telegram bot."
license = "MIT"
repository = "https://git.ily.rs/lew/guestbook"
diff --git a/README.md b/README.md
index 6dc28ea..0f3e54f 100644
--- a/README.md
+++ b/README.md
@@ -3,14 +3,15 @@
`guestbook` is a self-hosted guestbook web service with:
- entries stored in plaintext,
-- optional [drawing canvas](#drawing) for visitors to sketch alongside their message,
-- notifications and moderation via [Telegram](#telegram) (including drawing previews),
+- a [drawing canvas](#drawing) for visitors to sketch alongside their message,
+- [voice notes](#voice-notes) for visitors to record a short audio clip,
+- notifications and moderation via [Telegram](#telegram),
- spam prevention via honeypot and/or [captcha](#captcha),
-- completely customisable [styling](#customisation),
+- fairly customisable [styling](#customisation),
and more, written in Rust, and inspired by [t0.vc/g](https://t0.vc/g).
-`guestbook` is a single binary that serves a single-page guestbook aimed at personal sites. There's a form for visitors to submit a name, message, and optionally a link to their own site. Visitors can also draw a picture if the drawing feature is enabled. Entries are written to plain text files with TOML frontmatter, and are initially marked as pending. The frontmatter can be manually edited to mark entries as approved or denied, or a Telegram bot can be hooked up for notifications and moderation (drawings are sent as photos so you can see them before approving). Running the Telegram bot just requires handing over a bot token, and it'll run off the same binary.
+`guestbook` is a single binary that serves a single-page guestbook aimed at personal sites. There's a form for visitors to submit a name, message, and optionally a link to their own site. Visitors can also draw a picture or leave a voice note if those features are enabled. Entries are written to plain text files with TOML frontmatter, and are initially marked as pending. The frontmatter can be manually edited to mark entries as approved or denied, or a Telegram bot can be hooked up for notifications and moderation (drawings are sent as photos and voice notes as voice messages so you can review them before approving). Running the Telegram bot just requires handing over a bot token, and it'll run off the same binary.
Everything is configured through environment variables (see [`.env.example`](#default-config) for the defaults). If you're hosting with Nix, there's a flake that can set up the `guestbook` service end-to-end, running on a systemd service with a Caddy reverse proxy. Optionally, just ignore the flake and set up all the extra stuff yourself.
@@ -182,6 +183,21 @@ Running `guestbook` with no env vars will give you a working guestbook on `local
# Supports {{title}} and {{style}} placeholders. Use "##,
- label = config.label_drawing,
w = config.canvas_width,
h = config.canvas_height,
)
@@ -88,6 +109,70 @@ pub fn render_form(config: &Config) -> String {
String::new()
};
+ let voice_note_section = if config.enable_voice_notes {
+ format!(
+ r##"add a voice note "##,
+ max_dur = config.voice_note_max_duration,
+ )
+ } else {
+ String::new()
+ };
+
format!(
r#"{prompt}
"#,
prompt = config.form_prompt,
label_name = config.label_name,
@@ -108,6 +192,7 @@ pub fn render_form(config: &Config) -> String {
th = config.textarea_height,
captcha_section = captcha_section,
drawing_section = drawing_section,
+ voice_note_section = voice_note_section,
button = config.button_text,
)
}
@@ -195,14 +280,22 @@ fn render_entry(entry: &Entry, config: &Config) -> String {
};
let drawing_html = if !entry.meta.drawing.is_empty() {
format!(
- "\n ",
+ " ",
escape_html(&entry.meta.drawing)
)
} else {
String::new()
};
+ let voice_note_html = if !entry.meta.voice_note.is_empty() {
+ format!(
+ " ",
+ escape_html(&entry.meta.voice_note)
+ )
+ } else {
+ String::new()
+ };
format!(
- "\n{header}\n{drawing_html}\n{body} \n\n{} \n",
+ "\n{header}\n{drawing_html}{voice_note_html}\n{body} \n\n{} \n",
config.separator
)
}
@@ -234,9 +327,10 @@ mod tests {
captcha_exact: false,
captcha_casesensitive: false,
enable_drawings: false,
- label_drawing: "Draw (optional):".into(),
canvas_width: 400,
canvas_height: 200,
+ enable_voice_notes: false,
+ voice_note_max_duration: 20,
template: None,
success_template: None,
separator: "---".into(),
@@ -259,6 +353,7 @@ mod tests {
date: date.into(),
website: String::new(),
drawing: String::new(),
+ voice_note: String::new(),
status: Status::Approved,
},
body: body.into(),
@@ -426,21 +521,20 @@ mod tests {
}
#[test]
- fn test_render_form_shows_canvas_when_drawings_enabled() {
+ fn test_render_form_shows_drawing_toggle_when_enabled() {
let mut config = test_config();
config.enable_drawings = true;
let form = render_form(&config);
- assert!(form.contains(""));
}
+
+ #[test]
+ fn test_render_entry_with_voice_note() {
+ let config = test_config();
+ let mut entry = make_entry("alice", "2026-04-10", "Hello!");
+ entry.meta.voice_note = "1744300800_abcd1234.webm".into();
+ let form = render_form(&config);
+ let html = render_page(DEFAULT_TEMPLATE, &config, &[entry], &form);
+ assert!(html.contains(r#""#));
+ }
+
+ #[test]
+ fn test_render_entry_voice_note_works_without_html_injection() {
+ let mut config = test_config();
+ config.enable_html_injection = false;
+ let mut entry = make_entry("alice", "2026-04-10", "");
+ entry.meta.voice_note = "1744300800_abcd1234.webm".into();
+ let form = render_form(&config);
+ let html = render_page(DEFAULT_TEMPLATE, &config, &[entry], &form);
+ assert!(html.contains(r#""#));
+ assert!(html.contains("<script>"));
+ }
+
+ #[test]
+ fn test_render_entry_without_voice_note() {
+ let config = test_config();
+ let entry = make_entry("alice", "2026-04-10", "Hello!");
+ let form = render_form(&config);
+ let html = render_page(DEFAULT_TEMPLATE, &config, &[entry], &form);
+ assert!(!html.contains(">)>) {
- while let Some((entry, drawing_bytes)) = rx.recv().await {
+pub async fn notification_task(bot: Bot, chat_id: ChatId, mut rx: Receiver<(Entry, Option>, Option>)>) {
+ while let Some((entry, drawing_bytes, voice_bytes)) = rx.recv().await {
notify(&bot, chat_id, &entry).await;
if let Some(bytes) = drawing_bytes {
if let Err(e) = bot.send_photo(
@@ -29,6 +29,14 @@ pub async fn notification_task(bot: Bot, chat_id: ChatId, mut rx: Receiver<(Entr
tracing::error!("failed to send drawing photo: {e}");
}
}
+ if let Some(bytes) = voice_bytes {
+ if let Err(e) = bot.send_voice(
+ chat_id,
+ teloxide::types::InputFile::memory(bytes).file_name("voice_note.webm"),
+ ).await {
+ tracing::error!("failed to send voice note: {e}");
+ }
+ }
}
}
diff --git a/src/web.rs b/src/web.rs
index 72abfac..0a46563 100644
--- a/src/web.rs
+++ b/src/web.rs
@@ -18,7 +18,7 @@ use crate::render::{self, DEFAULT_TEMPLATE, render_error_page, render_success_pa
pub struct AppState {
pub config: Config,
- pub tx: tokio::sync::mpsc::Sender<(Entry, Option>)>,
+ pub tx: tokio::sync::mpsc::Sender<(Entry, Option>, Option>)>,
}
#[derive(Deserialize)]
@@ -33,6 +33,8 @@ pub struct SubmitForm {
captcha: String,
#[serde(default)]
drawing: String,
+ #[serde(default)]
+ voice_note: String,
}
pub fn router(state: Arc) -> Router {
@@ -40,6 +42,7 @@ pub fn router(state: Arc) -> Router {
.route("/", get(index))
.route("/submit", post(submit))
.route("/drawings/{filename}", get(serve_drawing))
+ .route("/voice_notes/{filename}", get(serve_voice_note))
.layer(DefaultBodyLimit::max(2 * 1024 * 1024))
.with_state(state)
}
@@ -90,6 +93,33 @@ async fn serve_drawing(
}
}
+async fn serve_voice_note(
+ State(state): State>,
+ AxumPath(filename): AxumPath,
+) -> Response {
+ if !filename.ends_with(".webm")
+ || !filename[..filename.len() - 5]
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
+ {
+ return StatusCode::NOT_FOUND.into_response();
+ }
+
+ let path = state.config.data_dir.join("voice_notes").join(&filename);
+ match std::fs::read(&path) {
+ Ok(bytes) => (
+ StatusCode::OK,
+ [
+ (header::CONTENT_TYPE, "audio/webm"),
+ (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
+ ],
+ bytes,
+ )
+ .into_response(),
+ Err(_) => StatusCode::NOT_FOUND.into_response(),
+ }
+}
+
async fn submit(
State(state): State>,
Form(form): Form,
@@ -185,6 +215,34 @@ async fn submit(
None
};
+ // Process voice note if enabled and provided
+ let voice_note_bytes: Option> = if state.config.enable_voice_notes && !form.voice_note.is_empty() {
+ let b64 = form.voice_note
+ .strip_prefix("data:audio/webm;codecs=opus;base64,")
+ .unwrap_or("");
+ if b64.is_empty() {
+ None
+ } else {
+ let bytes = match base64::engine::general_purpose::STANDARD.decode(b64) {
+ Ok(b) => b,
+ Err(_) => return Html(render_error_page(&state.config, "Invalid voice note data.")),
+ };
+ let max = state.config.max_voice_note_bytes();
+ if max > 0 && bytes.len() > max {
+ return Html(render_error_page(&state.config, &format!("Voice note is too large (max {} bytes).", max)));
+ }
+
+ // Validate WebM: magic bytes
+ if bytes.len() < 4 || &bytes[..4] != b"\x1a\x45\xdf\xa3" {
+ return Html(render_error_page(&state.config, "Invalid voice note format."));
+ }
+
+ Some(bytes)
+ }
+ } else {
+ None
+ };
+
let now = chrono::Utc::now();
let epoch = now.timestamp();
let short_id = &Uuid::new_v4().to_string()[..8];
@@ -205,6 +263,20 @@ async fn submit(
} else {
String::new()
};
+
+ let voice_note_filename = if let Some(ref bytes) = voice_note_bytes {
+ let vn_name = format!("{prefix}.webm");
+ let vn_dir = state.config.data_dir.join("voice_notes");
+ std::fs::create_dir_all(&vn_dir).ok();
+ if let Err(e) = std::fs::write(vn_dir.join(&vn_name), bytes) {
+ tracing::error!("failed to write voice note: {e}");
+ return Html(render_error_page(&state.config, "Something went wrong. Please try again."));
+ }
+ vn_name
+ } else {
+ String::new()
+ };
+
let entry = Entry {
id: filename.trim_end_matches(".txt").to_string(),
meta: EntryMeta {
@@ -212,6 +284,7 @@ async fn submit(
date,
website,
drawing: drawing_filename,
+ voice_note: voice_note_filename,
status: Status::Pending,
},
body: message,
@@ -227,7 +300,7 @@ async fn submit(
}
// Notify telegram task
- let _ = state.tx.send((entry, drawing_bytes)).await;
+ let _ = state.tx.send((entry, drawing_bytes, voice_note_bytes)).await;
Html(render_success_page(&state.config))
}
@@ -262,9 +335,10 @@ mod tests {
captcha_exact: false,
captcha_casesensitive: false,
enable_drawings: false,
- label_drawing: "Draw (optional):".into(),
canvas_width: 400,
canvas_height: 200,
+ enable_voice_notes: false,
+ voice_note_max_duration: 20,
template: None,
success_template: None,
separator: "---".into(),
@@ -279,7 +353,7 @@ mod tests {
}
}
- fn test_app(config: Config) -> (Router, tokio::sync::mpsc::Receiver<(Entry, Option>)>) {
+ fn test_app(config: Config) -> (Router, tokio::sync::mpsc::Receiver<(Entry, Option>, Option>)>) {
let (tx, rx) = tokio::sync::mpsc::channel(32);
let state = Arc::new(AppState { config, tx });
(router(state), rx)
@@ -602,6 +676,12 @@ mod tests {
assert_eq!(status, StatusCode::NOT_FOUND);
}
+ fn fake_webm() -> Vec {
+ let mut webm = vec![0x1A, 0x45, 0xDF, 0xA3];
+ webm.extend_from_slice(&[0; 50]);
+ webm
+ }
+
/// Build a fake but valid PNG with the given dimensions.
fn fake_png(width: u32, height: u32) -> Vec {
let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
@@ -818,4 +898,187 @@ mod tests {
assert!(body.contains("Name and message are required"));
assert!(body.contains("back"));
}
+
+ #[tokio::test]
+ async fn test_submit_with_voice_note() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = test_config(dir.path());
+ config.enable_voice_notes = true;
+ let (app, _rx) = test_app(config);
+
+ let webm = fake_webm();
+ let voice_data = base64::engine::general_purpose::STANDARD.encode(&webm);
+ let data_url = format!("data:audio/webm;codecs=opus;base64,{voice_data}");
+ let body = format!(
+ "name=alice&message=hello&voice_note={}",
+ urlencoding::encode(&data_url)
+ );
+ let (_, resp) = post_form(&app, &body).await;
+ assert!(resp.contains("pending approval"));
+
+ let entries: Vec<_> = std::fs::read_dir(dir.path().join("entries"))
+ .unwrap()
+ .collect();
+ assert_eq!(entries.len(), 1);
+ let content = std::fs::read_to_string(entries[0].as_ref().unwrap().path()).unwrap();
+ assert!(content.contains("voice_note = "));
+
+ let voice_notes: Vec<_> = std::fs::read_dir(dir.path().join("voice_notes"))
+ .unwrap()
+ .collect();
+ assert_eq!(voice_notes.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn test_submit_without_voice_note() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = test_config(dir.path());
+ config.enable_voice_notes = true;
+ let (app, _rx) = test_app(config);
+ let (_, resp) = post_form(&app, "name=alice&message=hello").await;
+ assert!(resp.contains("pending approval"));
+
+ let vn_dir = dir.path().join("voice_notes");
+ if vn_dir.exists() {
+ let count = std::fs::read_dir(&vn_dir).unwrap().count();
+ assert_eq!(count, 0);
+ }
+ }
+
+ #[tokio::test]
+ async fn test_submit_voice_note_too_large() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = test_config(dir.path());
+ config.enable_voice_notes = true;
+ config.voice_note_max_duration = 1;
+ let (app, _rx) = test_app(config);
+
+ let mut webm = vec![0x1A, 0x45, 0xDF, 0xA3];
+ webm.extend_from_slice(&[0; 20_000]);
+ let voice_data = base64::engine::general_purpose::STANDARD.encode(&webm);
+ let data_url = format!("data:audio/webm;codecs=opus;base64,{voice_data}");
+ let body = format!(
+ "name=alice&message=hello&voice_note={}",
+ urlencoding::encode(&data_url)
+ );
+ let (_, resp) = post_form(&app, &body).await;
+ assert!(resp.contains("too large"));
+ }
+
+ #[tokio::test]
+ async fn test_submit_voice_note_rejects_non_webm() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = test_config(dir.path());
+ config.enable_voice_notes = true;
+ let (app, _rx) = test_app(config);
+
+ let voice_data = base64::engine::general_purpose::STANDARD.encode(b"not a webm file");
+ let data_url = format!("data:audio/webm;codecs=opus;base64,{voice_data}");
+ let body = format!(
+ "name=alice&message=hello&voice_note={}",
+ urlencoding::encode(&data_url)
+ );
+ let (_, resp) = post_form(&app, &body).await;
+ assert!(resp.contains("Invalid voice note"));
+ }
+
+ #[tokio::test]
+ async fn test_submit_voice_note_ignored_when_disabled() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = test_config(dir.path());
+ config.enable_voice_notes = false;
+ let (app, _rx) = test_app(config);
+
+ let webm = fake_webm();
+ let voice_data = base64::engine::general_purpose::STANDARD.encode(&webm);
+ let data_url = format!("data:audio/webm;codecs=opus;base64,{voice_data}");
+ let body = format!(
+ "name=alice&message=hello&voice_note={}",
+ urlencoding::encode(&data_url)
+ );
+ let (_, resp) = post_form(&app, &body).await;
+ assert!(resp.contains("pending approval"));
+
+ let entries: Vec<_> = std::fs::read_dir(dir.path().join("entries"))
+ .unwrap()
+ .collect();
+ let content = std::fs::read_to_string(entries[0].as_ref().unwrap().path()).unwrap();
+ assert!(content.contains("voice_note = \"\""));
+ }
+
+ #[tokio::test]
+ async fn test_serve_voice_note() {
+ let dir = tempfile::tempdir().unwrap();
+ let config = test_config(dir.path());
+ let (app, _rx) = test_app(config);
+
+ let vn_dir = dir.path().join("voice_notes");
+ std::fs::create_dir_all(&vn_dir).unwrap();
+ let webm_bytes = b"\x1a\x45\xdf\xa3fake";
+ std::fs::write(vn_dir.join("test123.webm"), webm_bytes).unwrap();
+
+ let (status, body) = get_path(&app, "/voice_notes/test123.webm").await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(body, webm_bytes);
+ }
+
+ #[tokio::test]
+ async fn test_serve_voice_note_not_found() {
+ let dir = tempfile::tempdir().unwrap();
+ let config = test_config(dir.path());
+ let (app, _rx) = test_app(config);
+
+ let (status, _) = get_path(&app, "/voice_notes/nonexistent.webm").await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+ }
+
+ #[tokio::test]
+ async fn test_serve_voice_note_rejects_path_traversal() {
+ let dir = tempfile::tempdir().unwrap();
+ let config = test_config(dir.path());
+ let (app, _rx) = test_app(config);
+
+ let (status, _) = get_path(&app, "/voice_notes/../entries/secret.txt").await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+ }
+
+ #[tokio::test]
+ async fn test_voice_note_full_roundtrip() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = test_config(dir.path());
+ config.enable_voice_notes = true;
+ let (app, _rx) = test_app(config);
+
+ // Submit with a voice note
+ let webm = fake_webm();
+ let voice_data = base64::engine::general_purpose::STANDARD.encode(&webm);
+ let data_url = format!("data:audio/webm;codecs=opus;base64,{voice_data}");
+ let body = format!(
+ "name=alice&message=hello&voice_note={}",
+ urlencoding::encode(&data_url)
+ );
+ post_form(&app, &body).await;
+
+ // Approve the entry
+ let entries_dir = dir.path().join("entries");
+ let entry_file = std::fs::read_dir(&entries_dir).unwrap().next().unwrap().unwrap();
+ let content = std::fs::read_to_string(entry_file.path()).unwrap();
+ let id = entry_file.path().file_stem().unwrap().to_str().unwrap().to_string();
+ let mut entry = entries::Entry::parse(&id, &content).unwrap();
+ entry.meta.status = entries::Status::Approved;
+ std::fs::write(entry_file.path(), entry.to_file_contents()).unwrap();
+
+ let vn_filename = entry.meta.voice_note.clone();
+ assert!(!vn_filename.is_empty(), "entry should have a voice_note filename");
+
+ // Verify index shows the voice note
+ let html = get_index(&app).await;
+ assert!(html.contains("entry-voice-note"));
+ assert!(html.contains(&format!("/voice_notes/{vn_filename}")));
+
+ // Verify the voice note file is served
+ let (status, bytes) = get_path(&app, &format!("/voice_notes/{vn_filename}")).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(bytes, webm);
+ }
}
diff --git a/templates/default.css b/templates/default.css
index d3503ca..f0fc797 100644
--- a/templates/default.css
+++ b/templates/default.css
@@ -15,7 +15,10 @@
.guestbook-textarea {
box-sizing: border-box;
}
-.guestbook-button {}
+.guestbook-button {
+ display: block;
+ margin-top: 1em;
+}
/* Drawings */
.guestbook-canvas {
@@ -29,6 +32,13 @@
.guestbook-canvas-tools a {
cursor: pointer;
}
+.guestbook-drawing-inline a {
+ cursor: pointer;
+}
+.guestbook-drawing-content {
+ display: block;
+ margin-bottom: 1em;
+}
.guestbook-swatch {
display: inline-block;
width: 0.85em;
@@ -51,6 +61,26 @@
max-width: 100%;
}
+/* Voice notes */
+.guestbook-voice-record.recording {
+ color: red;
+}
+.guestbook-voice-timer {
+ font-variant-numeric: tabular-nums;
+}
+.guestbook-voice-playback:empty {
+ display: none;
+}
+.guestbook-voice-playback {
+ display: block;
+ white-space: normal;
+}
+audio {
+ display: block;
+ margin-top: 0.6em;
+ height: 2em;
+}
+
/* Entries */
.entry-header {}
.entry-date {}