From 4e8fb6a8f55ec9e50282c6a4a719d819f7f19b7c Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 4 Nov 2026 13:46:18 +0100 Subject: [PATCH] [browser] Autofill for Edge and Chrome: custos-browser (which login fits which page, native messaging frames), custos-native (the host), the MV3 extension --- Cargo.lock | 17 ++ crates/custos-browser/Cargo.toml | 10 + crates/custos-browser/src/framing.rs | 66 +++++++ crates/custos-browser/src/lib.rs | 281 +++++++++++++++++++++++++++ crates/custos-native/Cargo.toml | 15 ++ crates/custos-native/src/main.rs | 240 +++++++++++++++++++++++ extension/background.js | 91 +++++++++ extension/content.js | 173 +++++++++++++++++ extension/manifest.json | 38 ++++ extension/popup.css | 77 ++++++++ extension/popup.html | 20 ++ extension/popup.js | 50 +++++ 12 files changed, 1078 insertions(+) create mode 100644 crates/custos-browser/Cargo.toml create mode 100644 crates/custos-browser/src/framing.rs create mode 100644 crates/custos-browser/src/lib.rs create mode 100644 crates/custos-native/Cargo.toml create mode 100644 crates/custos-native/src/main.rs create mode 100644 extension/background.js create mode 100644 extension/content.js create mode 100644 extension/manifest.json create mode 100644 extension/popup.css create mode 100644 extension/popup.html create mode 100644 extension/popup.js diff --git a/Cargo.lock b/Cargo.lock index fb1a50b..2844dc8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -327,6 +327,13 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "custos-browser" +version = "0.9.0" +dependencies = [ + "zeroize", +] + [[package]] name = "custos-gen" version = "0.14.1" @@ -373,6 +380,16 @@ dependencies = [ "thiserror", ] +[[package]] +name = "custos-native" +version = "0.9.0" +dependencies = [ + "custos-browser", + "serde_json", + "windows-sys", + "zeroize", +] + [[package]] name = "custos-qr" version = "0.14.1" diff --git a/crates/custos-browser/Cargo.toml b/crates/custos-browser/Cargo.toml new file mode 100644 index 0000000..40c9b0f --- /dev/null +++ b/crates/custos-browser/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "custos-browser" +description = "Custos in the browser: which login may be filled into which page, and Chrome's native messaging frames" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +zeroize.workspace = true diff --git a/crates/custos-browser/src/framing.rs b/crates/custos-browser/src/framing.rs new file mode 100644 index 0000000..96ed8b9 --- /dev/null +++ b/crates/custos-browser/src/framing.rs @@ -0,0 +1,66 @@ +//! Chrome's native messaging frames: a 32-bit length in native byte order (little-endian on every machine +//! Custos runs on), then that many bytes of UTF-8 JSON. Messages to the host are capped here at 64 KiB (the +//! desktop's pipe limit); Chrome itself refuses messages to the browser over 1 MB. +//! +//! Frames can hold a login's password: they are `Zeroizing`, so the bytes are wiped when dropped. + +use std::io::{self, Read, Write}; + +use zeroize::Zeroizing; + +/// The largest message the extension may send to the host. +pub const MAX_TO_HOST: usize = 64 * 1024; +/// The largest message Chrome accepts from a host. +pub const MAX_TO_BROWSER: usize = 1024 * 1024; + +/// Reads one frame. `Ok(None)` when the browser closed the stream (the extension disconnected). +pub fn read_frame(r: &mut impl Read) -> io::Result>>> { + let mut len = [0u8; 4]; + match r.read_exact(&mut len) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None), + Err(e) => return Err(e), + } + let n = u32::from_le_bytes(len) as usize; + if n > MAX_TO_HOST { + return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large")); + } + let mut buf = Zeroizing::new(vec![0u8; n]); + r.read_exact(&mut buf)?; + Ok(Some(buf)) +} + +/// Writes one frame and flushes it (Chrome reads frame by frame). +pub fn write_frame(w: &mut impl Write, msg: &[u8]) -> io::Result<()> { + if msg.len() > MAX_TO_BROWSER { + return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large")); + } + w.write_all(&(msg.len() as u32).to_le_bytes())?; + w.write_all(msg)?; + w.flush() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn frames_round_trip_and_oversized_ones_are_refused() { + let mut out = Vec::new(); + write_frame(&mut out, br#"{"op":"browser_status"}"#).unwrap(); + write_frame(&mut out, b"{}").unwrap(); + assert_eq!(&out[..4], &23u32.to_le_bytes()); + let mut r = &out[..]; + assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), br#"{"op":"browser_status"}"#); + assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), b"{}"); + assert!(read_frame(&mut r).unwrap().is_none(), "end of stream is the extension going away"); + // A length over the limit is refused before anything is allocated. + let big = ((MAX_TO_HOST + 1) as u32).to_le_bytes(); + assert_eq!(read_frame(&mut &big[..]).unwrap_err().kind(), io::ErrorKind::InvalidData); + // A frame cut short is an error, not a short message. + let mut cut = 10u32.to_le_bytes().to_vec(); + cut.extend_from_slice(b"{}"); + assert!(read_frame(&mut &cut[..]).is_err()); + assert!(write_frame(&mut Vec::new(), &vec![b' '; MAX_TO_BROWSER + 1]).is_err()); + } +} diff --git a/crates/custos-browser/src/lib.rs b/crates/custos-browser/src/lib.rs new file mode 100644 index 0000000..d59e2ae --- /dev/null +++ b/crates/custos-browser/src/lib.rs @@ -0,0 +1,281 @@ +//! What the browser extension may fill where (docs/BROWSER.md). The extension and its native host live in +//! this public repository; the rules that decide which login goes into which page live here too, so the +//! desktop app and anyone reviewing the extension apply the same ones. +//! +//! - [`Origin`]: a page's origin as the browser reports it (never as the page claims). +//! - [`login_matches`]: does a login's stored URL belong to that origin? Its host or a subdomain of it, +//! same scheme, same port when the login names one. Never a "similar" name, so look-alike domains +//! (`paypa1.com`, `paypal.com.evil.net`) never match. +//! - [`framing`]: Chrome's native messaging frames (a 4-byte little-endian length, then JSON). +//! +//! ``` +//! use custos_browser::{login_matches, Origin}; +//! let page = Origin::parse("https://accounts.github.com/login?return=/")?; +//! assert!(login_matches("https://github.com", &page).is_some()); +//! assert!(login_matches("https://github.com.evil.net", &page).is_none()); +//! # Ok::<(), custos_browser::OriginError>(()) +//! ``` + +pub mod framing; + +use std::fmt; + +/// A page's origin: scheme, host (lowercase, no trailing dot) and port (the scheme's default when absent). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Origin { + pub scheme: Scheme, + pub host: String, + pub port: u16, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Scheme { + Https, + Http, +} + +impl Scheme { + fn default_port(self) -> u16 { + match self { + Scheme::Https => 443, + Scheme::Http => 80, + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub enum OriginError { + /// Not an `http(s)://host…` URL. + NotWeb, + /// A host that is empty, too long or has characters a host cannot have. + BadHost, + BadPort, +} + +impl fmt::Display for OriginError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + OriginError::NotWeb => "not a web address", + OriginError::BadHost => "not a valid host", + OriginError::BadPort => "not a valid port", + }) + } +} + +impl std::error::Error for OriginError {} + +/// Splits `scheme://host:port/…` (userinfo refused: `https://bank.com@evil.net` must not read as bank.com). +fn split(url: &str, default: Option) -> Result<(Scheme, String, Option), OriginError> { + let url = url.trim(); + let (scheme, rest) = match url.split_once("://") { + Some((s, rest)) => match s.to_ascii_lowercase().as_str() { + "https" => (Scheme::Https, rest), + "http" => (Scheme::Http, rest), + _ => return Err(OriginError::NotWeb), + }, + None => (default.ok_or(OriginError::NotWeb)?, url), + }; + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + if authority.contains('@') { + return Err(OriginError::BadHost); + } + let (host, port) = if let Some(v6) = authority.strip_prefix('[') { + let (h, after) = v6.split_once(']').ok_or(OriginError::BadHost)?; + (format!("[{}]", h.to_ascii_lowercase()), after.strip_prefix(':')) + } else { + match authority.rsplit_once(':') { + Some((h, p)) => (h.to_ascii_lowercase(), Some(p)), + None => (authority.to_ascii_lowercase(), None), + } + }; + let host = host.trim_end_matches('.').to_string(); + let ok = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_' | '[' | ']' | ':'); + if host.is_empty() || host.len() > 253 || !host.chars().all(ok) || host.contains("..") { + return Err(OriginError::BadHost); + } + let port = match port { + None | Some("") => None, + Some(p) => Some( + p.parse::() + .map_err(|_| OriginError::BadPort) + .and_then(|n| if n == 0 { Err(OriginError::BadPort) } else { Ok(n) })?, + ), + }; + Ok((scheme, host, port)) +} + +impl Origin { + /// A page URL as the browser reports it (`sender.url`, the tab's URL). + pub fn parse(url: &str) -> Result { + let (scheme, host, port) = split(url, None)?; + Ok(Origin { scheme, port: port.unwrap_or(scheme.default_port()), host }) + } + + fn is_loopback(&self) -> bool { + self.host == "localhost" + || self.host.ends_with(".localhost") + || self.host == "127.0.0.1" + || self.host == "[::1]" + } + + fn is_ip(&self) -> bool { + self.host.starts_with('[') + || self.host.split('.').all(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit())) + } + + /// May a login be filled into this page at all? Only over https, or plain http on this machine. + pub fn fillable(&self) -> bool { + self.scheme == Scheme::Https || self.is_loopback() + } +} + +impl fmt::Display for Origin { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let scheme = match self.scheme { + Scheme::Https => "https", + Scheme::Http => "http", + }; + if self.port == self.scheme.default_port() { + write!(f, "{scheme}://{}", self.host) + } else { + write!(f, "{scheme}://{}:{}", self.host, self.port) + } + } +} + +/// How well a login's URL fits a page, best first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Match { + /// The page is on the login's host itself (`www.` counts as the host). + Exact, + /// The page is on a subdomain of the login's host (`accounts.github.com` for `github.com`). + Subdomain, +} + +/// Does the login stored with `item_url` belong on `page`? `None` when it must not be offered there. +/// +/// A stored URL without a scheme (`github.com/login`) means https. The page must be fillable, the schemes +/// equal, the port equal when the stored URL names one (else the page's must be the scheme's default), and +/// the page's host the login's host or a subdomain of it. A login for a bare top-level name (`com`) or for +/// an IP address matches only that exact host. +pub fn login_matches(item_url: &str, page: &Origin) -> Option { + if !page.fillable() { + return None; + } + let (scheme, host, port) = split(item_url, Some(Scheme::Https)).ok()?; + if scheme != page.scheme || port.unwrap_or(scheme.default_port()) != page.port { + return None; + } + let strip = |h: &str| h.strip_prefix("www.").map(str::to_string).unwrap_or_else(|| h.to_string()); + let (item, at) = (strip(&host), strip(&page.host)); + if item == at { + return Some(Match::Exact); + } + if page.is_ip() || !item.contains('.') || item.starts_with('[') { + return None; + } + at.strip_suffix(&item).filter(|rest| rest.ends_with('.')).map(|_| Match::Subdomain) +} + +/// The best match among a login's URLs. +pub fn best_match<'a>(urls: impl IntoIterator, page: &Origin) -> Option { + urls.into_iter().filter_map(|u| login_matches(u, page)).min() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn page(u: &str) -> Origin { + Origin::parse(u).unwrap() + } + + #[test] + fn origins_parse_as_the_browser_reports_them() { + assert_eq!( + page("https://GitHub.com./login?x=1#y"), + Origin { scheme: Scheme::Https, host: "github.com".into(), port: 443 } + ); + assert_eq!(page("http://localhost:5173/").port, 5173); + assert_eq!(page("https://[::1]:8443/").host, "[::1]"); + assert_eq!(page("https://bank.cz").to_string(), "https://bank.cz"); + assert_eq!(page("http://127.0.0.1:8080/a").to_string(), "http://127.0.0.1:8080"); + for bad in [ + "ftp://x.cz", + "file:///C:/a.html", + "chrome-extension://abc/", + "javascript:alert(1)", + "about:blank", + "https://", + "https://a..b.cz/", + "https://bank.cz:99999/", + "https://bank.cz:0/", + "https://bad host.cz/", + ] { + assert!(Origin::parse(bad).is_err(), "{bad}"); + } + // Userinfo is refused outright: it is how look-alike links hide their real host. + assert_eq!(Origin::parse("https://bank.cz@evil.net/"), Err(OriginError::BadHost)); + } + + #[test] + fn a_login_matches_its_host_and_its_subdomains_only() { + let gh = page("https://github.com/login"); + assert_eq!(login_matches("https://github.com", &gh), Some(Match::Exact)); + assert_eq!(login_matches("github.com/login", &gh), Some(Match::Exact), "no scheme means https"); + assert_eq!(login_matches("https://www.github.com/", &gh), Some(Match::Exact)); + assert_eq!(login_matches("https://github.com", &page("https://www.github.com/")), Some(Match::Exact)); + assert_eq!(login_matches("https://github.com", &page("https://gist.github.com/")), Some(Match::Subdomain)); + // A login for a subdomain does not go to its parent or its siblings. + assert_eq!(login_matches("https://gist.github.com", &gh), None); + assert_eq!(login_matches("https://gist.github.com", &page("https://api.github.com/")), None); + // Look-alikes never match. + for evil in [ + "https://github.com.evil.net/", + "https://evilgithub.com/", + "https://github.co/", + "https://githuh.com/", + "https://xn--gthub-cta.com/", + ] { + assert_eq!(login_matches("https://github.com", &page(evil)), None, "{evil}"); + } + } + + #[test] + fn scheme_port_and_plain_http_are_strict() { + // Never over plain http on the internet, even for a login saved with http. + assert_eq!(login_matches("http://intranet.example", &page("http://intranet.example/")), None); + // On this machine plain http is fine, with the port the login names. + assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:5173/login")), Some(Match::Exact)); + assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:8080/")), None); + assert_eq!(login_matches("http://localhost", &page("http://localhost:8080/")), None); + // An https login does not go to the http page of the same host, nor the other way round. + assert_eq!(login_matches("https://localhost", &page("http://localhost/")), None); + assert_eq!( + login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa:5001/")), + Some(Match::Exact) + ); + assert_eq!(login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa/")), None); + } + + #[test] + fn bare_names_and_addresses_match_exactly_only() { + assert_eq!(login_matches("https://192.168.1.1", &page("https://192.168.1.1/")), Some(Match::Exact)); + assert_eq!(login_matches("https://168.1.1", &page("https://192.168.1.1/")), None); + assert_eq!(login_matches("https://cz", &page("https://bank.cz/")), None); + assert_eq!(login_matches("https://[::1]", &page("https://[::1]/")), Some(Match::Exact)); + assert_eq!(login_matches("not a url at all", &page("https://bank.cz/")), None); + assert_eq!(login_matches("", &page("https://bank.cz/")), None); + } + + #[test] + fn the_best_of_several_urls_wins() { + let p = page("https://www.github.com/"); + assert_eq!(best_match(["https://gitlab.com", "https://github.com"], &p), Some(Match::Exact)); + assert_eq!(best_match(["https://gitlab.com"], &p), None); + assert_eq!( + best_match(["https://github.com", "https://www.github.com"], &page("https://gist.github.com/")), + Some(Match::Subdomain) + ); + } +} diff --git a/crates/custos-native/Cargo.toml b/crates/custos-native/Cargo.toml new file mode 100644 index 0000000..8d61733 --- /dev/null +++ b/crates/custos-native/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "custos-native" +description = "Custos's native messaging host: the browser extension's way to the desktop Custos" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +custos-browser = { path = "../custos-browser" } +serde_json.workspace = true +zeroize.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Pipes", "Win32_System_Threading"] } diff --git a/crates/custos-native/src/main.rs b/crates/custos-native/src/main.rs new file mode 100644 index 0000000..9eae75e --- /dev/null +++ b/crates/custos-native/src/main.rs @@ -0,0 +1,240 @@ +//! custos-native: the browser extension's native messaging host (docs/BROWSER.md). Edge or Chrome starts it +//! when the extension connects, and talks to it over stdin/stdout in native messaging frames. It forwards +//! three requests to the desktop Custos over its Domi pipe and returns the answers: +//! +//! - `browser_status`: is Custos running and unlocked; +//! - `browser_match { origin }`: the logins for a page (title, username; never a password); +//! - `browser_fill { id, origin }`: one login's username, password and 2FA code, when it matches the page. +//! +//! The host adds nothing and decides nothing: Custos checks the origin against the login and asks the +//! user once whether this host may use web logins. It forwards only those three requests, rebuilt from +//! their known fields, so the extension cannot reach Custos's other Domi requests through it. It refuses +//! a pipe that is not served by custos.exe. + +use std::io::{self, Write}; + +use custos_browser::framing::{read_frame, write_frame}; +use serde_json::{Value, json}; +use zeroize::Zeroizing; + +const PIPE: &str = r"\\.\pipe\custos-domi"; +const OPS: &[&str] = &["browser_status", "browser_match", "browser_fill"]; + +/// The request Custos gets: only known fields, of the right types. +fn rebuild(msg: &[u8]) -> Result { + let v: Value = serde_json::from_slice(msg).map_err(|_| "bad_request")?; + let op = v.get("op").and_then(Value::as_str).filter(|o| OPS.contains(o)).ok_or("bad_request")?; + let mut out = json!({ "op": op, "app": "Custos for your browser" }); + if op != "browser_status" { + let origin = v.get("origin").and_then(Value::as_str).filter(|o| o.len() <= 2048).ok_or("bad_request")?; + out["origin"] = origin.into(); + } + if op == "browser_fill" { + let id = v.get("id").and_then(Value::as_str).filter(|i| i.len() <= 128).ok_or("bad_request")?; + out["id"] = id.into(); + } + // The extension's own request number comes back with the answer, so it can pair them. + if let Some(n) = v.get("seq").and_then(Value::as_u64) { + out["seq"] = n.into(); + } + Ok(out) +} + +fn error(code: &str, seq: Option) -> Vec { + serde_json::to_vec(&json!({ "ok": false, "error": code, "seq": seq })).unwrap_or_default() +} + +fn answer(msg: &[u8], pipe: &str) -> Zeroizing> { + let seq = serde_json::from_slice::(msg).ok().and_then(|v| v.get("seq").and_then(Value::as_u64)); + let req = match rebuild(msg) { + Ok(r) => r, + Err(code) => return Zeroizing::new(error(code, seq)), + }; + let bytes = Zeroizing::new(serde_json::to_vec(&req).unwrap_or_default()); + match pipe::call(pipe, &bytes) { + Ok(resp) => { + // Custos does not know the extension's request number: put it back. + let Ok(mut v) = serde_json::from_slice::(&resp) else { + return Zeroizing::new(error("bad_answer", seq)); + }; + if let (Some(obj), Some(n)) = (v.as_object_mut(), seq) { + obj.insert("seq".into(), n.into()); + } + let out = Zeroizing::new(serde_json::to_vec(&v).unwrap_or_default()); + zeroize_json(v); + out + } + Err(code) => Zeroizing::new(error(code, seq)), + } +} + +/// Wipes the strings of a parsed answer (it can hold a password) before dropping it. +fn zeroize_json(v: Value) { + use zeroize::Zeroize; + match v { + Value::String(mut s) => s.zeroize(), + Value::Array(a) => a.into_iter().for_each(zeroize_json), + Value::Object(o) => o.into_iter().for_each(|(_, v)| zeroize_json(v)), + _ => {} + } +} + +fn main() { + // Tests point the host at another Custos. + let pipe = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_string()); + let (mut stdin, stdout) = (io::stdin().lock(), io::stdout()); + loop { + let msg = match read_frame(&mut stdin) { + Ok(Some(m)) => m, + // The extension disconnected, or sent something that is not a frame: done. + Ok(None) | Err(_) => return, + }; + let out = answer(&msg, &pipe); + let mut w = stdout.lock(); + if write_frame(&mut w, &out).is_err() || w.flush().is_err() { + return; + } + } +} + +#[cfg(windows)] +mod pipe { + use std::time::Duration; + + use windows_sys::Win32::Foundation::{ + CloseHandle, ERROR_FILE_NOT_FOUND, ERROR_PIPE_BUSY, GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE, + INVALID_HANDLE_VALUE, + }; + use windows_sys::Win32::Storage::FileSystem::{CreateFileW, OPEN_EXISTING, ReadFile, WriteFile}; + use windows_sys::Win32::System::Pipes::{ + GetNamedPipeServerProcessId, PIPE_READMODE_MESSAGE, SetNamedPipeHandleState, WaitNamedPipeW, + }; + use windows_sys::Win32::System::Threading::{ + OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW, + }; + use zeroize::Zeroizing; + + struct Handle(HANDLE); + impl Drop for Handle { + fn drop(&mut self) { + unsafe { CloseHandle(self.0) }; + } + } + + fn wide(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() + } + + fn server_exe(h: HANDLE) -> Option { + unsafe { + let mut pid = 0u32; + if GetNamedPipeServerProcessId(h, &mut pid) == 0 { + return None; + } + let p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if p.is_null() { + return None; + } + let p = Handle(p); + let mut buf = vec![0u16; 1024]; + let mut len = buf.len() as u32; + let ok = QueryFullProcessImageNameW(p.0, 0, buf.as_mut_ptr(), &mut len); + (ok != 0).then(|| String::from_utf16_lossy(&buf[..len as usize])) + } + } + + /// One request, one answer. The error is a code the extension shows as a sentence. + pub fn call(name: &str, request: &[u8]) -> Result>, &'static str> { + let w = wide(name); + unsafe { + let mut h = INVALID_HANDLE_VALUE; + // Busy: every instance is in use. Not found: Custos is between instances for a moment, or not running. + for _ in 0..50 { + h = CreateFileW( + w.as_ptr(), + GENERIC_READ | GENERIC_WRITE, + 0, + std::ptr::null(), + OPEN_EXISTING, + 0, + std::ptr::null_mut(), + ); + if h != INVALID_HANDLE_VALUE { + break; + } + match GetLastError() { + ERROR_PIPE_BUSY => { + WaitNamedPipeW(w.as_ptr(), 200); + } + ERROR_FILE_NOT_FOUND => std::thread::sleep(Duration::from_millis(20)), + _ => break, + } + } + if h == INVALID_HANDLE_VALUE { + return Err("not_running"); + } + let h = Handle(h); + // Anything else serving this pipe could collect passwords: only custos.exe gets the request. + if !server_exe(h.0).unwrap_or_default().to_lowercase().ends_with("\\custos.exe") { + return Err("not_custos"); + } + let mode = PIPE_READMODE_MESSAGE; + SetNamedPipeHandleState(h.0, &mode, std::ptr::null(), std::ptr::null()); + let mut n = 0u32; + if WriteFile(h.0, request.as_ptr(), request.len() as u32, &mut n, std::ptr::null_mut()) == 0 { + return Err("not_running"); + } + let mut buf = Zeroizing::new(vec![0u8; 64 * 1024]); + if ReadFile(h.0, buf.as_mut_ptr(), buf.len() as u32, &mut n, std::ptr::null_mut()) == 0 { + return Err("no_answer"); + } + buf.truncate(n as usize); + Ok(buf) + } + } +} + +#[cfg(not(windows))] +mod pipe { + pub fn call(_: &str, _: &[u8]) -> Result>, &'static str> { + Err("not_running") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_three_browser_requests_pass_rebuilt_from_known_fields() { + let fill = rebuild(br#"{"op":"browser_fill","id":"abc","origin":"https://github.com","seq":7,"ref":"domi://arca/x","namespace":"arca"}"#).unwrap(); + assert_eq!( + fill, + json!({ "op": "browser_fill", "id": "abc", "origin": "https://github.com", "seq": 7, "app": "Custos for your browser" }) + ); + assert_eq!(rebuild(br#"{"op":"browser_status"}"#).unwrap()["op"], "browser_status"); + assert!(rebuild(br#"{"op":"browser_match","origin":"https://a.cz"}"#).is_ok()); + // Custos's other Domi requests never pass through the browser's host. + for other in [ + r#"{"op":"get","ref":"domi://arca/rclone-config-pass"}"#, + r#"{"op":"list","namespace":"arca"}"#, + r#"{"op":"set","ref":"domi://x/y","value":"v"}"#, + r#"{"op":"subkey"}"#, + ] { + assert_eq!(rebuild(other.as_bytes()), Err("bad_request"), "{other}"); + } + // Missing or wrong fields. + assert!(rebuild(br#"{"op":"browser_fill","origin":"https://a.cz"}"#).is_err()); + assert!(rebuild(br#"{"op":"browser_match","origin":5}"#).is_err()); + assert!(rebuild(b"not json").is_err()); + } + + #[test] + fn without_custos_the_answer_says_so_and_keeps_the_request_number() { + let out = answer(br#"{"op":"browser_status","seq":3}"#, r"\\.\pipe\custos-test-nobody-here"); + let v: Value = serde_json::from_slice(&out).unwrap(); + assert_eq!(v, json!({ "ok": false, "error": "not_running", "seq": 3 })); + let bad: Value = serde_json::from_slice(&answer(br#"{"op":"get","seq":4}"#, PIPE)).unwrap(); + assert_eq!(bad, json!({ "ok": false, "error": "bad_request", "seq": 4 })); + } +} diff --git a/extension/background.js b/extension/background.js new file mode 100644 index 0000000..527c110 --- /dev/null +++ b/extension/background.js @@ -0,0 +1,91 @@ +// Custos's service worker (docs/BROWSER.md). It owns the connection to the native host and answers the +// content scripts and the popup. The page origin it sends to Custos is always the browser's (`sender.url`, +// the tab's URL), never what a page says about itself; Custos decides which logins belong to it. + +const HOST = 'cz.marek_novak.custos'; + +/** The native host, connected on first use; Edge and Chrome keep the worker alive while it is open. */ +let port = null; +let seq = 0; +const waiting = new Map(); + +function connect() { + if (port) return port; + port = chrome.runtime.connectNative(HOST); + port.onMessage.addListener((msg) => { + const w = waiting.get(msg.seq); + if (!w) return; + waiting.delete(msg.seq); + w(msg); + }); + port.onDisconnect.addListener(() => { + // Not registered, or the host exited: every open request fails the same way. + const why = chrome.runtime.lastError?.message ?? ''; + const error = /not found|forbidden/i.test(why) ? 'not_connected' : 'not_running'; + for (const w of waiting.values()) w({ ok: false, error }); + waiting.clear(); + port = null; + }); + return port; +} + +function ask(request) { + return new Promise((resolve) => { + const n = ++seq; + waiting.set(n, resolve); + try { + connect().postMessage({ ...request, seq: n }); + } catch { + waiting.delete(n); + resolve({ ok: false, error: 'not_connected' }); + } + // Custos may wait up to a minute for an unlock or an approval. + setTimeout(() => { + if (waiting.delete(n)) resolve({ ok: false, error: 'no_answer' }); + }, 75_000); + }); +} + +/** `https://host[:port]` of a page or frame URL; null for anything Custos never fills. */ +function originOf(url) { + try { + const u = new URL(url); + if (u.protocol !== 'https:' && u.protocol !== 'http:') return null; + return u.origin; + } catch { + return null; + } +} + +chrome.runtime.onMessage.addListener((msg, sender, reply) => { + // Only this extension's own pages and content scripts reach here; pages cannot send to it. + if (sender.id !== chrome.runtime.id) return false; + (async () => { + switch (msg?.kind) { + case 'status': + return reply(await ask({ op: 'browser_status' })); + case 'match': { + // From a content script: the logins for the frame it runs in. + const origin = originOf(sender.url); + if (!origin) return reply({ ok: false, error: 'no_match' }); + return reply({ ...(await ask({ op: 'browser_match', origin })), origin }); + } + case 'fill': { + // The secrets go back to the frame that asked, and only if Custos agrees the login belongs there. + const origin = originOf(sender.url); + if (!origin || typeof msg.id !== 'string') return reply({ ok: false, error: 'no_match' }); + return reply(await ask({ op: 'browser_fill', id: msg.id, origin })); + } + case 'match-tab': { + // From the popup: the logins for the active tab's page. + const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + const origin = tab && originOf(tab.url); + if (!origin) return reply({ ok: false, error: 'no_match', tab: tab?.id ?? null }); + return reply({ ...(await ask({ op: 'browser_match', origin })), origin, tab: tab.id }); + } + default: + return reply({ ok: false, error: 'bad_request' }); + } + })(); + return true; +}); diff --git a/extension/content.js b/extension/content.js new file mode 100644 index 0000000..3035777 --- /dev/null +++ b/extension/content.js @@ -0,0 +1,173 @@ +// Custos's content script (docs/BROWSER.md): finds login fields, offers the logins Custos has for this +// frame's site, and fills the one the person picks. Nothing is filled without a click. The button and the +// list live in a closed shadow root, out of the page's reach; logins are asked for only when the list opens. +(() => { + const SENTENCES = { + not_connected: 'Connect this browser in Custos first: Settings → Browser.', + not_running: 'Custos is not running. Start it, then try again.', + not_custos: 'Something other than Custos answered. Nothing was sent.', + locked: 'Custos is locked. Unlock it, then try again.', + denied: 'Custos did not allow this browser to use your logins.', + not_found: 'That login is no longer in Custos.', + no_match: 'That login does not belong to this site.', + no_answer: 'Custos did not answer.', + }; + const say = (code) => SENTENCES[code] ?? 'Custos could not do that.'; + + const visible = (el) => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none' && !el.disabled && !el.readOnly; + }; + const isText = (el) => el instanceof HTMLInputElement && ['text', 'email', 'tel'].includes(el.type); + const isOtp = (el) => + el instanceof HTMLInputElement && + (el.autocomplete === 'one-time-code' || /(^|[^a-z])(otp|totp|2fa|mfa|one.?time|verification.?code)/i.test(`${el.name} ${el.id}`)); + const isUserName = (el) => isText(el) && /username|email/i.test(`${el.autocomplete} ${el.name} ${el.id} ${el.type}`); + + /** The username field of a password field: the one the page marks, else the last text field before it. */ + function usernameFor(pw) { + const inputs = [...(pw.form ?? document).querySelectorAll('input')].filter(visible); + const marked = inputs.find((el) => isText(el) && /username|email/i.test(el.autocomplete)); + if (marked) return marked; + for (let i = inputs.indexOf(pw) - 1; i >= 0; i--) if (isText(inputs[i]) && !isOtp(inputs[i])) return inputs[i]; + return null; + } + + /** The fields a login fills, around `near` (the focused field) or on the whole page. */ + function fieldsAround(near) { + const all = [...document.querySelectorAll('input')].filter(visible); + const otp = (near && isOtp(near) ? near : null) ?? all.find(isOtp) ?? null; + const scope = near?.form ? [...near.form.querySelectorAll('input')].filter(visible) : all; + const pass = (near?.type === 'password' ? near : null) ?? scope.find((el) => el.type === 'password') ?? null; + const user = pass ? usernameFor(pass) : ((near && isUserName(near) ? near : null) ?? scope.find(isUserName) ?? null); + return { user, pass, otp }; + } + + const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set; + function put(el, value) { + if (!el || typeof value !== 'string' || !value) return; + el.focus(); + setValue.call(el, value); + el.dispatchEvent(new Event('input', { bubbles: true })); + el.dispatchEvent(new Event('change', { bubbles: true })); + } + + async function fill(id, near) { + const r = await chrome.runtime.sendMessage({ kind: 'fill', id }); + if (!r?.ok) return say(r?.error); + const f = fieldsAround(near); + put(f.user, r.username); + put(f.pass, r.password); + if (f.otp) put(f.otp, r.totp); + return null; + } + + // ---- the button and the list ---- + + const host = document.createElement('custos-fill'); + const root = host.attachShadow({ mode: 'closed' }); + root.innerHTML = ` + + + `; + const chip = root.querySelector('.chip'); + const menu = root.querySelector('.menu'); + let field = null; + + function place() { + if (!field || !field.isConnected) return hide(); + const r = field.getBoundingClientRect(); + chip.style.left = `${Math.max(0, r.right - 28)}px`; + chip.style.top = `${r.top + Math.max(0, (r.height - 24) / 2)}px`; + menu.style.left = `${Math.max(4, r.left)}px`; + menu.style.top = `${r.bottom + 4}px`; + } + + function hide() { + chip.hidden = true; + menu.hidden = true; + field = null; + } + + function note(text) { + menu.replaceChildren(Object.assign(document.createElement('div'), { className: 'note', textContent: text })); + menu.hidden = false; + } + + async function open() { + const target = field; + note('Asking Custos…'); + const r = await chrome.runtime.sendMessage({ kind: 'match' }); + if (field !== target) return; + if (!r?.ok) return note(say(r?.error)); + if (!r.logins.length) return note('Custos has no login for this site.'); + const head = Object.assign(document.createElement('div'), { className: 'head', textContent: 'Custos' }); + const items = r.logins.map((l) => { + const b = Object.assign(document.createElement('button'), { className: 'login', type: 'button' }); + b.setAttribute('role', 'menuitem'); + b.append( + Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }), + Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }), + ); + b.addEventListener('click', async () => { + const why = await fill(l.id, target); + if (why) note(why); + else hide(); + }); + return b; + }); + menu.replaceChildren(head, ...items); + items[0]?.focus(); + } + + chip.addEventListener('click', () => (menu.hidden ? void open() : (menu.hidden = true))); + // A press inside the shadow root is a press on `host` for the page: keep the field's focus logic out of it. + host.addEventListener('mousedown', (e) => e.preventDefault()); + + document.addEventListener( + 'focusin', + (e) => { + const el = e.target; + if (!(el instanceof HTMLInputElement) || !visible(el)) return; + if (el.type !== 'password' && !isOtp(el) && !(isText(el) && fieldsAround(el).pass) && !isUserName(el)) return; + if (!host.isConnected) document.documentElement.append(host); + field = el; + menu.hidden = true; + chip.hidden = false; + place(); + }, + true, + ); + document.addEventListener('keydown', (e) => e.key === 'Escape' && !menu.hidden && hide(), true); + document.addEventListener('pointerdown', (e) => e.target !== host && e.target !== field && hide(), true); + window.addEventListener('scroll', place, true); + window.addEventListener('resize', place); + + // The popup's choice, in the top frame: fill the page's login form. + chrome.runtime.onMessage.addListener((msg, sender, reply) => { + if (sender.id !== chrome.runtime.id || msg?.kind !== 'fill-now' || typeof msg.id !== 'string') return false; + fill(msg.id, null).then((why) => reply({ ok: !why, error: why })); + return true; + }); +})(); diff --git a/extension/manifest.json b/extension/manifest.json new file mode 100644 index 0000000..da2ce26 --- /dev/null +++ b/extension/manifest.json @@ -0,0 +1,38 @@ +{ + "manifest_version": 3, + "name": "Custos", + "short_name": "Custos", + "description": "Fills your logins from the Custos on this computer, only into the site they belong to.", + "version": "0.10.0", + "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs+NtlDNsfBr8q2WbrurbDDfX4rL2dTHsNZToKBKradRb5WZU3wjHAcBMsPlYCiqHF4c/KUyGQ33mpPb0aXA5l3w7n6JgMLHPQBbCw5v076ViF6NIE3a0LOoffDg9ZQmfIJcgjb9baX2qS8VaEFTsEzb/BgQ2Ewx/BPHwZaFeJkucBsIeRZnaPajdqViaNDQdq91VnxIoSGr21Sc+9ZxfZL288S6wATdlDYBUyUZZjVwggHfiwdDmQQMdnFtks2r38V25h+t3ruGCi2mArj8DO1so1oX/NulLNT+6VBP6r/ap228af3rNNcv7sPeriI90ORqzh4Lwni8Hq1lzKuXLrwIDAQAB", + "minimum_chrome_version": "116", + "permissions": [ + "nativeMessaging", + "activeTab" + ], + "background": { + "service_worker": "background.js" + }, + "action": { + "default_title": "Custos", + "default_popup": "popup.html" + }, + "content_scripts": [ + { + "matches": [ + "https://*/*", + "http://localhost/*", + "http://127.0.0.1/*", + "http://*.localhost/*" + ], + "js": [ + "content.js" + ], + "all_frames": true, + "run_at": "document_idle" + } + ], + "content_security_policy": { + "extension_pages": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'" + } +} diff --git a/extension/popup.css b/extension/popup.css new file mode 100644 index 0000000..571295a --- /dev/null +++ b/extension/popup.css @@ -0,0 +1,77 @@ +:root { + color-scheme: dark; + --bg: #101216; + --panel: #15181d; + --hover: #262b33; + --line: #2b3038; + --fg: #e8ebf0; + --muted: #9aa3b1; + --accent: #c9d1dc; +} +body { + width: 320px; + margin: 0; + background: var(--bg); + color: var(--fg); + font: 13px/1.45 "Segoe UI", system-ui, sans-serif; +} +header { + display: flex; + align-items: baseline; + gap: 10px; + padding: 12px 14px 10px; + border-bottom: 1px solid var(--line); + background: var(--panel); +} +.wordmark { + color: var(--accent); + font-size: 12px; + letter-spacing: 0.3em; +} +.site { + overflow: hidden; + color: var(--muted); + white-space: nowrap; + text-overflow: ellipsis; +} +main { + padding: 8px; +} +.note { + margin: 6px 6px 10px; +} +.logins { + margin: 0; + padding: 0; + list-style: none; +} +.logins button { + display: grid; + width: 100%; + padding: 8px 10px; + border: 0; + border-radius: 8px; + background: none; + color: inherit; + font: inherit; + text-align: left; + cursor: pointer; +} +.logins button:hover, +.logins button:focus-visible { + background: var(--hover); + outline: none; +} +.title { + font-weight: 600; +} +.user { + color: var(--muted); + font-size: 12px; +} +footer { + padding: 8px 14px 12px; + border-top: 1px solid var(--line); + color: var(--muted); + font-size: 12px; +} diff --git a/extension/popup.html b/extension/popup.html new file mode 100644 index 0000000..4b2cd2e --- /dev/null +++ b/extension/popup.html @@ -0,0 +1,20 @@ + + + + +Custos + + + + +
+ CUSTOS + +
+
+

Asking Custos…

+
    +
    + + + diff --git a/extension/popup.js b/extension/popup.js new file mode 100644 index 0000000..59f040e --- /dev/null +++ b/extension/popup.js @@ -0,0 +1,50 @@ +// The toolbar popup: the logins Custos has for the active tab's site; a click fills the page's login form +// (the top frame's content script asks for the secrets itself, so they go only where they belong). +const SENTENCES = { + not_connected: 'Connect this browser in Custos first: Settings → Browser.', + not_running: 'Custos is not running. Start it, then try again.', + not_custos: 'Something other than Custos answered. Nothing was sent.', + locked: 'Custos is locked. Unlock it, then try again.', + denied: 'Custos did not allow this browser to use your logins.', + not_found: 'That login is no longer in Custos.', + no_match: 'Custos fills only web pages (https, or this computer).', + no_answer: 'Custos did not answer.', +}; +const say = (code) => SENTENCES[code] ?? 'Custos could not do that.'; +const note = document.getElementById('note'); +const list = document.getElementById('logins'); + +async function show() { + const r = await chrome.runtime.sendMessage({ kind: 'match-tab' }); + if (r?.origin) document.getElementById('site').textContent = new URL(r.origin).host; + if (!r?.ok) { + note.textContent = say(r?.error); + return; + } + if (!r.logins.length) { + note.textContent = 'Custos has no login for this site.'; + return; + } + note.hidden = true; + for (const l of r.logins) { + const li = document.createElement('li'); + const b = Object.assign(document.createElement('button'), { type: 'button' }); + b.append( + Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }), + Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }), + ); + b.addEventListener('click', async () => { + const done = await chrome.tabs.sendMessage(r.tab, { kind: 'fill-now', id: l.id }, { frameId: 0 }).catch(() => null); + if (done?.ok) window.close(); + else { + note.hidden = false; + note.textContent = done?.error ?? 'This page has no login form Custos can fill.'; + } + }); + li.append(b); + list.append(li); + } + list.querySelector('button')?.focus(); +} + +void show();