diff --git a/src/agent.rs b/src/agent.rs index 7b568bb..9adfc68 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1968,26 +1968,67 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< if call.name == crate::vault::TOOL || call.name == crate::vault::CARD_TOOL || call.name == crate::vault::CONTACT_TOOL { enum Plan { Login(Box), - Card(String), - Contact(String), + Card((String, crate::vault_store::Item)), + Contact((String, crate::vault_store::Item)), } - let planned: Result<(Plan, String, String), String> = if call.name == crate::vault::TOOL { - crate::vault::plan_login(&call.args).map(|pl| { - let q = pl.question(); - let grant = if pl.matched { format!("login:{}", pl.host) } else { String::new() }; - (Plan::Login(Box::new(pl)), q, grant) - }) - } else if call.name == crate::vault::CARD_TOOL { - crate::vault::plan_card(&call.args).map(|(host, c)| { - let msg = format!("用保險庫的卡片({} •••• {})在 {host} 填入付款資料(Bot 看不到卡號和安全碼)", c.display_title(), c.last4); - (Plan::Card(host), msg, String::new()) - }) - } else { - crate::vault::plan_contact(&call.args).map(|(host, c)| { - let msg = format!("把保險庫的聯絡資訊「{}」填進 {host} 的表單", c.display_title()); - let grant = format!("contact:{host}"); - (Plan::Contact(host), msg, grant) - }) + // The fill lands in the same browser browser_* uses: the chosen computer's, + // the cloud box's, or this one's. The vault store and the person's approval + // stay on this computer; a chosen computer spends one entry's secret per call. + let (place, _who) = browser_place(&job, "browser_open", &call.args); + let v0 = tools::args_of(&call.args); + let profile = v0["profile"].as_str().unwrap_or("").to_string(); + let plan_here = || -> Result<(Plan, String, String), String> { + if call.name == crate::vault::TOOL { + crate::vault::plan_login(&call.args).map(|pl| { + let q = pl.question(); + let grant = if pl.matched { format!("login:{}", pl.host) } else { String::new() }; + (Plan::Login(Box::new(pl)), q, grant) + }) + } else if call.name == crate::vault::CARD_TOOL { + crate::vault::plan_card(&call.args).map(|(host, c)| { + let msg = format!("用保險庫的卡片({} •••• {})在 {host} 填入付款資料(Bot 看不到卡號和安全碼)", c.display_title(), c.last4); + (Plan::Card((host, c)), msg, String::new()) + }) + } else { + crate::vault::plan_contact(&call.args).map(|(host, c)| { + let msg = format!("把保險庫的聯絡資訊「{}」填進 {host} 的表單", c.display_title()); + let grant = format!("contact:{host}"); + (Plan::Contact((host, c)), msg, grant) + }) + } + }; + // On a chosen computer the page lives over the relay: read its url there, + // plan with this computer's vault, fill there only after the person allows. + let planned: Result<(Plan, String, String), String> = match &place { + BrowserAt::Device(h) => match crate::remote::run_on_device(h, crate::vault::REMOTE_TOOL, &serde_json::json!({"kind": "host", "profile": profile}).to_string(), &job.via_name) + .and_then(|r| if r["ok"].as_bool().unwrap_or(false) { Ok(r) } else { Err(r["text"].as_str().unwrap_or("那台電腦的瀏覽器無法使用").to_string()) }) + { + Ok(t) => { + let host = t["host"].as_str().unwrap_or("").to_string(); + let url = t["url"].as_str().unwrap_or("").to_string(); + if call.name == crate::vault::TOOL { + crate::vault::plan_login_on(&host, &v0).map(|pl| { + let q = pl.question(); + let grant = if pl.matched { format!("login:{}", pl.host) } else { String::new() }; + (Plan::Login(Box::new(pl)), q, grant) + }) + } else if call.name == crate::vault::CARD_TOOL { + crate::vault::plan_card_at(&v0, &url).map(|(h, c)| { + let msg = format!("用保險庫的卡片({} •••• {})在 {h} 填入付款資料(Bot 看不到卡號和安全碼)", c.display_title(), c.last4); + (Plan::Card((h, c)), msg, String::new()) + }) + } else { + crate::vault::plan_contact_at(&v0).map(|c| { + let msg = format!("把保險庫的聯絡資訊「{}」填進 {host} 的表單", c.display_title()); + let grant = format!("contact:{host}"); + (Plan::Contact((host.clone(), c)), msg, grant) + }) + } + } + Err(e) => Err(e), + } + BrowserAt::Box => crate::botbrowser::in_box(plan_here), + BrowserAt::Here => plan_here(), }; let (output, status) = match planned { Err(e) => (e, ToolStatus::Failed), @@ -2012,10 +2053,20 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< ("使用者沒有允許使用保險庫的這個項目。請改問使用者。".to_string(), ToolStatus::Denied) } else { started(); - let r = match plan { - Plan::Login(pl) => crate::vault::fill_login_with(&pl, tools::args_of(&call.args)["submit"].as_bool().unwrap_or(false), remember_site), - Plan::Card(host) => crate::vault::fill_card_on(&call.args, Some(&host)), - Plan::Contact(host) => crate::vault::fill_contact_on(&call.args, Some(&host)), + let submit = tools::args_of(&call.args)["submit"].as_bool().unwrap_or(false); + let r = match (&plan, &place) { + (Plan::Login(pl), BrowserAt::Device(h)) => remote_vault_login(h, &job, pl, submit, remember_site), + (Plan::Login(pl), _) => crate::vault::fill_login_with(pl, submit, remember_site), + (Plan::Card((host, c)), BrowserAt::Device(h)) => { + let a = serde_json::json!({"kind": "form", "values": crate::vault::card_values(c), "site": host, "profile": profile, "https": true}).to_string(); + remote_vault_page(h, &job, &a).and_then(|page| crate::vault::card_fill_text(c, &page)) + } + (Plan::Card((host, _)), _) => crate::vault::fill_card_on(&call.args, Some(host)), + (Plan::Contact((host, c)), BrowserAt::Device(h)) => { + let a = serde_json::json!({"kind": "form", "values": crate::vault::contact_values(c), "site": host, "profile": profile}).to_string(); + remote_vault_page(h, &job, &a).and_then(|page| crate::vault::contact_fill_text(c, &page)) + } + (Plan::Contact((host, _)), _) => crate::vault::fill_contact_on(&call.args, Some(host)), }; match r { Ok(t) => (t, ToolStatus::Done), @@ -2418,6 +2469,25 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< }); } +/// A vault fill on the computer that has the browser: send this one entry's secret over the +/// account's relay, get the page's answer. The host guard in the fill script there holds. +fn remote_vault_page(host: &str, job: &Job, args: &str) -> Result { + let r = crate::remote::run_on_device(host, crate::vault::REMOTE_TOOL, args, &job.via_name)?; + if r["ok"].as_bool().unwrap_or(false) { + Ok(r["page"].clone()) + } else { + Err(r["text"].as_str().unwrap_or("那台電腦填入失敗").to_string()) + } +} + +/// A vault login on the computer that has the browser: the secret from this computer's vault, +/// the fill there, the wording here (the vault store and the new-site memory stay here). +fn remote_vault_login(host: &str, job: &Job, pl: &crate::vault::LoginPlan, submit: bool, remember_site: bool) -> Result { + let (u, p, source) = crate::vault::login_secret_of(pl)?; + let args = serde_json::json!({"kind": "login", "username": u, "password": p, "site": pl.host, "profile": pl.profile, "submit": submit}).to_string(); + remote_vault_page(host, job, &args).and_then(|page| crate::vault::login_fill_text(pl, &u, &source, submit, &page, remember_site)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/remote.rs b/src/remote.rs index 6081620..d4de36b 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -985,6 +985,11 @@ fn device_run(v: &Value, s: &Settings, via_relay: bool, from: &str) -> Resp { let (text, ok, img) = crate::web::run_full(tool, &v.to_string(), &std::sync::atomic::AtomicBool::new(false)); return Resp::json(&json!({"text": text, "ok": ok, "image": img})); } + // 保險庫填入 on this computer's browser: the brain planned it, the person approved it; this + // one command carries that entry's secret (vault::REMOTE_TOOL); the page's host guard holds. + if tool == crate::vault::REMOTE_TOOL { + return Resp::json(&crate::vault::run_remote(args)); + } if crate::macapps::is_mac_tool(tool) && cfg!(target_os = "macos") { let (text, ok) = crate::macapps::run(tool, args); return Resp::json(&json!({"text": text, "ok": ok})); diff --git a/src/vault.rs b/src/vault.rs index f4f0871..da5c3da 100644 --- a/src/vault.rs +++ b/src/vault.rs @@ -14,6 +14,35 @@ const LABEL: &str = "AnyBot 登入"; pub const LIST_TOOL: &str = "vault_list"; pub const CARD_TOOL: &str = "browser_fill_card"; pub const CONTACT_TOOL: &str = "browser_fill_contact"; +/// The vault's internal tool: the mechanical fill on the computer that has the browser. The +/// brain plans (the vault store stays there), the person approves, and one entry's secret +/// rides this one command over the account's encrypted relay to the person's own computer; +/// the script there spends it only on the page it belongs to (the host guard bails out when +/// the page changed). Never offered to the model: only AnyBot-to-AnyBot. +pub const REMOTE_TOOL: &str = "browser_vault_fill"; + +/// One vault step on this machine's browser. kind: "host" — the current tab (for the brain's +/// plan); "login" — username/password into the login page; "form" — card/contact values from +/// the brain into the form. Answers {ok, page}, {ok, url, host} or {ok:false, text}. +pub fn run_remote(args: &str) -> Value { + let v = crate::tools::args_of(args); + let profile = profile_of(&v); + let ran = |js: &str| -> Value { + match crate::botbrowser::eval_current(profile.as_deref(), js) { + Ok((_, r)) => serde_json::json!({"ok": true, "page": r.as_str().and_then(|s| serde_json::from_str::(s).ok()).unwrap_or(Value::Null)}), + Err(e) => serde_json::json!({"ok": false, "text": e}), + } + }; + match v["kind"].as_str().unwrap_or("") { + "host" => match crate::botbrowser::eval_current(profile.as_deref(), "1") { + Ok((url, _)) => serde_json::json!({"ok": true, "url": url, "host": host_of(&url)}), + Err(e) => serde_json::json!({"ok": false, "text": e}), + }, + "login" => ran(&fill_script_for_host(v["username"].as_str().unwrap_or(""), v["password"].as_str().unwrap_or(""), v["submit"].as_bool().unwrap_or(false), v["site"].as_str())), + "form" => ran(&form_fill_script_for_host(&v["values"], v["site"].as_str(), v["https"].as_bool().unwrap_or(false))), + other => serde_json::json!({"ok": false, "text": format!("不懂的保險庫填入種類「{other}」")}), + } +} /// The vault tools the bot gets (with AnyBot's browser). pub fn specs() -> Vec { @@ -410,16 +439,29 @@ pub fn fill_login(plan: &LoginPlan, submit: bool) -> Result { } pub fn fill_login_with(plan: &LoginPlan, submit: bool, remember_site: bool) -> Result { - let (username, password, source) = match (&plan.item, &plan.other) { - (Some(i), _) => { - let (u, p) = crate::vault_store::login_secret(&i.id).ok_or("保險庫裡沒有這筆登入資訊")?; - (u, p, "保險庫") - } - (None, Some(l)) => (l.username.clone(), l.password.clone(), l.source), - _ => return Err("沒有可用的登入資料".into()), - }; + let (username, password, source) = login_secret_of(plan)?; let (_, r) = crate::botbrowser::eval_current(plan.profile.as_deref(), &fill_script_for_host(&username, &password, submit, Some(&plan.host)))?; let got: Value = r.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default(); + login_fill_text(plan, &username, &source, submit, &got, remember_site) +} + +/// The secret of a planned login: (username, password, where it came from). The brain keeps +/// the vault; only this one entry's secret travels to the computer that has the browser. +pub(crate) fn login_secret_of(plan: &LoginPlan) -> Result<(String, String, String), String> { + match (&plan.item, &plan.other) { + (Some(i), _) => { + let (u, p) = crate::vault_store::login_secret(&i.id).ok_or("保險庫裡沒有這筆登入資訊")?; + Ok((u, p, "保險庫".to_string())) + } + (None, Some(l)) => Ok((l.username.clone(), l.password.clone(), l.source.to_string())), + _ => Err("沒有可用的登入資料".into()), + } +} + +/// What a fill script answered (`got`, its JSON), said to the bot: the host guard bails on a +/// changed page, the wording tells the bot the next step. 「一律允許」 remembers the new site +/// in the vault — here, on the brain, where the vault lives. +pub(crate) fn login_fill_text(plan: &LoginPlan, username: &str, source: &str, submit: bool, got: &Value, remember_site: bool) -> Result { if let Some(now_host) = got["wrong_host"].as_str() { return Err(format!("頁面網址在等待核准期間變成了 {now_host}(原本是 {}),已取消填入密碼以防釣魚。", plan.host)); } @@ -543,11 +585,16 @@ fn filled_summary(r: &Value) -> (Vec<&'static str>, u64) { /// For the approval question: (current host, card label) without secrets. pub fn plan_card(args: &str) -> Result<(String, crate::vault_store::Item), String> { let v = crate::tools::args_of(args); - let id = v["card_id"].as_str().unwrap_or("").to_string(); - let card = crate::vault_store::get(&id).filter(|i| i.kind == crate::vault_store::Kind::Card).ok_or("保險庫裡沒有這張卡片(先用 vault_list 看 id)")?; let profile = profile_of(&v); let (url, _) = crate::botbrowser::eval_current(profile.as_deref(), "1")?; - let host = host_of(&url); + plan_card_at(&v, &url) +} + +/// The card plan for the page open at `url` — read on the computer that has the browser. +pub(crate) fn plan_card_at(v: &Value, url: &str) -> Result<(String, crate::vault_store::Item), String> { + let id = v["card_id"].as_str().unwrap_or("").to_string(); + let card = crate::vault_store::get(&id).filter(|i| i.kind == crate::vault_store::Kind::Card).ok_or("保險庫裡沒有這張卡片(先用 vault_list 看 id)")?; + let host = host_of(url); if !url.starts_with("https://") && host != "127.0.0.1" && host != "localhost" { return Err(format!("目前的分頁不是安全的 HTTPS 網頁({url}),為了保護卡號不會填入。")); } @@ -564,23 +611,32 @@ pub fn fill_card_on(args: &str, expected_host: Option<&str>) -> Result Value { + serde_json::json!({ "cc-number": c.number, "cc-exp": format!("{:02}/{:02}", c.exp_month, c.exp_year % 100), "cc-exp-month": format!("{:02}", c.exp_month), "cc-exp-year": c.exp_year.to_string(), "cc-csc": c.csc, "cc-name": c.holder, - }); - let (_, r) = crate::botbrowser::eval_current(profile.as_deref(), &form_fill_script_for_host(&values, expected_host, true))?; - let got: Value = r.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default(); + }) +} + +/// What the card fill script answered, said to the bot (no secrets in the words). +pub(crate) fn card_fill_text(c: &crate::vault_store::Item, got: &Value) -> Result { if let Some(now_host) = got["wrong_host"].as_str() { return Err(format!("頁面網址在等待核准期間變成了 {now_host},已取消填入卡號。")); } if got.get("insecure").is_some() { return Err("頁面已切換成非 HTTPS 連線,已取消填入卡號。".into()); } - let (names, frames) = filled_summary(&got); + let (names, frames) = filled_summary(got); if names.is_empty() { return Err(if frames > 0 { "這一頁的付款欄位在付款服務的框架裡,AnyBot 填不進去。請使用者自己填卡號,或改用網站提供的其他付款方式。".into() @@ -593,10 +649,15 @@ pub fn fill_card_on(args: &str, expected_host: Option<&str>) -> Result Result<(String, crate::vault_store::Item), String> { let v = crate::tools::args_of(args); - let id = v["contact_id"].as_str().unwrap_or("").to_string(); - let c = crate::vault_store::get(&id).filter(|i| i.kind == crate::vault_store::Kind::Contact).ok_or("保險庫裡沒有這筆聯絡資訊(先用 vault_list 看 id)")?; let profile = profile_of(&v); - Ok((current_host_in(profile.as_deref())?, c)) + let host = current_host_in(profile.as_deref())?; + Ok((host, plan_contact_at(&v)?)) +} + +/// The contact item an id names (no browser: works on the brain for a page read remotely). +pub(crate) fn plan_contact_at(v: &Value) -> Result { + let id = v["contact_id"].as_str().unwrap_or("").to_string(); + crate::vault_store::get(&id).filter(|i| i.kind == crate::vault_store::Kind::Contact).ok_or("保險庫裡沒有這筆聯絡資訊(先用 vault_list 看 id)".into()) } #[cfg(test)] @@ -607,18 +668,27 @@ pub fn fill_contact(args: &str) -> Result { pub fn fill_contact_on(args: &str, expected_host: Option<&str>) -> Result { let v = crate::tools::args_of(args); let profile = profile_of(&v); - let (_, c) = plan_contact(args)?; - let values = serde_json::json!({ + let c = plan_contact_at(&v)?; + let (_, r) = crate::botbrowser::eval_current(profile.as_deref(), &form_fill_script_for_host(&contact_values(&c), expected_host, false))?; + let got: Value = r.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default(); + contact_fill_text(&c, &got) +} + +/// The contact form values (they travel to the browser's computer for one fill). +pub(crate) fn contact_values(c: &crate::vault_store::Item) -> Value { + serde_json::json!({ "name": c.name, "address-line1": c.address.line1, "address-line2": c.address.line2, "address-level2": c.address.city, "address-level1": c.address.region, "postal-code": c.address.postal, "country": c.address.country, "tel": c.phones.first().cloned().unwrap_or_default(), "email": c.emails.first().cloned().unwrap_or_default(), - }); - let (_, r) = crate::botbrowser::eval_current(profile.as_deref(), &form_fill_script_for_host(&values, expected_host, false))?; - let got: Value = r.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default(); + }) +} + +/// What the contact fill script answered, said to the bot. +pub(crate) fn contact_fill_text(c: &crate::vault_store::Item, got: &Value) -> Result { if let Some(now_host) = got["wrong_host"].as_str() { return Err(format!("頁面網址在等待核准期間變成了 {now_host},已取消填入聯絡資訊。")); } - let (names, _) = filled_summary(&got); + let (names, _) = filled_summary(got); if names.is_empty() { return Err("這一頁找不到地址或聯絡欄位。".into()); }