Cotton code
364 lines · 14.8 KB · RustRaw
//! WhatsApp's passkey step, answered in Chrome.//!//! Since November 2026 WhatsApp asks a device it links for a WebAuthn//! assertion over its own options, for rpId `whatsapp.com`. Only a page whose//! origin is `https://web.whatsapp.com` may ask for one, and only a browser may//! ask at all: a WKWebView in this app is refused outright (macOS 26://! `isUserVerifyingPlatformAuthenticatorAvailable()` false, `credentials.get`//! a `NotAllowedError` in milliseconds) — AuthenticationServices grants//! passkeys for another site's rpId only to an app holding//! `com.apple.developer.web-browser.public-key-credential`, a managed//! entitlement for real browsers. So the assertion is asked in Chrome, through//! the session host's broker (Chrome on a//! pipe, no debugging port): a visible tab at web.whatsapp.com runs//! `navigator.credentials.get` with WhatsApp's options, Chrome shows its own//! passkey sheet (this Mac's passkey under Touch ID, or the phone by its QR),//! and the assertion comes back in the browser's JSON shape for the helper.//! When Chrome refuses without asking (the window was not focused) the page//! shows one large "Use passkey" button, and a click asks again. Nothing of//! WhatsApp Web is kept: its site data is cleared and the tab closed after.use std::path::PathBuf;use std::process::Command;use std::sync::Mutex;use std::time::{Duration, Instant};use serde_json::{json, Value};use tungstenite::Message;/// The session host's name in `Contents/Helpers`: the Chrome broker this/// module asks WhatsApp's passkey through.pub const HOST_BINARY: &str = "cotton-session-host";/// The one origin WhatsApp's rpId admits for a linked web device.pub const ORIGIN: &str = "https://web.whatsapp.com";/// The broker profile the passkey tab opens in: no account lives in it.const PROFILE: &str = "whatsapp/link";/// How long the person has for the passkey sheet: whatsmeow's own handoff/// time, after which the helper ends the pairing anyway.pub const ASK_FOR: Duration = Duration::from_secs(5 * 60);/// How long one plain DevTools call may take.const CALL_TIMEOUT: Duration = Duration::from_secs(30);/// The page script: `OPTIONS` is WhatsApp's request (types.WebAuthnPublicKey,/// base64url fields), answered as `PublicKeyCredential.toJSON()` would.const ASSERT_JS: &str = r#"(async (options) => {  const bytes = (s) => {    s = s.replace(/-/g, '+').replace(/_/g, '/');    while (s.length % 4) s += '=';    return Uint8Array.from(atob(s), (c) => c.charCodeAt(0)).buffer;  };  const text = (buffer) => {    let s = '';    for (const b of new Uint8Array(buffer)) s += String.fromCharCode(b);    return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');  };  const publicKey = { challenge: bytes(options.challenge), rpId: options.rpId };  if (options.timeout) publicKey.timeout = options.timeout;  if (options.userVerification) publicKey.userVerification = options.userVerification;  if (options.extensions) publicKey.extensions = options.extensions;  if (options.allowCredentials) {    publicKey.allowCredentials = options.allowCredentials.map((c) => {      const credential = { type: c.type || 'public-key', id: bytes(c.id) };      if (c.transports) credential.transports = c.transports;      return credential;    });  }  const ask = async () => {    const credential = await navigator.credentials.get({ publicKey });    const r = credential.response;    return {      id: credential.id,      rawId: text(credential.rawId),      type: credential.type,      response: {        clientDataJSON: text(r.clientDataJSON),        authenticatorData: text(r.authenticatorData),        signature: text(r.signature),        userHandle: r.userHandle ? text(r.userHandle) : null,      },    };  };  // WhatsApp Web's own page shows its login QR, which would link a Chrome  // session and not Cotton: the page is covered while Cotton asks.  const cover = document.createElement('div');  cover.id = 'cotton-passkey-cover';  cover.style.cssText = 'position:fixed;inset:0;z-index:2147483646;background:#f7f5f0;display:flex;' +    'flex-direction:column;align-items:center;justify-content:center;gap:24px;padding:32px;' +    'font:17px -apple-system,system-ui;color:#222;text-align:center';  const note = document.createElement('div');  note.id = 'cotton-passkey-note';  note.style.cssText = 'max-width:360px;line-height:1.4';  note.textContent = 'Cotton is linking WhatsApp. Give your passkey when Chrome asks: Touch ID, or scan Chrome\'s QR with your phone.';  cover.append(note);  document.body.append(cover);  try {    const answer = await ask();    cover.remove();    return answer;  } catch {    // Refused without asking the person (the window was not in front), or    // the sheet was dismissed: one large button asks again on a click.    return await new Promise((resolve) => {      const button = document.createElement('button');      button.id = 'cotton-use-passkey';      button.textContent = 'Use passkey';      button.style.cssText = 'width:320px;height:120px;font:600 28px -apple-system,system-ui;border:0;' +        'border-radius:24px;background:#1a7f5a;color:#fff;box-shadow:0 12px 40px rgba(0,0,0,.25);cursor:pointer';      note.textContent = 'Cotton is linking WhatsApp. Click Use passkey, then give it: Touch ID, or scan Chrome\'s QR with your phone.';      button.onclick = async () => {        button.disabled = true;        try {          const answer = await ask();          cover.remove();          resolve(answer);        } catch (again) {          note.textContent = 'The passkey was not given (' + again.name + '). Click Use passkey to try again.';          button.disabled = false;        }      };      cover.append(button);    });  }})(OPTIONS)"#;/// The page script for `options`.pub fn assert_script(options: &Value) -> String {    ASSERT_JS.replace("OPTIONS", &options.to_string())}/// Where WhatsApp's passkey is asked for: [`crate::vault_passkey::VaultPasskey`]/// (Cotton Keys, then [`ChromePasskey`]);/// the importer's tests stand a fake in for it.pub trait PasskeyBrowser: Send + Sync {    /// Open web.whatsapp.com on the person's screen and answer the assertion    /// for `options`, blocking until the person gives it, the tab is closed or    /// [`ASK_FOR`] runs out.    fn assert(&self, pairing: &str, options: &Value) -> Result<Value, String>;    /// Close what [`PasskeyBrowser::assert`] opened for `pairing`, keeping    /// nothing of WhatsApp Web. Harmless when nothing is open.    fn close(&self, pairing: &str);    /// Who answered (or is answering) `pairing`, in the card's words: the    /// vault signer says Cotton Keys, or Chrome and why. `None` says nothing.    fn answered_by(&self, _pairing: &str) -> Option<String> {        None    }    /// The importer's object client, handed in on every probe while WhatsApp    /// is not linked: the vault signer reads its passkey rows through it.    fn see_object(&self, _object: &crate::object::ObjectClient) {}}/// Chrome, through `cotton-session-host browser profile-up`.pub struct ChromePasskey {    host: PathBuf,    data_dir: PathBuf,    /// The tab open for a pairing: (pairing, broker socket, target id).    open: Mutex<Option<(String, PathBuf, String)>>,}impl ChromePasskey {    pub fn new(host: PathBuf, data_dir: PathBuf) -> ChromePasskey {        ChromePasskey {            host,            data_dir,            open: Mutex::new(None),        }    }    /// The profile on the person's screen; answers the broker's socket.    fn profile_up(&self) -> Result<PathBuf, String> {        if !self.host.is_file() {            return Err("This build carries no browser helper (cotton-session-host).".to_string());        }        let out = Command::new(&self.host)            .env("COTTON_MAC_DATA_DIR", &self.data_dir)            .args(["browser", "profile-up", "--profile", PROFILE, "--visible"])            .output()            .map_err(|e| format!("the session host could not start — {e}"))?;        if !out.status.success() {            return Err(String::from_utf8_lossy(&out.stderr).trim().to_string());        }        Ok(PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()))    }    fn forget(socket: &PathBuf, target: &str) {        if let Ok(mut devtools) = Devtools::connect(socket) {            let _ = devtools.call(                None,                "Storage.clearDataForOrigin",                json!({ "origin": ORIGIN, "storageTypes": "all" }),                CALL_TIMEOUT,            );            let _ = devtools.call(                None,                "Target.closeTarget",                json!({ "targetId": target }),                CALL_TIMEOUT,            );        }    }}impl PasskeyBrowser for ChromePasskey {    fn assert(&self, pairing: &str, options: &Value) -> Result<Value, String> {        self.close(pairing);        let socket = self.profile_up()?;        let mut devtools = Devtools::connect(&socket)?;        let made = devtools.call(            None,            "Target.createTarget",            json!({ "url": format!("{ORIGIN}/") }),            CALL_TIMEOUT,        )?;        let target = made["targetId"].as_str().unwrap_or_default().to_string();        *self.open.lock().unwrap_or_else(|p| p.into_inner()) =            Some((pairing.to_string(), socket.clone(), target.clone()));        let answer = (|| {            devtools.call(                None,                "Target.activateTarget",                json!({ "targetId": target }),                CALL_TIMEOUT,            )?;            let attached = devtools.call(                None,                "Target.attachToTarget",                json!({ "targetId": target, "flatten": true }),                CALL_TIMEOUT,            )?;            let session = attached["sessionId"].as_str().map(str::to_string);            // The origin must be WhatsApp's before the page may ask.            let loaded = Instant::now();            loop {                let state = devtools.call(                    session.clone(),                    "Runtime.evaluate",                    json!({ "expression": "location.origin + ' ' + document.readyState", "returnByValue": true }),                    CALL_TIMEOUT,                )?;                let said = state["result"]["value"].as_str().unwrap_or_default();                if said.starts_with(ORIGIN) && !said.ends_with("loading") {                    break;                }                if loaded.elapsed() > Duration::from_secs(60) {                    return Err("web.whatsapp.com did not load in Chrome".to_string());                }                std::thread::sleep(Duration::from_millis(250));            }            devtools.call(                session.clone(),                "Page.bringToFront",                json!({}),                CALL_TIMEOUT,            )?;            let answer = devtools.call(                session,                "Runtime.evaluate",                json!({ "expression": assert_script(options), "awaitPromise": true, "returnByValue": true, "userGesture": true }),                ASK_FOR,            )?;            if let Some(thrown) = answer.get("exceptionDetails") {                let why = thrown["exception"]["description"]                    .as_str()                    .or(thrown["text"].as_str())                    .unwrap_or("the page threw");                return Err(format!("Chrome did not give the passkey: {why}"));            }            Ok(answer["result"]["value"].clone())        })();        self.close(pairing);        answer    }    fn close(&self, pairing: &str) {        let open = {            let mut open = self.open.lock().unwrap_or_else(|p| p.into_inner());            match open.as_ref() {                Some((held, _, _)) if held == pairing => open.take(),                _ => None,            }        };        if let Some((_, socket, target)) = open {            ChromePasskey::forget(&socket, &target);        }    }}/// A blocking DevTools connection to the broker: one call at a time, events/// skipped.struct Devtools {    ws: tungstenite::WebSocket<std::os::unix::net::UnixStream>,    next: u64,}impl Devtools {    fn connect(socket: &PathBuf) -> Result<Devtools, String> {        let stream = std::os::unix::net::UnixStream::connect(socket)            .map_err(|e| format!("the browser broker is not answering — {e}"))?;        let (ws, _) = tungstenite::client("ws://localhost/devtools/browser", stream)            .map_err(|e| format!("the browser broker refused the connection — {e}"))?;        Ok(Devtools { ws, next: 1 })    }    fn call(        &mut self,        session: Option<String>,        method: &str,        params: Value,        timeout: Duration,    ) -> Result<Value, String> {        let id = self.next;        self.next += 1;        let mut message = json!({ "id": id, "method": method, "params": params });        if let Some(session) = &session {            message["sessionId"] = Value::from(session.as_str());        }        self.ws            .send(Message::text(message.to_string()))            .map_err(|e| format!("{method}: {e}"))?;        let deadline = Instant::now() + timeout;        loop {            let left = deadline.saturating_duration_since(Instant::now());            if left.is_zero() {                return Err(format!("{method} was not answered in time"));            }            self.ws                .get_ref()                .set_read_timeout(Some(left.min(Duration::from_secs(1))))                .map_err(|e| e.to_string())?;            match self.ws.read() {                Ok(Message::Text(text)) => {                    let answer: Value = serde_json::from_str(text.as_str()).unwrap_or_default();                    // The tab was closed under the call (a cancel, or the person).                    if answer["method"] == "Target.detachedFromTarget"                        && session                            .as_deref()                            .is_some_and(|s| answer["params"]["sessionId"] == s)                    {                        return Err("the WhatsApp tab was closed".to_string());                    }                    if answer["id"].as_u64() != Some(id) {                        continue;                    }                    return match answer.get("error") {                        Some(error) => Err(format!("{method}: {error}")),                        None => Ok(answer["result"].clone()),                    };                }                Ok(_) => {}                Err(tungstenite::Error::Io(error))                    if matches!(                        error.kind(),                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut                    ) => {}                Err(_) => return Err("the browser closed".to_string()),            }        }    }}