diff --git a/crates/waybetter-host/Cargo.lock b/crates/waybetter-host/Cargo.lock index 9d7c133..ebf4293 100644 --- a/crates/waybetter-host/Cargo.lock +++ b/crates/waybetter-host/Cargo.lock @@ -2993,6 +2993,15 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "libc", +] + [[package]] name = "system-deps" version = "6.2.2" @@ -3813,6 +3822,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "sys-locale", "tauri", "tempfile", "url", diff --git a/crates/waybetter-host/Cargo.toml b/crates/waybetter-host/Cargo.toml index 6a92768..54830b6 100644 --- a/crates/waybetter-host/Cargo.toml +++ b/crates/waybetter-host/Cargo.toml @@ -24,6 +24,8 @@ sha2 = "0.10" chrono = { version = "0.4", default-features = false, features = ["clock"] } minisign-verify = "0.2" base64 = "0.22" +# The OS language preference (first run, "Follow system"); no dependencies of its own on desktop. +sys-locale = "0.3" tauri = { version = "2", features = ["unstable"], optional = true } [target.'cfg(windows)'.dependencies] diff --git a/crates/waybetter-host/src/i18n.rs b/crates/waybetter-host/src/i18n.rs new file mode 100644 index 0000000..187dea4 --- /dev/null +++ b/crates/waybetter-host/src/i18n.rs @@ -0,0 +1,230 @@ +//! Native side of wayBetter i18n. +//! +//! The shell owns language: it loads the catalogs, picks the locale (follow the site, follow the +//! system, or the owner's pick) and hands native code the few strings native UI needs (dialog +//! titles, notifications, the site runtime's own words) as [`NativeStrings`]. These are data only: +//! validated here (bounded, plain text, no markup or control characters), kept in app data so the +//! next launch has them before the shell loads, and delivered to site tabs as a JSON value. +//! +//! [`system_locales`] reads the OS preference for the first run and for "Follow system". + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// At most this many strings reach native code (the site runtime's, the kit's, bundled plugins', native UI's). +pub const MAX_STRINGS: usize = 4000; +/// Longest message accepted. +pub const MAX_VALUE: usize = 2000; +/// Longest key accepted. +pub const MAX_KEY: usize = 96; +/// Total bytes of keys and values. +pub const MAX_TOTAL: usize = 512 * 1024; + +/// A BCP 47 language tag as the catalogs use it: `tr`, `pt-BR`, `zh-Hant`, `ar-x-fm`. +pub fn valid_tag(tag: &str) -> bool { + if tag.is_empty() || tag.len() > 35 { + return false; + } + let mut parts = tag.split('-'); + let Some(language) = parts.next() else { return false }; + if !(2..=3).contains(&language.len()) || !language.bytes().all(|b| b.is_ascii_alphabetic()) { + return false; + } + parts.all(|part| (1..=8).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphanumeric())) +} + +/// Writing direction of a tag (by primary language). +pub fn is_rtl(tag: &str) -> bool { + let language = tag.split('-').next().unwrap_or("").to_ascii_lowercase(); + matches!(language.as_str(), "ar" | "arc" | "ckb" | "dv" | "fa" | "he" | "iw" | "ks" | "ps" | "sd" | "syr" | "ug" | "ur" | "yi") +} + +fn valid_key(key: &str) -> bool { + !key.is_empty() + && key.len() <= MAX_KEY + && key.as_bytes()[0].is_ascii_lowercase() + && key.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) +} + +/// Plain text only: no markup, no control or bidi-override characters (newlines and tabs are fine). +pub fn valid_text(value: &str) -> bool { + if value.len() > MAX_VALUE { + return false; + } + let lower = value.to_ascii_lowercase(); + if lower.contains("javascript:") || lower.contains("<") || lower.contains("<") || lower.contains("<") { + return false; + } + let mut chars = value.chars().peekable(); + while let Some(ch) = chars.next() { + if ch == '<' { + if let Some(next) = chars.clone().find(|c| !c.is_whitespace()) { + if next.is_ascii_alphabetic() || matches!(next, '/' | '!' | '?') { + return false; + } + } + } + let code = ch as u32; + let control = (ch.is_control() && !matches!(ch, '\n' | '\t' | '\r')) || (0x202A..=0x202E).contains(&code) || (0x2066..=0x2069).contains(&code); + if control { + return false; + } + } + true +} + +/// The strings native code and site tabs need, in the owner's language. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase", default)] +pub struct NativeStrings { + /// Active locale (a catalog tag). + pub locale: String, + /// The owner's choice: `site` (follow the site's own language), `system`, or a locale tag. + pub preference: String, + pub messages: BTreeMap, +} + +impl NativeStrings { + /// Checks everything the shell sent; any bad entry refuses the whole set. + pub fn validated(self) -> Result { + if !valid_tag(&self.locale) { + return Err("VALIDATION: invalid locale".into()); + } + if !(self.preference == "site" || self.preference == "system" || valid_tag(&self.preference)) { + return Err("VALIDATION: language preference must be \"site\", \"system\" or a locale".into()); + } + if self.messages.len() > MAX_STRINGS { + return Err("VALIDATION: too many strings".into()); + } + let mut total = 0; + for (key, value) in &self.messages { + if !valid_key(key) { + return Err(format!("VALIDATION: invalid string key {:?}", key.chars().take(40).collect::())); + } + if !valid_text(value) { + return Err(format!("VALIDATION: string {key} is not plain text")); + } + total += key.len() + value.len(); + } + if total > MAX_TOTAL { + return Err("VALIDATION: strings too large".into()); + } + Ok(self) + } + + /// The message for `key`, or `fallback` (English, compiled in) when there is none. + pub fn get<'a>(&'a self, key: &str, fallback: &'a str) -> &'a str { + self.messages.get(key).map(String::as_str).filter(|value| !value.is_empty()).unwrap_or(fallback) + } + + /// `get` with `{name}` placeholders filled in, in one pass: values are inserted as text and are + /// never scanned for placeholders themselves. Unknown `{…}` stays as written. + pub fn format(&self, key: &str, fallback: &str, params: &[(&str, &str)]) -> String { + let template = self.get(key, fallback); + let mut out = String::with_capacity(template.len()); + let mut rest = template; + while let Some(open) = rest.find('{') { + out.push_str(&rest[..open]); + let tail = &rest[open..]; + let value = tail.find('}').and_then(|close| params.iter().find(|(name, _)| *name == &tail[1..close]).map(|(_, value)| (close, value))); + match value { + Some((close, value)) => { + out.push_str(value); + rest = &tail[close + 1..]; + } + None => { + out.push('{'); + rest = &tail[1..]; + } + } + } + out.push_str(rest); + out + } + + /// The strings whose keys start with one of `prefixes`, as the JSON value a site tab receives. + pub fn page_payload(&self, prefixes: &[&str]) -> serde_json::Value { + let messages: serde_json::Map = self + .messages + .iter() + .filter(|(key, _)| prefixes.iter().any(|prefix| key.starts_with(prefix))) + .map(|(key, value)| (key.clone(), serde_json::Value::String(value.clone()))) + .collect(); + serde_json::json!({ "locale": self.locale, "dir": if is_rtl(&self.locale) { "rtl" } else { "ltr" }, "messages": messages }) + } +} + +/// The OS language preferences, most preferred first (`tr-TR`, `en-US`), as valid tags. +pub fn system_locales() -> Vec { + sys_locale::get_locales() + .map(|tag| tag.replace('_', "-")) + // POSIX locales may carry an encoding or modifier (`tr_TR.UTF-8@euro`). + .map(|tag| tag.split(['.', '@']).next().unwrap_or("").to_owned()) + .filter(|tag| valid_tag(tag)) + .take(8) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn strings(messages: &[(&str, &str)]) -> NativeStrings { + NativeStrings { + locale: "tr".into(), + preference: "site".into(), + messages: messages.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(), + } + } + + #[test] + fn tags_are_validated() { + for good in ["tr", "pt-BR", "zh-Hant", "ar-x-fm", "fil", "en-GB"] { + assert!(valid_tag(good), "{good}"); + } + for bad in ["", "t", "english", "tr_TR", "tr-", "tr-", "a-b", "zh-Hant-TW-far-too-long-for-a-language-tag"] { + assert!(!valid_tag(bad), "{bad}"); + } + assert!(is_rtl("ar-x-fm") && is_rtl("he") && !is_rtl("tr")); + } + + #[test] + fn strings_are_plain_text_only() { + assert!(strings(&[("native.alert.title", "“{keyword}” geçti"), ("x.toast.saved", "Kaydedildi\n")]).validated().is_ok()); + for bad in ["", "a < b /