| 1 | //! Install identity and the constant half of the batch envelope. |
| 2 | |
| 3 | use std::path::Path; |
| 4 | |
| 5 | use anyhow::{Context, Result}; |
| 6 | use serde::{Deserialize, Serialize}; |
| 7 | |
| 8 | use crate::buffer; |
| 9 | use crate::event::{Arch, Libc, Os}; |
| 10 | |
| 11 | /// How long an install id may live before it is replaced. |
| 12 | /// |
| 13 | /// A never-rotating id plus one batch per session from the user's IP is a |
| 14 | /// longitudinal IP and travel trace. Rotation bounds that join. It costs |
| 15 | /// longitudinal accuracy, and the docs say so in those words: **no count derived |
| 16 | /// from `install_id` is a user count.** |
| 17 | pub const ROTATION_DAYS: i64 = 90; |
| 18 | |
| 19 | /// The on-disk install identity. |
| 20 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 21 | pub struct InstallId { |
| 22 | /// Format version of this file. |
| 23 | pub schema_version: u32, |
| 24 | /// A random v4 UUID. |
| 25 | /// |
| 26 | /// Never derived from hostname, MAC, `machine-id`, `$HOME`, username, or |
| 27 | /// executable path. A derived id is a device fingerprint: it survives |
| 28 | /// reinstall and re-identifies a user across their own opt-out, which is the |
| 29 | /// single thing an install id must never do. |
| 30 | pub install_id: String, |
| 31 | /// When this id was minted, RFC3339 UTC. |
| 32 | pub rotated_at: String, |
| 33 | } |
| 34 | |
| 35 | /// Per-machine telemetry bookkeeping. Never contains anything about the user's |
| 36 | /// work — only what this crate needs to avoid re-reporting an install and to |
| 37 | /// rate-limit its own flushes. |
| 38 | #[derive(Debug, Clone, Default, Serialize, Deserialize)] |
| 39 | pub struct TelemetryState { |
| 40 | /// Format version of this file. |
| 41 | #[serde(default)] |
| 42 | pub schema_version: u32, |
| 43 | /// The app version last seen on this machine. |
| 44 | #[serde(default)] |
| 45 | pub last_version: Option<String>, |
| 46 | /// When a flush was last *attempted*, RFC3339 UTC. Attempt, not success, so |
| 47 | /// a permanently offline machine tries at most once per interval. |
| 48 | #[serde(default)] |
| 49 | pub last_flush: Option<String>, |
| 50 | } |
| 51 | |
| 52 | /// Read the install id, minting a fresh one if it is missing, unreadable, |
| 53 | /// **not a UUID**, or older than [`ROTATION_DAYS`]. |
| 54 | /// |
| 55 | /// The UUID check is not a formatting nicety. `install_id` is the one |
| 56 | /// envelope field read verbatim off disk into a batch, so without it the file |
| 57 | /// is a free-form string slot on the wire for anything that can write |
| 58 | /// `$CODEWHALE_HOME/telemetry/install_id.json`. Minting a fresh random id is |
| 59 | /// always the safe direction — the cost is one rotation, and the docs already |
| 60 | /// say no count derived from `install_id` is a user count. |
| 61 | pub fn read_or_create_install_id(root: &Path) -> Result<InstallId> { |
| 62 | let path = buffer::install_id_path(root); |
| 63 | let existing = std::fs::read_to_string(&path) |
| 64 | .ok() |
| 65 | .and_then(|body| serde_json::from_str::<InstallId>(&body).ok()) |
| 66 | .filter(|record| uuid::Uuid::parse_str(record.install_id.trim()).is_ok()) |
| 67 | .filter(|record| !is_expired(&record.rotated_at)); |
| 68 | if let Some(record) = existing { |
| 69 | return Ok(record); |
| 70 | } |
| 71 | let record = InstallId { |
| 72 | schema_version: 1, |
| 73 | install_id: uuid::Uuid::new_v4().to_string(), |
| 74 | rotated_at: now_rfc3339(), |
| 75 | }; |
| 76 | buffer::ensure_dir(root)?; |
| 77 | codewhale_config::persistence::atomic_write_json(&path, &record) |
| 78 | .with_context(|| format!("failed to write {}", path.display()))?; |
| 79 | Ok(record) |
| 80 | } |
| 81 | |
| 82 | fn is_expired(rotated_at: &str) -> bool { |
| 83 | let Ok(parsed) = chrono::DateTime::parse_from_rfc3339(rotated_at) else { |
| 84 | // An unreadable timestamp is treated as expired: minting a fresh random |
| 85 | // id is always the safe direction. |
| 86 | return true; |
| 87 | }; |
| 88 | let age = chrono::Utc::now().signed_duration_since(parsed.with_timezone(&chrono::Utc)); |
| 89 | age.num_days() >= ROTATION_DAYS |
| 90 | } |
| 91 | |
| 92 | /// Read `state.json`, or a default when it is missing or unreadable. |
| 93 | #[must_use] |
| 94 | pub fn read_state(root: &Path) -> TelemetryState { |
| 95 | std::fs::read_to_string(buffer::state_path(root)) |
| 96 | .ok() |
| 97 | .and_then(|body| serde_json::from_str::<TelemetryState>(&body).ok()) |
| 98 | .unwrap_or_default() |
| 99 | } |
| 100 | |
| 101 | /// Write `state.json`. |
| 102 | pub fn write_state(root: &Path, state: &TelemetryState) -> Result<()> { |
| 103 | buffer::ensure_dir(root)?; |
| 104 | let path = buffer::state_path(root); |
| 105 | codewhale_config::persistence::atomic_write_json(&path, state) |
| 106 | .with_context(|| format!("failed to write {}", path.display())) |
| 107 | } |
| 108 | |
| 109 | /// RFC3339 UTC at second precision. The only timestamp this crate produces, and |
| 110 | /// it is per-**batch**: individual events carry no timestamps at all. |
| 111 | #[must_use] |
| 112 | pub fn now_rfc3339() -> String { |
| 113 | chrono::Utc::now() |
| 114 | .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) |
| 115 | .to_string() |
| 116 | } |
| 117 | |
| 118 | /// The build sha of a release-CI binary, or `None`. |
| 119 | /// |
| 120 | /// Sourced from `CODEWHALE_RELEASE_BUILD_SHA`, a rustc-env this crate's build |
| 121 | /// script emits **only** when `DEEPSEEK_BUILD_SHA` or `GITHUB_SHA` was present |
| 122 | /// in the build environment. `null` for every locally built binary, |
| 123 | /// unconditionally, with no runtime lookup of any kind. |
| 124 | /// |
| 125 | /// Never `CODEWHALE_BUILD_COMMIT` — that falls back to the builder's own `HEAD` |
| 126 | /// on a local build. Never `Thread.git_sha` — that is the *user's* workspace |
| 127 | /// commit and a red line, one identifier away by name. |
| 128 | #[must_use] |
| 129 | pub fn release_build_sha() -> Option<String> { |
| 130 | option_env!("CODEWHALE_RELEASE_BUILD_SHA").and_then(short_hex_sha) |
| 131 | } |
| 132 | |
| 133 | /// Reduce a full sha to the first 12 lowercase hex characters, rejecting |
| 134 | /// anything that is not a sha. |
| 135 | #[must_use] |
| 136 | pub fn short_hex_sha(value: &str) -> Option<String> { |
| 137 | let trimmed = value.trim().to_ascii_lowercase(); |
| 138 | if trimmed.len() < 12 || !trimmed.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 139 | return None; |
| 140 | } |
| 141 | Some(trimmed.chars().take(12).collect()) |
| 142 | } |
| 143 | |
| 144 | /// The OS family this binary is running on, mapped onto the closed whitelist. |
| 145 | #[must_use] |
| 146 | pub fn current_os() -> Os { |
| 147 | match std::env::consts::OS { |
| 148 | "linux" => Os::Linux, |
| 149 | "macos" => Os::Macos, |
| 150 | "windows" => Os::Windows, |
| 151 | "freebsd" => Os::Freebsd, |
| 152 | "android" => Os::Android, |
| 153 | _ => Os::Other, |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | /// The CPU family, mapped onto the closed whitelist. |
| 158 | #[must_use] |
| 159 | pub fn current_arch() -> Arch { |
| 160 | match std::env::consts::ARCH { |
| 161 | "x86_64" => Arch::X86_64, |
| 162 | "aarch64" => Arch::Aarch64, |
| 163 | _ => Arch::Other, |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /// The libc this binary was **compiled** against. |
| 168 | #[must_use] |
| 169 | pub fn current_libc() -> Libc { |
| 170 | if cfg!(target_env = "gnu") { |
| 171 | Libc::Gnu |
| 172 | } else if cfg!(target_env = "musl") { |
| 173 | Libc::Musl |
| 174 | } else { |
| 175 | Libc::None |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// Whether both stdin and stdout are terminals. |
| 180 | /// |
| 181 | /// This varies because consent is machine-scoped: a decision recorded on a TTY |
| 182 | /// authorizes later headless runs on the same home. |
| 183 | #[must_use] |
| 184 | pub fn current_tty() -> bool { |
| 185 | use std::io::IsTerminal as _; |
| 186 | std::io::stdin().is_terminal() && std::io::stdout().is_terminal() |
| 187 | } |
| 188 | |
| 189 | /// Reduce a panic location to something that is safe to send. |
| 190 | /// |
| 191 | /// Emit a `crates/…` path verbatim; reduce **everything else** to the literal |
| 192 | /// `<dep>`. There is no `--remap-path-prefix` in this repo, so a panic inside a |
| 193 | /// registry dependency yields |
| 194 | /// `/Users/<builder>/.cargo/registry/src/…/ratatui-0.29.0/src/…` — the build |
| 195 | /// machine's username, shipped from every user's binary. |
| 196 | /// The allowlist itself lives in [`crate::event::is_reduced_panic_site`], and |
| 197 | /// this function is defined as "the candidate if the predicate accepts it". |
| 198 | /// Two copies of one charset would drift, and the drain path re-checks the |
| 199 | /// predicate against events read back off disk — a reducer that could emit |
| 200 | /// something the checker rejects would silently delete real panics. |
| 201 | #[must_use] |
| 202 | pub fn reduce_panic_site(file: &str, line: u32, column: u32) -> String { |
| 203 | let candidate = format!("{}:{line}:{column}", file.replace('\\', "/")); |
| 204 | if crate::event::is_reduced_panic_site(&candidate) { |
| 205 | candidate |
| 206 | } else { |
| 207 | "<dep>".to_string() |
| 208 | } |
| 209 | } |
| 210 |