1pub mod frontmatter;
12
13pub fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> &str {
28 if s.len() <= max_bytes {
29 return s;
30 }
31 let mut end = max_bytes;
32 while end > 0 && !s.is_char_boundary(end) {
33 end -= 1;
34 }
35 &s[..end]
36}
37
38pub fn truncate_chars(s: &str, max: usize, marker: &str) -> String {
40 if s.chars().count() <= max {
41 s.to_string()
42 } else {
43 let head: String = s.chars().take(max).collect();
44 format!("{head}{marker}")
45 }
46}
47
48pub fn scrub_secrets(text: &str) -> String {
53 const MASK: &str = "***";
54 const SECRET_NAMES: &[&str] = &["token", "key", "secret", "passw", "auth", "credential"];
55 let is_boundary =
56 |c: char| c.is_whitespace() || matches!(c, '"' | '\'' | '&' | '?' | ',' | ';');
57 let mut out = String::with_capacity(text.len());
58 let mut after_scheme = false;
59 let mut rest = text;
60 while !rest.is_empty() {
61 let end = rest.find(is_boundary).unwrap_or(rest.len());
62 let (word, tail) = rest.split_at(end);
63 let masked = if word.is_empty() {
64 None
65 } else if after_scheme {
66 Some(MASK.to_string())
67 } else if let Some((name, value)) = word.split_once('=') {
68 let lower = name.to_ascii_lowercase();
69 (!value.is_empty() && SECRET_NAMES.iter().any(|n| lower.contains(n)))
70 .then(|| format!("{name}={MASK}"))
71 } else if (word.starts_with("sk-") || word.starts_with("sk_")) && word.len() >= 10 {
72 Some(MASK.to_string())
73 } else {
74 None
75 };
76 if !word.is_empty() {
77 after_scheme = matches!(word, "Bearer" | "bearer" | "Basic" | "basic");
78 }
79 out.push_str(masked.as_deref().unwrap_or(word));
80 let sep_len = tail.chars().next().map_or(0, char::len_utf8);
81 out.push_str(&tail[..sep_len]);
82 rest = &tail[sep_len..];
83 }
84 out
85}
86
87pub fn scrub_url(text: &str) -> String {
90 let scrubbed = scrub_secrets(text);
91 let mut out = String::with_capacity(scrubbed.len());
92 let mut rest = scrubbed.as_str();
93 while let Some(at) = rest.find("://") {
94 let (head, tail) = rest.split_at(at + 3);
95 out.push_str(head);
96 let end = tail
97 .find(|c: char| matches!(c, '/' | '?' | '#') || c.is_whitespace())
98 .unwrap_or(tail.len());
99 let (authority, after) = tail.split_at(end);
100 match authority
101 .rsplit_once('@')
102 .and_then(|(userinfo, host)| Some((userinfo.split_once(':')?.0, host)))
103 {
104 Some((user, host)) => out.push_str(&format!("{user}:***@{host}")),
105 None => out.push_str(authority),
106 }
107 rest = after;
108 }
109 out.push_str(rest);
110 out
111}
112
113#[cfg(test)]
114mod tests {
115 use super::truncate_at_char_boundary as t;
116
117 #[test]
118 fn shorter_than_budget_is_returned_whole() {
119 assert_eq!(t("hello", 10), "hello");
120 assert_eq!(t("中文", 100), "中文");
121 assert_eq!(t("", 0), "");
122 }
123
124 #[test]
125 fn ascii_cuts_exactly_at_the_budget() {
126 assert_eq!(t("hello world", 5), "hello");
127 }
128
129 #[test]
132 fn every_byte_offset_of_a_multibyte_string_is_safe() {
133 let s = "中文测试abc混合デ";
134 for n in 0..=s.len() + 4 {
135 let out = t(s, n);
136 assert!(
137 out.len() <= n.min(s.len()),
138 "n={n} produced {} bytes",
139 out.len()
140 );
141 assert!(s.starts_with(out), "n={n} produced a non-prefix");
142 }
143 }
144
145 #[test]
146 fn cut_moves_backwards_never_forwards() {
147 assert_eq!(t("中文测试", 5), "中");
149 assert_eq!(t("中文测试", 6), "中文");
150 assert_eq!(t("中文", 0), "");
152 assert_eq!(t("中文", 2), "");
153 }
154
155 #[test]
156 fn combining_marks_and_emoji_survive() {
157 let s = "e\u{301}👨👩👧"; for n in 0..=s.len() {
159 let out = t(s, n);
160 assert!(s.starts_with(out));
161 }
162 }
163
164 #[test]
165 fn truncate_long_string() {
166 let s: String = "x".repeat(3000);
167 let t = super::truncate_chars(&s, 100, "[truncated]");
168 assert_eq!(t.chars().count(), 100 + "[truncated]".chars().count());
169 assert!(t.ends_with("[truncated]"));
170 }
171
172 #[test]
173 fn truncate_short_string_is_passthrough() {
174 let t = super::truncate_chars("hi", 10, "[truncated]");
175 assert_eq!(t, "hi");
176 }
177
178 #[test]
179 fn scrub_secrets_masks_keys_bearers_and_secret_named_values() {
180 use super::scrub_secrets;
181 let line = "got sk-abcdef1234567890 and Authorization: Bearer abc.def \
182 from https://x.test/cb?token=hunter2&page=2 --api-key=zzz";
183 let out = scrub_secrets(line);
184 for leaked in ["abcdef1234567890", "abc.def", "hunter2", "zzz"] {
185 assert!(!out.contains(leaked), "{leaked} in {out}");
186 }
187 assert!(
188 out.contains("page=2") && out.contains("https://x.test/cb"),
189 "{out}"
190 );
191 }
192}