//! "Send a report" (phone diagnostics part 3, owner's ruling 12 Oct 2026): the//! app bundles what a session needs to debug it without the owner — its//! reported state, the last lines of its own log and the core's, and the//! device's registry files — into ONE text document in the owner's personal//! database, "Phone report · 12 Oct 16:02". It is an ordinary capture//! (`phone::media::write_media`, kind `document`), so it is written on this//! device's copy and goes up with the next exchange: it works offline, and an//! assistant reads it with `get_document` / `get_document_bytes`.//!//! NOTHING SECRET LEAVES IN IT. Every line passes through//! [`cotton_core::device::reported_state::redact_line`] (the shared secret//! rules, `Bearer`, URL queries, `token=`-style pairs), and the registry files//! are read as JSON with every credential-named value replaced before they are//! printed (procedure c47ae4d4).use std::path::Path;use serde_json::{Map, Value};use cotton_core::device::reported_state::redact_line;use cotton_core::media::keys::MediaKind;usecrate::handle::CottonHandle;usecrate::methods::MethodError;usecrate::phone::media::{write_media, CaptureMediaArgs, CaptureTiers};pubconst METHOD: &str = "diagnostics.report";/// How many lines of each log a report keeps, newest last.pubconst LOG_LINES: usize = 500;/// A log line longer than this is cut: one runaway line must not be the report.const LINE_MAX: usize = 2_000;const REDACTED: &str = "‹redacted›";/// One headed part of the report.#[derive(Debug, Clone, PartialEq, Eq)]pubstructSection {pub heading: String,pub lines: Vec<String>,}implSection {pubfn new(heading: implInto<String>, lines: Vec<String>) -> Self {Self { heading: heading.into(), lines } }}/// The report's text: the title, then each section under its heading, every/// line redacted. The one place a report's words are put together, so the one/// place the redaction is proven.#[must_use]pubfn report_text(title: &str, sections: &[Section]) -> String {letmut out = String::new(); out.push_str(&clean(title)); out.push('\n');for section in sections { out.push_str("\n## "); out.push_str(&clean(§ion.heading)); out.push('\n');if section.lines.is_empty() { out.push_str("(nothing)\n"); }for line in §ion.lines { out.push_str(&clean(line)); out.push('\n'); } } out}/// One line, redacted and capped.fn clean(line: &str) -> String {let line = redact_line(line);if line.chars().count() <= LINE_MAX {return line; }letmut cut: String = line.chars().take(LINE_MAX - 1).collect(); cut.push('…'); cut}/// The last [`LOG_LINES`] of `lines`.#[must_use]pubfn tail(lines: Vec<String>) -> Vec<String> {let skip = lines.len().saturating_sub(LOG_LINES); lines.into_iter().skip(skip).collect()}/// A registry file as lines: its JSON pretty-printed with every value under a/// credential-named key replaced, or the reason it could not be read. A file/// that is not JSON is never printed raw — its bytes are not known to be safe.#[must_use]pubfn registry_file(path: &Path) -> Vec<String> {let raw = match std::fs::read_to_string(path) {Ok(raw) => raw,Err(error) if error.kind() == std::io::ErrorKind::NotFound => {return vec!["(no file)".to_string()]; }Err(error) => return vec![format!("(not read: {error})")], };match serde_json::from_str::<Value>(&raw) {Ok(mut value) => { redact_json(&mut value); serde_json::to_string_pretty(&value) .unwrap_or_default() .lines() .map(str::to_string) .collect() }Err(error) => vec![format!("(not JSON, not printed: {error})")], }}/// Replace every value whose key names a credential, at any depth.pubfn redact_json(value: &mutValue) {match value {Value::Object(map) => {for (key, child) in map.iter_mut() {if names_a_credential(key) && !child.is_null() { *child = Value::from(REDACTED); } else { redact_json(child); } } }Value::Array(items) => items.iter_mut().for_each(redact_json), _ => {} }}/// `deviceKey`, `privateKey`, `accessToken`, `secret`, `password`,/// `passcode`, `signature`, `pairingCode` … — but not `keyId`-style names/// that merely start with the word.fn names_a_credential(key: &str) -> bool {let key = key.to_ascii_lowercase(); ["token", "secret", "password", "passcode", "signature", "cookie", "credential"] .iter() .any(|word| key.contains(word)) || key.ends_with("key") || key.ends_with("code")// AUDIT E: `privateKeyB64`, `vaultKeyWrap`, `wrappedKey` and their kind, which the endings above miss. || key.contains("private") || key.contains("wrap") || (key.contains("key") && (key.ends_with("b64") || key.ends_with("base64") || key.ends_with("bytes")))}#[cfg(test)]mod credential_names { #[test]fn a_key_by_any_spelling_is_redacted_and_a_key_id_is_not() {for name in ["privateKey", "privateKeyB64", "vaultKeyWrap", "wrappedKey", "dataKeyBase64", "deviceKey", "accessToken", "pairingCode"] { assert!(super::names_a_credential(name), "{name}"); }for name in ["keyId", "keyVersion", "keyboard", "title"] { assert!(!super::names_a_credential(name), "{name}"); } }}/// The state as pretty lines, or why there is none.#[must_use]pubfn state_lines(state: Option<&Value>) -> Vec<String> {match state {Some(state) => serde_json::to_string_pretty(state) .unwrap_or_default() .lines() .map(str::to_string) .collect(),None => vec!["(not read: the sync loop was busy)".to_string()], }}/// `diagnostics.report { title, log?: [string], extra?: [{heading, lines}] }`/// — build the report and file it in the personal database: the Debug group/// (`shell::diagnostics::debug_sections`), then `extra` (what only the app can/// say), the app's own log ring (Swift, oldest first), the core's, and the/// registry files.////// Answers `{documentId, text}`; a refused write answers `{refused, text}` so/// the app can say why and hand the text over another way — never a silent/// success.pubfn report(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let title = request .get("title") .and_then(Value::as_str) .map(str::trim) .filter(|title| !title.is_empty()) .ok_or_else(|| MethodError::new("bad_request", "`title` names the report"))? .to_string();let client = handle.client();let layout = client.layout().clone();letmut sections: Vec<Section> = super::diagnostics::debug_sections(handle) .into_iter() .map(|section| Section::new(section.heading, section.lines)) .collect(); sections.extend(extra_sections(request)?); sections.push(Section::new("App log", tail(strings(request.get("log"))))); sections.push(Section::new("Core log", tail(handle.log().lines().iter().map(super::log_ring::file_line).collect()), )); sections.push(Section::new("connection.json", registry_file(&layout.connection_json()))); sections.push(Section::new("database-appearance.json", registry_file(&layout.root().join(crate::phone::database_appearance::FILE)), ));let text = report_text(&title, §ions);match file(&client, &layout, &title, &text) {Ok(document_id) => Ok(serde_json::json!({ "documentId": document_id, "text": text })),Err(refused) => Ok(serde_json::json!({ "refused": refused, "text": text })), }}fn strings(value: Option<&Value>) -> Vec<String> { value .and_then(Value::as_array) .map(|items| items.iter().filter_map(Value::as_str).map(str::to_string).collect()) .unwrap_or_default()}fn extra_sections(request: &Value) -> Result<Vec<Section>, MethodError> {letSome(extra) = request.get("extra") else {returnOk(Vec::new()); };let items = extra .as_array() .ok_or_else(|| MethodError::new("bad_request", "`extra` is a list of {heading, lines}"))?;Ok(items .iter() .filter_map(|item| {let heading = item.get("heading")?.as_str()?;Some(Section::new(heading, strings(item.get("lines")))) }) .collect())}/// Write the text to a scratch file, capture it as a document, title it, and/// drop the scratch copy (the store holds its own). Answers the document id.pub(crate) fn file( client: &super::client::ClientController, layout: &cotton_client::layout::Layout, title: &str, text: &str,) -> Result<String, String> {let dir = layout.root().join("client").join("reports"); std::fs::create_dir_all(&dir).map_err(|error| format!("the report could not be written: {error}"))?;let path = dir.join(format!("report-{}.txt", std::process::id()));// not a copy: a report file. std::fs::write(&path, text).map_err(|error| format!("the report could not be written: {error}"))?;let args = CaptureMediaArgs { path: path.clone(), mime: "text/plain".to_string(), filename: Some(format!("{title}.txt")), kind: MediaKind::Document, taken_at: None, tiers: CaptureTiers::default(), book: None, upload: Default::default(), };let device_key = client.self_device_id();let written = client.write_rows(METHOD, &mut |ctx| {let answer = write_media(ctx, layout, &args, device_key.as_deref())?;let id = answer .get("recordId") .and_then(Value::as_str) .ok_or("the capture named no document")? .to_string();letmut patch = Map::new(); patch.insert("title".to_string(), Value::from(title)); cotton_tools::mcp::handlers::common::update_row(ctx, "cotton_documents", &id, patch) .map_err(|failure| failure.to_string())?;Ok(Value::from(id)) });// not a copy: a report file.let _ = std::fs::remove_file(&path);let written = written?;crate::authoring::own_answer(written) .as_str() .map(str::to_string) .ok_or_else(|| "the capture named no document".to_string())}#[cfg(test)]#[path = "report_tests.rs"]mod tests;