//! Closed bridge from a declared Settings command to a platform-kept flow.//!//! A flow is not an engine write. The UI owns its confirmation, credential,//! screenshot, or navigation and performs any later native method itself.use serde_json::{json, Map, Value};usecrate::{handle::CottonHandle, methods::MethodError};const FLOWS: &[&str] = &["leaveDatabase", "reportProblem", "vaultUnlock", "signIn", "signOut", "eraseThisDevice", "shareInk", "keepFilm","removeFilmDownload", "keepBook", "removeBookDownload","addBookFile", "keepSong", "removeSongDownload", "keepAlbum", "removeAlbumDownload",];/// This device's own acts the app runs, offered only on this device's own/// row (`device.json`'s Sign in, Sign out and Erase — the app holds the/// credential, `PersonalObject` — and Share ink, the ink the phone kept,/// `InkCapture`).const SESSION_FLOWS: &[&str] = &["signIn", "signOut", "eraseThisDevice", "shareInk"];/// Answer the closed platform request for a kept flow.////// Wire shape: `{flow, origin_table, origin_id, target_database?}`. `target_database`/// is accepted only for Leave, because method dispatch consumes the ordinary/// top-level database scope before this module sees a request.pubfn open_flow(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let request = request.as_object().ok_or_else(|| bad("settings.openFlow needs an object"))?; reject_unknown(request, &["flow", "origin_table", "origin_id", "target_database"])?;let flow = required_text(request, "flow")?;if !FLOWS.contains(&flow) { returnErr(bad("settings.openFlow has an unknown flow")); }let table = required_text(request, "origin_table")?;let id = required_text(request, "origin_id")?;let target = request.get("target_database").map(|value| nonempty(value, "target_database")).transpose()?;let captured_database = handle.client().reading_database_id();let database = match flow {"leaveDatabase" => leave_database(handle, table, id, target)?,"reportProblem" => {if table != "project_feedback" || id != "new" || target.is_some() {returnErr(bad("reportProblem is a report-list flow")); } captured_database }// Unlock only resumes the already-refused native action. It takes no// callback or method, so it cannot be turned into an arbitrary write."vaultUnlock" => {if target.is_some() { returnErr(bad("vaultUnlock does not take a database target")); } captured_database } film ifsuper::films::FLOWS.contains(&film) => {if target.is_some() { returnErr(bad("a film's flow does not take a database target")); }super::films::flow_origin(&handle.client(), film, table, id)?; captured_database } book ifsuper::books::FLOWS.contains(&book) => {if target.is_some() { returnErr(bad("a book's flow does not take a database target")); }super::books::flow_origin(&handle.client(), book, table, id)?; captured_database } song ifsuper::songs::FLOWS.contains(&song) => {if target.is_some() { returnErr(bad("a song's or an album's flow does not take a database target")); }super::songs::flow_origin(&handle.client(), song, table, id)?; captured_database } session if SESSION_FLOWS.contains(&session) => {let own = handle.client().self_device_id();if table != "device" || own.as_deref() != Some(id) || target.is_some() {returnErr(bad("this flow comes only from this device's own row")); } captured_database } _ => unreachable!("FLOWS checked above"), };Ok(json!({"platform_action": "open_flow","flow": flow,"origin": {"table": table, "id": id},"database": database, }))}fn leave_database( handle: &CottonHandle, table: &str, id: &str, target: Option<&str>,) -> Result<Option<String>, MethodError> {let database = leave_target(table, id, target)?;// name_database is the authoritative held-file guard; it never silently// falls back to the current database when a stale page supplies an id.let _named = handle.client().name_database(Some(database)) .map_err(|reason| MethodError::new("database_not_held", reason))?;let page = crate::phone::database_appearance::page(&handle.client(), &Map::from_iter([("databaseId".into(), Value::from(database))])) .map_err(|reason| MethodError::new("unreadable", reason))?;if page["canLeave"] != Value::Bool(true) {returnErr(MethodError::new("flow_refused", "this database cannot be left")); }Ok(Some(database.to_string()))}fn leave_target<'a>(table: &str, id: &'a str, target: Option<&'a str>) -> Result<&'a str, MethodError> {if table != "database" { returnErr(bad("leaveDatabase comes only from a database row")); }let database = target.unwrap_or(id);if id != database { returnErr(bad("leaveDatabase target does not match its origin")); }Ok(database)}fn required_text<'a>(object: &'a Map<String, Value>, key: &str) -> Result<&'a str, MethodError> { object.get(key).ok_or_else(|| bad(&format!("settings.openFlow needs `{key}`"))) .and_then(|value| nonempty(value, key))}fn nonempty<'a>(value: &'a Value, key: &str) -> Result<&'a str, MethodError> { value.as_str().filter(|value| !value.trim().is_empty()) .ok_or_else(|| bad(&format!("`{key}` is non-empty text")))}fn reject_unknown(object: &Map<String, Value>, allowed: &[&str]) -> Result<(), MethodError> {if object.keys().any(|key| !allowed.contains(&key.as_str())) {returnErr(bad("settings.openFlow has an unknown field")); }Ok(())}fn bad(message: &str) -> MethodError { MethodError::new("bad_request", message) }#[cfg(test)]mod tests {usesuper::*;use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};fn open(path: &std::path::Path) -> CottonHandle {CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: path.to_string_lossy().into(), previous_container_path: None, }, app_version: None, time_zone: Some("Etc/UTC".into()), device_secret: Some(URL_SAFE_NO_PAD.encode([17u8; 32])), vault_secret: None, flavor: cotton_core::flavor::Flavor::Dev, manifest: None, }).expect("phone handle") }/// RULE: a kept-flow bridge is a closed platform effect, so a settings/// command can never smuggle a follow-up method, arguments, or a claimed/// successful mutation through an otherwise read-only boundary. #[test]fn bridge_refuses_arbitrary_follow_up_data() {let request = Map::from_iter([ ("flow".into(), Value::from("reportProblem")), ("origin_table".into(), Value::from("report")), ("origin_id".into(), Value::from("new")), ("method".into(), Value::from("usage.record")), ]); assert!(reject_unknown(&request, &["flow", "origin_table", "origin_id", "target_database"]).is_err()); assert!(!FLOWS.contains(&"usage.record")); }/// RULE: Leave carries the exact row id as its target; a changed page must/// not redirect the irreversible flow to another held database. #[test]fn leave_origin_and_target_must_be_identical() { assert!(leave_target("database", "shown-database", Some("old-database")).is_err()); assert_eq!(leave_target("database", "shown-database", None).unwrap(), "shown-database"); }/// RULE: dispatch returns a descriptor with the original database scope,/// never a receipt or an engine result that would falsely say the report/// sheet completed before the person has written and sent anything. #[test]fn dispatcher_returns_a_scoped_report_flow_descriptor_without_a_write() {let dir = tempfile::tempdir().expect("tempdir");let handle = open(dir.path());let born = crate::methods::dispatch(&handle, "workspace.startLocal", &json!({})) .expect("personal database");let database = born["workspaceId"].as_str().expect("workspace id");let answer = crate::methods::dispatch(&handle, "settings.openFlow", &json!({"flow":"reportProblem", "origin_table":"project_feedback", "origin_id":"new" })).expect("closed report descriptor"); assert_eq!(answer["platform_action"], "open_flow"); assert_eq!(answer["flow"], "reportProblem"); assert_eq!(answer["origin"], json!({"table":"project_feedback","id":"new"})); assert_eq!(answer["database"], database); assert!(answer.get("receipt").is_none()); assert!(answer.get("engine").is_none()); }/// RULE: Sign in, Sign out, Share ink and Erase are this device's own acts: each is a/// flow the app runs from this device's own row, and from any other row it/// is refused, so no page can sign the phone out from another device's card. #[test]fn session_flows_come_only_from_this_devices_own_row() {let dir = tempfile::tempdir().expect("tempdir");let handle = open(dir.path());crate::methods::dispatch(&handle, "workspace.startLocal", &json!({})).expect("personal database");let own = handle.client().self_device_id().expect("this device's id");for flow in SESSION_FLOWS {let answer = crate::methods::dispatch(&handle, "settings.openFlow", &json!({"flow": flow, "origin_table": "device", "origin_id": own })).expect("this device's own flow"); assert_eq!(answer["platform_action"], "open_flow"); assert_eq!(answer["flow"], *flow); assert!(answer.get("receipt").is_none());for (table, id) in [("device", "another-device"), ("todo", own.as_str())] { assert!(crate::methods::dispatch(&handle, "settings.openFlow", &json!({"flow": flow, "origin_table": table, "origin_id": id })).is_err(), "{flow} from {table}/{id}"); } } }}