diff --git a/Cargo.lock b/Cargo.lock index fb406e33f..8841deb2f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -570,6 +570,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.1" @@ -938,6 +944,7 @@ dependencies = [ "hound", "http-body-util", "hyper-util", + "image", "lark-channel", "md-5", "mime_guess", @@ -1986,6 +1993,15 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + [[package]] name = "fiat-crypto" version = "0.2.9" @@ -2540,7 +2556,7 @@ dependencies = [ "tokio", "tower-service", "tracing", - "windows-registry 0.5.3", + "windows-registry 0.6.1", ] [[package]] @@ -2692,6 +2708,30 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "image-webp", + "moxcms", + "num-traits", + "png", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + [[package]] name = "include_dir" version = "0.7.4" @@ -3385,6 +3425,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "multer" version = "3.1.0" @@ -4282,6 +4332,19 @@ dependencies = [ "time", ] +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.0", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + [[package]] name = "polyval" version = "0.6.2" @@ -4444,6 +4507,18 @@ dependencies = [ "cc", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quick-xml" version = "0.42.0" diff --git a/Cargo.toml b/Cargo.toml index 5dc8ea277..e22ca7b76 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,6 +62,7 @@ globset = "0.4" http-body-util = "0.1" hyper-util = { version = "0.1.20", default-features = false, features = ["client-proxy"] } hmac = "0.12" +image = { version = "0.25.9", default-features = false, features = ["png", "webp"] } # 0.9.0 unconditionally enables ConPTY cursor inheritance and regresses native # Windows streams (wezterm/wezterm#6783). Keep the last stable ConPTY behavior. portable-pty = "=0.8.1" diff --git a/crates/cccc-web/Cargo.toml b/crates/cccc-web/Cargo.toml index be5a62306..e6725a53e 100644 --- a/crates/cccc-web/Cargo.toml +++ b/crates/cccc-web/Cargo.toml @@ -58,6 +58,7 @@ takecell.workspace = true tempfile.workspace = true hound.workspace = true hmac.workspace = true +image.workspace = true http-body-util.workspace = true hyper-util.workspace = true tokio.workspace = true diff --git a/crates/cccc-web/src/im_runtime.rs b/crates/cccc-web/src/im_runtime.rs index 6f655ef8e..e6c8252bf 100644 --- a/crates/cccc-web/src/im_runtime.rs +++ b/crates/cccc-web/src/im_runtime.rs @@ -12,6 +12,7 @@ mod commands; mod dingtalk; mod dingtalk_inbound; mod dingtalk_outbound; +mod dingtalk_outbound_attachment; mod dingtalk_outbound_media; mod dingtalk_outbound_report; mod dingtalk_streaming; diff --git a/crates/cccc-web/src/im_runtime/dingtalk_outbound.rs b/crates/cccc-web/src/im_runtime/dingtalk_outbound.rs index 7dba83ff2..a4b307511 100644 --- a/crates/cccc-web/src/im_runtime/dingtalk_outbound.rs +++ b/crates/cccc-web/src/im_runtime/dingtalk_outbound.rs @@ -1,6 +1,8 @@ +use super::dingtalk_outbound_attachment::prepare_attachment; +#[cfg(test)] +use super::dingtalk_outbound_attachment::{MAX_ATTACHMENT_BYTES, validate_loaded_size}; use super::dingtalk_outbound_media::AttachmentMedia; use super::dingtalk_outbound_report::{AttachmentDeliveryReport, persist_failures}; -use super::outbound_attachment::safe_filename; use super::outbound_chunks::split_message; use cccc_core::HomeLayout; use dingtalk_stream::DingTalkStreamClient; @@ -9,7 +11,6 @@ use serde_json::{Value, json}; use std::collections::HashSet; use std::sync::Arc; -const MAX_ATTACHMENT_BYTES: u64 = 10 * 1024 * 1024; const OPENAPI_BASE: &str = "https://api.dingtalk.com"; const OTO_ENDPOINT: &str = "/v1.0/robot/oToMessages/batchSend"; const GROUP_ENDPOINT: &str = "/v1.0/robot/groupMessages/send"; @@ -68,7 +69,7 @@ impl DingTalkOutboundSender { } } for attachment in attachments { - let item = match self.prepare(attachment).await { + let item = match prepare_attachment(&self.home, &self.group_id, attachment).await { Ok(item) => item, Err(error) => { mark_routes_failed(&mut report, &routes); @@ -155,43 +156,6 @@ impl DingTalkOutboundSender { delivered } - async fn prepare(&self, value: &Value) -> Result { - let relative = value - .get("path") - .and_then(Value::as_str) - .ok_or_else(|| "attachment path is missing".to_owned())?; - let path = cccc_core::blobs::resolve(&self.home, &self.group_id, relative) - .map_err(|error| error.to_string())?; - if path.metadata().map_err(|error| error.to_string())?.len() > MAX_ATTACHMENT_BYTES { - return Err("attachment exceeds 10 MiB before read".into()); - } - let raw = tokio::fs::read(&path) - .await - .map_err(|error| error.to_string())?; - validate_loaded_size(&raw)?; - let title = value - .get("title") - .and_then(Value::as_str) - .and_then(safe_filename) - .or_else(|| path.file_name().and_then(|name| name.to_str())) - .unwrap_or("file") - .to_owned(); - let mime = value - .get("mime_type") - .and_then(Value::as_str) - .filter(|mime| !mime.trim().is_empty()) - .or_else(|| mime_guess::from_path(&path).first_raw()) - .unwrap_or("application/octet-stream") - .to_owned(); - let is_image = mime.starts_with("image/"); - Ok(PreparedAttachment { - raw, - title, - mime, - is_image, - }) - } - async fn deliver( &self, token: &str, @@ -316,19 +280,6 @@ fn send_result_succeeded(value: &Value) -> bool { == Some(true) } -fn validate_loaded_size(raw: &[u8]) -> Result<(), String> { - (raw.len() as u64 <= MAX_ATTACHMENT_BYTES) - .then_some(()) - .ok_or_else(|| "attachment exceeds 10 MiB after read".into()) -} - -struct PreparedAttachment { - raw: Vec, - title: String, - mime: String, - is_image: bool, -} - fn attachment_payload(media_id: &str, filename: &str, is_image: bool) -> Value { let (key, params) = if is_image { ("sampleImageMsg", json!({"photoURL":media_id})) diff --git a/crates/cccc-web/src/im_runtime/dingtalk_outbound_attachment.rs b/crates/cccc-web/src/im_runtime/dingtalk_outbound_attachment.rs new file mode 100644 index 000000000..00e635d8c --- /dev/null +++ b/crates/cccc-web/src/im_runtime/dingtalk_outbound_attachment.rs @@ -0,0 +1,105 @@ +use super::outbound_attachment::safe_filename; +use cccc_core::HomeLayout; +use image::{ImageFormat, ImageReader}; +use serde_json::Value; +use std::io::Cursor; +use std::path::Path; + +pub(super) const MAX_ATTACHMENT_BYTES: u64 = 10 * 1024 * 1024; +const MAX_WEBP_DECODE_ALLOCATION: u64 = 64 * 1024 * 1024; + +pub(super) struct PreparedAttachment { + pub(super) raw: Vec, + pub(super) title: String, + pub(super) mime: String, + pub(super) is_image: bool, +} + +pub(super) async fn prepare_attachment( + home: &HomeLayout, + group_id: &str, + value: &Value, +) -> Result { + let relative = value + .get("path") + .and_then(Value::as_str) + .ok_or_else(|| "attachment path is missing".to_owned())?; + let path = + cccc_core::blobs::resolve(home, group_id, relative).map_err(|error| error.to_string())?; + if path.metadata().map_err(|error| error.to_string())?.len() > MAX_ATTACHMENT_BYTES { + return Err("attachment exceeds 10 MiB before read".into()); + } + let raw = tokio::fs::read(&path) + .await + .map_err(|error| error.to_string())?; + validate_loaded_size(&raw)?; + let title = value + .get("title") + .and_then(Value::as_str) + .and_then(safe_filename) + .or_else(|| path.file_name().and_then(|name| name.to_str())) + .unwrap_or("file") + .to_owned(); + let mime = value + .get("mime_type") + .and_then(Value::as_str) + .filter(|mime| !mime.trim().is_empty()) + .or_else(|| mime_guess::from_path(&path).first_raw()) + .unwrap_or("application/octet-stream") + .to_owned(); + let webp = mime + .split(';') + .next() + .unwrap_or_default() + .trim() + .eq_ignore_ascii_case("image/webp") + || Path::new(&title) + .extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| extension.eq_ignore_ascii_case("webp")) + || (raw.starts_with(b"RIFF") && raw.get(8..12) == Some(b"WEBP")); + if webp { + // Decoding/compressing images must not block the IM event loop. + return tokio::task::spawn_blocking(move || webp_to_png(raw, title)) + .await + .map_err(|_| "DingTalk WebP conversion did not complete".to_owned())?; + } + Ok(PreparedAttachment { + raw, + title, + is_image: mime.starts_with("image/"), + mime, + }) +} + +fn webp_to_png(raw: Vec, title: String) -> Result { + let mut reader = ImageReader::with_format(Cursor::new(raw), ImageFormat::WebP); + let mut limits = image::Limits::default(); + limits.max_alloc = Some(MAX_WEBP_DECODE_ALLOCATION); + reader.limits(limits); + let image = reader + .decode() + .map_err(|error| format!("DingTalk WebP decode failed: {error}"))?; + let mut output = Cursor::new(Vec::new()); + image + .write_to(&mut output, ImageFormat::Png) + .map_err(|error| format!("DingTalk PNG encoding failed: {error}"))?; + let raw = output.into_inner(); + // A small compressed WebP can become a larger PNG; keep the same upload cap. + validate_loaded_size(&raw)?; + Ok(PreparedAttachment { + raw, + title: Path::new(&title) + .with_extension("png") + .to_string_lossy() + .into_owned(), + mime: "image/png".into(), + is_image: true, + }) +} + +pub(super) fn validate_loaded_size(raw: &[u8]) -> Result<(), String> { + (raw.len() as u64 <= MAX_ATTACHMENT_BYTES) + .then_some(()) + .ok_or_else(|| "attachment exceeds 10 MiB after read".into()) +} diff --git a/crates/cccc-web/src/im_runtime/dingtalk_outbound_tests.rs b/crates/cccc-web/src/im_runtime/dingtalk_outbound_tests.rs index 6c762f024..3d536b355 100644 --- a/crates/cccc-web/src/im_runtime/dingtalk_outbound_tests.rs +++ b/crates/cccc-web/src/im_runtime/dingtalk_outbound_tests.rs @@ -7,6 +7,9 @@ use axum::{Json, Router}; use serde_json::json; use tokio::sync::mpsc; +#[path = "dingtalk_outbound_webp_tests.rs"] +mod webp; + #[derive(Debug, PartialEq, Eq)] struct CapturedUpload { raw: Vec, diff --git a/crates/cccc-web/src/im_runtime/dingtalk_outbound_webp_tests.rs b/crates/cccc-web/src/im_runtime/dingtalk_outbound_webp_tests.rs new file mode 100644 index 000000000..a48008e30 --- /dev/null +++ b/crates/cccc-web/src/im_runtime/dingtalk_outbound_webp_tests.rs @@ -0,0 +1,65 @@ +use super::*; +use image::{ExtendedColorType, ImageFormat}; + +fn webp_fixture() -> (Vec, Vec) { + let pixels = vec![255, 0, 0, 255, 0, 255, 0, 128]; + let mut bytes = Vec::new(); + image::codecs::webp::WebPEncoder::new_lossless(&mut bytes) + .encode(&pixels, 2, 1, ExtendedColorType::Rgba8) + .expect("encode synthetic WebP"); + (bytes, pixels) +} + +#[tokio::test] +async fn webp_attachment_is_sent_as_a_real_png_without_changing_the_source_blob() { + let (_temp, sender, mut requests, mut uploads) = test_sender(ServerMode::Success).await; + let (webp, pixels) = webp_fixture(); + let blob = cccc_core::blobs::store(&sender.home, &sender.group_id, &webp).expect("blob"); + let report = sender + .send_attachments( + &[target("2", "cid-group", "")], + &[json!({"path":blob.path,"title":"overview.webp","mime_type":"image/webp"})], + ) + .await; + + assert_eq!(report.delivered_targets, 1); + assert!(report.failures.is_empty()); + // Only the external media boundary is fake; preparation and HTTP send are real. + let upload = uploads.recv().await.expect("media upload"); + assert_eq!(upload.file_type, "image"); + assert_eq!(upload.filename, "overview.png"); + assert_eq!(upload.mime, "image/png"); + assert!(upload.raw.starts_with(b"\x89PNG\r\n\x1a\n")); + let decoded = image::load_from_memory_with_format(&upload.raw, ImageFormat::Png) + .expect("valid PNG") + .into_rgba8(); + assert_eq!(decoded.dimensions(), (2, 1)); + assert_eq!(decoded.into_raw(), pixels); + let (_, _, payload) = requests.recv().await.expect("OpenAPI send"); + assert_eq!(payload["msgKey"], "sampleImageMsg"); + assert_eq!(payload["msgParam"], r#"{"photoURL":"@media"}"#); + let original = cccc_core::blobs::resolve(&sender.home, &sender.group_id, &blob.path) + .expect("original blob"); + assert_eq!(std::fs::read(original).expect("read source"), webp); +} + +#[tokio::test] +async fn invalid_webp_fails_before_upload_or_message_send() { + let (_temp, sender, mut requests, mut uploads) = test_sender(ServerMode::Success).await; + let blob = + cccc_core::blobs::store(&sender.home, &sender.group_id, b"broken WebP").expect("blob"); + let report = sender + .send_attachments( + &[target("2", "cid-group", "")], + &[json!({"path":blob.path,"title":"broken.webp","mime_type":"image/webp"})], + ) + .await; + + assert_eq!(report.delivered_targets, 0); + assert!(report.failed_chat_ids.contains("cid-group")); + assert_eq!(report.failures.len(), 1); + assert_eq!(report.failures[0].stage, "prepare"); + assert!(report.failures[0].error.contains("WebP decode failed")); + assert!(uploads.try_recv().is_err()); + assert!(requests.try_recv().is_err()); +} diff --git a/docs/guide/im-bridge/dingtalk.md b/docs/guide/im-bridge/dingtalk.md index 44be08dfc..9fb13d91f 100644 --- a/docs/guide/im-bridge/dingtalk.md +++ b/docs/guide/im-bridge/dingtalk.md @@ -177,6 +177,8 @@ DingTalk supports these message types through the Rust worker: - **Image/File**: Outbound attachments uploaded through DingTalk OpenAPI - **AI Card Streaming**: User-facing agent responses are created as one card per authorized chat and updated progressively with a typewriter effect +For DingTalk delivery, CCCC converts WebP images to PNG (the first frame for animated WebP) while retaining the original attachment. The 10 MiB CCCC attachment limit is checked both before and after conversion. Other formats remain subject to [DingTalk's media upload restrictions](https://open.dingtalk.com/document/orgapp/upload-media-files). + The native worker consumes `chat.stream` start/update/end frames, throttles intermediate full-snapshot writes, and always sends the final frame. A chat suppresses the matching completed Markdown message only after its card finalization succeeds with the exact complete content; otherwise the completed message remains the fallback, so one failed, normalized, or overlong target does not affect other subscribed chats. Long final replies are delivered in lossless 4,096-character / 64-line chunks. ### File Sharing