1use std::collections::VecDeque;
47use std::time::Duration;
48
49use serde::Serialize;
50use serde_json::Value as Json;
51use web_time::Instant;
52
53use crate::host::{Event, Seq, redact_private};
54
55pub const WINDOW: Duration = Duration::from_secs(5 * 60);
57
58pub const CAP: usize = 20_000;
61
62pub const SECRET: &str = "[redacted]";
64
65#[derive(Clone, Debug, PartialEq)]
67pub struct RecorderConfig {
68 pub window: Duration,
70 pub skip: Vec<String>,
73 pub cap: usize,
75}
76
77impl Default for RecorderConfig {
78 fn default() -> Self {
79 Self {
80 window: WINDOW,
81 skip: Vec::new(),
82 cap: CAP,
83 }
84 }
85}
86
87impl RecorderConfig {
88 #[must_use]
90 pub fn window(mut self, window: Duration) -> Self {
91 self.window = window.max(Duration::from_secs(1));
92 self
93 }
94
95 #[must_use]
97 pub fn skip(mut self, pattern: &str) -> Self {
98 self.skip.push(pattern.into());
99 self
100 }
101
102 #[must_use]
104 pub fn cap(mut self, cap: usize) -> Self {
105 self.cap = cap.max(1);
106 self
107 }
108
109 pub fn skips(&self, kind: &str) -> bool {
111 self.skip
112 .iter()
113 .any(|p| crate::bus::bus_contract_journal::kind_matches(p, kind))
114 }
115}
116
117#[derive(Clone, Debug, PartialEq, Serialize)]
120pub struct Recorded {
121 pub seq: Seq,
122 pub ago_ms: u64,
124 pub source: String,
125 pub cause: Option<Seq>,
126 pub name: String,
127 pub data: Json,
128}
129
130#[derive(Debug)]
132pub struct Recorder {
133 config: RecorderConfig,
134 entries: VecDeque<(Instant, Event)>,
135 last: Seq,
137 missed: u64,
140 capped: u64,
142}
143
144impl Recorder {
145 pub fn new(config: RecorderConfig) -> Self {
146 Self {
147 config,
148 entries: VecDeque::new(),
149 last: 0,
150 missed: 0,
151 capped: 0,
152 }
153 }
154
155 pub fn config(&self) -> &RecorderConfig {
156 &self.config
157 }
158
159 pub fn last(&self) -> Seq {
161 self.last
162 }
163
164 pub fn lost(&self) -> (u64, u64) {
167 (self.missed, self.capped)
168 }
169
170 pub fn record(&mut self, now: Instant, events: &[Event], redactor: &Redactor) {
173 for e in events {
174 if e.seq <= self.last {
175 continue;
176 }
177 if self.last > 0 && e.seq > self.last + 1 {
180 self.missed += e.seq - self.last - 1;
181 }
182 self.last = e.seq;
183 if self.config.skips(&e.name) {
184 continue;
185 }
186 if self.entries.len() >= self.config.cap {
187 self.entries.pop_front();
188 self.capped += 1;
189 }
190 self.entries.push_back((now, redactor.event(e)));
191 }
192 self.prune(now);
193 }
194
195 pub fn prune(&mut self, now: Instant) {
197 let window = self.config.window;
198 while let Some((at, _)) = self.entries.front() {
199 if now.saturating_duration_since(*at) > window {
200 self.entries.pop_front();
201 } else {
202 break;
203 }
204 }
205 }
206
207 pub fn window(&self, now: Instant) -> Vec<Recorded> {
209 let window = self.config.window;
210 self.entries
211 .iter()
212 .filter(|(at, _)| now.saturating_duration_since(*at) <= window)
213 .map(|(at, e)| Recorded {
214 seq: e.seq,
215 ago_ms: u64::try_from(now.saturating_duration_since(*at).as_millis())
216 .unwrap_or(u64::MAX),
217 source: e.source.clone(),
218 cause: e.cause,
219 name: e.name.clone(),
220 data: e.data.clone(),
221 })
222 .collect()
223 }
224}
225
226#[derive(Clone, Debug, Default, PartialEq)]
229pub struct Redactor {
230 home: Option<String>,
232 secrets: Vec<String>,
234}
235
236impl Redactor {
237 pub fn new(home: Option<&str>, secrets: &[&str]) -> Self {
240 let home = home
241 .map(|h| h.trim_end_matches(['/', '\\']).to_string())
242 .filter(|h| !h.is_empty());
243 let mut secrets: Vec<String> = secrets
244 .iter()
245 .map(|s| s.trim().to_string())
246 .filter(|s| s.len() >= 8)
247 .collect();
248 secrets.sort_by_key(|s| std::cmp::Reverse(s.len()));
250 Self { home, secrets }
251 }
252
253 pub fn from_env(vars: &[(String, String)], home: Option<&str>) -> Self {
257 let secrets: Vec<&str> = vars
258 .iter()
259 .filter(|(n, _)| secret_name(n))
260 .map(|(_, v)| v.as_str())
261 .collect();
262 Self::new(home, &secrets)
263 }
264
265 pub fn current() -> Self {
267 #[cfg(not(target_arch = "wasm32"))]
268 {
269 let vars: Vec<(String, String)> = std::env::vars().collect();
270 let home = std::env::home_dir();
271 Self::from_env(&vars, home.as_deref().and_then(|h| h.to_str()))
272 }
273 #[cfg(target_arch = "wasm32")]
274 {
275 Self::default()
276 }
277 }
278
279 pub fn event(&self, e: &Event) -> Event {
282 let mut v = serde_json::json!({ "seq": e.seq, "name": e.name, "data": e.data });
283 redact_private(&mut v);
284 let mut data = v.get_mut("data").map(Json::take).unwrap_or(Json::Null);
285 self.json(&mut data);
286 Event {
287 seq: e.seq,
288 source: self.text(&e.source),
289 cause: e.cause,
290 name: e.name.clone(),
291 data,
292 }
293 }
294
295 pub fn json(&self, v: &mut Json) {
297 match v {
298 Json::String(s) => *s = self.value(s),
299 Json::Array(items) => items.iter_mut().for_each(|x| self.json(x)),
300 Json::Object(o) => {
301 let taken = std::mem::take(o);
302 for (k, mut x) in taken {
303 self.json(&mut x);
304 o.insert(self.text(&k), x);
305 }
306 }
307 _ => {}
308 }
309 }
310
311 pub fn value(&self, value: &str) -> String {
314 let v = value.trim();
315 let b = v.as_bytes();
316 let drive = b.len() > 3
317 && b[0].is_ascii_alphabetic()
318 && b[1] == b':'
319 && (b[2] == b'\\' || b[2] == b'/');
320 let rooted = v.starts_with("file:")
321 || v.starts_with("~/")
322 || v.starts_with("~\\")
323 || (v.starts_with('/') && v.len() > 1)
324 || drive;
325 if rooted && !v.contains(['\n', '"']) && !v.contains(": ") {
326 let masked = self.unsecret(v).replace(' ', "\u{1}");
327 return scrub_paths(&masked).replace('\u{1}', " ");
328 }
329 self.text(value)
330 }
331
332 fn unsecret(&self, text: &str) -> String {
334 let mut out = text.to_string();
335 for s in &self.secrets {
336 if out.contains(s.as_str()) {
337 out = out.replace(s.as_str(), SECRET);
338 }
339 }
340 match &self.home {
341 Some(home) => home_to_tilde(&out, home),
342 None => out,
343 }
344 }
345
346 pub fn text(&self, text: &str) -> String {
349 scrub_paths(&self.unsecret(text))
350 }
351}
352
353fn secret_name(name: &str) -> bool {
356 let n = name.to_ascii_uppercase();
357 [
358 "TOKEN",
359 "SECRET",
360 "CLIENT_ID",
361 "PASSWORD",
362 "PASSWD",
363 "KEY",
364 "CREDENTIAL",
365 "AUTH",
366 ]
367 .iter()
368 .any(|s| n.contains(s))
369}
370
371fn home_to_tilde(text: &str, home: &str) -> String {
374 let mut out = String::with_capacity(text.len());
375 let mut rest = text;
376 while let Some(at) = rest.find(home) {
377 let after = &rest[at + home.len()..];
378 out.push_str(&rest[..at]);
379 if after.is_empty()
380 || after.starts_with(['/', '\\', ' ', '"', '\'', ')', ',', ':', ';', '\n'])
381 {
382 out.push('~');
383 } else {
384 out.push_str(home);
385 }
386 rest = after;
387 }
388 out.push_str(rest);
389 out
390}
391
392fn boundary(c: Option<char>) -> bool {
394 c.is_none_or(|c| c.is_whitespace() || matches!(c, '"' | '\'' | '(' | '[' | '=' | '<' | ','))
395}
396
397fn path_end(s: &str) -> usize {
400 let mut chars = s.char_indices().peekable();
401 while let Some((i, c)) = chars.next() {
402 let next = chars.peek().map(|(_, c)| *c);
403 let stop = c.is_whitespace()
404 || matches!(c, '"' | '\'' | ')' | ']' | '>' | ',')
405 || (matches!(c, ':' | ';') && next.is_none_or(char::is_whitespace));
406 if stop {
407 return i;
408 }
409 }
410 s.len()
411}
412
413fn reduced(root: &str, path: &str) -> String {
416 let file = path.rsplit(['/', '\\']).next().unwrap_or("");
417 let ext = file
418 .rsplit_once('.')
419 .filter(|(stem, ext)| !stem.is_empty() && !ext.is_empty() && ext.len() <= 5)
420 .map(|(_, ext)| format!(".{ext}"))
421 .unwrap_or_default();
422 format!("{root}/…{ext}")
423}
424
425fn scrub_paths(text: &str) -> String {
428 let mut out = String::with_capacity(text.len());
429 let mut prev: Option<char> = None;
430 let mut i = 0;
431 while i < text.len() {
432 let rest = &text[i..];
433 let c = rest.chars().next().unwrap_or(' ');
434 if boundary(prev) {
435 let (prefix, body) = match rest.strip_prefix("file://") {
437 Some(b) => ("file://", b),
438 None => match rest.strip_prefix("file:") {
439 Some(b) => ("file:", b),
440 None => ("", rest),
441 },
442 };
443 let root = if body.starts_with("~/") || body.starts_with("~\\") {
444 Some(("~", 1))
445 } else if body.starts_with('/')
446 && body[1..].chars().next().is_some_and(|c| !c.is_whitespace())
447 {
448 Some(("", 0))
449 } else {
450 let b = body.as_bytes();
451 (b.len() > 3
452 && b[0].is_ascii_alphabetic()
453 && b[1] == b':'
454 && (b[2] == b'\\' || b[2] == b'/'))
455 .then(|| (&body[..2], 2))
456 };
457 if let Some((root, skip)) = root {
458 let end = path_end(body);
459 if end > skip + 1 {
460 out.push_str(prefix);
461 out.push_str(&reduced(root, &body[..end]));
462 i += prefix.len() + end;
463 prev = Some('…');
464 continue;
465 }
466 }
467 }
468 out.push(c);
469 prev = Some(c);
470 i += c.len_utf8();
471 }
472 out
473}
474
475pub type AliasFn = dyn Fn(&str) -> bool;
477
478pub struct Aliases<'a> {
483 prefix: &'a str,
484 matches: &'a AliasFn,
485 seen: std::collections::HashMap<String, usize>,
486}
487
488impl std::fmt::Debug for Aliases<'_> {
489 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
490 f.debug_struct("Aliases")
491 .field("prefix", &self.prefix)
492 .field("seen", &self.seen.len())
493 .finish_non_exhaustive()
494 }
495}
496
497impl<'a> Aliases<'a> {
498 pub fn new(prefix: &'a str, matches: &'a AliasFn) -> Self {
499 Self {
500 prefix,
501 matches,
502 seen: std::collections::HashMap::new(),
503 }
504 }
505
506 pub fn len(&self) -> usize {
508 self.seen.len()
509 }
510
511 pub fn is_empty(&self) -> bool {
512 self.seen.is_empty()
513 }
514
515 pub fn text(&mut self, text: &str) -> String {
517 let mut out = String::with_capacity(text.len());
518 let mut token = String::new();
519 let flush = |token: &mut String, out: &mut String, me: &mut Self| {
520 if token.is_empty() {
521 return;
522 }
523 if (me.matches)(token) {
524 let n = me.seen.len() + 1;
525 let n = *me.seen.entry(std::mem::take(token)).or_insert(n);
526 out.push_str(&format!("{}-{n}", me.prefix));
527 } else {
528 out.push_str(token);
529 token.clear();
530 }
531 };
532 for c in text.chars() {
533 if c.is_ascii_alphanumeric() {
534 token.push(c);
535 } else {
536 flush(&mut token, &mut out, self);
537 out.push(c);
538 }
539 }
540 flush(&mut token, &mut out, self);
541 out
542 }
543
544 pub fn json(&mut self, v: &mut Json) {
546 match v {
547 Json::String(s) => *s = self.text(s),
548 Json::Array(items) => items.iter_mut().for_each(|x| self.json(x)),
549 Json::Object(o) => {
550 let taken = std::mem::take(o);
551 for (k, mut x) in taken {
552 let k = self.text(&k);
553 self.json(&mut x);
554 o.insert(k, x);
555 }
556 }
557 _ => {}
558 }
559 }
560}
561
562#[derive(Clone, Debug, PartialEq, Serialize)]
565pub struct Bundle {
566 pub version: String,
568 pub platform: String,
569 pub page: Option<String>,
571 pub window_s: u64,
573 pub missed: u64,
577 pub capped: u64,
578 pub journal: Vec<Recorded>,
580 pub context: std::collections::BTreeMap<String, Json>,
582 pub bus: Json,
584}
585
586impl Bundle {
587 pub fn text(&self) -> String {
589 let json = serde_json::to_string_pretty(self).unwrap_or_default();
590 format!(
591 "<details><summary>Diagnostic report</summary>\n\n```json\n{json}\n```\n</details>\n"
592 )
593 }
594}
595
596pub fn bus_description(bus: &dyn bus_contract::Bus) -> Json {
599 let mut points: Vec<_> = bus.points();
600 points.sort_by_key(|p| p.id);
601 let mut out = serde_json::Map::new();
602 for p in points {
603 let listeners: Vec<String> = bus
604 .listeners(p.id)
605 .unwrap_or_default()
606 .into_iter()
607 .map(|l| l.id)
608 .collect();
609 out.insert(
610 p.id.to_string(),
611 serde_json::json!({ "kind": format!("{:?}", p.kind), "listeners": listeners }),
612 );
613 }
614 Json::Object(out)
615}
616
617#[cfg(test)]
618mod tests {
619 use super::*;
620 use serde_json::json;
621
622 fn ann() -> Redactor {
623 Redactor::new(Some("/home/ann"), &["tok-56789012"])
624 }
625
626 fn ev(seq: Seq, name: &str, data: Json) -> Event {
627 Event {
628 seq,
629 source: "user".into(),
630 cause: None,
631 name: name.into(),
632 data,
633 }
634 }
635
636 #[test]
637 fn paths_keep_their_root_and_extension_only() {
638 let r = ann();
639 assert_eq!(
642 r.text("/home/ann/Photos/Jane wedding.raw"),
643 "~/… wedding.raw"
644 );
645 assert_eq!(r.value("/home/ann/Photos/Jane wedding.raw"), "~/….raw");
646 assert_eq!(r.value("not a path: /home/ann/x y"), "not a path: ~/… y");
647 assert_eq!(
648 r.text("/home/ann/Photos/a.raw: unreadable"),
649 "~/….raw: unreadable"
650 );
651 assert_eq!(r.text("/home/anna/b.jpg"), "/….jpg");
652 assert_eq!(r.text("file:/home/ann/x"), "file:~/…");
653 assert_eq!(r.text("file:///mnt/card/DCIM"), "file:///…");
654 assert_eq!(r.text("C:\\Users\\Ann\\c.NEF"), "C:/….NEF");
655 assert_eq!(
656 r.text("open \"/run/media/ann/CARD\" now"),
657 "open \"/…\" now"
658 );
659 assert_eq!(r.text("https://github.com/o/r"), "https://github.com/o/r");
661 assert_eq!(r.text("1/2 and a / b"), "1/2 and a / b");
662 assert_eq!(r.text("photos/2024"), "photos/2024");
663 assert_eq!(r.text("~"), "~");
664 }
665
666 #[test]
667 fn secrets_are_blanked_and_short_values_left() {
668 let r = Redactor::from_env(
669 &[
670 ("SOME_TOKEN".into(), "tok-56789012".into()),
671 ("API_KEY".into(), "short".into()),
672 ("LANG".into(), "fr_FR.UTF-8".into()),
673 ],
674 None,
675 );
676 assert_eq!(r.text("sent tok-56789012 to x"), "sent [redacted] to x");
677 assert_eq!(r.text("short fr_FR.UTF-8"), "short fr_FR.UTF-8");
678 }
679
680 #[test]
681 fn a_private_command_reads_private_and_strings_are_scrubbed() {
682 let r = ann();
683 let e = r.event(&ev(
684 4,
685 "command.done",
686 json!({ "command": "accounts.connect", "result": "ann@example.org", "private": true }),
687 ));
688 assert_eq!(e.data["result"], crate::host::REDACTED);
689 let e = r.event(&ev(
690 5,
691 "image.refused",
692 json!({ "why": "locked: /home/ann/a.raw", "/home/ann/k": [ "/srv/x.tif" ] }),
693 ));
694 assert_eq!(e.data["why"], "locked: ~/….raw");
695 assert_eq!(e.data["~/…"][0], "/….tif");
696 }
697
698 #[test]
699 fn the_window_is_by_time_and_skipped_kinds_never_enter() {
700 let mut rec = Recorder::new(
701 RecorderConfig::default()
702 .window(Duration::from_secs(60))
703 .skip("view.*"),
704 );
705 let t0 = Instant::now();
706 let r = Redactor::default();
707 rec.record(t0, &[ev(1, "engine.gpu_lost", json!(null))], &r);
708 let burst: Vec<Event> = (2..3000).map(|n| ev(n, "view.frame", json!(n))).collect();
710 rec.record(t0 + Duration::from_secs(10), &burst, &r);
711 let w = rec.window(t0 + Duration::from_secs(30));
712 assert_eq!(w.len(), 1);
713 assert_eq!(w[0].name, "engine.gpu_lost");
714 assert_eq!(w[0].ago_ms, 30_000);
715 assert_eq!(rec.last(), 2999);
716 rec.prune(t0 + Duration::from_secs(61));
718 assert!(rec.window(t0 + Duration::from_secs(61)).is_empty());
719 }
720
721 #[test]
722 fn ids_get_one_alias_each_in_order_of_appearance() {
723 let hex = |t: &str| t.len() == 8 && t.chars().all(|c| c.is_ascii_hexdigit());
724 let mut a = Aliases::new("photo", &hex);
725 let mut v = json!([
726 { "image": "deadbeef" },
727 { "image": "0badf00d", "text": "after deadbeef, cafe" },
728 { "deadbeef": 1 },
729 ]);
730 a.json(&mut v);
731 assert_eq!(v[0]["image"], "photo-1");
732 assert_eq!(v[1]["image"], "photo-2");
733 assert_eq!(v[1]["text"], "after photo-1, cafe");
734 assert_eq!(v[2]["photo-1"], 1);
735 assert_eq!(a.len(), 2);
736 }
737
738 #[test]
739 fn entries_dropped_between_reads_are_counted() {
740 let mut rec = Recorder::new(RecorderConfig::default().cap(2));
741 let t = Instant::now();
742 let r = Redactor::default();
743 rec.record(t, &[ev(10, "a", json!(1))], &r);
744 rec.record(t, &[ev(14, "b", json!(1)), ev(15, "c", json!(1))], &r);
745 assert_eq!(rec.lost(), (3, 1));
746 let names: Vec<_> = rec.window(t).into_iter().map(|e| e.name).collect();
747 assert_eq!(names, ["b", "c"]);
748 }
749}