diff --git a/PROTOCOL.md b/PROTOCOL.md index f1caad7..b0c20c1 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -244,7 +244,7 @@ Quick Ask's `quick_shot` fails with `helper_failed` (the message is the helper's | `ask_keychain` | none | `{}`: asks macOS again, in a child, about every secret it refused; sends `keychain_changed` (and again when the child ends). Refused to devices on the LAN | | `lan_status` | none | `{on, port?, urls?, tailscaleUrls?, fingerprint?, devices:[Device]}`: whether the LAN client is serving, its URLs on local networks, its URLs on the user's Tailscale network (the MagicDNS name, then 100.64.0.0/10 addresses), its self-signed certificate's SHA-256 fingerprint, and paired devices | | `set_lan` | `on` | `{}` with the new `lan_status`; turns the LAN client on or off and remembers it in `lan/on` | -| `pair_device` | none | `{code, expiresAt}`: opens a 6-digit pairing code that lasts 5 minutes or 5 tries; only one open at a time | +| `pair_device` | none | `{code, expiresAt, url?, qr?}`: opens a 6-digit pairing code that lasts 5 minutes or 5 tries; only one open at a time. When a network address is available, `url` is `https://:/?pair=` and `qr` is `{size, rows}` for rendering a QR code. Paired Devices also serve `/manifest.webmanifest`, `/icon.svg`, `/sw.js`, and authenticated Web Push endpoints `GET /api/push/key`, `POST /api/push/subscribe`, `POST /api/push/unsubscribe` (VAPID key stored in Keychain; secret prompts never carry bot text or secret names in push payloads). | | `remove_device` | `device` (an id) | `{}`: forgets the device, ending its active sessions immediately | | `get_channels` | `bot` | `{channels: [{kind, hasToken, pairing, chats: [{chat, name}], error}]}`: one entry for `telegram` and one for `discord`. The token itself is never sent back. `pairing` says whether the code last given by `pair_channel` still lets a chat in. `error` says why the channel is not connected, else `null` | | `set_channel` | `bot`, `kind`, `token` (empty: remove) | `{}`: saves the bot token of the channel and connects, or removes the channel and its paired chats. Code `token_in_use` when another bot has the same token | diff --git a/appd/src/core.rs b/appd/src/core.rs index 62e8ee6..6b07f06 100644 --- a/appd/src/core.rs +++ b/appd/src/core.rs @@ -7158,6 +7158,19 @@ impl Core { if let Some(used) = used { self.routine_tokens(bot, id, used); } + if matches!( + ev, + Event::TurnEnd { + reason: proto::TurnEnd::Done, + .. + } + ) { + let summary = ended.as_ref().map(|(s, _)| s.as_str()).unwrap_or(""); + self.lan.notify_push(crate::push::payload_for_done( + &self.name_of(bot), + summary, + )); + } } self.broadcast(&json!({"type": "bots_changed"})); } @@ -7200,8 +7213,13 @@ impl Core { return; }; self.record(bot, &conversation, with_context(&ev)); - if matches!(ev, Event::Question { .. }) { + if let Event::Question { title, secret, .. } = &ev { self.broadcast(&json!({"type": "bots_changed"})); + self.lan.notify_push(crate::push::payload_for_question( + &self.name_of(bot), + title, + secret.is_some(), + )); } // The bot has replied: the conversation is titled, if it has no title yet. if let Event::TurnEnd { diff --git a/appd/src/lan.rs b/appd/src/lan.rs index 23629c8..3f274e2 100644 --- a/appd/src/lan.rs +++ b/appd/src/lan.rs @@ -5,6 +5,7 @@ use crate::keychain; use crate::paths; +use crate::push::Push; use crate::sys::{self, log, now_ms}; use proto::MAX_WINDOW_FRAME; use rustls::pki_types::pem::PemObject; @@ -99,10 +100,12 @@ struct State { asked: u64, } -/// The state, and the switch: held while serving is turned on or off, which can take seconds, -/// so that such requests run one after another. It holds the thread that accepts connections, -/// if one runs. The state's own lock is never held that long. -pub struct Lan(Mutex, Mutex>>); +/// The state, the switch (held while serving is turned on or off), and the Web Push store. +pub struct Lan( + Mutex, + Mutex>>, + Arc, +); fn lock(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner()) @@ -133,11 +136,16 @@ impl Lan { devices, ..State::default() }; - let lan = Arc::new(Lan(Mutex::new(state), Mutex::new(None))); + let lan = Arc::new(Lan(Mutex::new(state), Mutex::new(None), Push::load())); lan.resume(); lan } + /// Sends a Web Push notification to all subscribed paired devices on a background thread. + pub fn notify_push(&self, payload: Value) { + self.2.notify(payload); + } + /// Serves if the user left it on and it is not serving: at start, and again when the /// Keychain, which held back the certificate's key, has been answered. pub fn resume(self: &Arc) { @@ -255,12 +263,29 @@ impl Lan { return Err("turn on the page for other devices first".into()); } let code = sys::pair_code(); + let port = state.port; + let magic_dns = state.magic_dns.clone(); state.code = Some(Code { code: code.clone(), until: Instant::now() + CODE_LIFE, tries: 0, }); - Ok(json!({"code": code, "expiresAt": now_ms() + CODE_LIFE.as_millis() as u64})) + let (lan, tailnet) = split(addresses()); + let first_host = magic_dns + .or_else(|| tailnet.first().map(Ipv4Addr::to_string)) + .or_else(|| lan.first().map(Ipv4Addr::to_string)); + let mut out = json!({ + "code": code, + "expiresAt": now_ms() + CODE_LIFE.as_millis() as u64, + }); + if let Some(host) = first_host { + let url = format!("https://{host}:{port}/?pair={code}"); + if let Some(qr) = proto::qr::encode(&url) { + out["qr"] = json!({"size": qr.size, "rows": qr.rows()}); + } + out["url"] = json!(url); + } + Ok(out) } /// Forgets a device; its open pages lose their connection at once. @@ -272,6 +297,7 @@ impl Lan { return Err(format!("no device `{device}`")); } state.sessions.retain(|_, s| s.device != device); + self.2.remove_device(device); save(&state.devices) } @@ -366,7 +392,9 @@ impl Lan { }; } // Only the page itself sends this; a page of another site cannot without asking. - if r.method != "POST" && r.path != "/api/recv" || r.header("x-bate") != Some("1") { + let is_get_ok = + r.method == "GET" && matches!(r.path.as_str(), "/api/recv" | "/api/push/key"); + if (r.method != "POST" && !is_get_ok) || r.header("x-bate") != Some("1") { return Answer::error(403, "not from Bate's page"); } if r.path == "/api/pair" { @@ -378,6 +406,37 @@ impl Lan { let session = query(&r.query, "session"); match r.path.as_str() { "/api/session" => self.open_session(&device), + "/api/push/key" => match self.2.public_key() { + Ok(public_key) => Answer::json(200, &json!({"publicKey": public_key})), + Err(e) => Answer::error(500, &e), + }, + "/api/push/subscribe" => { + let Ok(v) = serde_json::from_slice::(&r.body) else { + return Answer::error(400, "send {endpoint, keys: {p256dh, auth}}"); + }; + let endpoint = v["endpoint"].as_str().unwrap_or(""); + let p256dh = v["keys"]["p256dh"] + .as_str() + .or_else(|| v["p256dh"].as_str()) + .unwrap_or(""); + let auth = v["keys"]["auth"] + .as_str() + .or_else(|| v["auth"].as_str()) + .unwrap_or(""); + match self.2.subscribe(&device, endpoint, p256dh, auth) { + Ok(()) => Answer::json(200, &json!({})), + Err(e) => Answer::error(400, &e), + } + } + "/api/push/unsubscribe" => { + let endpoint = serde_json::from_slice::(&r.body) + .ok() + .and_then(|v| v["endpoint"].as_str().map(str::to_owned)); + match self.2.unsubscribe(&device, endpoint.as_deref()) { + Ok(()) => Answer::json(200, &json!({})), + Err(e) => Answer::error(500, &e), + } + } "/api/send" | "/api/recv" => { let found = lock(&self.0).sessions.get(session).cloned(); let Some(s) = found.filter(|s| s.device == device) else { @@ -870,14 +929,20 @@ fn static_file(path: &str) -> Answer { "png" => "image/png", "ico" => "image/x-icon", "woff2" => "font/woff2", + "webmanifest" => "application/manifest+json; charset=utf-8", + "json" => "application/json; charset=utf-8", _ => "application/octet-stream", }; + let mut headers = vec![ + ("content-type", kind.into()), + ("content-security-policy", PAGE_POLICY.into()), + ]; + if path == "/sw.js" { + headers.push(("service-worker-allowed", "/".into())); + } Answer { status: 200, - headers: vec![ - ("content-type", kind.into()), - ("content-security-policy", PAGE_POLICY.into()), - ], + headers, body: body.to_vec(), } } diff --git a/appd/src/main.rs b/appd/src/main.rs index ad884ca..2859f18 100644 --- a/appd/src/main.rs +++ b/appd/src/main.rs @@ -31,6 +31,7 @@ mod paths; mod precheck; mod project_server; mod proxy; +mod push; mod report; mod roles; mod schedule; diff --git a/appd/src/push.rs b/appd/src/push.rs new file mode 100644 index 0000000..45c5b81 --- /dev/null +++ b/appd/src/push.rs @@ -0,0 +1,477 @@ +//! Web Push (RFC 8292 VAPID + RFC 8291 `aes128gcm`) for paired Devices. +//! +//! The VAPID P-256 private key lives only in macOS Keychain (`vapid.key`); only its 65-byte +//! uncompressed public key is exposed to paired Devices. Delivery runs on a background thread so +//! `Core::run` never blocks. Secret prompts never carry bot text or secret names in payloads. + +use crate::keychain; +use crate::paths; +use crate::sys::log; +use ring::aead::{AES_128_GCM, Aad, LessSafeKey, Nonce, UnboundKey}; +use ring::agreement::{self, EphemeralPrivateKey, UnparsedPublicKey}; +use ring::hkdf; +use ring::rand::{SecureRandom, SystemRandom}; +use ring::signature::{ECDSA_P256_SHA256_FIXED_SIGNING, EcdsaKeyPair, KeyPair}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::fs; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +const KEYCHAIN_ACCOUNT: &str = "vapid.key"; +const MAX_SUBSCRIPTIONS: usize = 32; +const MAX_BODY_CHARS: usize = 120; + +/// One paired device's Web Push subscription. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Subscription { + pub device: String, + pub endpoint: String, + pub p256dh: String, + pub auth: String, +} + +/// Thread-safe store of active Web Push subscriptions (`lan/push.json`). +#[derive(Default)] +pub struct Push(Mutex>); + +fn file_path() -> PathBuf { + paths::home().join("lan").join("push.json") +} + +impl Push { + pub fn load() -> Arc { + let list = fs::read(file_path()) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default(); + Arc::new(Push(Mutex::new(list))) + } + + /// Returns the base64url-encoded 65-byte uncompressed VAPID public key, generating and storing + /// a P-256 keypair in Keychain on first use. + pub fn public_key(&self) -> Result { + let pair = load_or_create_vapid_key()?; + Ok(b64url_encode(pair.public_key().as_ref())) + } + + pub fn subscribe( + &self, + device: &str, + endpoint: &str, + p256dh: &str, + auth: &str, + ) -> Result<(), String> { + validate_subscription(endpoint, p256dh, auth)?; + let mut list = self.0.lock().unwrap_or_else(|e| e.into_inner()); + list.retain(|s| s.endpoint != endpoint); + if list.len() >= MAX_SUBSCRIPTIONS { + list.remove(0); + } + list.push(Subscription { + device: device.to_owned(), + endpoint: endpoint.to_owned(), + p256dh: p256dh.to_owned(), + auth: auth.to_owned(), + }); + save(&list) + } + + pub fn unsubscribe(&self, device: &str, endpoint: Option<&str>) -> Result<(), String> { + let mut list = self.0.lock().unwrap_or_else(|e| e.into_inner()); + match endpoint { + Some(ep) => list.retain(|s| !(s.device == device && s.endpoint == ep)), + None => list.retain(|s| s.device != device), + } + save(&list) + } + + pub fn remove_device(&self, device: &str) { + let mut list = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let before = list.len(); + list.retain(|s| s.device != device); + if list.len() != before { + let _ = save(&list); + } + } + + /// Sends a Web Push notification to every subscribed device on a background thread. + pub fn notify(self: &Arc, payload: Value) { + let subs: Vec = self.0.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if subs.is_empty() { + return; + } + let this = Arc::clone(self); + std::thread::spawn(move || { + let Ok(pair) = load_or_create_vapid_key() else { + return; + }; + let plain = payload.to_string().into_bytes(); + let agent = ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(10))) + .http_status_as_error(false) + .build() + .new_agent(); + let mut expired = Vec::new(); + for sub in subs { + match send_one(&agent, &pair, &sub, &plain) { + Ok(status) if status == 404 || status == 410 => { + expired.push((sub.device, sub.endpoint)); + } + Ok(_) => {} + Err(e) => log!("web push failed for {}: {e}", sub.device), + } + } + if !expired.is_empty() { + let mut list = this.0.lock().unwrap_or_else(|e| e.into_inner()); + for (dev, ep) in expired { + list.retain(|s| !(s.device == dev && s.endpoint == ep)); + } + let _ = save(&list); + } + }); + } +} + +/// Safe push payload for a bot question (`Needs you`). Secret cards NEVER include bot text or +/// secret details. +pub fn payload_for_question(bot_name: &str, title: &str, is_secret: bool) -> Value { + let who = clip(bot_name, 40); + if is_secret { + return json!({ + "title": "Bate", + "body": format!("{who} needs a secret on your Mac."), + "tag": "bate-secret", + }); + } + let body = clip(title.trim(), MAX_BODY_CHARS); + json!({ + "title": format!("{who} needs you"), + "body": if body.is_empty() { "Open Bate to answer.".to_owned() } else { body }, + "tag": "bate-ask", + }) +} + +/// Safe push payload when a routine or unattended turn finishes. +pub fn payload_for_done(bot_name: &str, summary: &str) -> Value { + let who = clip(bot_name, 40); + let first_line = summary + .lines() + .find(|l| !l.trim().is_empty()) + .unwrap_or("") + .trim(); + let body = clip(first_line, MAX_BODY_CHARS); + json!({ + "title": format!("{who} finished"), + "body": if body.is_empty() { "A routine finished.".to_owned() } else { body }, + "tag": "bate-done", + }) +} + +fn clip(s: &str, max_chars: usize) -> String { + let clean: String = s.chars().filter(|c| !c.is_control()).collect(); + match clean.char_indices().nth(max_chars) { + Some((end, _)) => format!("{}…", &clean[..end]), + None => clean, + } +} + +fn validate_subscription(endpoint: &str, p256dh: &str, auth: &str) -> Result<(), String> { + let allow_local = std::env::var("APPD_PUSH_ALLOW_LOCALHOST").as_deref() == Ok("1"); + let valid_scheme = endpoint.starts_with("https://") + || (allow_local && endpoint.starts_with("http://127.0.0.1:")); + if !valid_scheme || endpoint.len() > 2048 || endpoint.chars().any(char::is_whitespace) { + return Err("push endpoint must be an https URL".into()); + } + let pub_bytes = b64url_decode(p256dh).ok_or("invalid p256dh key")?; + if pub_bytes.len() != 65 || pub_bytes[0] != 0x04 { + return Err("p256dh must be a 65-byte uncompressed P-256 point".into()); + } + let auth_bytes = b64url_decode(auth).ok_or("invalid auth secret")?; + if auth_bytes.len() != 16 { + return Err("auth secret must be 16 bytes".into()); + } + Ok(()) +} + +fn save(list: &[Subscription]) -> Result<(), String> { + let path = file_path(); + if let Some(parent) = path.parent() { + let _ = crate::sys::create_private_dir(parent); + } + let tmp = path.with_extension("tmp"); + let bytes = serde_json::to_vec(list).map_err(|e| e.to_string())?; + fs::write(&tmp, bytes) + .and_then(|()| fs::rename(&tmp, &path)) + .map_err(|e| format!("push subscriptions not saved: {e}")) +} + +fn load_or_create_vapid_key() -> Result { + let rng = SystemRandom::new(); + if let Some(stored) = keychain::get(KEYCHAIN_ACCOUNT).map_err(|e| e.to_string())? + && let Some(pkcs8) = b64url_decode(&stored) + && let Ok(pair) = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, &pkcs8, &rng) + { + return Ok(pair); + } + let doc = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, &rng) + .map_err(|_| "cannot generate VAPID key".to_owned())?; + let encoded = b64url_encode(doc.as_ref()); + keychain::put(KEYCHAIN_ACCOUNT, &encoded).map_err(|e| e.to_string())?; + EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, doc.as_ref(), &rng) + .map_err(|_| "cannot parse generated VAPID key".to_owned()) +} + +fn endpoint_origin(endpoint: &str) -> Result { + let (scheme, rest) = endpoint.split_once("://").ok_or("bad endpoint URL")?; + let host_port = rest.split('/').next().ok_or("bad endpoint host")?; + if host_port.is_empty() { + return Err("empty endpoint host".into()); + } + Ok(format!("{scheme}://{host_port}")) +} + +/// Builds an RFC 8292 VAPID `Authorization` header (`vapid t=, k=`). +fn vapid_auth_header(pair: &EcdsaKeyPair, endpoint: &str) -> Result { + let aud = endpoint_origin(endpoint)?; + let exp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) + + 12 * 3600; + let header = b64url_encode(br#"{"typ":"JWT","alg":"ES256"}"#); + let claims = json!({ + "aud": aud, + "exp": exp, + "sub": "mailto:bate@localhost", + }) + .to_string(); + let claims_b64 = b64url_encode(claims.as_bytes()); + let signing_input = format!("{header}.{claims_b64}"); + let rng = SystemRandom::new(); + let sig = pair + .sign(&rng, signing_input.as_bytes()) + .map_err(|_| "VAPID signing failed".to_owned())?; + let jwt = format!("{signing_input}.{}", b64url_encode(sig.as_ref())); + let pub_b64 = b64url_encode(pair.public_key().as_ref()); + Ok(format!("vapid t={jwt}, k={pub_b64}")) +} + +struct Len(usize); +impl hkdf::KeyType for Len { + fn len(&self) -> usize { + self.0 + } +} + +/// Encrypts `plaintext` according to RFC 8291 (`aes128gcm` content coding). +fn encrypt_rfc8291(p256dh: &[u8], auth_secret: &[u8], plaintext: &[u8]) -> Result, String> { + let rng = SystemRandom::new(); + let mut salt = [0u8; 16]; + rng.fill(&mut salt).map_err(|_| "rng failed")?; + let ephemeral = + EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng).map_err(|_| "ecdh failed")?; + let as_pub = ephemeral + .compute_public_key() + .map_err(|_| "pub key failed")?; + let as_pub_bytes = as_pub.as_ref(); + let ua_pub = UnparsedPublicKey::new(&agreement::ECDH_P256, p256dh); + + let shared = agreement::agree_ephemeral(ephemeral, &ua_pub, |secret| secret.to_vec()) + .map_err(|_| "ecdh agree failed")?; + + // PRK_key = HKDF-Extract(salt=auth_secret, IKM=ecdh_secret) + let auth_salt = hkdf::Salt::new(hkdf::HKDF_SHA256, auth_secret); + let prk_key = auth_salt.extract(&shared); + let mut key_info = Vec::with_capacity(14 + p256dh.len() + as_pub_bytes.len()); + key_info.extend_from_slice(b"WebPush: info\0"); + key_info.extend_from_slice(p256dh); + key_info.extend_from_slice(as_pub_bytes); + let mut ikm = [0u8; 32]; + prk_key + .expand(&[&key_info], Len(32)) + .and_then(|okm| okm.fill(&mut ikm)) + .map_err(|_| "hkdf ikm failed")?; + + // PRK = HKDF-Extract(salt=salt, IKM=ikm) + let msg_salt = hkdf::Salt::new(hkdf::HKDF_SHA256, &salt); + let prk = msg_salt.extract(&ikm); + let mut cek = [0u8; 16]; + prk.expand(&[b"Content-Encoding: aes128gcm\0"], Len(16)) + .and_then(|okm| okm.fill(&mut cek)) + .map_err(|_| "hkdf cek failed")?; + let mut nonce_bytes = [0u8; 12]; + prk.expand(&[b"Content-Encoding: nonce\0"], Len(12)) + .and_then(|okm| okm.fill(&mut nonce_bytes)) + .map_err(|_| "hkdf nonce failed")?; + + // Plaintext + RFC 8188 delimiter 0x02 (final record). + let mut buf = Vec::with_capacity(plaintext.len() + 1 + AES_128_GCM.tag_len()); + buf.extend_from_slice(plaintext); + buf.push(0x02); + let key = LessSafeKey::new(UnboundKey::new(&AES_128_GCM, &cek).map_err(|_| "aead key")?); + key.seal_in_place_append_tag( + Nonce::assume_unique_for_key(nonce_bytes), + Aad::empty(), + &mut buf, + ) + .map_err(|_| "aead seal failed")?; + + // RFC 8188 header: salt(16) || rs(4, BE=4096) || idlen(1=65) || keyid(65) || ciphertext. + let mut out = Vec::with_capacity(16 + 4 + 1 + as_pub_bytes.len() + buf.len()); + out.extend_from_slice(&salt); + out.extend_from_slice(&4096u32.to_be_bytes()); + out.push(as_pub_bytes.len() as u8); + out.extend_from_slice(as_pub_bytes); + out.extend_from_slice(&buf); + Ok(out) +} + +fn send_one( + agent: &ureq::Agent, + pair: &EcdsaKeyPair, + sub: &Subscription, + plaintext: &[u8], +) -> Result { + let p256dh = b64url_decode(&sub.p256dh).ok_or("invalid p256dh")?; + let auth = b64url_decode(&sub.auth).ok_or("invalid auth")?; + let body = encrypt_rfc8291(&p256dh, &auth, plaintext)?; + let auth_header = vapid_auth_header(pair, &sub.endpoint)?; + let resp = agent + .post(&sub.endpoint) + .header("TTL", "300") + .header("Content-Encoding", "aes128gcm") + .header("Content-Type", "application/octet-stream") + .header("Authorization", &auth_header) + .send(&body[..]) + .map_err(|e| e.to_string())?; + Ok(resp.status().as_u16()) +} + +/// Base64url encoding without padding (RFC 4648 Section 5). +pub fn b64url_encode(bytes: &[u8]) -> String { + const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let n = chunk + .iter() + .enumerate() + .fold(0u32, |acc, (i, &b)| acc | (u32::from(b) << (16 - 8 * i))); + let count = chunk.len() + 1; + for i in 0..count { + out.push(TABLE[((n >> (18 - 6 * i)) & 63) as usize] as char); + } + } + out +} + +/// Base64url decoding (accepts padded or unpadded input). +pub fn b64url_decode(input: &str) -> Option> { + let trimmed = input.trim_end_matches('='); + let mut out = Vec::with_capacity((trimmed.len() * 3) / 4); + let val = |b: u8| -> Option { + match b { + b'A'..=b'Z' => Some(b - b'A'), + b'a'..=b'z' => Some(b - b'a' + 26), + b'0'..=b'9' => Some(b - b'0' + 52), + b'-' | b'+' => Some(62), + b'_' | b'/' => Some(63), + _ => None, + } + }; + let bytes = trimmed.as_bytes(); + let mut i = 0; + while i < bytes.len() { + let rem = bytes.len() - i; + if rem == 1 { + return None; + } + let a = val(bytes[i])?; + let b = val(bytes[i + 1])?; + out.push((a << 2) | (b >> 4)); + if rem >= 3 { + let c = val(bytes[i + 2])?; + out.push((b << 4) | (c >> 2)); + if rem >= 4 { + let d = val(bytes[i + 3])?; + out.push((c << 6) | d); + } + } + i += 4; + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn base64url_round_trips() { + for sample in [&b""[..], b"f", b"fo", b"foo", &[0u8, 255, 128, 63, 62]] { + let enc = b64url_encode(sample); + assert!(!enc.contains('=')); + assert_eq!(b64url_decode(&enc).as_deref(), Some(sample)); + } + } + + #[test] + fn secret_prompt_payload_redacts_bot_text_and_secret_names() { + let payload = + payload_for_question("Ada", "Type secret github_password for example.com", true); + let text = payload.to_string(); + assert!(!text.contains("github_password")); + assert!(!text.contains("example.com")); + assert_eq!(payload["tag"], "bate-secret"); + assert!(payload["body"].as_str().unwrap().contains("Ada")); + + let normal = payload_for_question("Ada", "Run cargo test?", false); + assert_eq!(normal["title"], "Ada needs you"); + assert_eq!(normal["body"], "Run cargo test?"); + assert_eq!(normal["tag"], "bate-ask"); + } + + #[test] + fn vapid_jwt_and_rfc8291_encryption_produce_valid_frames() { + let rng = SystemRandom::new(); + let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, &rng).unwrap(); + let pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, pkcs8.as_ref(), &rng) + .unwrap(); + + let header = vapid_auth_header(&pair, "https://push.example.net/sub/123").unwrap(); + assert!(header.starts_with("vapid t=")); + let token = header + .strip_prefix("vapid t=") + .unwrap() + .split(", k=") + .next() + .unwrap(); + let parts: Vec<&str> = token.split('.').collect(); + assert_eq!(parts.len(), 3); + assert_eq!(b64url_decode(parts[2]).unwrap().len(), 64); + + // Encrypt against a freshly generated UA P-256 public key + 16-byte auth secret. + let ua_key = EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng).unwrap(); + let ua_pub = ua_key.compute_public_key().unwrap(); + let auth = [7u8; 16]; + let body = encrypt_rfc8291(ua_pub.as_ref(), &auth, br#"{"title":"Bate"}"#).unwrap(); + // Header: 16 salt + 4 rs + 1 idlen(65) + 65 pubkey = 86 bytes, plus ciphertext+tag. + assert!(body.len() > 86 + 16); + assert_eq!(body[20], 65); + assert_eq!(body[21], 0x04); + } + + #[test] + fn subscription_validation_rejects_non_https_and_bad_keys() { + let rng = SystemRandom::new(); + let ua_key = EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng).unwrap(); + let p256dh = b64url_encode(ua_key.compute_public_key().unwrap().as_ref()); + let auth = b64url_encode(&[1u8; 16]); + + assert!(validate_subscription("https://push.example.net/1", &p256dh, &auth).is_ok()); + assert!(validate_subscription("http://evil.example.net/1", &p256dh, &auth).is_err()); + assert!(validate_subscription("https://push.example.net/1", "short", &auth).is_err()); + assert!(validate_subscription("https://push.example.net/1", &p256dh, "short").is_err()); + } +} diff --git a/appd/tests/service.rs b/appd/tests/service.rs index 247d7ad..bda588d 100644 --- a/appd/tests/service.rs +++ b/appd/tests/service.rs @@ -19589,3 +19589,92 @@ fn fallback_model_persists_across_restarts_and_can_be_cleared() { .unwrap(); assert!(row.get("fallbackModel").is_none(), "{row}"); } + +#[test] +fn pwa_manifest_qr_pairing_and_web_push_subscription_lifecycle() { + let home = home("pwa-qr-push"); + let _service = Service::start_with(&home, |c| { + c.env("APPD_LAN_PORT", "0"); + }); + let mut w = Window::connect(&home); + let lan = w.ok("set_lan", json!({"on": true})); + let port = lan["port"].as_u64().unwrap(); + let pair = w.ok("pair_device", json!({})); + let code = pair["code"].as_str().unwrap().to_owned(); + if let Some(url) = pair["url"].as_str() { + assert!(url.ends_with(&format!("/?pair={code}")), "{pair}"); + let qr = &pair["qr"]; + let size = qr["size"].as_u64().unwrap() as usize; + let rows = qr["rows"].as_array().unwrap(); + assert_eq!(rows.len(), size); + } + + let mut device = Device::new(port); + // Static PWA assets are served over HTTPS. + let (status, manifest, _) = device.call("GET", "/manifest.webmanifest", "", false); + assert_eq!(status, 200, "{manifest}"); + let parsed: Value = serde_json::from_str(&manifest).unwrap(); + assert_eq!(parsed["name"], "Bate"); + assert_eq!(parsed["display"], "standalone"); + let (status, sw, _) = device.call("GET", "/sw.js", "", false); + assert_eq!(status, 200); + assert!(sw.contains("showNotification"), "{sw}"); + let (status, icon, _) = device.call("GET", "/icon.svg", "", false); + assert_eq!(status, 200); + assert!(icon.contains(" = + serde_json::from_slice(&fs::read(home.join("lan/push.json")).unwrap()).unwrap(); + assert!( + saved.is_empty(), + "removing device clears push subs: {saved:?}" + ); +} diff --git a/native/src/settings_devices.rs b/native/src/settings_devices.rs index a919d22..7a89e14 100644 --- a/native/src/settings_devices.rs +++ b/native/src/settings_devices.rs @@ -11,7 +11,7 @@ use crate::times; use crate::tokens::*; use serde::Deserialize; use serde_json::json; -use weft::El; +use weft::{Align, Color, El, Icon, col, el, icon, row}; type V = El; @@ -41,6 +41,8 @@ struct Code { code: String, #[serde(rename = "expiresAt")] expires_at: i64, + #[serde(default)] + url: Option, } const SWITCH: &str = "settings-lan"; @@ -138,16 +140,53 @@ pub fn groups(app: &App, k: &Tokens) -> Vec { .output(&key) .and_then(|out| serde_json::from_value::(out.clone()).ok()); match code.map(|c| (seconds_left(&c, app.now), c)) { - Some((left, code)) if left > 0 => rows.push(forms::setting_wide( - k, - &format!( - "Enter this code on the other device ({}:{:02} left)", - left / 60, - left % 60 - ), - None, - forms::code(k, "pair-code", &code.code), - )), + Some((left, code)) if left > 0 => { + let pair_url = code.url.clone().or_else(|| { + lan.tailscale_urls + .first() + .or_else(|| lan.urls.first()) + .map(|base| format!("{base}?pair={}", code.code)) + }); + let qr = pair_url + .as_deref() + .and_then(proto::qr::encode) + .and_then(|q| { + Icon::from_svg(&format!("pair-qr-{}", code.code), &q.to_svg()).ok() + }); + let body = match qr { + Some(qr_icon) => row() + .gap(SPACE_3) + .align(Align::Start) + .child( + col() + .grow(1.0) + .child(forms::code(k, "pair-code", &code.code)), + ) + .child( + el().key("pair-qr") + .w(148.0) + .h(148.0) + .shrink(0.0) + .radius(RADIUS_L) + .fill(Color::WHITE) + .border(1.0, k.border) + .child(icon(qr_icon).size(146.0).color(Color::BLACK).el()), + ), + None => forms::code(k, "pair-code", &code.code), + }; + rows.push(forms::setting_wide( + k, + &format!( + "Enter this code on the other device ({}:{:02} left)", + left / 60, + left % 60 + ), + pair_url + .as_ref() + .map(|_| "Or scan the QR code with your phone to open Bate and fill in the code."), + body, + )); + } _ => rows.push(forms::setting( k, "Pairing", diff --git a/native/tests/settings.rs b/native/tests/settings.rs index 50daa01..2502938 100644 --- a/native/tests/settings.rs +++ b/native/tests/settings.rs @@ -590,6 +590,10 @@ fn pairing_shows_the_code_with_its_time_and_a_copy_and_closing_the_network_forge idle(&mut w); assert_eq!(fields_of(&only(&w, "pair_device")), json!({})); assert!(shows(&mut w.rt, "739204")); + assert!( + has_key(&mut w.rt, "pair-qr"), + "QR code renders beside pairing code" + ); assert!(shows( &mut w.rt, "Enter this code on the other device (5:00 left)" diff --git a/native/tests/snapshots/native-settings-pairing-dark.png b/native/tests/snapshots/native-settings-pairing-dark.png index 3bb452c..6d20e6d 100644 Binary files a/native/tests/snapshots/native-settings-pairing-dark.png and b/native/tests/snapshots/native-settings-pairing-dark.png differ diff --git a/native/tests/snapshots/native-settings-pairing-dark.tree b/native/tests/snapshots/native-settings-pairing-dark.tree index 2815389..56cb683 100644 --- a/native/tests/snapshots/native-settings-pairing-dark.tree +++ b/native/tests/snapshots/native-settings-pairing-dark.tree @@ -144,9 +144,9 @@ generic @0,0,1000,700 text @288,258,51,18 t="Updates" button #settings-nav-report @280,284,176,30 lb="Bug report" ck=false tab text @288,290,64.55,18 t="Bug report" - generic #settings-page @480,60,512,632 sc=0,460,0,832 - generic @480,-392,488,1432 - generic @480,-392,488,1432 + generic #settings-page @480,60,512,632 sc=0,460,0,938 + generic @480,-392,488,1538 + generic @480,-392,488,1538 generic @480,-392,488,80 generic #anchor-appearance @480,-400,1,700 generic #group-appearance @480,-392,488,80 @@ -191,12 +191,12 @@ generic @0,0,1000,700 generic @480,-2,488,46 button #settings-save @480,6,53.79,30 lb="Save" tab text @492,12,29.79,18 t="Save" - generic @480,68,488,388 - generic @480,68,488,300 + generic @480,68,488,494 + generic @480,68,488,406 generic #anchor-devices @480,60,1,700 - generic #group-devices @480,68,488,300 + generic #group-devices @480,68,488,406 heading @480,68,488,18 t="Other devices" - generic @480,90,488,278 + generic @480,90,488,384 generic @480,90,488,36 generic @480,99,444,18 text @480,99,444,18 t="Let devices on this network open Bate" @@ -219,105 +219,110 @@ generic @0,0,1000,700 text @496,234,402.09,18 t="AB:12:CD:34:EF:56:AB:12:CD:34:EF:56:AB:12:CD:34" button #copy-fingerprint @922.09,230,45.91,26 lb="Copy" tab text @930.09,235,29.91,16 t="Copy" - generic @480,276,488,92 - generic @480,280,488,18 + generic @480,276,488,198 + generic @480,280,488,34 text @480,280,488,18 t="Enter this code on the other device (5:00 left)" - generic @480,306,488,58 - generic @480,314,434.09,42 - text @496,326,402.09,18 t="739204" - button #copy-pair-code @922.09,322,45.91,26 lb="Copy" tab - text @930.09,327,29.91,16 t="Copy" - generic #group-paired @480,392,488,64 - heading @480,392,488,18 t="Paired devices" - generic @480,414,488,42 - generic @480,414,488,42 - generic @480,418,410.07,34 - text @480,418,410.07,18 t="Sam's phone" - text @480,436,410.07,16 t="Last seen Today 21:33" - generic @906.07,422,61.93,26 - button #settings-remove-device-dev1 @906.07,422,61.93,26 lb="Remove Sam's phone" tab - text @914.07,427,45.93,16 t="Remove" - generic @480,480,488,148 - generic #anchor-helper @480,472,1,700 - generic #group-helper @480,480,488,148 - heading @480,480,488,18 t="Bate Helper" - generic @480,502,488,126 - generic @480,502,488,42 - generic @480,506,327.2,34 - text @480,506,327.2,18 t="Accessibility" - text @480,524,327.2,16 t="Read and control other apps: Allowed" - generic @823.2,510,144.8,26 - button #settings-open-accessibility @823.2,510,144.8,26 lb="Open System Settings: Accessibility" tab - text @831.2,515,128.8,16 t="Open System Settings" - generic @480,544,488,42 - generic @480,548,327.2,34 - text @480,548,327.2,18 t="Screen Recording" - text @480,566,327.2,16 t="Pictures of windows: Not allowed" - generic @823.2,552,144.8,26 - button #settings-open-screen_recording @823.2,552,144.8,26 lb="Open System Settings: Screen Recording" tab - text @831.2,557,128.8,16 t="Open System Settings" - generic @480,586,488,42 - generic @480,590,327.2,34 - text @480,590,327.2,18 t="Full Disk Access" - text @480,608,327.2,16 t="Read your Messages history: Not known yet" - generic @823.2,594,144.8,26 - button #settings-open-full_disk_access @823.2,594,144.8,26 lb="Open System Settings: Full Disk Access" tab - text @831.2,599,128.8,16 t="Open System Settings" - generic @480,652,488,196 - generic #anchor-quick @480,644,1,700 - generic #group-quick @480,652,488,196 - heading @480,652,488,18 t="Quick Ask" - generic @480,674,488,174 - generic @480,674,488,58 - generic @480,678,343.13,50 - text @480,678,343.13,18 t="Shortcut" - text @480,696,343.13,32 t="Opens a small panel over any app, to ask a bot at once. Off until you set one. It needs Ctrl, Alt or Cmd." - generic @839.13,690,128.87,26 - generic @839.13,690,128.87,26 - button #settings-shortcut @839.13,690,74.36,26 lb="Shortcut" tab - text @847.13,695,58.36,16 t="⌃⌥Space" - button #settings-shortcut-clear @921.5,690,46.5,26 lb="Clear" tab - text @929.5,695,30.5,16 t="Clear" - generic @480,732,488,58 - generic @480,736,444,50 - text @480,736,444,18 t="Use selected text" - text @480,754,444,32 t="The text selected in the front app goes with your question as a quote. macOS asks for Accessibility the first time." - generic @940,753,28,16 - switch #settings-selection @940,753,28,16 lb="Use selected text" ck tab - generic @954,755,12,12 - generic @480,790,488,58 - generic @480,794,444,50 - text @480,794,444,18 t="Attach a screenshot" - text @480,812,444,32 t="The screen, or a window you pick, goes with your question as a picture. macOS asks for Screen Recording the first time." - generic @940,811,28,16 - switch #settings-screenshot @940,811,28,16 lb="Attach a screenshot" ck=false tab - generic @942,813,12,12 - generic @480,872,488,80 - generic #anchor-updates @480,864,1,700 - generic #group-updates @480,872,488,80 - heading @480,872,488,18 t="Updates" - generic @480,894,488,58 - generic @480,894,488,58 - generic @480,898,260.46,50 - text @480,898,260.46,18 t="Bate 0.9.0" - text @480,916,260.46,32 t="Version 0.9.1 is ready. Installs when no reply is running." - generic @756.46,910,211.54,26 - generic @756.46,910,211.54,26 - button #settings-check-update @756.46,910,122.38,26 lb="Check for updates" tab - text @764.46,915,106.38,16 t="Check for updates" - button #settings-install-update @886.84,910,81.16,26 lb="Install 0.9.1" tab - text @894.84,915,65.16,16 t="Install 0.9.1" - generic @480,976,488,64 - generic #anchor-report @480,968,1,700 - generic #anchor-end @480,70976,1,700 - generic #group-report @480,976,488,64 - heading @480,976,488,18 t="Bug report" - generic @480,998,488,42 - generic @480,998,488,42 - generic @480,1002,343.33,34 - text @480,1002,343.33,18 t="Logs and a summary of the settings" - text @480,1020,343.33,16 t="Conversations are not included." - generic @839.33,1006,128.67,26 - button #settings-report @839.33,1006,128.67,26 lb="Export a bug report" tab - text @847.33,1011,112.67,16 t="Export a bug report" + text @480,298,488,16 t="Or scan the QR code with your phone to open Bate and fill in the code." + generic @480,322,488,148 + generic @480,322,328,58 + generic @480,322,328,58 + generic @480,330,274.09,42 + text @496,342,242.09,18 t="739204" + button #copy-pair-code @762.09,338,45.91,26 lb="Copy" tab + text @770.09,343,29.91,16 t="Copy" + generic #pair-qr @820,322,148,148 + image @821,323,146,146 deco + generic #group-paired @480,498,488,64 + heading @480,498,488,18 t="Paired devices" + generic @480,520,488,42 + generic @480,520,488,42 + generic @480,524,410.07,34 + text @480,524,410.07,18 t="Sam's phone" + text @480,542,410.07,16 t="Last seen Today 21:33" + generic @906.07,528,61.93,26 + button #settings-remove-device-dev1 @906.07,528,61.93,26 lb="Remove Sam's phone" tab + text @914.07,533,45.93,16 t="Remove" + generic @480,586,488,148 + generic #anchor-helper @480,578,1,700 + generic #group-helper @480,586,488,148 + heading @480,586,488,18 t="Bate Helper" + generic @480,608,488,126 + generic @480,608,488,42 + generic @480,612,327.2,34 + text @480,612,327.2,18 t="Accessibility" + text @480,630,327.2,16 t="Read and control other apps: Allowed" + generic @823.2,616,144.8,26 + button #settings-open-accessibility @823.2,616,144.8,26 lb="Open System Settings: Accessibility" tab + text @831.2,621,128.8,16 t="Open System Settings" + generic @480,650,488,42 + generic @480,654,327.2,34 + text @480,654,327.2,18 t="Screen Recording" + text @480,672,327.2,16 t="Pictures of windows: Not allowed" + generic @823.2,658,144.8,26 + button #settings-open-screen_recording @823.2,658,144.8,26 lb="Open System Settings: Screen Recording" tab + text @831.2,663,128.8,16 t="Open System Settings" + generic @480,692,488,42 + generic @480,696,327.2,34 + text @480,696,327.2,18 t="Full Disk Access" + text @480,714,327.2,16 t="Read your Messages history: Not known yet" + generic @823.2,700,144.8,26 + button #settings-open-full_disk_access @823.2,700,144.8,26 lb="Open System Settings: Full Disk Access" tab + text @831.2,705,128.8,16 t="Open System Settings" + generic @480,758,488,196 + generic #anchor-quick @480,750,1,700 + generic #group-quick @480,758,488,196 + heading @480,758,488,18 t="Quick Ask" + generic @480,780,488,174 + generic @480,780,488,58 + generic @480,784,343.13,50 + text @480,784,343.13,18 t="Shortcut" + text @480,802,343.13,32 t="Opens a small panel over any app, to ask a bot at once. Off until you set one. It needs Ctrl, Alt or Cmd." + generic @839.13,796,128.87,26 + generic @839.13,796,128.87,26 + button #settings-shortcut @839.13,796,74.36,26 lb="Shortcut" tab + text @847.13,801,58.36,16 t="⌃⌥Space" + button #settings-shortcut-clear @921.5,796,46.5,26 lb="Clear" tab + text @929.5,801,30.5,16 t="Clear" + generic @480,838,488,58 + generic @480,842,444,50 + text @480,842,444,18 t="Use selected text" + text @480,860,444,32 t="The text selected in the front app goes with your question as a quote. macOS asks for Accessibility the first time." + generic @940,859,28,16 + switch #settings-selection @940,859,28,16 lb="Use selected text" ck tab + generic @954,861,12,12 + generic @480,896,488,58 + generic @480,900,444,50 + text @480,900,444,18 t="Attach a screenshot" + text @480,918,444,32 t="The screen, or a window you pick, goes with your question as a picture. macOS asks for Screen Recording the first time." + generic @940,917,28,16 + switch #settings-screenshot @940,917,28,16 lb="Attach a screenshot" ck=false tab + generic @942,919,12,12 + generic @480,978,488,80 + generic #anchor-updates @480,970,1,700 + generic #group-updates @480,978,488,80 + heading @480,978,488,18 t="Updates" + generic @480,1000,488,58 + generic @480,1000,488,58 + generic @480,1004,260.46,50 + text @480,1004,260.46,18 t="Bate 0.9.0" + text @480,1022,260.46,32 t="Version 0.9.1 is ready. Installs when no reply is running." + generic @756.46,1016,211.54,26 + generic @756.46,1016,211.54,26 + button #settings-check-update @756.46,1016,122.38,26 lb="Check for updates" tab + text @764.46,1021,106.38,16 t="Check for updates" + button #settings-install-update @886.84,1016,81.16,26 lb="Install 0.9.1" tab + text @894.84,1021,65.16,16 t="Install 0.9.1" + generic @480,1082,488,64 + generic #anchor-report @480,1074,1,700 + generic #anchor-end @480,71082,1,700 + generic #group-report @480,1082,488,64 + heading @480,1082,488,18 t="Bug report" + generic @480,1104,488,42 + generic @480,1104,488,42 + generic @480,1108,343.33,34 + text @480,1108,343.33,18 t="Logs and a summary of the settings" + text @480,1126,343.33,16 t="Conversations are not included." + generic @839.33,1112,128.67,26 + button #settings-report @839.33,1112,128.67,26 lb="Export a bug report" tab + text @847.33,1117,112.67,16 t="Export a bug report" generic @992,8,8,684 diff --git a/native/tests/snapshots/native-settings-pairing-light.png b/native/tests/snapshots/native-settings-pairing-light.png index c1048ec..c31d39f 100644 Binary files a/native/tests/snapshots/native-settings-pairing-light.png and b/native/tests/snapshots/native-settings-pairing-light.png differ diff --git a/native/tests/snapshots/native-settings-pairing-light.tree b/native/tests/snapshots/native-settings-pairing-light.tree index 2815389..56cb683 100644 --- a/native/tests/snapshots/native-settings-pairing-light.tree +++ b/native/tests/snapshots/native-settings-pairing-light.tree @@ -144,9 +144,9 @@ generic @0,0,1000,700 text @288,258,51,18 t="Updates" button #settings-nav-report @280,284,176,30 lb="Bug report" ck=false tab text @288,290,64.55,18 t="Bug report" - generic #settings-page @480,60,512,632 sc=0,460,0,832 - generic @480,-392,488,1432 - generic @480,-392,488,1432 + generic #settings-page @480,60,512,632 sc=0,460,0,938 + generic @480,-392,488,1538 + generic @480,-392,488,1538 generic @480,-392,488,80 generic #anchor-appearance @480,-400,1,700 generic #group-appearance @480,-392,488,80 @@ -191,12 +191,12 @@ generic @0,0,1000,700 generic @480,-2,488,46 button #settings-save @480,6,53.79,30 lb="Save" tab text @492,12,29.79,18 t="Save" - generic @480,68,488,388 - generic @480,68,488,300 + generic @480,68,488,494 + generic @480,68,488,406 generic #anchor-devices @480,60,1,700 - generic #group-devices @480,68,488,300 + generic #group-devices @480,68,488,406 heading @480,68,488,18 t="Other devices" - generic @480,90,488,278 + generic @480,90,488,384 generic @480,90,488,36 generic @480,99,444,18 text @480,99,444,18 t="Let devices on this network open Bate" @@ -219,105 +219,110 @@ generic @0,0,1000,700 text @496,234,402.09,18 t="AB:12:CD:34:EF:56:AB:12:CD:34:EF:56:AB:12:CD:34" button #copy-fingerprint @922.09,230,45.91,26 lb="Copy" tab text @930.09,235,29.91,16 t="Copy" - generic @480,276,488,92 - generic @480,280,488,18 + generic @480,276,488,198 + generic @480,280,488,34 text @480,280,488,18 t="Enter this code on the other device (5:00 left)" - generic @480,306,488,58 - generic @480,314,434.09,42 - text @496,326,402.09,18 t="739204" - button #copy-pair-code @922.09,322,45.91,26 lb="Copy" tab - text @930.09,327,29.91,16 t="Copy" - generic #group-paired @480,392,488,64 - heading @480,392,488,18 t="Paired devices" - generic @480,414,488,42 - generic @480,414,488,42 - generic @480,418,410.07,34 - text @480,418,410.07,18 t="Sam's phone" - text @480,436,410.07,16 t="Last seen Today 21:33" - generic @906.07,422,61.93,26 - button #settings-remove-device-dev1 @906.07,422,61.93,26 lb="Remove Sam's phone" tab - text @914.07,427,45.93,16 t="Remove" - generic @480,480,488,148 - generic #anchor-helper @480,472,1,700 - generic #group-helper @480,480,488,148 - heading @480,480,488,18 t="Bate Helper" - generic @480,502,488,126 - generic @480,502,488,42 - generic @480,506,327.2,34 - text @480,506,327.2,18 t="Accessibility" - text @480,524,327.2,16 t="Read and control other apps: Allowed" - generic @823.2,510,144.8,26 - button #settings-open-accessibility @823.2,510,144.8,26 lb="Open System Settings: Accessibility" tab - text @831.2,515,128.8,16 t="Open System Settings" - generic @480,544,488,42 - generic @480,548,327.2,34 - text @480,548,327.2,18 t="Screen Recording" - text @480,566,327.2,16 t="Pictures of windows: Not allowed" - generic @823.2,552,144.8,26 - button #settings-open-screen_recording @823.2,552,144.8,26 lb="Open System Settings: Screen Recording" tab - text @831.2,557,128.8,16 t="Open System Settings" - generic @480,586,488,42 - generic @480,590,327.2,34 - text @480,590,327.2,18 t="Full Disk Access" - text @480,608,327.2,16 t="Read your Messages history: Not known yet" - generic @823.2,594,144.8,26 - button #settings-open-full_disk_access @823.2,594,144.8,26 lb="Open System Settings: Full Disk Access" tab - text @831.2,599,128.8,16 t="Open System Settings" - generic @480,652,488,196 - generic #anchor-quick @480,644,1,700 - generic #group-quick @480,652,488,196 - heading @480,652,488,18 t="Quick Ask" - generic @480,674,488,174 - generic @480,674,488,58 - generic @480,678,343.13,50 - text @480,678,343.13,18 t="Shortcut" - text @480,696,343.13,32 t="Opens a small panel over any app, to ask a bot at once. Off until you set one. It needs Ctrl, Alt or Cmd." - generic @839.13,690,128.87,26 - generic @839.13,690,128.87,26 - button #settings-shortcut @839.13,690,74.36,26 lb="Shortcut" tab - text @847.13,695,58.36,16 t="⌃⌥Space" - button #settings-shortcut-clear @921.5,690,46.5,26 lb="Clear" tab - text @929.5,695,30.5,16 t="Clear" - generic @480,732,488,58 - generic @480,736,444,50 - text @480,736,444,18 t="Use selected text" - text @480,754,444,32 t="The text selected in the front app goes with your question as a quote. macOS asks for Accessibility the first time." - generic @940,753,28,16 - switch #settings-selection @940,753,28,16 lb="Use selected text" ck tab - generic @954,755,12,12 - generic @480,790,488,58 - generic @480,794,444,50 - text @480,794,444,18 t="Attach a screenshot" - text @480,812,444,32 t="The screen, or a window you pick, goes with your question as a picture. macOS asks for Screen Recording the first time." - generic @940,811,28,16 - switch #settings-screenshot @940,811,28,16 lb="Attach a screenshot" ck=false tab - generic @942,813,12,12 - generic @480,872,488,80 - generic #anchor-updates @480,864,1,700 - generic #group-updates @480,872,488,80 - heading @480,872,488,18 t="Updates" - generic @480,894,488,58 - generic @480,894,488,58 - generic @480,898,260.46,50 - text @480,898,260.46,18 t="Bate 0.9.0" - text @480,916,260.46,32 t="Version 0.9.1 is ready. Installs when no reply is running." - generic @756.46,910,211.54,26 - generic @756.46,910,211.54,26 - button #settings-check-update @756.46,910,122.38,26 lb="Check for updates" tab - text @764.46,915,106.38,16 t="Check for updates" - button #settings-install-update @886.84,910,81.16,26 lb="Install 0.9.1" tab - text @894.84,915,65.16,16 t="Install 0.9.1" - generic @480,976,488,64 - generic #anchor-report @480,968,1,700 - generic #anchor-end @480,70976,1,700 - generic #group-report @480,976,488,64 - heading @480,976,488,18 t="Bug report" - generic @480,998,488,42 - generic @480,998,488,42 - generic @480,1002,343.33,34 - text @480,1002,343.33,18 t="Logs and a summary of the settings" - text @480,1020,343.33,16 t="Conversations are not included." - generic @839.33,1006,128.67,26 - button #settings-report @839.33,1006,128.67,26 lb="Export a bug report" tab - text @847.33,1011,112.67,16 t="Export a bug report" + text @480,298,488,16 t="Or scan the QR code with your phone to open Bate and fill in the code." + generic @480,322,488,148 + generic @480,322,328,58 + generic @480,322,328,58 + generic @480,330,274.09,42 + text @496,342,242.09,18 t="739204" + button #copy-pair-code @762.09,338,45.91,26 lb="Copy" tab + text @770.09,343,29.91,16 t="Copy" + generic #pair-qr @820,322,148,148 + image @821,323,146,146 deco + generic #group-paired @480,498,488,64 + heading @480,498,488,18 t="Paired devices" + generic @480,520,488,42 + generic @480,520,488,42 + generic @480,524,410.07,34 + text @480,524,410.07,18 t="Sam's phone" + text @480,542,410.07,16 t="Last seen Today 21:33" + generic @906.07,528,61.93,26 + button #settings-remove-device-dev1 @906.07,528,61.93,26 lb="Remove Sam's phone" tab + text @914.07,533,45.93,16 t="Remove" + generic @480,586,488,148 + generic #anchor-helper @480,578,1,700 + generic #group-helper @480,586,488,148 + heading @480,586,488,18 t="Bate Helper" + generic @480,608,488,126 + generic @480,608,488,42 + generic @480,612,327.2,34 + text @480,612,327.2,18 t="Accessibility" + text @480,630,327.2,16 t="Read and control other apps: Allowed" + generic @823.2,616,144.8,26 + button #settings-open-accessibility @823.2,616,144.8,26 lb="Open System Settings: Accessibility" tab + text @831.2,621,128.8,16 t="Open System Settings" + generic @480,650,488,42 + generic @480,654,327.2,34 + text @480,654,327.2,18 t="Screen Recording" + text @480,672,327.2,16 t="Pictures of windows: Not allowed" + generic @823.2,658,144.8,26 + button #settings-open-screen_recording @823.2,658,144.8,26 lb="Open System Settings: Screen Recording" tab + text @831.2,663,128.8,16 t="Open System Settings" + generic @480,692,488,42 + generic @480,696,327.2,34 + text @480,696,327.2,18 t="Full Disk Access" + text @480,714,327.2,16 t="Read your Messages history: Not known yet" + generic @823.2,700,144.8,26 + button #settings-open-full_disk_access @823.2,700,144.8,26 lb="Open System Settings: Full Disk Access" tab + text @831.2,705,128.8,16 t="Open System Settings" + generic @480,758,488,196 + generic #anchor-quick @480,750,1,700 + generic #group-quick @480,758,488,196 + heading @480,758,488,18 t="Quick Ask" + generic @480,780,488,174 + generic @480,780,488,58 + generic @480,784,343.13,50 + text @480,784,343.13,18 t="Shortcut" + text @480,802,343.13,32 t="Opens a small panel over any app, to ask a bot at once. Off until you set one. It needs Ctrl, Alt or Cmd." + generic @839.13,796,128.87,26 + generic @839.13,796,128.87,26 + button #settings-shortcut @839.13,796,74.36,26 lb="Shortcut" tab + text @847.13,801,58.36,16 t="⌃⌥Space" + button #settings-shortcut-clear @921.5,796,46.5,26 lb="Clear" tab + text @929.5,801,30.5,16 t="Clear" + generic @480,838,488,58 + generic @480,842,444,50 + text @480,842,444,18 t="Use selected text" + text @480,860,444,32 t="The text selected in the front app goes with your question as a quote. macOS asks for Accessibility the first time." + generic @940,859,28,16 + switch #settings-selection @940,859,28,16 lb="Use selected text" ck tab + generic @954,861,12,12 + generic @480,896,488,58 + generic @480,900,444,50 + text @480,900,444,18 t="Attach a screenshot" + text @480,918,444,32 t="The screen, or a window you pick, goes with your question as a picture. macOS asks for Screen Recording the first time." + generic @940,917,28,16 + switch #settings-screenshot @940,917,28,16 lb="Attach a screenshot" ck=false tab + generic @942,919,12,12 + generic @480,978,488,80 + generic #anchor-updates @480,970,1,700 + generic #group-updates @480,978,488,80 + heading @480,978,488,18 t="Updates" + generic @480,1000,488,58 + generic @480,1000,488,58 + generic @480,1004,260.46,50 + text @480,1004,260.46,18 t="Bate 0.9.0" + text @480,1022,260.46,32 t="Version 0.9.1 is ready. Installs when no reply is running." + generic @756.46,1016,211.54,26 + generic @756.46,1016,211.54,26 + button #settings-check-update @756.46,1016,122.38,26 lb="Check for updates" tab + text @764.46,1021,106.38,16 t="Check for updates" + button #settings-install-update @886.84,1016,81.16,26 lb="Install 0.9.1" tab + text @894.84,1021,65.16,16 t="Install 0.9.1" + generic @480,1082,488,64 + generic #anchor-report @480,1074,1,700 + generic #anchor-end @480,71082,1,700 + generic #group-report @480,1082,488,64 + heading @480,1082,488,18 t="Bug report" + generic @480,1104,488,42 + generic @480,1104,488,42 + generic @480,1108,343.33,34 + text @480,1108,343.33,18 t="Logs and a summary of the settings" + text @480,1126,343.33,16 t="Conversations are not included." + generic @839.33,1112,128.67,26 + button #settings-report @839.33,1112,128.67,26 lb="Export a bug report" tab + text @847.33,1117,112.67,16 t="Export a bug report" generic @992,8,8,684 diff --git a/proto/src/lib.rs b/proto/src/lib.rs index fb8733d..c6bc02e 100644 --- a/proto/src/lib.rs +++ b/proto/src/lib.rs @@ -17,6 +17,7 @@ pub mod memory; pub mod paths; pub mod permissions; pub mod projects; +pub mod qr; pub mod quick; pub mod routines; pub mod secrets; diff --git a/proto/src/qr.rs b/proto/src/qr.rs new file mode 100644 index 0000000..e82e636 --- /dev/null +++ b/proto/src/qr.rs @@ -0,0 +1,610 @@ +//! Pure-Rust ISO/IEC 18004 QR Code encoder (Byte mode, EC level M, versions 1–10). +//! Used to render pairing QR codes in both `native` (via SVG) and `window/ui` (via rows) with zero +//! external dependencies. + +/// A QR Code matrix (`size` x `size`, `true` = dark module). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Qr { + pub size: usize, + pub modules: Vec, +} + +impl Qr { + #[inline] + pub fn get(&self, x: usize, y: usize) -> bool { + self.modules[y * self.size + x] + } + + /// Compact row strings (`'1'` = dark, `'0'` = light) for JSON transport to the web UI. + pub fn rows(&self) -> Vec { + (0..self.size) + .map(|y| { + (0..self.size) + .map(|x| if self.get(x, y) { '1' } else { '0' }) + .collect() + }) + .collect() + } + + /// Self-contained monochrome SVG with a 4-module quiet zone (`fill="#000"`). + pub fn to_svg(&self) -> String { + let quiet = 4usize; + let dim = self.size + quiet * 2; + let mut d = String::new(); + for y in 0..self.size { + let mut x = 0; + while x < self.size { + if !self.get(x, y) { + x += 1; + continue; + } + let start = x; + while x < self.size && self.get(x, y) { + x += 1; + } + let w = x - start; + use std::fmt::Write; + let _ = write!(d, "M{},{}h{}v1h-{}z", start + quiet, y + quiet, w, w); + } + } + format!( + "\ + " + ) + } +} + +/// Parameters for QR versions 1..=10 at Error Correction Level M (ISO/IEC 18004 Table 9). +struct VersionSpec { + version: usize, + total_data: usize, + ec_per_block: usize, + g1_blocks: usize, + g1_data: usize, + g2_blocks: usize, + g2_data: usize, + align: &'static [usize], +} + +const VERSIONS: [VersionSpec; 10] = [ + VersionSpec { + version: 1, + total_data: 16, + ec_per_block: 10, + g1_blocks: 1, + g1_data: 16, + g2_blocks: 0, + g2_data: 0, + align: &[], + }, + VersionSpec { + version: 2, + total_data: 28, + ec_per_block: 16, + g1_blocks: 1, + g1_data: 28, + g2_blocks: 0, + g2_data: 0, + align: &[6, 18], + }, + VersionSpec { + version: 3, + total_data: 44, + ec_per_block: 26, + g1_blocks: 1, + g1_data: 44, + g2_blocks: 0, + g2_data: 0, + align: &[6, 22], + }, + VersionSpec { + version: 4, + total_data: 64, + ec_per_block: 18, + g1_blocks: 2, + g1_data: 32, + g2_blocks: 0, + g2_data: 0, + align: &[6, 26], + }, + VersionSpec { + version: 5, + total_data: 86, + ec_per_block: 24, + g1_blocks: 2, + g1_data: 43, + g2_blocks: 0, + g2_data: 0, + align: &[6, 30], + }, + VersionSpec { + version: 6, + total_data: 108, + ec_per_block: 16, + g1_blocks: 4, + g1_data: 27, + g2_blocks: 0, + g2_data: 0, + align: &[6, 34], + }, + VersionSpec { + version: 7, + total_data: 124, + ec_per_block: 18, + g1_blocks: 4, + g1_data: 31, + g2_blocks: 0, + g2_data: 0, + align: &[6, 22, 38], + }, + VersionSpec { + version: 8, + total_data: 154, + ec_per_block: 22, + g1_blocks: 2, + g1_data: 38, + g2_blocks: 2, + g2_data: 39, + align: &[6, 24, 42], + }, + VersionSpec { + version: 9, + total_data: 182, + ec_per_block: 22, + g1_blocks: 3, + g1_data: 36, + g2_blocks: 2, + g2_data: 37, + align: &[6, 26, 46], + }, + VersionSpec { + version: 10, + total_data: 216, + ec_per_block: 26, + g1_blocks: 4, + g1_data: 43, + g2_blocks: 1, + g2_data: 44, + align: &[6, 28, 50], + }, +]; + +/// Encodes UTF-8 `text` into a QR Code (Byte mode, EC level M). Returns `None` if `text` is +/// empty or exceeds version 10 capacity (213 bytes). +pub fn encode(text: &str) -> Option { + let bytes = text.as_bytes(); + if bytes.is_empty() { + return None; + } + let spec = VERSIONS.iter().find(|v| { + let count_bits = if v.version <= 9 { 8 } else { 16 }; + let needed_bits = 4 + count_bits + bytes.len() * 8; + needed_bits <= v.total_data * 8 + })?; + + let codewords = make_codewords(bytes, spec); + let size = spec.version * 4 + 17; + let mut base = vec![false; size * size]; + let mut func = vec![false; size * size]; + + place_functions(spec, size, &mut base, &mut func); + place_data(size, &codewords, &mut base, &func); + + let mut best_mask = 0u8; + let mut best_penalty = u32::MAX; + let mut best_modules = Vec::new(); + for mask in 0..8u8 { + let mut candidate = base.clone(); + apply_mask(size, mask, &mut candidate, &func); + write_format(size, mask, &mut candidate); + if spec.version >= 7 { + write_version(spec.version, size, &mut candidate); + } + let p = penalty(size, &candidate); + if p < best_penalty { + best_penalty = p; + best_mask = mask; + best_modules = candidate; + } + } + let _ = best_mask; + Some(Qr { + size, + modules: best_modules, + }) +} + +fn push_bits(bits: &mut Vec, val: u32, len: usize) { + for i in (0..len).rev() { + bits.push(((val >> i) & 1) != 0); + } +} + +fn make_codewords(bytes: &[u8], spec: &VersionSpec) -> Vec { + let mut bits = Vec::with_capacity(spec.total_data * 8); + // Byte mode indicator (0100) + character count indicator. + push_bits(&mut bits, 0b0100, 4); + let count_bits = if spec.version <= 9 { 8 } else { 16 }; + push_bits(&mut bits, bytes.len() as u32, count_bits); + for &b in bytes { + push_bits(&mut bits, u32::from(b), 8); + } + let cap = spec.total_data * 8; + let term = (cap - bits.len()).min(4); + push_bits(&mut bits, 0, term); + while !bits.len().is_multiple_of(8) { + bits.push(false); + } + let mut data = Vec::with_capacity(spec.total_data); + for chunk in bits.chunks(8) { + let byte = chunk + .iter() + .fold(0u8, |acc, &bit| (acc << 1) | u8::from(bit)); + data.push(byte); + } + let pads = [0xECu8, 0x11u8]; + let mut pad_i = 0; + while data.len() < spec.total_data { + data.push(pads[pad_i % 2]); + pad_i += 1; + } + + // Split into RS blocks and compute EC codewords. + let poly = rs_generator(spec.ec_per_block); + let mut data_blocks: Vec<&[u8]> = Vec::with_capacity(spec.g1_blocks + spec.g2_blocks); + let mut ec_blocks: Vec> = Vec::with_capacity(spec.g1_blocks + spec.g2_blocks); + let mut offset = 0; + for (count, len) in [ + (spec.g1_blocks, spec.g1_data), + (spec.g2_blocks, spec.g2_data), + ] { + for _ in 0..count { + let block = &data[offset..offset + len]; + offset += len; + ec_blocks.push(rs_remainder(block, &poly)); + data_blocks.push(block); + } + } + + // Interleave data codewords, then EC codewords. + let max_data = spec.g1_data.max(spec.g2_data); + let mut out = Vec::with_capacity(spec.total_data + ec_blocks.len() * spec.ec_per_block); + for i in 0..max_data { + for block in &data_blocks { + if i < block.len() { + out.push(block[i]); + } + } + } + for i in 0..spec.ec_per_block { + for ec in &ec_blocks { + out.push(ec[i]); + } + } + out +} + +fn gf_mul(mut a: u8, mut b: u8) -> u8 { + let mut res = 0u8; + for _ in 0..8 { + if (b & 1) != 0 { + res ^= a; + } + let hi = (a & 0x80) != 0; + a <<= 1; + if hi { + a ^= 0x1D; + } + b >>= 1; + } + res +} + +fn rs_generator(degree: usize) -> Vec { + let mut poly = vec![1u8]; + let mut root = 1u8; + for _ in 0..degree { + let mut next = vec![0u8; poly.len() + 1]; + for (i, &c) in poly.iter().enumerate() { + next[i] ^= c; + next[i + 1] ^= gf_mul(c, root); + } + poly = next; + root = gf_mul(root, 2); + } + // Leading coefficient is always 1; drop it for synthetic division. + poly.remove(0); + poly +} + +fn rs_remainder(data: &[u8], poly: &[u8]) -> Vec { + let mut rem = vec![0u8; poly.len()]; + for &b in data { + let factor = b ^ rem[0]; + rem.rotate_left(1); + rem[poly.len() - 1] = 0; + for (r, &g) in rem.iter_mut().zip(poly.iter()) { + *r ^= gf_mul(g, factor); + } + } + rem +} + +fn set_func(size: usize, x: usize, y: usize, dark: bool, mods: &mut [bool], func: &mut [bool]) { + mods[y * size + x] = dark; + func[y * size + x] = true; +} + +fn place_finder(size: usize, cx: isize, cy: isize, mods: &mut [bool], func: &mut [bool]) { + for dy in -4..=4isize { + for dx in -4..=4isize { + let (x, y) = (cx + dx, cy + dy); + if x >= 0 && y >= 0 && (x as usize) < size && (y as usize) < size { + let dist = dx.abs().max(dy.abs()); + let dark = dist != 2 && dist != 4; + set_func(size, x as usize, y as usize, dark, mods, func); + } + } + } +} + +fn place_alignment(size: usize, cx: usize, cy: usize, mods: &mut [bool], func: &mut [bool]) { + for dy in -2..=2isize { + for dx in -2..=2isize { + let dist = dx.abs().max(dy.abs()); + let dark = dist != 1; + set_func( + size, + (cx as isize + dx) as usize, + (cy as isize + dy) as usize, + dark, + mods, + func, + ); + } + } +} + +fn place_functions(spec: &VersionSpec, size: usize, mods: &mut [bool], func: &mut [bool]) { + // Timing patterns. + for i in 0..size { + set_func(size, 6, i, i % 2 == 0, mods, func); + set_func(size, i, 6, i % 2 == 0, mods, func); + } + // Three finder patterns + separators. + let s = size as isize; + place_finder(size, 3, 3, mods, func); + place_finder(size, s - 4, 3, mods, func); + place_finder(size, 3, s - 4, mods, func); + + // Alignment patterns. + let coords = spec.align; + let last = coords.len().saturating_sub(1); + for (i, &cy) in coords.iter().enumerate() { + for (j, &cx) in coords.iter().enumerate() { + let skip = (i == 0 && (j == 0 || j == last)) || (i == last && j == 0); + if !skip { + place_alignment(size, cx, cy, mods, func); + } + } + } + + // Reserve format info strips (filled after masking). + for i in 0..=8 { + if i != 6 { + set_func(size, 8, i, false, mods, func); + set_func(size, i, 8, false, mods, func); + } + } + for i in 0..8 { + set_func(size, size - 1 - i, 8, false, mods, func); + set_func(size, 8, size - 1 - i, false, mods, func); + } + // Dark module. + set_func(size, 8, size - 8, true, mods, func); + + // Reserve version info blocks for versions >= 7. + if spec.version >= 7 { + for i in 0..6 { + for j in 0..3 { + set_func(size, size - 11 + j, i, false, mods, func); + set_func(size, i, size - 11 + j, false, mods, func); + } + } + } +} + +fn place_data(size: usize, codewords: &[u8], mods: &mut [bool], func: &[bool]) { + let mut bit_idx = 0usize; + let total_bits = codewords.len() * 8; + let mut right = (size - 1) as isize; + let mut upward = true; + while right >= 1 { + if right == 6 { + right -= 1; + } + for vert in 0..size { + let y = if upward { size - 1 - vert } else { vert }; + for j in 0..2 { + let x = (right - j) as usize; + if !func[y * size + x] { + let dark = if bit_idx < total_bits { + ((codewords[bit_idx / 8] >> (7 - (bit_idx % 8))) & 1) != 0 + } else { + false + }; + mods[y * size + x] = dark; + bit_idx += 1; + } + } + } + upward = !upward; + right -= 2; + } +} + +fn apply_mask(size: usize, mask: u8, mods: &mut [bool], func: &[bool]) { + for y in 0..size { + for x in 0..size { + if func[y * size + x] { + continue; + } + let flip = match mask { + 0 => (x + y).is_multiple_of(2), + 1 => y.is_multiple_of(2), + 2 => x.is_multiple_of(3), + 3 => (x + y).is_multiple_of(3), + 4 => (y / 2 + x / 3).is_multiple_of(2), + 5 => (x * y) % 2 + (x * y) % 3 == 0, + 6 => ((x * y) % 2 + (x * y) % 3).is_multiple_of(2), + _ => ((x + y) % 2 + (x * y) % 3).is_multiple_of(2), + }; + if flip { + mods[y * size + x] = !mods[y * size + x]; + } + } + } +} + +fn write_format(size: usize, mask: u8, mods: &mut [bool]) { + // EC Level M = 00 in format bits (L=01, M=00, Q=11, H=10). + let data = u32::from(mask & 7); + let mut rem = data << 10; + for i in (0..5).rev() { + if ((rem >> (i + 10)) & 1) != 0 { + rem ^= 0x537 << i; + } + } + let bits = ((data << 10) | rem) ^ 0x5412; + + // First copy around top-left finder. + for i in 0..6 { + mods[i * size + 8] = ((bits >> i) & 1) != 0; + } + mods[7 * size + 8] = ((bits >> 6) & 1) != 0; + mods[8 * size + 8] = ((bits >> 7) & 1) != 0; + mods[8 * size + 7] = ((bits >> 8) & 1) != 0; + for i in 9..15 { + mods[8 * size + (14 - i)] = ((bits >> i) & 1) != 0; + } + // Second copy split between top-right and bottom-left finders. + for i in 0..8 { + mods[8 * size + (size - 1 - i)] = ((bits >> i) & 1) != 0; + } + for i in 8..15 { + mods[(size - 15 + i) * size + 8] = ((bits >> i) & 1) != 0; + } + mods[(size - 8) * size + 8] = true; +} + +fn write_version(version: usize, size: usize, mods: &mut [bool]) { + let mut rem = (version as u32) << 12; + for i in (0..6).rev() { + if ((rem >> (i + 12)) & 1) != 0 { + rem ^= 0x1F25 << i; + } + } + let bits = ((version as u32) << 12) | rem; + for i in 0..18 { + let dark = ((bits >> i) & 1) != 0; + let a = size - 11 + (i % 3); + let b = i / 3; + mods[b * size + a] = dark; + mods[a * size + b] = dark; + } +} + +fn penalty(size: usize, mods: &[bool]) -> u32 { + let mut score = 0u32; + // Rule 1: 5+ same-color modules in a row or column. + for y in 0..size { + let (mut run_color, mut run_len) = (false, 0u32); + for x in 0..size { + let c = mods[y * size + x]; + if c == run_color { + run_len += 1; + if run_len == 5 { + score += 3; + } else if run_len > 5 { + score += 1; + } + } else { + run_color = c; + run_len = 1; + } + } + } + for x in 0..size { + let (mut run_color, mut run_len) = (false, 0u32); + for y in 0..size { + let c = mods[y * size + x]; + if c == run_color { + run_len += 1; + if run_len == 5 { + score += 3; + } else if run_len > 5 { + score += 1; + } + } else { + run_color = c; + run_len = 1; + } + } + } + // Rule 2: 2x2 blocks of same color. + for y in 0..size - 1 { + for x in 0..size - 1 { + let c = mods[y * size + x]; + if c == mods[y * size + x + 1] + && c == mods[(y + 1) * size + x] + && c == mods[(y + 1) * size + x + 1] + { + score += 3; + } + } + } + // Rule 4: balance of dark modules. + let dark = mods.iter().filter(|&&m| m).count(); + let total = size * size; + let k = (dark * 20).abs_diff(total * 10) / total; + score + (k as u32) * 10 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encodes_pairing_urls_deterministically_with_valid_finders_and_svg() { + let url = "https://192.168.1.42:47822/?pair=739204"; + let qr = encode(url).expect("fits in version 3"); + assert_eq!(qr, encode(url).unwrap(), "deterministic"); + assert!(qr.size >= 21 && (qr.size - 17).is_multiple_of(4)); + // Top-left 7x7 finder corners and 3x3 center are dark, ring around center is light. + assert!(qr.get(0, 0) && qr.get(6, 0) && qr.get(0, 6) && qr.get(6, 6)); + assert!(qr.get(3, 3)); + assert!(!qr.get(1, 1) && !qr.get(5, 5)); + // Timing pattern on row 6 alternates dark/light. + assert!(qr.get(8, 6) && !qr.get(9, 6) && qr.get(10, 6)); + // Dark module is always set. + assert!(qr.get(8, qr.size - 8)); + + let rows = qr.rows(); + assert_eq!(rows.len(), qr.size); + assert!(rows.iter().all(|r| r.len() == qr.size)); + let svg = qr.to_svg(); + let dim = qr.size + 8; + assert!(svg.contains(&format!("viewBox=\"0 0 {dim} {dim}\""))); + assert!(svg.contains("213 bytes returns None. + let long = format!( + "https://{}.tailnet.ts.net:47822/?pair=123456", + "a".repeat(120) + ); + let big = encode(&long).expect("version 8..10"); + assert!(big.size >= 45); + assert!(encode("").is_none()); + assert!(encode(&"x".repeat(300)).is_none()); + } +} diff --git a/window/ui/index.html b/window/ui/index.html index 6d2e5b6..57671aa 100644 --- a/window/ui/index.html +++ b/window/ui/index.html @@ -2,7 +2,15 @@ + + + + + Bate + + + diff --git a/window/ui/public/icon.svg b/window/ui/public/icon.svg new file mode 100644 index 0000000..0105b71 --- /dev/null +++ b/window/ui/public/icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/window/ui/public/manifest.webmanifest b/window/ui/public/manifest.webmanifest new file mode 100644 index 0000000..a1d6614 --- /dev/null +++ b/window/ui/public/manifest.webmanifest @@ -0,0 +1,16 @@ +{ + "name": "Bate", + "short_name": "Bate", + "start_url": "/", + "display": "standalone", + "background_color": "#ffffff", + "theme_color": "#7c5cdb", + "icons": [ + { + "src": "/icon.svg", + "sizes": "any", + "type": "image/svg+xml", + "purpose": "any maskable" + } + ] +} diff --git a/window/ui/public/sw.js b/window/ui/public/sw.js new file mode 100644 index 0000000..3ded900 --- /dev/null +++ b/window/ui/public/sw.js @@ -0,0 +1,26 @@ +// Minimal service worker for Bate Web Push notifications on paired Devices. +self.addEventListener("push", (event) => { + let data = { title: "Bate", body: "Open Bate.", tag: "bate" }; + try { + if (event.data) data = { ...data, ...event.data.json() }; + } catch { + if (event.data) data.body = event.data.text(); + } + event.waitUntil( + self.registration.showNotification(data.title || "Bate", { + body: data.body || "", + tag: data.tag || "bate", + icon: "/icon.svg", + }), + ); +}); + +self.addEventListener("notificationclick", (event) => { + event.notification.close(); + event.waitUntil( + self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((list) => { + if (list.length > 0) return list[0].focus(); + return self.clients.openWindow("/"); + }), + ); +}); diff --git a/window/ui/src/Devices.tsx b/window/ui/src/Devices.tsx index de6cd72..9561c9d 100644 --- a/window/ui/src/Devices.tsx +++ b/window/ui/src/Devices.tsx @@ -12,10 +12,12 @@ type Lan = { devices: { id: string; name: string; createdAt: number; lastSeen: number }[]; }; +type PairCode = { code: string; expiresAt: number; url?: string; qr?: { size: number; rows: string[] } }; + /** Other devices on this network: the switch, where to go, the certificate, pairing, and who is paired. */ export function Devices() { const [lan, setLan] = useState(); - const [code, setCode] = useState<{ code: string; expiresAt: number }>(); + const [code, setCode] = useState(); const [now, setNow] = useState(Date.now()); const { run, fail, saved, error } = useSaves(); const load = () => request("lan_status").then(setLan, (e: Error) => fail("load", e.message)); @@ -60,12 +62,19 @@ export function Devices() { )} {code && left > 0 ? ( - - + +
+ + {code.qr && } +
) : ( - + )} @@ -86,9 +95,51 @@ export function Devices() { ); } +/** Monochrome vector QR code with a 4-module quiet zone. */ +function QrCode({ size, rows }: { size: number; rows: string[] }) { + const quiet = 4; + const dim = size + quiet * 2; + const parts: string[] = []; + for (let y = 0; y < rows.length; y++) { + const row = rows[y]; + let x = 0; + while (x < row.length) { + if (row[x] !== "1") { + x++; + continue; + } + const start = x; + while (x < row.length && row[x] === "1") x++; + const w = x - start; + parts.push(`M${start + quiet},${y + quiet}h${w}v1h-${w}z`); + } + } + return ( + + + + ); +} + +/** Reads and clears `?pair=` from the URL when opened via QR code. */ +function initialPairCode(): string { + try { + const params = new URLSearchParams(window.location.search); + const pair = params.get("pair")?.trim() ?? ""; + if (pair) { + params.delete("pair"); + const next = params.toString(); + window.history.replaceState(null, "", `${window.location.pathname}${next ? `?${next}` : ""}${window.location.hash}`); + } + return pair; + } catch { + return ""; + } +} + /** Asks for the code shown in Bate's window, on a device not yet paired. */ export function Pair({ onPair }: { onPair: (code: string, name: string) => Promise }) { - const [code, setCode] = useState(""); + const [code, setCode] = useState(initialPairCode); const [name, setName] = useState(navigator.platform || "This device"); const [error, setError] = useState(""); const [state, setState] = useState<"" | "busy" | "paired">(""); diff --git a/window/ui/src/service.ts b/window/ui/src/service.ts index b957f39..4069b0b 100644 --- a/window/ui/src/service.ts +++ b/window/ui/src/service.ts @@ -57,6 +57,39 @@ export async function pair(code: string, name: string) { const r = await api("/api/pair", JSON.stringify({ code, name })); if (!r.ok) throw new Error(((await r.json()) as { error: string }).error); paired(); + void registerWebPush(); +} + +function decodeBase64Url(s: string): Uint8Array { + const pad = "=".repeat((4 - (s.length % 4)) % 4); + const raw = atob((s + pad).replace(/-/g, "+").replace(/_/g, "/")); + const out = new Uint8Array(new ArrayBuffer(raw.length)); + for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i); + return out; +} + +/** Registers `/sw.js` and subscribes this paired device to Web Push when the browser already grants Notification permission. */ +export async function registerWebPush(): Promise { + if (inShell || !("serviceWorker" in navigator) || !("PushManager" in window)) return false; + try { + const reg = await navigator.serviceWorker.register("/sw.js"); + if (typeof Notification === "undefined" || Notification.permission !== "granted") return false; + let sub = await reg.pushManager.getSubscription(); + if (!sub) { + const r = await api("/api/push/key"); + if (!r.ok) return false; + const { publicKey } = (await r.json()) as { publicKey: string }; + sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: decodeBase64Url(publicKey) }); + } + const resp = await api("/api/push/subscribe", JSON.stringify(sub.toJSON())); + return resp.ok; + } catch { + return false; + } +} + +if (!inShell && typeof window !== "undefined") { + void registerWebPush(); } /** Opens one more window, a page of its own with its own connection. */ diff --git a/window/ui/src/style.css b/window/ui/src/style.css index 72e008f..8183b40 100644 --- a/window/ui/src/style.css +++ b/window/ui/src/style.css @@ -745,3 +745,10 @@ svg.pin { width: var(--size-small); height: var(--size-small); margin-right: var .quick .answer > p { margin: var(--space-2) 0 0; } .quick .question { margin: 0; } .quick > .error, .quick form > .error, .quick form > .note { margin: 0; } + +/* Pairing QR code in Settings -> Devices and mobile PWA safe-area insets. */ +.pair-qr-box { display: flex; flex-wrap: wrap; align-items: flex-start; gap: var(--space-3); } +.pair-qr { width: 152px; height: 152px; flex: 0 0 auto; border-radius: var(--radius); background: #fff; color: #000; border: 1px solid var(--border); shape-rendering: crispEdges; } +@media (display-mode: standalone) { + body { padding-top: env(safe-area-inset-top); padding-bottom: env(safe-area-inset-bottom); box-sizing: border-box; } +}