Additional Bug fixes

This commit is contained in:
unknown
2026-05-22 11:50:59 +02:00
parent 10bfdfb914
commit a0f7efcd34
12 changed files with 372 additions and 135 deletions

View File

@@ -150,6 +150,8 @@ async fn run_bot() {
let config = Arc::new(Config::load().expect("Failed to load config"));
tokio::fs::create_dir_all("data").await.ok();
let db = Arc::new(Database::open("data/db.sqlite").expect("Failed to open database"));
db.run_migrations().await.expect("Failed to run migrations");
@@ -201,6 +203,23 @@ async fn handle_message(
msg: Message,
storage: Arc<InMemStorage<BotState>>,
ctx: BotContext,
) -> HandlerResult {
let chat_id = msg.chat.id;
if let Err(e) = handle_message_inner(bot.clone(), msg, storage, ctx).await {
tracing::error!("handle_message error: {}", e);
let _ = bot.send_message(chat_id, "<b>An error occurred.</b> Please try again.")
.parse_mode(ParseMode::Html)
.await;
}
Ok(())
}
#[inline(never)]
async fn handle_message_inner(
bot: Bot,
msg: Message,
storage: Arc<InMemStorage<BotState>>,
ctx: BotContext,
) -> HandlerResult {
let user = match &msg.from {
Some(u) => u.clone(),
@@ -219,7 +238,9 @@ async fn handle_message(
};
if matches!(db_user.role, UserRole::Banned) || !ctx.moderation.is_allowed(user_id).await {
bot.send_message(chat_id, "[ Banned ] You are not allowed to use this service.").await?;
bot.send_message(chat_id, "<b>[ Banned ]</b> You are not allowed to use this service.")
.parse_mode(ParseMode::Html)
.await?;
dialogue.exit().await?;
return Ok(());
}
@@ -232,7 +253,9 @@ async fn handle_message(
"/reload" => {
if is_admin(&bot, msg.chat.id, user.id).await {
ctx.moderation.load().await?;
bot.send_message(chat_id, "Moderation lists reloaded.").await?;
bot.send_message(chat_id, "<b>Moderation lists reloaded.</b>")
.parse_mode(ParseMode::Html)
.await?;
}
return Ok(());
}
@@ -312,6 +335,23 @@ async fn handle_callback(
q: CallbackQuery,
storage: Arc<InMemStorage<BotState>>,
ctx: BotContext,
) -> HandlerResult {
let chat_id = q.message.as_ref().map(|m| m.chat().id).unwrap_or(ChatId(q.from.id.0 as i64));
if let Err(e) = handle_callback_inner(bot.clone(), q, storage, ctx).await {
tracing::error!("handle_callback error: {}", e);
let _ = bot.send_message(chat_id, "<b>An error occurred.</b> Please try again.")
.parse_mode(ParseMode::Html)
.await;
}
Ok(())
}
#[inline(never)]
async fn handle_callback_inner(
bot: Bot,
q: CallbackQuery,
storage: Arc<InMemStorage<BotState>>,
ctx: BotContext,
) -> HandlerResult {
// CallbackQuery (and the Message it may contain) are very large structs.
// Extract only the fields we need and drop q before the first .await so
@@ -323,8 +363,10 @@ async fn handle_callback(
let message_id = q.message.as_ref().map(|m| m.id());
drop(q);
bot.answer_callback_query(&callback_id).await.ok();
if !ctx.moderation.is_allowed(user_id).await {
bot.answer_callback_query(&callback_id).text("Not allowed").await?;
bot.answer_callback_query(&callback_id).text("Not allowed").await.ok();
return Ok(());
}
@@ -332,7 +374,7 @@ async fn handle_callback(
let parts: Vec<&str> = data.split(':').collect();
if parts.len() < 3 || parts[0] != "v1" {
bot.answer_callback_query(&callback_id).await?;
bot.answer_callback_query(&callback_id).await.ok();
return Ok(());
}
@@ -357,15 +399,15 @@ async fn handle_callback(
"menu" => match parts[2] {
"upload_media" => {
dialogue.update(BotState::UploadStaging { items: vec![], upload_type: UploadType::Media }).await?;
send_staging_message(&bot, chat_id, &[], UploadType::Media).await?;
send_staging_message(&bot, chat_id, &[], UploadType::Media, ctx.config.upload_limits.max_batch_size).await?;
}
"upload_doc" => {
dialogue.update(BotState::UploadStaging { items: vec![], upload_type: UploadType::Document }).await?;
send_staging_message(&bot, chat_id, &[], UploadType::Document).await?;
send_staging_message(&bot, chat_id, &[], UploadType::Document, ctx.config.upload_limits.max_batch_size).await?;
}
"upload_text" => {
dialogue.update(BotState::UploadStaging { items: vec![], upload_type: UploadType::Text }).await?;
send_staging_message(&bot, chat_id, &[], UploadType::Text).await?;
send_staging_message(&bot, chat_id, &[], UploadType::Text, ctx.config.upload_limits.max_batch_size).await?;
}
"prev_uploads" => {
dialogue.update(BotState::ViewingPrevious { page: 0 }).await?;
@@ -373,7 +415,9 @@ async fn handle_callback(
}
"report" => {
dialogue.update(BotState::Reporting).await?;
bot.send_message(chat_id, "Send me the content link or content ID to report.").await?;
bot.send_message(chat_id, "Send me the <code>content link</code> or <code>content ID</code> to report.")
.parse_mode(ParseMode::Html)
.await?;
}
"main" => {
send_main_menu(&bot, chat_id, &dialogue).await?;
@@ -385,7 +429,7 @@ async fn handle_callback(
let state = dialogue.get_or_default().await?;
if let BotState::UploadStaging { items, .. } = state {
if items.is_empty() {
bot.answer_callback_query(&callback_id).text("No items to upload.").await?;
bot.answer_callback_query(&callback_id).text("No items to upload.").await.ok();
} else {
let options = UploadOptions {
allow_download: true,
@@ -398,7 +442,9 @@ async fn handle_callback(
}
"cancel" => {
if let Some(mid) = message_id {
bot.edit_message_text(chat_id, mid, "Upload cancelled.").await.ok();
bot.edit_message_text(chat_id, mid, "<i>Upload cancelled.</i>")
.parse_mode(ParseMode::Html)
.await.ok();
}
dialogue.update(BotState::MainMenu).await?;
}
@@ -425,7 +471,9 @@ async fn handle_callback(
}
}
"set_password" => {
bot.send_message(chat_id, "Send the password (max 32 chars) or /skip to skip.").await?;
bot.send_message(chat_id, "Send the <code>password</code> (max <b>32</b> chars) or <code>/skip</code> to skip.")
.parse_mode(ParseMode::Html)
.await?;
}
"confirm_final" => {
let state = dialogue.get_or_default().await?;
@@ -436,7 +484,7 @@ async fn handle_callback(
}
"back" => {
dialogue.update(BotState::UploadStaging { items: vec![], upload_type: UploadType::Media }).await?;
send_staging_message(&bot, chat_id, &[], UploadType::Media).await?;
send_staging_message(&bot, chat_id, &[], UploadType::Media, ctx.config.upload_limits.max_batch_size).await?;
}
_ => {}
},
@@ -456,7 +504,6 @@ async fn handle_callback(
_ => {}
}
bot.answer_callback_query(&callback_id).await?;
Ok(())
}
@@ -481,30 +528,31 @@ async fn send_main_menu(bot: &Bot, chat_id: ChatId, dialogue: &BotDialogue) -> H
],
vec![
InlineKeyboardButton::callback("[ Upload Text ]", "v1:menu:upload_text"),
InlineKeyboardButton::callback("[ Previous Uploads ]", "v1:menu:prev_uploads"),
InlineKeyboardButton::callback("[ My Uploads ]", "v1:menu:prev_uploads"),
],
vec![
InlineKeyboardButton::callback("[ Report Content ]", "v1:menu:report"),
],
]);
bot.send_message(chat_id, "Choose from the menu below. Administrators can be contacted here: @harmfulmeowbot")
bot.send_message(chat_id, "<b>Main Menu</b>\n\nChoose from the menu below.\n<i>Administrators can be contacted here:</i> <a href=\"https://t.me/harmfulmeowbot?start=submit\">t.me/harmfulmeowbot?start=submit</a>")
.parse_mode(ParseMode::Html)
.reply_markup(keyboard)
.await?;
dialogue.update(BotState::MainMenu).await?;
Ok(())
}
async fn send_staging_message(bot: &Bot, chat_id: ChatId, items: &[StagedItem], upload_type: UploadType) -> HandlerResult {
async fn send_staging_message(bot: &Bot, chat_id: ChatId, items: &[StagedItem], upload_type: UploadType, max_batch_size: usize) -> HandlerResult {
let type_label = match upload_type {
UploadType::Media => "Media",
UploadType::Document => "Documents",
UploadType::Text => "Text",
};
let text = if items.is_empty() {
format!("[ Staging {} (0/10) ]\n\nSend me files to add them.", type_label)
format!("<b>[ Staging {} ]</b>\n\n<i>Send me files to add them.</i>\n\n<code>0/{}</code> items", type_label, max_batch_size)
} else {
let list: String = items.iter().map(|i| format!("- {}\n", i.file_name)).collect();
format!("[ Staging {} ({}/10) ]\n\n{}", type_label, items.len(), list)
let list: String = items.iter().map(|i| format!("• <code>{}</code>\n", i.file_name)).collect();
format!("<b>[ Staging {} ]</b> <code>{}/{}</code>\n\n{}", type_label, items.len(), max_batch_size, list)
};
let keyboard = InlineKeyboardMarkup::new(vec![vec![
@@ -513,6 +561,7 @@ async fn send_staging_message(bot: &Bot, chat_id: ChatId, items: &[StagedItem],
]]);
bot.send_message(chat_id, text)
.parse_mode(ParseMode::Html)
.reply_markup(keyboard)
.await?;
Ok(())
@@ -528,7 +577,9 @@ async fn handle_staging_message(
upload_type: UploadType,
) -> HandlerResult {
if items.len() >= ctx.config.upload_limits.max_batch_size {
bot.send_message(msg.chat.id, "Maximum batch size reached.").await?;
bot.send_message(msg.chat.id, "<b>Maximum batch size reached.</b>")
.parse_mode(ParseMode::Html)
.await?;
return Ok(());
}
@@ -598,7 +649,7 @@ async fn handle_staging_message(
if let Some(item) = new_item {
items.push(item);
dialogue.update(BotState::UploadStaging { items: items.clone(), upload_type }).await?;
send_staging_message(bot, chat_id, &items, upload_type).await?;
send_staging_message(bot, chat_id, &items, upload_type, ctx.config.upload_limits.max_batch_size).await?;
}
Ok(())
@@ -611,22 +662,22 @@ async fn refresh_options_message(
options: &UploadOptions,
) -> HandlerResult {
let destroy_text = match options.max_views {
Some(n) => format!("Auto-destroy: {} views", n),
None => "Auto-destroy: Off".to_string(),
Some(n) => format!("Auto-destroy: <b>{}</b> views", n),
None => "Auto-destroy: <i>Off</i>".to_string(),
};
let download_text = if options.allow_download {
"Allow download: Yes"
"Allow download: <b>Yes</b>"
} else {
"Allow download: No"
"Allow download: <b>No</b>"
};
let password_text = if options.password.is_some() {
"Password: Set"
"Password: <b>Set</b>"
} else {
"Password: None"
"Password: <i>None</i>"
};
let text = format!(
"[ Upload Options ]\n\n{}\n{}\n{}\n\nConfirm when ready.",
"<b>[ Upload Options ]</b>\n\n{}\n{}\n{}\n\n<i>Confirm when ready.</i>",
destroy_text, download_text, password_text
);
@@ -640,11 +691,12 @@ async fn refresh_options_message(
],
vec![
InlineKeyboardButton::callback("[ Back ]", "v1:opt:back"),
InlineKeyboardButton::callback("[ Confirm & Upload ]", "v1:opt:confirm_final"),
InlineKeyboardButton::callback("[ Confirm ]", "v1:opt:confirm_final"),
],
]);
bot.send_message(chat_id, text)
.parse_mode(ParseMode::Html)
.reply_markup(keyboard)
.await?;
Ok(())
@@ -659,11 +711,15 @@ async fn finalize_upload(
dialogue: &BotDialogue,
ctx: &BotContext,
) -> HandlerResult {
let status_msg = bot.send_message(chat_id, "[ Encrypting and storing... ]").await?;
let status_msg = bot.send_message(chat_id, "<i>[ Encrypting and storing... ]</i>")
.parse_mode(ParseMode::Html)
.await?;
let total_size: u64 = items.iter().map(|i| i.size).sum();
if total_size > ctx.config.upload_limits.max_total_batch_bytes {
bot.edit_message_text(chat_id, status_msg.id, "[ Error: total batch size exceeds limit. ]").await?;
bot.edit_message_text(chat_id, status_msg.id, "<b>[ Error ]</b> Total batch size exceeds limit.")
.parse_mode(ParseMode::Html)
.await?;
dialogue.update(BotState::MainMenu).await?;
return Ok(());
}
@@ -672,7 +728,9 @@ async fn finalize_upload(
if let Ok(temp_path) = std::fs::canonicalize(&ctx.config.storage.paths.temp) {
if let Ok(info) = fs2::available_space(&temp_path) {
if info < total_size * 2 {
bot.edit_message_text(chat_id, status_msg.id, "[ Error: insufficient storage space. ]").await?;
bot.edit_message_text(chat_id, status_msg.id, "<b>[ Error ]</b> Insufficient storage space.")
.parse_mode(ParseMode::Html)
.await?;
dialogue.update(BotState::MainMenu).await?;
return Ok(());
}
@@ -767,10 +825,14 @@ async fn finalize_upload(
attrs.join(", ")
};
let result_text = format!(
"[ Upload Complete ]\n\nLink: <code>{}</code>\n\nFiles: {} | {}",
let mut result_text = format!(
"<b>[ Upload Complete ]</b>\n\nLink: <code>{}</code>\n\nFiles: <b>{}</b> | <i>{}</i>",
link, items.len(), attr_text
);
if let Some(ref pw) = options.password {
let direct_link = format!("{}/?cxid={}&sc={}", base_url, content_id.as_str(), pw);
result_text.push_str(&format!("\n\n<i>Direct Access Link:</i> <code>{}</code>", direct_link));
}
bot.edit_message_text(chat_id, status_msg.id, result_text)
.parse_mode(ParseMode::Html)
@@ -793,12 +855,14 @@ async fn show_previous_uploads(
let total_pages = (total + 9) / 10;
if items.is_empty() {
bot.send_message(chat_id, "You have no uploads.").await?;
bot.send_message(chat_id, "<i>You have no uploads.</i>")
.parse_mode(ParseMode::Html)
.await?;
return Ok(());
}
let base_url = &ctx.config.server.base_url;
let mut text = format!("[ Your Uploads ] Page {}/{}\n\n", page + 1, total_pages.max(1));
let mut text = format!("<b>[ My Uploads ]</b> Page {}/{}\n\n", page + 1, total_pages.max(1));
for content in &items {
let file_repo = ContentFileRepo::new(ctx.db.conn());
let files = file_repo.list_by_content(&content.id).await?;
@@ -814,10 +878,28 @@ async fn show_previous_uploads(
}
let attr_text = if attrs.is_empty() { "no options".to_string() } else { attrs.join(", ") };
text.push_str(&format!(
"- <code>{}</code> ({} files) [{}]\n {}?cxid={}\n\n",
content.id.as_str(), files.len(), attr_text, base_url, content.id.as_str()
));
if content.password_hash.is_some() {
text.push_str(&format!(
"• <code>{}</code> ({} files) [{}]\n {}?cxid={} <i>(password protected)</i>\n",
content.id.as_str(), files.len(), attr_text, base_url, content.id.as_str()
));
} else {
text.push_str(&format!(
"• <code>{}</code> ({} files) [{}]\n {}?cxid={}\n",
content.id.as_str(), files.len(), attr_text, base_url, content.id.as_str()
));
}
text.push('\n');
}
let mut keyboard_rows = vec![];
for content in &items {
keyboard_rows.push(vec![
InlineKeyboardButton::callback(
format!("[ Del {} ]", content.id.as_str()),
format!("v1:admin:delcontent:{}", content.id.as_str())
)
]);
}
let mut buttons = vec![];
@@ -828,10 +910,12 @@ async fn show_previous_uploads(
if page + 1 < total_pages {
buttons.push(InlineKeyboardButton::callback(">>", format!("v1:prev:page:{}", page + 1)));
}
let keyboard = InlineKeyboardMarkup::new(vec![buttons, vec![
keyboard_rows.push(buttons);
keyboard_rows.push(vec![
InlineKeyboardButton::callback("[ Main Menu ]", "v1:menu:main"),
]]);
]);
let keyboard = InlineKeyboardMarkup::new(keyboard_rows);
bot.send_message(chat_id, text)
.parse_mode(ParseMode::Html)
@@ -860,7 +944,7 @@ async fn handle_report(
for &group_id in &ctx.config.groups.review_group_ids {
let report_text = format!(
"[ NEW REPORT ] #{}\n\nCXID: <code>{}</code>\nReporter: <code>{}</code>\nOwner: <code>{}</code>\nUploaded: {}\nFiles: {}",
"<b>[ NEW REPORT ]</b> #{}\n\nCXID: <code>{}</code>\nReporter: <code>{}</code>\nOwner: <code>{}</code>\nUploaded: <i>{}</i>\nFiles: <b>{}</b>",
report_id,
cxid,
reporter_id,
@@ -871,7 +955,7 @@ async fn handle_report(
let keyboard = InlineKeyboardMarkup::new(vec![
vec![
InlineKeyboardButton::callback("[ Delete + Blacklist ]", format!("v1:admin:delblk:{}", report_id)),
InlineKeyboardButton::callback("[ Rmv + Ban ]", format!("v1:admin:delblk:{}", report_id)),
InlineKeyboardButton::callback("[ Delete Only ]", format!("v1:admin:del:{}", report_id)),
],
vec![
@@ -887,7 +971,9 @@ async fn handle_report(
.ok();
}
bot.send_message(chat_id, "Report submitted. Moderators will review it shortly.").await?;
bot.send_message(chat_id, "<b>Report submitted.</b> Moderators will review it shortly.")
.parse_mode(ParseMode::Html)
.await?;
dialogue.update(BotState::MainMenu).await?;
Ok(())
}
@@ -899,8 +985,37 @@ async fn handle_admin_callback(
parts: &[&str],
ctx: &BotContext,
) -> HandlerResult {
match parts[2] {
"delcontent" => {
let cxid = parts[3];
let content_id = ContentId::try_from(cxid)?;
let content_repo = ContentRepo::new(ctx.db.conn());
let content = match content_repo.get(&content_id).await? {
Some(c) => c,
None => {
bot.send_message(chat_id, "<b>Content not found.</b>")
.parse_mode(ParseMode::Html).await?;
return Ok(());
}
};
let is_admin = is_admin_in_chat(bot, chat_id, UserId(user_id as u64)).await;
if !is_admin && content.user_id != user_id {
bot.send_message(chat_id, "<b>Unauthorized.</b>")
.parse_mode(ParseMode::Html).await?;
return Ok(());
}
ctx.pipeline.delete_content(&content_id, ctx.config.content.keep_content).await.ok();
content_repo.set_status(&content_id, ContentStatus::Deleted).await.ok();
bot.send_message(chat_id, format!("Content <code>{}</code> deleted.", cxid))
.parse_mode(ParseMode::Html).await?;
return Ok(());
}
_ => {}
}
if !is_admin_in_chat(bot, chat_id, UserId(user_id as u64)).await {
bot.send_message(chat_id, "Unauthorized.").await?;
bot.send_message(chat_id, "<b>Unauthorized.</b>")
.parse_mode(ParseMode::Html).await?;
return Ok(());
}
@@ -909,7 +1024,8 @@ async fn handle_admin_callback(
let report = match report_repo.get(report_id).await? {
Some(r) => r,
None => {
bot.send_message(chat_id, "Report not found.").await?;
bot.send_message(chat_id, "<b>Report not found.</b>")
.parse_mode(ParseMode::Html).await?;
return Ok(());
}
};
@@ -918,27 +1034,28 @@ async fn handle_admin_callback(
let content = match content_repo.get(&report.content_id).await? {
Some(c) => c,
None => {
bot.send_message(chat_id, "Content not found.").await?;
bot.send_message(chat_id, "<b>Content not found.</b>")
.parse_mode(ParseMode::Html).await?;
return Ok(());
}
};
match parts[2] {
"delblk" => {
ctx.pipeline.delete_content(&report.content_id, !ctx.config.content.keep_content).await.ok();
ctx.pipeline.delete_content(&report.content_id, ctx.config.content.keep_content).await.ok();
content_repo.set_status(&report.content_id, ContentStatus::Deleted).await.ok();
ctx.moderation.blacklist(content.user_id).await.ok();
let user_repo = UserRepo::new(ctx.db.conn());
user_repo.set_role(content.user_id, "banned").await.ok();
report_repo.resolve(report_id, ReportStatus::Actioned, user_id).await.ok();
bot.send_message(chat_id, format!("Deleted content {} and blacklisted user {}", report.content_id.as_str(), content.user_id))
bot.send_message(chat_id, format!("Deleted content <code>{}</code> and blacklisted user <code>{}</code>", report.content_id.as_str(), content.user_id))
.parse_mode(ParseMode::Html).await?;
}
"del" => {
ctx.pipeline.delete_content(&report.content_id, !ctx.config.content.keep_content).await.ok();
ctx.pipeline.delete_content(&report.content_id, ctx.config.content.keep_content).await.ok();
content_repo.set_status(&report.content_id, ContentStatus::Deleted).await.ok();
report_repo.resolve(report_id, ReportStatus::Actioned, user_id).await.ok();
bot.send_message(chat_id, format!("Deleted content {}", report.content_id.as_str()))
bot.send_message(chat_id, format!("Deleted content <code>{}</code>", report.content_id.as_str()))
.parse_mode(ParseMode::Html).await?;
}
"blk" => {
@@ -946,12 +1063,12 @@ async fn handle_admin_callback(
let user_repo = UserRepo::new(ctx.db.conn());
user_repo.set_role(content.user_id, "banned").await.ok();
report_repo.resolve(report_id, ReportStatus::Actioned, user_id).await.ok();
bot.send_message(chat_id, format!("Blacklisted user {}", content.user_id))
bot.send_message(chat_id, format!("Blacklisted user <code>{}</code>", content.user_id))
.parse_mode(ParseMode::Html).await?;
}
"ign" => {
report_repo.resolve(report_id, ReportStatus::Dismissed, user_id).await.ok();
bot.send_message(chat_id, format!("Ignored report #{}", report_id))
bot.send_message(chat_id, format!("Ignored report <code>#{}</code>", report_id))
.parse_mode(ParseMode::Html).await?;
}
_ => {}

View File

@@ -141,11 +141,20 @@ struct IdListFile {
async fn load_id_set(path: &Path) -> Result<HashSet<i64>> {
if !path.exists() {
tokio::fs::write(path, "[]")
.await
.map_err(|e| cgcx_core::CgcxError::Moderation(e.to_string()))?;
return Ok(HashSet::new());
}
let json = tokio::fs::read_to_string(path)
.await
.map_err(|e| cgcx_core::CgcxError::Moderation(e.to_string()))?;
// Accept either a plain array or the IdListFile object format
if let Ok(ids) = serde_json::from_str::<Vec<i64>>(&json) {
return Ok(ids.into_iter().collect());
}
let file: IdListFile = serde_json::from_str(&json)
.map_err(|e| cgcx_core::CgcxError::Moderation(e.to_string()))?;
Ok(file.ids.into_iter().collect())

View File

@@ -20,7 +20,7 @@ use tower_http::{
catch_panic::CatchPanicLayer,
compression::CompressionLayer,
cors::{AllowOrigin, CorsLayer},
services::{ServeDir, ServeFile},
services::ServeDir,
timeout::TimeoutLayer,
trace::TraceLayer,
};
@@ -71,6 +71,14 @@ struct VerifyPasswordRequest {
struct FileQuery {
#[serde(default)]
download: bool,
#[serde(rename = "sc", default)]
sc: Option<String>,
}
#[derive(Deserialize, Default)]
struct ScQuery {
#[serde(rename = "sc", default)]
sc: Option<String>,
}
struct ByteRange {
@@ -88,16 +96,21 @@ impl From<CgcxError> for AppError {
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, msg) = match self.0 {
let (status, msg) = match &self.0 {
CgcxError::NotFound => (StatusCode::NOT_FOUND, "Not found"),
CgcxError::Unauthorized => (StatusCode::UNAUTHORIZED, "Unauthorized"),
CgcxError::Forbidden => (StatusCode::FORBIDDEN, "Forbidden"),
CgcxError::BadRequest(ref m) => (StatusCode::BAD_REQUEST, m.as_str()),
CgcxError::BadRequest(_) => (StatusCode::BAD_REQUEST, "Bad request"),
CgcxError::InvalidContentId(_) => (StatusCode::BAD_REQUEST, "Bad request"),
CgcxError::RateLimited => (StatusCode::TOO_MANY_REQUESTS, "Rate limited"),
CgcxError::InsufficientStorage => (StatusCode::INSUFFICIENT_STORAGE, "Insufficient storage"),
_ => (StatusCode::INTERNAL_SERVER_ERROR, "Internal error"),
other => {
tracing::error!("Internal server error: {}", other);
(StatusCode::INTERNAL_SERVER_ERROR, "Internal error")
}
};
(status, msg.to_string()).into_response()
let body = serde_json::json!({ "error": msg });
(status, [(header::CONTENT_TYPE, "application/json")], body.to_string()).into_response()
}
}
@@ -123,6 +136,8 @@ async fn main() -> cgcx_core::Result<()> {
let config = Arc::new(Config::load()?);
config.validate()?;
tokio::fs::create_dir_all("data").await.ok();
let db = Arc::new(Database::open("data/db.sqlite")?);
db.run_migrations().await?;
@@ -171,8 +186,7 @@ async fn main() -> cgcx_core::Result<()> {
config: Arc::new(password_governor_conf),
});
let static_service = ServeDir::new("frontend/dist")
.fallback(ServeFile::new("frontend/dist/index.html"));
let static_service = ServeDir::new("frontend/dist/assets");
let mut origins: Vec<HeaderValue> = vec![
config.server.base_url.parse().expect("invalid server.base_url"),
@@ -215,12 +229,12 @@ async fn main() -> cgcx_core::Result<()> {
.route("/api/content/{cxid}", get(get_metadata))
.route("/api/content/{cxid}/file/{file_idx}", get(serve_file))
.merge(password_route)
.fallback_service(static_service)
.nest_service("/assets", static_service)
.fallback(fallback)
.layer(tower_governor::GovernorLayer {
config: Arc::new(governor_conf),
})
.layer(compression)
.layer(cors)
.layer(axum::middleware::from_fn(security_headers))
.layer(TraceLayer::new_for_http())
.layer(TimeoutLayer::with_status_code(
@@ -228,6 +242,7 @@ async fn main() -> cgcx_core::Result<()> {
Duration::from_secs(30),
))
.layer(CatchPanicLayer::new())
.layer(cors)
.with_state(state.clone());
// Spawn background sweeper task
@@ -259,6 +274,18 @@ async fn main() -> cgcx_core::Result<()> {
Ok(())
}
async fn fallback(uri: axum::http::Uri) -> Response {
let path = uri.path();
tracing::info!("fallback: path={}", path);
if path.starts_with("/api/") {
return (StatusCode::NOT_FOUND, Json(serde_json::json!({"error": "Not found"}))).into_response();
}
match tokio::fs::read_to_string("frontend/dist/index.html").await {
Ok(html) => (StatusCode::OK, [(header::CONTENT_TYPE, "text/html")], html).into_response(),
Err(_) => (StatusCode::NOT_FOUND, "Frontend not built").into_response(),
}
}
async fn security_headers(req: axum::http::Request<Body>, next: Next) -> Response {
let mut response = next.run(req).await;
let headers = response.headers_mut();
@@ -281,21 +308,56 @@ async fn security_headers(req: axum::http::Request<Body>, next: Next) -> Respons
}
async fn health() -> impl IntoResponse {
tracing::info!("health");
axum::Json(HealthResponse {
status: "ok".into(),
})
}
fn password_from_request(
headers: &HeaderMap,
query_sc: Option<&str>,
cxid: &str,
password_hash: Option<&str>,
cookie_secret: &[u8],
) -> bool {
if let Some(sc) = query_sc {
if let Some(hash) = password_hash {
use argon2::{Argon2, PasswordHash, PasswordVerifier};
if let Ok(parsed_hash) = PasswordHash::new(hash) {
if Argon2::default().verify_password(sc.as_bytes(), &parsed_hash).is_ok() {
return true;
}
}
}
}
headers
.get_all(header::COOKIE)
.iter()
.any(|v| {
v.to_str().ok().map(|s| {
s.split(';').any(|part| {
let part = part.trim();
part.starts_with("cgcx_pw=") && verify_cookie(cxid, &part[8..], cookie_secret)
})
}).unwrap_or(false)
})
}
async fn get_metadata(
State(state): State<AppState>,
Path(cxid): Path<String>,
Query(query): Query<ScQuery>,
headers: HeaderMap,
) -> AppResult<Response> {
tracing::info!("get_metadata: cxid={}", cxid);
let content_id = ContentId::try_from(cxid.as_str())?;
let repo = ContentRepo::new(state.db.conn());
let content = repo.get(&content_id).await?.ok_or(CgcxError::NotFound)?;
if content.status == cgcx_core::ContentStatus::Deleted || content.status == cgcx_core::ContentStatus::Blacklisted {
tracing::warn!("get_metadata returning NotFound for cxid={}", cxid);
return Err(CgcxError::NotFound.into());
}
@@ -304,23 +366,13 @@ async fn get_metadata(
return Ok(Response::builder()
.status(StatusCode::GONE)
.body(Body::empty())
.unwrap());
.map_err(|e| CgcxError::Storage(format!("response build failed: {}", e)))?);
}
}
if content.password_hash.is_some() {
let cookie_valid = headers
.get_all(header::COOKIE)
.iter()
.any(|v| {
v.to_str().ok().map(|s| {
s.split(';').any(|part| {
let part = part.trim();
part.starts_with("__Host-pw=") && verify_cookie(&cxid, &part[10..], &state.cookie_secret)
})
}).unwrap_or(false)
});
if !cookie_valid {
if !password_from_request(&headers, query.sc.as_deref(), &cxid, content.password_hash.as_deref(), &state.cookie_secret) {
tracing::warn!("get_metadata returning Unauthorized for cxid={}", cxid);
return Err(CgcxError::Unauthorized.into());
}
}
@@ -342,12 +394,12 @@ async fn get_metadata(
current_views: content.view_count,
allow_download: content.allow_download,
created_at: content.created_at.to_rfc3339(),
}).map_err(|e| CgcxError::BadRequest(format!("json serialization: {}", e)))?;
}).map_err(|_| CgcxError::BadRequest("json serialization".into()))?;
Ok(Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(body))
.unwrap())
.map_err(|e| CgcxError::Storage(format!("response build failed: {}", e)))?)
}
async fn verify_password(
@@ -355,6 +407,7 @@ async fn verify_password(
Path(cxid): Path<String>,
Json(req): Json<VerifyPasswordRequest>,
) -> AppResult<impl IntoResponse> {
tracing::info!("verify_password: cxid={}", cxid);
let content_id = ContentId::try_from(cxid.as_str())?;
let repo = ContentRepo::new(state.db.conn());
let content = repo.get(&content_id).await?.ok_or(CgcxError::NotFound)?;
@@ -363,7 +416,7 @@ async fn verify_password(
return Ok(Response::builder()
.status(StatusCode::NO_CONTENT)
.body(Body::empty())
.unwrap());
.map_err(|e| CgcxError::Storage(format!("response build failed: {}", e)))?);
};
use argon2::{Argon2, PasswordHash, PasswordVerifier};
@@ -373,12 +426,13 @@ async fn verify_password(
.verify_password(req.password.as_bytes(), &parsed_hash)
.is_ok();
if !valid {
tracing::warn!("verify_password returning Unauthorized for cxid={}", cxid);
return Err(CgcxError::Unauthorized.into());
}
let cookie_value = make_cookie_value(&cxid, &state.cookie_secret);
let cookie = format!(
"__Host-pw={}; Max-Age=3600; SameSite=Strict; Secure; HttpOnly; Path=/",
"cgcx_pw={}; Max-Age=3600; SameSite=Strict; HttpOnly; Path=/",
cookie_value
);
@@ -386,7 +440,7 @@ async fn verify_password(
.status(StatusCode::NO_CONTENT)
.header(header::SET_COOKIE, cookie)
.body(Body::empty())
.unwrap())
.map_err(|e| CgcxError::Storage(format!("response build failed: {}", e)))?)
}
async fn serve_file(
@@ -395,11 +449,13 @@ async fn serve_file(
Query(query): Query<FileQuery>,
headers: HeaderMap,
) -> AppResult<impl IntoResponse> {
tracing::info!("serve_file: cxid={} file_idx={}", cxid, file_idx);
let content_id = ContentId::try_from(cxid.as_str())?;
let repo = ContentRepo::new(state.db.conn());
let content = repo.get(&content_id).await?.ok_or(CgcxError::NotFound)?;
if content.status == cgcx_core::ContentStatus::Deleted || content.status == cgcx_core::ContentStatus::Blacklisted {
tracing::warn!("serve_file returning NotFound for cxid={}", cxid);
return Err(CgcxError::NotFound.into());
}
@@ -408,28 +464,19 @@ async fn serve_file(
return Ok(Response::builder()
.status(StatusCode::GONE)
.body(Body::empty())
.unwrap());
.map_err(|e| CgcxError::Storage(format!("response build failed: {}", e)))?);
}
}
if content.password_hash.is_some() {
let cookie_valid = headers
.get_all(header::COOKIE)
.iter()
.any(|v| {
v.to_str().ok().map(|s| {
s.split(';').any(|part| {
let part = part.trim();
part.starts_with("__Host-pw=") && verify_cookie(&cxid, &part[10..], &state.cookie_secret)
})
}).unwrap_or(false)
});
if !cookie_valid {
if !password_from_request(&headers, query.sc.as_deref(), &cxid, content.password_hash.as_deref(), &state.cookie_secret) {
tracing::warn!("serve_file returning Unauthorized for cxid={}", cxid);
return Err(CgcxError::Unauthorized.into());
}
}
if query.download && !content.allow_download {
tracing::warn!("serve_file returning Forbidden (download not allowed) for cxid={}", cxid);
return Err(CgcxError::Forbidden.into());
}
@@ -437,6 +484,27 @@ async fn serve_file(
let files = file_repo.list_by_content(&content_id).await?;
let file = files.iter().find(|f| f.file_index == file_idx).ok_or(CgcxError::NotFound)?;
// Handle zero-size files early to avoid underflow in range parsing
if file.size_bytes == 0 {
let etag = format!("\"{}\"", hex::encode(&file.encrypted_hash));
let content_type = file.mime_type.clone();
let sanitized_name = sanitize_content_disposition(&file.original_name);
let disposition = if query.download && content.allow_download {
format!("attachment; filename=\"{}\"", sanitized_name)
} else {
format!("inline; filename=\"{}\"", sanitized_name)
};
return Ok(Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, content_type)
.header(header::CONTENT_DISPOSITION, disposition)
.header(header::ETAG, etag)
.header(header::CONTENT_LENGTH, "0")
.header(header::CACHE_CONTROL, "private, no-store, max-age=0")
.body(Body::empty())
.map_err(|e| CgcxError::Storage(format!("response build failed: {}", e)))?);
}
// Path traversal validation
let canonical_path = tokio::fs::canonicalize(&file.stored_path).await
.map_err(|e| {
@@ -445,6 +513,7 @@ async fn serve_file(
})?;
if !state.allowed_roots.iter().any(|root| canonical_path.starts_with(root)) {
tracing::error!("Path traversal blocked: {:?}", canonical_path);
tracing::warn!("serve_file returning Forbidden (path traversal) for cxid={}", cxid);
return Err(CgcxError::Forbidden.into());
}
@@ -457,7 +526,7 @@ async fn serve_file(
.status(StatusCode::NOT_MODIFIED)
.header(header::ETAG, etag.clone())
.body(Body::empty())
.unwrap());
.map_err(|e| CgcxError::Storage(format!("response build failed: {}", e)))?);
}
}
@@ -471,7 +540,7 @@ async fn serve_file(
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(header::CONTENT_RANGE, format!("bytes */{}", file.size_bytes))
.body(Body::empty())
.unwrap());
.map_err(|e| CgcxError::Storage(format!("response build failed: {}", e)))?);
}
}
} else {
@@ -559,7 +628,7 @@ async fn serve_file(
let body_stream = tokio_stream::wrappers::ReceiverStream::new(rx);
let body = Body::from_stream(body_stream);
Ok(response.body(body).unwrap())
Ok(response.body(body).map_err(|e| CgcxError::Storage(format!("response build failed: {}", e)))?)
}
async fn stream_decrypted_file(
@@ -587,6 +656,10 @@ async fn stream_decrypted_file(
break; // EOF at message boundary
}
let msg_len = u32::from_le_bytes(len_buf) as usize;
if msg_len > 50_000_000 {
let _ = tx.send(Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "message too large"))).await;
return Err(CgcxError::Crypto("message length exceeds sanity bound".into()));
}
let mut msg_buf = vec![0u8; msg_len];
file.read_exact(&mut msg_buf).await.map_err(|e| CgcxError::Storage(e.to_string()))?;