1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
|
//! Website Contact Form
// 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 axum::{
extract::{Form, State},
response::Html,
routing::post,
Router,
};
use chrono::Utc;
use serde::Deserialize;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::Arc;
#[derive(Clone)]
struct AppConfig {
bind_addr: String,
cert_path: PathBuf,
inbox_dir: PathBuf,
sq_bin: PathBuf,
}
impl AppConfig {
fn from_env() -> Self {
let home = std::env::var("HOME").unwrap_or_else(|_| "/home/ops".into());
Self {
bind_addr: std::env::var("BIND_ADDR").unwrap_or_else(|_| "0.0.0.0:8085".into()),
cert_path: PathBuf::from(
std::env::var("CERT_PATH")
.unwrap_or_else(|_| format!("{}/stack/contact-cert.pgp", home)),
),
inbox_dir: PathBuf::from(
std::env::var("INBOX_DIR")
.unwrap_or_else(|_| format!("{}/stack/inbox", home)),
),
sq_bin: PathBuf::from(
std::env::var("SQ_BIN")
.unwrap_or_else(|_| format!("{}/.cargo/bin/sq", home)),
),
}
}
}
#[derive(Deserialize)]
struct ContactForm {
sender: Option<String>,
message: String,
}
#[tokio::main]
async fn main() {
let config = Arc::new(AppConfig::from_env());
let app = Router::new()
.route("/send-message", post(handle_message))
.with_state(config.clone());
let listener = tokio::net::TcpListener::bind(&config.bind_addr)
.await
.unwrap_or_else(|_| panic!("Failed to bind to {}", config.bind_addr));
println!("Contact backend listening on http://{}", config.bind_addr);
println!("Using PQC Cert: {:?}", config.cert_path);
println!("Storing inbox in: {:?}", config.inbox_dir);
axum::serve(listener, app).await.unwrap();
}
async fn handle_message(
State(config): State<Arc<AppConfig>>,
Form(form): Form<ContactForm>,
) -> Html<&'static str> {
let message = form.message.trim();
if message.is_empty() {
return Html(ERROR_PAGE);
}
let raw_sender = form.sender.as_deref().unwrap_or("").trim();
let sender_display = if raw_sender.is_empty() {
"Anonymous"
} else {
raw_sender
};
let now = Utc::now();
let timestamp_str = now.format("%Y-%m-%d_%H-%M-%S").to_string();
let sanitized_sender: String = raw_sender
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
.take(30)
.collect();
let filename = if sanitized_sender.is_empty() {
format!("{}.pgp", timestamp_str)
} else {
format!("{}_{}.pgp", timestamp_str, sanitized_sender)
};
let output_path = config.inbox_dir.join(filename);
let payload = format!(
"=== BEGIN MESSAGE ===\nSender: {}\nTimestamp: {}\n============================\n\n{}",
sender_display,
now.to_rfc3339(),
message
);
let mut child = match Command::new(&config.sq_bin)
.args([
"encrypt",
"--for-file",
config.cert_path.to_str().unwrap_or_default(),
"--without-signature",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
{
Ok(proc) => proc,
Err(e) => {
eprintln!("Failed to spawn sq binary ({:?}): {}", config.sq_bin, e);
return Html(ERROR_PAGE);
}
};
if let Some(mut stdin) = child.stdin.take() {
if stdin.write_all(payload.as_bytes()).is_err() {
return Html(ERROR_PAGE);
}
}
let output = match child.wait_with_output() {
Ok(out) => out,
Err(_) => return Html(ERROR_PAGE),
};
if !output.status.success() {
eprintln!(
"sq encryption failed: {}",
String::from_utf8_lossy(&output.stderr)
);
return Html(ERROR_PAGE);
}
if std::fs::write(&output_path, &output.stdout).is_err() {
eprintln!("Failed to write to file {:?}", output_path);
return Html(ERROR_PAGE);
}
Html(SUCCESS_PAGE)
}
const SUCCESS_PAGE: &str = r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Message Sent</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<div id="page">
<div class="badge">[ JS-free ]</div>
<div id="content">
<pre>
<a href="/" class="logo">
____ ___ _ _ _
| _ \ / _ \ / \ | \ | |
| | | | | | |/ _ \ | \| |
| |_| | |_| / ___ \| |\ |
|____/ \___/_/ \_\_| \_| LUU DUC TAI
</a>
+------------------------------------------------------------------------------+
| [+] Success: Message encrypted and delivered to inbox. |
+------------------------------------------------------------------------------+
<a href="/"><-- Return to Home Page</a>
</pre>
<div class="source-footer">
<a href="https://git.doan.luuduct.ai/stack/tree/contact-service/src/main.rs">[ Source Code ]</a>
</div>
</div>
</div>
</body>
</html>"#;
const ERROR_PAGE: &str = r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<pre>
[!] Error: Unable to process or encrypt message.
<a href="/message.html"><-- Try Again</a>
</pre>
</body>
</html>"#;
|