//! ProseGuard Wasm (`prose_guard_wasm`) — Zero-Dependency Rust + WebAssembly Engine for //! Client-Side AI-Generated Article Detection & Stylometric Forensics. //! //! Combines six orthogonal forensic signals inspired by open-source research: //! 1. **ZipPy LZ77 Sliding-Window Compression Redundancy** (`lz_entropy`) //! 2. **Binoculars Conditional Cross-Entropy Curvature Surrogate** (`lz_entropy`) //! 3. **Sentence Cadence Burstiness & Local Alternation Variance** (`stylometry`) //! 4. **GLTR 4-Band Lexical Predictability, MATTR-50 & Hapax Richness** (`stylometry`) //! 5. **Multilingual LLM Discourse Templates & Markdown Structural Symmetry** (`stylometry`) //! 6. **Invisible Unicode Watermark (`ZWSP`, `NNBSP`, `WJ`) & Sanitizer** (`watermark`) //! //! Security & Supply-Chain Invariant: `[dependencies]` in `Cargo.toml` is empty. #![deny(missing_docs)] pub mod cooccur_graph; pub mod diveye; pub mod gbdt; pub mod hash_tables; pub mod json_emit; pub mod lm_proxy; pub mod lz_entropy; pub mod ml_features; pub mod model; pub mod stylometry; pub mod trained_forest; pub mod watermark; use std::cell::RefCell; use crate::json_emit::serialize_report_json; use crate::model::{DetectError, DetectionConfig, GenrePreset, SensitivityMode, ValidatedArticle}; use crate::stylometry::analyze_article; use crate::watermark::sanitize_text; thread_local! { static REPORT_JSON_BUF: RefCell = const { RefCell::new(String::new()) }; static SANITIZED_TEXT_BUF: RefCell = const { RefCell::new(String::new()) }; static REMOVED_ZW_COUNT: RefCell = const { RefCell::new(0) }; static NORMALIZED_SPACE_COUNT: RefCell = const { RefCell::new(0) }; static ERROR_MSG_BUF: RefCell = const { RefCell::new(String::new()) }; } fn record_error(err: &DetectError) -> usize { ERROR_MSG_BUF.with(|slot| { *slot.borrow_mut() = err.to_string(); }); 0 } /// Computes IEEE 802.3 CRC-32 over a byte slice (`CRC32("123456789") == 0xCBF4_3926`). #[must_use] pub fn crc32_ieee(bytes: &[u8]) -> u32 { let mut crc = 0xFFFF_FFFFu32; for &byte in bytes { crc ^= u32::from(byte); for _ in 0..8 { let mask = (crc & 1).wrapping_neg(); crc = (crc >> 1) ^ (0xEDB8_8320u32 & mask); } } !crc } // ============================================================================ // Named WebAssembly FFI Adapter Boundary // ============================================================================ /// Allocates `size` bytes in WebAssembly linear memory and returns its base pointer. #[no_mangle] pub extern "C" fn wasm_alloc(size: usize) -> *mut u8 { if size == 0 { return core::ptr::null_mut(); } let mut buf = Vec::::with_capacity(size); let ptr = buf.as_mut_ptr(); core::mem::forget(buf); ptr } /// Reclaims a buffer previously allocated via `wasm_alloc(size)`. /// /// # Safety /// `ptr` must have been allocated by `wasm_alloc(size)` in the same linear memory instance /// and must not be freed more than once. #[no_mangle] pub unsafe extern "C" fn wasm_dealloc(ptr: *mut u8, size: usize) { if !ptr.is_null() && size > 0 { // SAFETY: Upheld by caller (`withWasmBuffer` RAII wrapper in `wasm-loader.js`). let _ = unsafe { Vec::from_raw_parts(ptr, 0, size) }; } } /// Runs IEEE 802.3 CRC-32 self-test across an FFI byte slice. /// /// # Safety /// If `len > 0`, `ptr` must point to `len` readable initialized bytes in Wasm linear memory. #[no_mangle] pub unsafe extern "C" fn wasm_crc32(ptr: *const u8, len: usize) -> u32 { if ptr.is_null() || len == 0 { return crc32_ieee(&[]); } // SAFETY: Caller guarantees `ptr..ptr+len` is valid in Wasm linear memory. let bytes = unsafe { core::slice::from_raw_parts(ptr, len) }; crc32_ieee(bytes) } /// Pointer to the latest UTF-8 JSON forensic report written by `wasm_analyze_article`. #[no_mangle] pub extern "C" fn wasm_report_ptr() -> *const u8 { REPORT_JSON_BUF.with(|buf| buf.borrow().as_ptr()) } /// Byte length of the latest UTF-8 JSON forensic report. #[no_mangle] pub extern "C" fn wasm_report_len() -> usize { REPORT_JSON_BUF.with(|buf| buf.borrow().len()) } /// Pointer to the latest sanitized UTF-8 string produced by `wasm_sanitize_text`. #[no_mangle] pub extern "C" fn wasm_sanitized_ptr() -> *const u8 { SANITIZED_TEXT_BUF.with(|buf| buf.borrow().as_ptr()) } /// Byte length of the latest sanitized UTF-8 string. #[no_mangle] pub extern "C" fn wasm_sanitized_len() -> usize { SANITIZED_TEXT_BUF.with(|buf| buf.borrow().len()) } /// Count of zero-width watermark characters stripped in the last `wasm_sanitize_text` call. #[no_mangle] pub extern "C" fn wasm_removed_zw_count() -> u32 { REMOVED_ZW_COUNT.with(|c| *c.borrow()) } /// Count of atypical spaces normalized in the last `wasm_sanitize_text` call. #[no_mangle] pub extern "C" fn wasm_normalized_space_count() -> u32 { NORMALIZED_SPACE_COUNT.with(|c| *c.borrow()) } /// Pointer to the last UTF-8 error message if `wasm_analyze_article` returned `0`. #[no_mangle] pub extern "C" fn wasm_error_ptr() -> *const u8 { ERROR_MSG_BUF.with(|e| e.borrow().as_ptr()) } /// Byte length of the last UTF-8 error message. #[no_mangle] pub extern "C" fn wasm_error_len() -> usize { ERROR_MSG_BUF.with(|e| e.borrow().len()) } /// Analyzes a UTF-8 article in WebAssembly linear memory and writes the JSON forensic report. /// Returns the report byte length on success, or `0` on domain validation error. /// /// # Safety /// If `len > 0`, `ptr` must reference `len` readable bytes in Wasm linear memory. #[no_mangle] pub unsafe extern "C" fn wasm_analyze_article( ptr: *const u8, len: usize, genre_code: u8, sensitivity_code: u8, inspect_watermarks: u8, inspect_markdown: u8, ) -> usize { if ptr.is_null() || len == 0 { return record_error(&DetectError::EmptyDocument); } // SAFETY: Caller (`withWasmBuffer`) allocated and populated `ptr..ptr+len`. let raw_bytes = unsafe { core::slice::from_raw_parts(ptr, len) }; let Ok(raw_str) = core::str::from_utf8(raw_bytes) else { return record_error(&DetectError::InvalidUtf8); }; let genre = match GenrePreset::from_code(genre_code) { Ok(g) => g, Err(e) => return record_error(&e), }; let sensitivity = match SensitivityMode::from_code(sensitivity_code) { Ok(s) => s, Err(e) => return record_error(&e), }; let validated = match ValidatedArticle::try_new(raw_str) { Ok(v) => v, Err(e) => return record_error(&e), }; let cfg = DetectionConfig { genre, sensitivity, inspect_watermarks: inspect_watermarks != 0, inspect_markdown_symmetry: inspect_markdown != 0, }; match analyze_article(validated, cfg) { Ok(report) => { let json = serialize_report_json(&report); let json_len = json.len(); REPORT_JSON_BUF.with(|slot| { *slot.borrow_mut() = json; }); json_len } Err(e) => record_error(&e), } } /// Strips invisible Unicode watermarks (`ZWSP`, `ZWNJ`, `ZWJ`, `WJ`, `BOM`) and normalizes /// atypical LLM spaces (`U+202F`, `U+00A0`) to standard ASCII spaces. /// Returns byte length of the sanitized UTF-8 buffer (or `0` if invalid UTF-8). /// /// # Safety /// If `len > 0`, `ptr` must reference `len` readable bytes in Wasm linear memory. #[no_mangle] pub unsafe extern "C" fn wasm_sanitize_text(ptr: *const u8, len: usize) -> usize { if ptr.is_null() || len == 0 { SANITIZED_TEXT_BUF.with(|slot| slot.borrow_mut().clear()); REMOVED_ZW_COUNT.with(|c| *c.borrow_mut() = 0); NORMALIZED_SPACE_COUNT.with(|c| *c.borrow_mut() = 0); return 0; } // SAFETY: Caller (`withWasmBuffer`) allocated and populated `ptr..ptr+len`. let raw_bytes = unsafe { core::slice::from_raw_parts(ptr, len) }; let Ok(raw_str) = core::str::from_utf8(raw_bytes) else { return record_error(&DetectError::InvalidUtf8); }; let result = sanitize_text(raw_str); let out_len = result.cleaned.len(); REMOVED_ZW_COUNT.with(|c| { *c.borrow_mut() = u32::try_from(result.removed_zero_width).unwrap_or(u32::MAX); }); NORMALIZED_SPACE_COUNT.with(|c| { *c.borrow_mut() = u32::try_from(result.normalized_spaces).unwrap_or(u32::MAX); }); SANITIZED_TEXT_BUF.with(|slot| { *slot.borrow_mut() = result.cleaned; }); out_len } #[cfg(test)] #[allow(clippy::expect_used)] mod tests { use super::*; use crate::model::VerdictBand; use crate::watermark::{is_atypical_llm_space, is_zero_width_watermark}; #[test] fn crc32_ieee_matches_standard_check_vector() { assert_eq!(crc32_ieee(b"123456789"), 0xCBF4_3926); } #[test] fn validation_rejects_empty_and_too_short_inputs_algebraically() { assert_eq!( ValidatedArticle::try_new(" \n\t "), Err(DetectError::EmptyDocument) ); assert_eq!( ValidatedArticle::try_new("Too short"), Err(DetectError::TooShort { observed_chars: 8, minimum_chars: 12 }) ); } // Law: forall s, sanitize_text(&sanitize_text(s).cleaned).cleaned == sanitize_text(s).cleaned #[test] fn sanitize_text_is_idempotent_and_erases_all_watermarks() { let fixtures = [ "Hello\u{200B} world\u{202F}from\u{FEFF} LLM\u{2060} output\u{00A0}test!", "值得\u{200C}注意\u{200D}的是\u{202F}这是一段测试文本。", "Clean human sentence without hidden codepoints.", ]; for sample in fixtures { let once = sanitize_text(sample); let twice = sanitize_text(&once.cleaned); assert_eq!(once.cleaned, twice.cleaned); assert_eq!(twice.removed_zero_width, 0); assert_eq!(twice.normalized_spaces, 0); assert!(!once .cleaned .chars() .any(|c| is_zero_width_watermark(c) || is_atypical_llm_space(c))); } } #[test] fn stereotypical_english_llm_essay_scores_substantially_higher_than_spiky_human_note() { let ai_essay = "\ In today's rapidly evolving landscape, artificial intelligence plays a pivotal role in transforming modern industries. \ Furthermore, it is important to note that organizations must delve into ethical frameworks to ensure sustainable innovation. \ Moreover, fostering a sense of transparency underscores the importance of responsible governance across global teams.\u{200B}\u{202F}\n\ - **Operational Efficiency**: Streamlining repetitive workflows across departments to maximize productivity.\n\ - **Strategic Alignment**: Navigating the complexities of digital transformation with a multifaceted approach.\n\ - **Scalable Architecture**: Building resilient pipelines that empower stakeholders across the ecosystem.\n\ In conclusion, embracing this paradigm shift is a testament to the enduring power of human-centric technology."; let human_note = "\ Clearly, this expenditure pattern is a massive misallocation of resources. \ The last 20% of network hashpower provides vastly less value to the ecosystem than those same resources would \ if they had gone into research and core protocol development. So why not just.... cut the PoW budget by 20% and redirect the funds to those other things instead? \ In early 2020, Justin Sun bought Steem-the-company, which is not the same thing as Steem-the-blockchain but did hold about 20% of the STEEM token supply."; let v_ai = ValidatedArticle::try_new(ai_essay).expect("valid ai sample"); let v_hu = ValidatedArticle::try_new(human_note).expect("valid human sample"); let rep_ai = analyze_article(v_ai, DetectionConfig::default()).expect("ai report"); let rep_hu = analyze_article(v_hu, DetectionConfig::default()).expect("human report"); assert!( rep_ai.overall_ai_score.get() > 0.72, "Expected high AI score, got {}", rep_ai.overall_ai_score.get() ); assert_eq!(rep_ai.verdict, VerdictBand::AiGenerated); assert!( rep_hu.overall_ai_score.get() < 0.42, "Expected low AI score for spiky human prose, got {}", rep_hu.overall_ai_score.get() ); assert!(rep_ai.overall_ai_score.get() > rep_hu.overall_ai_score.get() + 0.35); } #[test] fn chinese_llm_template_article_distinguished_from_colloquial_human_writing() { let zh_ai = "\ 在当今快速发展的数字时代,人工智能正在各个领域扮演着至关重要的角色。值得注意的是,企业不仅需要关注底层算力的提升,\ 而且还需要从多维度构建全方位的安全治理体系,从而实现真正的生态闭环。\u{200B}与此同时,如何平衡技术创新与隐私保护也是一把双刃剑。\ 总而言之,综上所述,只有持续赋能核心业务场景,才能在激烈的市场竞争中立于不败之地。"; let zh_human = "\ 凌晨两点半被报警电话吵醒,爬起来一看又是上游那个祖传接口超时!明明上周五联调的时候拍胸脯说绝对抗得住三千并发,\ 结果才刚切了十分之一流量,数据库连接池就直接打满躺平了。算了,先手动降级把队列消费停掉保命,明天早会必须把锅甩清楚。"; let r_ai = analyze_article( ValidatedArticle::try_new(zh_ai).expect("valid zh ai"), DetectionConfig::default(), ) .expect("zh ai report"); let r_hu = analyze_article( ValidatedArticle::try_new(zh_human).expect("valid zh human"), DetectionConfig::default(), ) .expect("zh human report"); assert!( r_ai.overall_ai_score.get() > r_hu.overall_ai_score.get() + 0.25, "Expected Chinese AI text ({}) > Chinese human text ({})", r_ai.overall_ai_score.get(), r_hu.overall_ai_score.get() ); assert!(r_ai.removable_watermark_chars >= 1); } // Law (Shapley Local Accuracy): forall x, expected_margin + sum_j shap[j] == unshifted_raw_margin(x) #[test] fn treeshap_satisfies_exact_local_accuracy_additivity_law() { use crate::gbdt::predict_with_treeshap; use crate::hash_tables::MlTablesView; use crate::ml_features::{extract_ml_features_with_tables, EMBEDDED_ML_TABLES}; use crate::trained_forest::with_trained_gbdt; let tables = MlTablesView::from_bytes(EMBEDDED_ML_TABLES).expect("valid ml_tables.bin"); let fixtures = [ "Clearly, this expenditure pattern is a massive misallocation of resources across protocol development.", "In today's rapidly evolving landscape, artificial intelligence plays a pivotal role in fostering innovation.", "刚刚我在下面看了一下,一些吐槽我觉得特别好。每天都有五亿人在说我们做的不好。", "プログラミングは本来楽しいものであり、楽しいからこそ能力が向上するのだと私は思います。", ]; for sample in fixtures { let bundle = extract_ml_features_with_tables(sample, true, tables); let pred = with_trained_gbdt(|gbdt| predict_with_treeshap(gbdt, &bundle.features, 0.0)) .expect("valid gbdt"); let shap_sum: f64 = pred.shap_values.iter().copied().sum(); let reconstructed = pred.expected_margin + shap_sum; let diff = (reconstructed - pred.raw_margin).abs(); assert!( diff < 1e-8, "TreeSHAP local accuracy violated: reconstructed={reconstructed}, raw={}, diff={diff}", pred.raw_margin ); } } // Law (Concave Mixture MLE Monotonicity): increasing AI token counts strictly increases/preserves alpha_hat in [0, 1] #[test] fn mixture_mle_solver_is_bounded_and_monotone() { use crate::hash_tables::{solve_mixture_mle, MlTablesView}; use crate::ml_features::EMBEDDED_ML_TABLES; use std::collections::BTreeMap; let tables = MlTablesView::from_bytes(EMBEDDED_ML_TABLES).expect("valid ml_tables.bin"); let mut human_heavy = BTreeMap::new(); let mut ai_heavy = BTreeMap::new(); for b in 0..512u16 { let (p, q) = tables.lookup_mle_probs(b); if p > q * 1.15 { human_heavy.insert(b, 10); ai_heavy.insert(b, 1); } else if q > p * 1.15 { human_heavy.insert(b, 1); ai_heavy.insert(b, 10); } } if !human_heavy.is_empty() && !ai_heavy.is_empty() { let (a_lo, _, _) = solve_mixture_mle(&human_heavy, tables); let (a_hi, _, _) = solve_mixture_mle(&ai_heavy, tables); assert!((0.0..=1.0).contains(&a_lo)); assert!((0.0..=1.0).contains(&a_hi)); assert!( a_hi >= a_lo, "Expected monotone MLE alpha_hat: {a_hi} >= {a_lo}" ); } } }