1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
//! iTerm2-style terminal triggers: user regexes watched against terminal
//! output, each firing an action. The pragmatic action set that covers real
//! trigger usage (per iTerm2 / kitty marks): **highlight** (recolour every
//! visible occurrence, live, scrollback included), **notify** (status-bar
//! notice with `\0`..`\9` capture interpolation), **bell** (status-bar
//! bell notice), **capture** (iTerm2's Capture Output: collect every
//! matched line into the CAPTURES panel, where clicking an entry jumps the
//! pane to that line), and **redact** (#360: paint the match as a run of
//! `•` of the same width, the grid untouched; a click on the mask pops the
//! real text; copies yield the real value unless the rule says
//! `"copy": "masked"`; the scrollback-to-editor dump is always masked). A
//! built-in redact set for the usual key shapes (AWS access key ids, secret
//! access keys and session tokens, OpenAI-style `sk-`, GitHub `ghp_`,
//! GitLab `glpat-`, Slack `xox`, Stripe `sk_live_`, Google `AIza`, JWTs,
//! bearer tokens, URL passwords) is on by default and switched off in
//! Settings. Auto-respond / run-command actions are deliberately absent:
//! they are the classic security footgun (hostile output typing into your
//! shell) and iTerm2 itself ships them behind warnings.
//!
//! Config lives at `~/.config/croft/triggers.json` (same tolerant JSONC
//! loading as `keybindings.json` / `snippets.json`; a bad row skips that row,
//! never blocks startup), reloaded on save.
//!
//! Evaluation model (iTerm2's, the safe one): highlight triggers are painted
//! at render time over the visible rows, so they cost nothing when the pane
//! is idle and persist into scrollback for free; notify / bell triggers are
//! matched once per completed output line by a byte-stream scanner in the
//! PTY reader thread, with escape sequences stripped, a `\r` treated as a
//! line rewrite (progress bars never spam), a hard per-line cap, and
//! alternate-screen content excluded POSITIONALLY (the scanner tracks
//! DECSET/DECRST 47/1047/1049 and RIS through the stream itself, so a
//! full-screen app's bytes never fire while primary text sharing a chunk
//! with a transition still does; iTerm2 skips alt output too).
use regex::Regex;
use std::path::{Path, PathBuf};
/// Hard cap on the completed-line buffer the notify/bell scanner matches
/// against; bytes past it are dropped (iTerm2 caps at the last few wrapped
/// rows for the same reason: never regex a gigabyte `cat`).
pub const LINE_CAP: usize = 2048;
/// What a matched trigger does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TriggerAction {
/// Recolour the matched span on every visible row (fg/bg from the row).
Highlight,
/// Status-bar notice; the message template interpolates `\0`..`\9`.
Notify,
/// Status-bar bell notice.
Bell,
/// Collect the matched line into the CAPTURES panel (iTerm2's Capture
/// Output); the message template labels the entry.
Capture,
/// Mask the matched span (capture group 1 when the regex has one, else
/// the whole match) at paint time; see [`redact_spans`].
Redact,
}
/// The glyph a redacted cell shows. One per masked char, so the row keeps
/// its width and columns line up.
pub const MASK: char = '\u{2022}';
/// One user trigger, compiled and ready to match.
#[derive(Clone, Debug)]
pub struct Trigger {
pub regex: Regex,
pub action: TriggerAction,
/// Highlight colours (either may be absent; the other side of the cell
/// style is left alone).
pub fg: Option<(u8, u8, u8)>,
pub bg: Option<(u8, u8, u8)>,
/// Notify message template; `\0` = whole match, `\1`..`\9` = groups.
pub message: Option<String>,
/// Redact only: a copy of a masked span yields the mask, not the value
/// (`"copy": "masked"`). Default: copies carry the real text.
pub copy_masked: bool,
/// Redact only: an UNLABELLED span (prefix plus body, no further
/// hyphen) must carry a digit or an uppercase letter to count, so
/// `sk-` plus a lowercase word is not a key. A labelled span
/// (`sk-ant-api03-…`) always counts. Built-in `sk-` uses it; user rules
/// do not.
pub needs_entropy: bool,
}
/// The user's trigger list. Shared read-only between the app, the render
/// loop, and every pane's reader thread.
#[derive(Clone, Debug, Default)]
pub struct TriggerSet {
/// The user's own rules, from `triggers.json`.
pub triggers: Vec<Trigger>,
/// Whether the built-in secret rules run in front of the user's (see
/// [`TriggerSet::with_builtin_redactions`]).
builtin_redactions: bool,
/// The rules that came from the user's file, for the reload status.
pub user_rules: usize,
/// What was wrong with the user's file: it did not parse at all, or
/// some rows were skipped. None when every row loaded.
pub problem: Option<String>,
}
/// One highlight span on a row, in char indices (the render colmap
/// translates to grid columns).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HighlightSpan {
pub start: usize,
pub len: usize,
pub fg: Option<(u8, u8, u8)>,
pub bg: Option<(u8, u8, u8)>,
}
/// One notify/bell/capture firing, drained by the app (status bar for
/// notify/bell, the CAPTURES panel for capture).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TriggerHit {
pub action: TriggerAction,
pub message: String,
/// The whole escape-stripped output line that matched, so a captured
/// entry can be jumped back to (and shown) in full.
pub line: String,
}
pub fn triggers_path() -> PathBuf {
crate::paths::config_dir().join("triggers.json")
}
/// One raw `triggers.json` row before compilation. Unknown actions, bad
/// regexes and disabled rows drop out in [`TriggerSet::from_json`].
#[derive(serde::Deserialize)]
struct TriggerRow {
regex: String,
action: String,
#[serde(default)]
fg: Option<String>,
#[serde(default)]
bg: Option<String>,
#[serde(default)]
message: Option<String>,
/// Redact rows: `"masked"` keeps the mask in copies; anything else
/// (or absent) copies the real value.
#[serde(default)]
copy: Option<String>,
#[serde(default = "enabled_default")]
enabled: bool,
}
fn enabled_default() -> bool {
true
}
/// `#rrggbb` → bytes; anything else is treated as unset.
fn parse_hex(s: &str) -> Option<(u8, u8, u8)> {
let hex = s.strip_prefix('#')?;
if hex.len() != 6 {
return None;
}
let n = u32::from_str_radix(hex, 16).ok()?;
Some(((n >> 16) as u8, (n >> 8) as u8, n as u8))
}
/// The starter file written on first "Open Terminal Triggers (JSON)".
pub const TEMPLATE: &str = r##"// croft terminal triggers: regexes watched on terminal output.
// "action": "highlight" recolour every visible occurrence ("fg"/"bg" as #rrggbb)
// "notify" status-bar notice ("message" template: \0 whole match, \1-\9 groups)
// "bell" status-bar bell notice
// "capture" collect matched lines into the CAPTURES panel (click jumps to the line)
// "redact" mask the match (group 1 if the regex has one) as •••• on screen;
// click the mask to see the value; "copy": "masked" masks copies too.
// Built-in key/token rules run first (Settings: Terminal: Redact Secrets).
// Highlights repaint live on the visible screen and persist into scrollback.
// notify/bell/capture fire once per completed output line (never inside full-screen apps).
// "enabled": false keeps a rule without running it.
[
{ "regex": "\\b(ERROR|FATAL|panicked)\\b", "action": "highlight", "fg": "#ffffff", "bg": "#c0392b" },
{ "regex": "\\bwarning\\b", "action": "highlight", "fg": "#000000", "bg": "#e5c07b", "enabled": false },
{ "regex": "(BUILD|Compiling|error): (.+)", "action": "notify", "message": "\\1: \\2", "enabled": false },
{ "regex": "(?i)x-api-key: *(\\S+)", "action": "redact", "copy": "masked", "enabled": false }
]
"##;
impl TriggerSet {
/// Load `triggers.json`, ignoring unparsable rows (a bad regex skips that
/// row, never blocks startup). A missing file yields an empty set.
pub fn load(path: &Path) -> Self {
let Ok(json) = std::fs::read_to_string(path) else {
return Self::default();
};
Self::from_json(&json)
}
pub fn from_json(json: &str) -> Self {
// Row by row, and JSONC like the template it starts from: parsed
// as one unit, a trailing comma or one row with `"enabled": "false"`
// dropped EVERY rule the user wrote, redact rules included, while
// the reload status still counted the built-ins as active.
let rows: Vec<serde_json::Value> =
match serde_json::from_str(&crate::jsonc::strip_jsonc(json)) {
Ok(rows) => rows,
Err(e) => {
return Self {
problem: Some(format!("triggers.json does not parse ({e})")),
..Self::default()
};
}
};
let total = rows.len();
let rows: Vec<TriggerRow> = rows
.into_iter()
.filter_map(|r| serde_json::from_value(r).ok())
.collect();
let mut skipped = total - rows.len();
let triggers: Vec<Trigger> = rows
.into_iter()
.filter(|r| r.enabled)
.filter_map(|r| {
let action = match r.action.as_str() {
"highlight" => TriggerAction::Highlight,
"notify" => TriggerAction::Notify,
"bell" => TriggerAction::Bell,
"capture" => TriggerAction::Capture,
"redact" => TriggerAction::Redact,
_ => return None,
};
let Ok(regex) = Regex::new(&r.regex) else {
skipped += 1;
return None;
};
Some(Trigger {
regex,
action,
fg: r.fg.as_deref().and_then(parse_hex),
bg: r.bg.as_deref().and_then(parse_hex),
message: r.message,
copy_masked: r.copy.as_deref() == Some("masked"),
needs_entropy: false,
})
})
.collect();
Self {
user_rules: triggers.len(),
triggers,
builtin_redactions: false,
problem: (skipped > 0).then(|| {
format!(
"{skipped} row{} of triggers.json skipped",
if skipped == 1 { "" } else { "s" }
)
}),
}
}
pub fn is_empty(&self) -> bool {
!self.builtin_redactions && self.triggers.is_empty()
}
/// The built-in secret rules in front of the user's own, so a key
/// shape the user never thought to list is still masked. Off in
/// Settings ("Terminal: Redact Secrets") means this is never called.
///
/// Only a flag: the rules themselves are compiled once per process, on
/// the thread startup gives them, and are first needed when a row with
/// text is masked, so building the editor never waits for them.
pub fn with_builtin_redactions(mut self) -> Self {
self.builtin_redactions = true;
self
}
/// Every redact rule for `line`: the built-in ones first, when they are
/// on and the line has text they could match (every built-in shape
/// carries non-blank text; a blank row must not wait for their compile),
/// then the user's.
fn redact_rules<'a>(&'a self, line: &str) -> impl Iterator<Item = &'a Trigger> {
let builtin: &[Trigger] = if self.builtin_redactions && !line.trim().is_empty() {
&BUILTIN_REDACTIONS
} else {
&[]
};
builtin
.iter()
.chain(&self.triggers)
.filter(|t| t.action == TriggerAction::Redact)
}
/// Whether any trigger paints (drives the render pass): highlight and
/// redact both act on the visible rows.
pub fn has_highlights(&self) -> bool {
self.builtin_redactions
|| self
.triggers
.iter()
.any(|t| matches!(t.action, TriggerAction::Highlight | TriggerAction::Redact))
}
/// Whether any trigger redacts (drives the copy / dump masking).
pub fn has_redactions(&self) -> bool {
self.builtin_redactions
|| self
.triggers
.iter()
.any(|t| t.action == TriggerAction::Redact)
}
/// Whether any trigger fires events (drives the reader-thread scan). The
/// built-in rules only redact.
pub fn has_events(&self) -> bool {
self.triggers
.iter()
.any(|t| !matches!(t.action, TriggerAction::Highlight | TriggerAction::Redact))
}
}
/// The key and token shapes masked out of the box (#360). Each pattern is
/// anchored on a distinctive prefix so ordinary words never match. A secret
/// with no prefix of its own (a bearer token, an AWS secret access key or
/// session token, a URL password) is anchored on what names it instead
/// (the `Authorization` header, the variable or field name, the `://user:`
/// before it) and masks only the value (group 1), leaving the name
/// readable (#921). PEM bodies are not covered: their base64 lines carry
/// no prefix to anchor on, and masking every long base64 line would eat
/// checksums and blobs. Compiled once per process, and shared by every
/// trigger set that turns them on.
static BUILTIN_REDACTIONS: std::sync::LazyLock<Vec<Trigger>> = std::sync::LazyLock::new(|| {
// (pattern, the span must carry a digit or an uppercase letter)
const PATTERNS: &[(&str, bool)] = &[
// AWS access key ids.
(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b", false),
// AWS secret access keys, the actual credential: 40 base64
// chars with no prefix, so anchored on the name in the
// credentials file, env vars, STS / IAM JSON and the
// `aws configure` prompt (`AWS Secret Access Key [None]: `).
(
r#"(?i:secret[_ ]?access[_ ]?key)(?: \[[^\]]*\])?["']?\s*[:=]\s*["']?([A-Za-z0-9/+=]{40,})"#,
false,
),
// AWS session tokens (`aws_session_token`, STS `SessionToken`,
// boto's legacy `aws_security_token`).
(
r#"(?i:session_?token|security_?token)["']?\s*[:=]\s*["']?([A-Za-z0-9/+=]{100,})"#,
false,
),
// OpenAI / Anthropic / OpenRouter-style secret keys: `sk-`, up
// to three short labels (`sk-proj-`, `sk-ant-api03-`, `sk-or-v1-`)
// and a long body. Entropy-gated: `sk-` also opens hyphenated
// prose ("sk-learn-preprocessingpipeline"), whose body is all
// lowercase letters.
(r"\bsk-(?:[A-Za-z0-9]{1,10}-){0,3}[A-Za-z0-9_]{16,}\b", true),
// GitHub tokens: classic (ghp_), OAuth (gho_), app (ghu_/ghs_/ghr_), fine-grained.
(
r"\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})\b",
false,
),
// Slack tokens.
(r"\bxox[abpors]-[A-Za-z0-9-]{10,}\b", false),
// GitLab tokens: personal (glpat-), deploy (gldt-), runner
// (glrt-), pipeline trigger (glptt-), OAuth app secret
// (gloas-), CI job (glcbt-).
(r"\bgl(?:pat|dt|rt|ptt|oas|cbt)-[A-Za-z0-9_-]{20,}", false),
// Stripe secret and restricted keys, live and test.
(r"\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}", false),
// Google API keys.
(r"\bAIza[0-9A-Za-z_-]{35,}", false),
// The password in a URL's userinfo (`postgres://user:pw@host`);
// the user and host stay readable. A raw `@` inside the password
// (`user:pa@ss@host`) is masked too: as URL parsers do, it runs
// to the last `@` before the path, query or fragment.
(r"://[^/\s:@]*:([^\s/?#]+)@", false),
// JWTs: three base64url segments, the first a JSON header.
(
r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b",
false,
),
// `Authorization: Bearer <token>` in header or JSON form
// (`"Authorization": "Bearer …"`) - only the token is masked.
// Anchored on the header so "Bearer" as an English word never
// matches; a closing quote, comma or semicolon stays outside.
(
r#"(?i)\bauthorization"? *: *"?bearer +([^\s'",;]{16,})"#,
false,
),
];
PATTERNS
.iter()
.map(|(r, needs_entropy)| Trigger {
regex: Regex::new(r).expect("built-in redaction regex compiles"),
action: TriggerAction::Redact,
fg: None,
bg: None,
message: None,
copy_masked: false,
needs_entropy: *needs_entropy,
})
.collect()
});
/// Compile the built-in secret rules now, so the first row with text finds
/// them ready. Startup calls this on a thread of its own: compiling them was
/// a fifth of the work every launch did before its first frame. A row that
/// needs them sooner waits for that compile to finish.
pub fn prewarm_builtin_redactions() {
std::sync::LazyLock::force(&BUILTIN_REDACTIONS);
}
/// One masked span on a row, in char indices.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RedactSpan {
pub start: usize,
pub len: usize,
/// Whether a copy of this span keeps the mask.
pub copy_masked: bool,
}
/// Every redact-trigger match on `line`: capture group 1 when the regex
/// has one (so a rule can name the secret inside a header), else the
/// whole match. Empty matches are skipped, and a span several rules match
/// is reported once.
pub fn redact_spans(line: &str, set: &TriggerSet) -> Vec<RedactSpan> {
let mut out: Vec<RedactSpan> = Vec::new();
for t in set.redact_rules(line) {
for caps in t.regex.captures_iter(line) {
let m = match caps.get(1) {
Some(g) => g,
None => match caps.get(0) {
Some(m) => m,
None => continue,
},
};
// The entropy test applies to an UNLABELLED match only: `sk-` plus
// a body that is all lowercase letters is a hyphenated word, but
// `sk-ant-api03-…` is a key shape whatever its body looks like.
// Masking a rare `sk-word-word` costs a click to reveal; missing
// a real key costs the transcript and history it lands in.
let labelled = m.as_str().matches('-').count() > 1;
let body = m.as_str().rsplit('-').next().unwrap_or(m.as_str());
if m.as_str().is_empty()
|| (t.needs_entropy
&& !labelled
&& !body
.chars()
.any(|c| c.is_ascii_digit() || c.is_ascii_uppercase()))
{
continue;
}
let (start, len) = (
line[..m.start()].chars().count(),
m.as_str().chars().count(),
);
// Two rules naming the same secret (a `glpat-` token that is
// also a URL password, a JWT that is also a bearer token) give
// one span: the status chip counts secrets, not rules.
if let Some(dup) = out.iter_mut().find(|s| s.start == start && s.len == len) {
dup.copy_masked |= t.copy_masked;
continue;
}
out.push(RedactSpan {
start,
len,
copy_masked: t.copy_masked,
});
}
}
out
}
/// The redacted char ranges `(start, len)` on each of `rows`, matched over
/// soft-wrapped rows joined as in [`mask_rows`], so a range on one row may
/// be the tail of a secret that began on the row above.
pub fn redacted_row_ranges(
rows: &[String],
wraps: &[bool],
set: &TriggerSet,
) -> Vec<Vec<(usize, usize)>> {
let mut out = vec![Vec::new(); rows.len()];
let mut i = 0;
while i < rows.len() {
let mut j = i;
while j + 1 < rows.len() && wraps.get(j).copied().unwrap_or(false) {
j += 1;
}
let joined: String = rows[i..=j].concat();
let spans = redact_spans(&joined, set);
let mut offset = 0;
for (r, row) in (i..=j).zip(&rows[i..=j]) {
let len = row.chars().count();
for s in &spans {
let (lo, hi) = (s.start.max(offset), (s.start + s.len).min(offset + len));
if lo < hi {
out[r].push((lo - offset, hi - lo));
}
}
offset += len;
}
i = j + 1;
}
out
}
/// [`mask_text`] over terminal rows, where `wraps[i]` says row `i`
/// soft-wraps into row `i + 1`. Wrapped rows are masked as the one logical
/// line they are, then split back, so a token the wrap cut in two (a JWT is
/// wider than most panes) is masked on both rows.
pub fn mask_rows(rows: &[String], wraps: &[bool], set: &TriggerSet) -> Vec<String> {
if !set.has_redactions() {
return rows.to_vec();
}
let mut out = Vec::with_capacity(rows.len());
let mut i = 0;
while i < rows.len() {
let mut j = i;
while j + 1 < rows.len() && wraps.get(j).copied().unwrap_or(false) {
j += 1;
}
let joined: String = rows[i..=j].concat();
let masked = mask_text(&joined, set, false);
let mut chars = masked.chars();
for row in &rows[i..=j] {
out.push(chars.by_ref().take(row.chars().count()).collect());
}
i = j + 1;
}
out
}
/// `text` with every redact-trigger match replaced by [`MASK`] runs of the
/// same char length, line by line. `copy_only` restricts the masking to
/// rules marked `"copy": "masked"` (the clipboard path); `false` masks
/// everything (the scrollback dump, and anything else that leaves the
/// pane as bytes). Returns the input untouched when nothing matches.
pub fn mask_text(text: &str, set: &TriggerSet, copy_only: bool) -> String {
if !set.has_redactions() {
return text.to_string();
}
let mut out = String::with_capacity(text.len());
for (i, line) in text.split('\n').enumerate() {
if i > 0 {
out.push('\n');
}
let spans: Vec<RedactSpan> = redact_spans(line, set)
.into_iter()
.filter(|s| !copy_only || s.copy_masked)
.collect();
if spans.is_empty() {
out.push_str(line);
continue;
}
for (k, c) in line.chars().enumerate() {
if spans.iter().any(|s| k >= s.start && k < s.start + s.len) {
out.push(MASK);
} else {
out.push(c);
}
}
}
out
}
/// Every highlight-trigger match on `line`, as char-index spans.
pub fn highlight_spans(line: &str, set: &TriggerSet) -> Vec<HighlightSpan> {
let mut out = Vec::new();
for t in &set.triggers {
if t.action != TriggerAction::Highlight {
continue;
}
for m in t.regex.find_iter(line) {
out.push(HighlightSpan {
start: line[..m.start()].chars().count(),
len: m.as_str().chars().count(),
fg: t.fg,
bg: t.bg,
});
}
}
out
}
/// Fill a notify/bell message from its template: `\0` = whole match,
/// `\1`..`\9` = capture groups. No template means the whole match.
fn interpolate(template: Option<&str>, caps: ®ex::Captures) -> String {
let whole = caps.get(0).map(|m| m.as_str()).unwrap_or_default();
let Some(template) = template else {
return whole.to_string();
};
let mut out = String::new();
let mut chars = template.chars().peekable();
while let Some(c) = chars.next() {
if c == '\\'
&& let Some(d) = chars.peek().and_then(|p| p.to_digit(10))
{
chars.next();
out.push_str(caps.get(d as usize).map(|m| m.as_str()).unwrap_or_default());
} else {
out.push(c);
}
}
out
}
/// Byte-stream scanner for notify/bell triggers: strips escape sequences,
/// buffers the current output line (capped), treats `\r` as a line rewrite
/// (reset without matching) and `\n` as line completion (match the event
/// triggers against the finished line).
#[derive(Default)]
pub struct TriggerScanner {
line: Vec<u8>,
state: ScanState,
/// A `\r` was seen and its meaning is still open: followed by `\n` it is
/// the PTY's plain CRLF line ending (complete the line); followed by
/// anything else it is an in-place rewrite (reset without matching).
/// Kept across chunks — a CR can be the last byte of a read.
cr_pending: bool,
/// Whether the byte position currently being scanned sits inside the
/// alternate screen. Tracked POSITIONALLY from DECSET/DECRST 47/1047/
/// 1049 (and RIS) in the stream itself, so alt-screen content never
/// fires and primary text sharing a chunk with a transition still does
/// — the chunk's final terminal mode says nothing about where a line
/// fell. Requires the scanner to see EVERY chunk, never a gated subset,
/// or the tracking (and the string state machine) desyncs.
in_alt: bool,
/// Parameter bytes of the CSI currently being consumed (bounded; only
/// needed to recognize the alt-screen DECSET/DECRST lists).
csi: Vec<u8>,
}
/// Longest CSI parameter list retained; a real DECSET list is far shorter.
const CSI_CAP: usize = 32;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum ScanState {
#[default]
Ground,
Esc,
Csi,
/// OSC / DCS / APC string bodies: swallowed until BEL or ST.
InString,
/// Saw ESC inside a string body (the first half of ST).
StringEsc,
}
impl TriggerScanner {
pub fn new() -> Self {
Self::default()
}
/// Feed a raw PTY chunk; completed lines are matched against `set`'s
/// event triggers and any firings appended to `out`.
pub fn scan(&mut self, bytes: &[u8], set: &TriggerSet, out: &mut Vec<TriggerHit>) {
self.scan_collect(bytes, set, out, None);
}
/// Like [`scan`](Self::scan), additionally pushing every completed
/// primary-screen line (escape-stripped, blank ones included — batch
/// matchers care about section-ending blanks) into `lines`. The watch
/// problem matchers (#252) consume these instead of running a second
/// byte scanner over the same stream.
pub fn scan_collect(
&mut self,
bytes: &[u8],
set: &TriggerSet,
out: &mut Vec<TriggerHit>,
mut lines: Option<&mut Vec<String>>,
) {
for &b in bytes {
// Resolve a pending `\r` now that its successor is known: CRLF is
// the PTY line ending (complete), a lone CR rewrites the line in
// place (progress bars, spinners — reset without matching, so
// only text that survives to a newline fires).
if self.cr_pending && self.state == ScanState::Ground {
self.cr_pending = false;
if b == b'\n' {
self.complete_line(set, out, lines.as_deref_mut());
continue;
}
self.reset_line();
}
match self.state {
ScanState::Ground => match b {
0x1b => self.state = ScanState::Esc,
b'\n' => self.complete_line(set, out, lines.as_deref_mut()),
b'\r' => self.cr_pending = true,
0x00..=0x1f | 0x7f => {}
_ => {
// Past the cap the byte is dropped; the capped prefix
// still matches on completion. Alt-screen bytes are
// consumed but never accumulated.
if !self.in_alt && self.line.len() < LINE_CAP {
self.line.push(b);
}
}
},
ScanState::Esc => {
self.state = match b {
b'[' => ScanState::Csi,
b']' | b'P' | b'X' | b'^' | b'_' => ScanState::InString,
// RIS: full reset, back on the primary screen.
b'c' => {
self.set_alt(false);
ScanState::Ground
}
_ => ScanState::Ground,
};
}
ScanState::Csi => {
if (0x40..=0x7e).contains(&b) {
if (b == b'h' || b == b'l') && self.csi.first() == Some(&b'?') {
let alt = self.csi[1..]
.split(|&c| c == b';')
.any(|p| p == b"47" || p == b"1047" || p == b"1049");
if alt {
self.set_alt(b == b'h');
}
}
self.csi.clear();
self.state = ScanState::Ground;
} else if b == 0x18 || b == 0x1a {
// CAN/SUB cancel the sequence (VT100).
self.csi.clear();
self.state = ScanState::Ground;
} else if b == 0x1b {
// ESC inside an incomplete CSI begins a NEW escape;
// retaining it as a parameter would let a malformed
// CSI swallow the following alt-screen entry.
self.csi.clear();
self.state = ScanState::Esc;
} else if self.csi.len() < CSI_CAP {
self.csi.push(b);
}
}
ScanState::InString => match b {
0x07 => self.state = ScanState::Ground,
0x1b => self.state = ScanState::StringEsc,
// CAN/SUB abort the control string (ECMA-48); staying
// in-string would swallow ordinary output and the alt
// boundary until an unrelated BEL/ST.
0x18 | 0x1a => self.state = ScanState::Ground,
_ => {}
},
ScanState::StringEsc => {
// `ESC \` (ST) ends the string; CAN/SUB abort it;
// anything else is still string body.
self.state = match b {
b'\\' => ScanState::Ground,
0x18 | 0x1a => ScanState::Ground,
_ => ScanState::InString,
};
}
}
}
}
/// Cross an alt-screen boundary: whatever partial primary line was
/// pending is stale on both edges (the shell repaints its prompt after
/// a full-screen app exits), so it must never splice with later text.
fn set_alt(&mut self, alt: bool) {
if self.in_alt != alt {
self.in_alt = alt;
self.reset_line();
self.cr_pending = false;
}
}
fn reset_line(&mut self) {
self.line.clear();
}
fn complete_line(
&mut self,
set: &TriggerSet,
out: &mut Vec<TriggerHit>,
lines: Option<&mut Vec<String>>,
) {
if self.in_alt {
self.reset_line();
return;
}
if let Some(lines) = lines {
lines.push(String::from_utf8_lossy(&self.line).into_owned());
}
if !self.line.is_empty() {
let line = String::from_utf8_lossy(&self.line);
for t in &set.triggers {
// Paint-only actions never become hits: a redact hit would
// carry the secret itself into the status bar.
if matches!(t.action, TriggerAction::Highlight | TriggerAction::Redact) {
continue;
}
if let Some(caps) = t.regex.captures(&line) {
out.push(TriggerHit {
action: t.action,
message: interpolate(t.message.as_deref(), &caps),
line: line.to_string(),
});
}
}
}
self.reset_line();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn set(json: &str) -> TriggerSet {
TriggerSet::from_json(json)
}
#[test]
fn redacted_ranges_follow_a_secret_across_a_wrap() {
let s = TriggerSet::default().with_builtin_redactions();
let rows = vec![
String::from("GH=ghp_abcdefghij"),
String::from("klmnopqrstuvwxyz0123456789 ok"),
];
let ranges = redacted_row_ranges(&rows, &[true, false], &s);
assert_eq!(ranges[0], vec![(3, 14)]);
assert_eq!(ranges[1], vec![(0, 26)]);
assert!(redacted_row_ranges(&rows, &[false, false], &s)[0].is_empty());
}
#[test]
fn one_bad_row_or_a_trailing_comma_keeps_the_other_rules() {
let set = TriggerSet::from_json(
r#"[
// mine
{ "regex": "x-api-key: (\\S+)", "action": "redact" },
{ "regex": "boom", "action": "highlight", "enabled": "false" },
{ "action": "highlight" },
{ "regex": "(", "action": "highlight" },
]"#,
);
assert_eq!(set.user_rules, 1);
assert_eq!(
set.problem.as_deref(),
Some("3 rows of triggers.json skipped")
);
let broken = TriggerSet::from_json("[{");
assert_eq!(broken.user_rules, 0);
assert!(broken.problem.unwrap().contains("does not parse"));
}
#[test]
fn config_rows_parse_and_bad_rows_are_skipped() {
let s = set(r##"// comment survives
[
{ "regex": "\\bERROR\\b", "action": "highlight", "fg": "#ffffff", "bg": "#c0392b" },
{ "regex": "((broken", "action": "highlight" },
{ "regex": "done", "action": "notify", "message": "finished: \\0" },
{ "regex": "beep", "action": "bell" },
{ "regex": "off", "action": "notify", "enabled": false },
{ "regex": "what", "action": "unknown-action" }
]"##);
assert_eq!(
s.triggers.len(),
3,
"bad regex, disabled and unknown-action rows must be skipped: {s:?}"
);
assert!(s.has_highlights());
assert!(s.has_events());
assert_eq!(s.triggers[0].fg, Some((0xff, 0xff, 0xff)));
assert_eq!(s.triggers[0].bg, Some((0xc0, 0x39, 0x2b)));
assert!(set("total garbage").is_empty());
assert!(set("").is_empty());
}
#[test]
fn redact_rows_parse_with_their_copy_mode() {
let s = set(r##"[
{ "regex": "secret=(\\S+)", "action": "redact", "copy": "masked" },
{ "regex": "token=\\S+", "action": "redact" }
]"##);
assert_eq!(s.triggers.len(), 2);
assert!(s.has_highlights(), "redact rides the paint pass");
assert!(s.has_redactions());
assert!(
!s.has_events(),
"redact never wakes the reader-thread scanner"
);
assert!(s.triggers[0].copy_masked);
assert!(!s.triggers[1].copy_masked);
}
#[test]
fn redact_spans_mask_group_one_when_present_else_the_whole_match() {
let s = set(r##"[
{ "regex": "secret=(\\S+)", "action": "redact", "copy": "masked" },
{ "regex": "token=\\S+", "action": "redact" }
]"##);
let spans = redact_spans("naïve secret=abc token=xyz", &s);
// "naïve secret=" is 13 chars: the group starts after the '='.
assert_eq!(
spans,
vec![
RedactSpan {
start: 13,
len: 3,
copy_masked: true
},
RedactSpan {
start: 17,
len: 9,
copy_masked: false
},
]
);
assert_eq!(
mask_text("naïve secret=abc token=xyz", &s, false),
"naïve secret=••• •••••••••",
"the dump masks every rule, width preserved"
);
assert_eq!(
mask_text("naïve secret=abc token=xyz", &s, true),
"naïve secret=••• token=xyz",
"a copy masks only rules marked copy=masked"
);
assert_eq!(
mask_text("line one\nsecret=q\n", &s, false),
"line one\nsecret=•\n",
"masking is per line and keeps the newlines"
);
}
/// A redact rule paints; it must never become a status-bar hit, or the
/// bar would print the secret the pane just masked.
#[test]
fn redact_rules_never_fire_as_hits() {
let s = TriggerSet::default().with_builtin_redactions();
let mut sc = TriggerScanner::new();
let mut out = Vec::new();
sc.scan(b"key AKIAIOSFODNN7EXAMPLE end\n", &s, &mut out);
assert!(out.is_empty(), "{out:?}");
let user = set(r##"[{ "regex": "hunter2", "action": "redact" }]"##);
sc.scan(b"pw hunter2\n", &user, &mut out);
assert!(out.is_empty(), "{out:?}");
assert!(!s.has_events(), "nothing here wakes the scanner");
}
#[test]
fn builtin_rules_mask_the_usual_key_shapes_and_leave_prose_alone() {
let s = TriggerSet::default().with_builtin_redactions();
let masked = |line: &str| mask_text(line, &s, false);
assert_eq!(
masked("export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE"),
"export AWS_ACCESS_KEY_ID=••••••••••••••••••••"
);
let key = "sk-proj-abcdefghijklmnopqrstuvwxyz0123";
assert_eq!(
masked(&format!("OPENAI_API_KEY={key}")),
format!("OPENAI_API_KEY={}", "•".repeat(key.len()))
);
assert_eq!(
masked("token: ghp_abcdefghijklmnopqrstuvwxyz0123456789"),
"token: ••••••••••••••••••••••••••••••••••••••••"
);
assert_eq!(
masked("xoxb-123456789012-abcdefGHIJ"),
"••••••••••••••••••••••••••••"
);
assert_eq!(
masked("ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"),
"•".repeat(40),
"a real token can be digit-free; the prefix is the anchor"
);
assert_eq!(masked("xoxb-abcdefghijklmnopqrstuvwx"), "•".repeat(29));
assert_eq!(
masked("sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGH"),
"•".repeat(42),
"one labelled segment is a key shape"
);
let ant = "sk-ant-api03-AbCdEf1234567890AbCdEf1234567890";
assert_eq!(masked(ant), "•".repeat(ant.len()), "two labels: Anthropic");
let or = "sk-or-v1-abcdef1234567890abcdef1234567890";
assert_eq!(masked(or), "•".repeat(or.len()), "two labels: OpenRouter");
let plain_body = "sk-abcdefghijklmnopqrstuvwxyzabcdefgH1";
assert_eq!(
masked(plain_body),
"•".repeat(plain_body.len()),
"no label, mixed body"
);
let lowercase_body = "sk-ant-api03-abcdefghijklmnopqrstuvwxyzabcdef";
assert_eq!(
masked(lowercase_body),
"•".repeat(lowercase_body.len()),
"a labelled key masks whatever its body looks like"
);
let labelled_word = "sk-learn-preprocessingtransformerspipeline";
assert_eq!(
masked(labelled_word),
"•".repeat(labelled_word.len()),
"a labelled lowercase token masks too: a click reveals it, a missed key never comes back"
);
assert_eq!(
masked(r#"{"Authorization": "Bearer tok_abcdef1234567890"}"#),
r#"{"Authorization": "Bearer ••••••••••••••••••••"}"#,
"the JSON header form"
);
assert_eq!(
masked("Authorization: Bearer abcdef0123456789ABCDEF, X-Other: 1"),
"Authorization: Bearer ••••••••••••••••••••••, X-Other: 1",
"a trailing comma stays outside"
);
assert_eq!(
masked("curl -H 'Authorization: Bearer abcdef0123456789ABCDEF' https://x"),
"curl -H 'Authorization: Bearer ••••••••••••••••••••••' https://x",
"the closing quote stays outside the mask"
);
assert_eq!(
masked("Authorization: Bearer abcdef0123456789ABCDEF"),
"Authorization: Bearer ••••••••••••••••••••••",
"a bearer header keeps its words, the token goes"
);
let jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
assert_eq!(masked(jwt), "•".repeat(jwt.chars().count()));
for prose in [
"cargo build --release",
"Bearer of bad news",
"Bearer responsibilities matter",
"run task sk-something-like-this-long",
"sk-preprocessingtransformerspipeline",
"the skeleton key",
"sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
] {
assert_eq!(masked(prose), prose, "prose must not be masked");
}
// The user's own rules come after the built-ins and still apply.
let both =
set(r##"[{ "regex": "hunter2", "action": "redact" }]"##).with_builtin_redactions();
assert_eq!(mask_text("pw hunter2", &both, false), "pw •••••••");
}
/// #921: the AWS secret access key is the credential (the `AKIA…` id
/// only names it), so it is masked wherever a variable, config key,
/// JSON field or `aws configure` prompt names it; GitLab, Stripe and
/// Google keys and URL passwords are masked by their own shapes.
#[test]
fn builtin_rules_mask_aws_secrets_and_other_credential_shapes() {
let s = TriggerSet::default().with_builtin_redactions();
let masked = |line: &str| mask_text(line, &s, false);
let dots = |v: &str| "•".repeat(v.chars().count());
// Samples are split so a secret scanner never takes them for keys.
let secret = concat!("wJalrXUtnFEMI/K7MDENG", "/bPxRfiCYEXAMPLEKEY");
let token = format!("IQoJb3JpZ2luX2Vj{}", "AbC0/+".repeat(20));
for (before, value, after) in [
("aws_secret_access_key = ", secret, ""),
("export AWS_SECRET_ACCESS_KEY=", secret, ""),
("AWS_SECRET_ACCESS_KEY='", secret, "'"),
("{'aws_secret_access_key': '", secret, "'}"),
(" \"SecretAccessKey\": \"", secret, "\","),
("AWS Secret Access Key [None]: ", secret, ""),
("aws_session_token = ", &token, ""),
("export AWS_SESSION_TOKEN=", &token, ""),
(" \"SessionToken\": \"", &token, "\""),
] {
assert_eq!(
masked(&format!("{before}{value}{after}")),
format!("{before}{}{after}", dots(value)),
"only the value goes, the name stays readable"
);
}
for key in [
format!("glpat-{}", "abcdefghijklmnopqrst"),
format!("glrt-{}", "t1_AbCdEfGhIjKlMnOpQrSt"),
format!("sk_{}_51H{}", "live", "abcdefGHIJKLmnop1234"),
format!("rk_{}_{}", "test", "abcdefGHIJKLmnop1234"),
format!("AIza{}", "SyA-1234567890abcdefghijklmnopqrstu"),
] {
assert_eq!(
masked(&format!("key {key} end")),
format!("key {} end", dots(&key))
);
}
assert_eq!(
masked("DATABASE_URL=postgres://admin:hunter2secret@db.example.com:5432/app"),
"DATABASE_URL=postgres://admin:•••••••••••••@db.example.com:5432/app",
"only the password goes; user and host stay readable"
);
assert_eq!(
masked("redis://:s3cret@cache:6379"),
"redis://:••••••@cache:6379"
);
assert_eq!(
masked("https://user:pa@ss@host/x?to=a@b"),
"https://user:•••••@host/x?to=a@b",
"a raw @ in the password is masked through the last @ before the path"
);
let clone_url = format!(
"origin https://oauth2:glpat-{}@gitlab.com/x.git",
"a".repeat(20)
);
assert_eq!(
redact_spans(&clone_url, &s).len(),
1,
"a token that is also a URL password is one secret on the status chip"
);
for prose in [
"AWS_SECRET_ACCESS_KEY=test",
"aws_secret_access_key = ${AWS_SECRET}",
"AWS_SESSION_TOKEN=short",
"https://example.com:8080/path@v2",
"ssh://git@github.com:22/org/repo.git",
"git@github.com:org/repo.git",
"sk_live_short",
"glpat-short",
] {
assert_eq!(masked(prose), prose, "not a credential");
}
}
#[test]
fn highlight_spans_are_char_indexed_per_trigger_colours() {
let s = set(r##"[
{ "regex": "ERROR", "action": "highlight", "bg": "#c0392b" },
{ "regex": "ok", "action": "highlight", "fg": "#00ff00" }
]"##);
let spans = highlight_spans("naïve ERROR then ok", &s);
assert_eq!(spans.len(), 2, "{spans:?}");
let err = &spans[0];
// "naïve " is 6 chars (7 bytes) — spans must be char-indexed.
assert_eq!((err.start, err.len), (6, 5));
assert_eq!(err.bg, Some((0xc0, 0x39, 0x2b)));
assert_eq!(err.fg, None);
assert_eq!((spans[1].start, spans[1].len), (17, 2));
}
#[test]
fn scanner_fires_on_completed_lines_with_interpolation() {
let s = set(r##"[
{ "regex": "BUILD (\\w+)", "action": "notify", "message": "build: \\1" },
{ "regex": "beep", "action": "bell" }
]"##);
let mut sc = TriggerScanner::new();
let mut out = Vec::new();
// Escape sequences are stripped; the line only fires on \n.
sc.scan(b"\x1b[32mBUILD \x1b[1mFAILED\x1b[0m", &s, &mut out);
assert!(out.is_empty(), "no newline yet: {out:?}");
sc.scan(b"\n", &s, &mut out);
assert_eq!(
out,
vec![TriggerHit {
action: TriggerAction::Notify,
message: String::from("build: FAILED"),
line: String::from("BUILD FAILED"),
}]
);
out.clear();
// \r rewrites the line: the overwritten progress text never fires.
sc.scan(b"beep 10%\rdone 100%\n", &s, &mut out);
assert!(out.is_empty(), "text before \\r must not fire: {out:?}");
// OSC bodies are swallowed even when split across chunks.
sc.scan(b"\x1b]0;beep title", &s, &mut out);
sc.scan(b"\x07real beep\n", &s, &mut out);
assert_eq!(out.len(), 1, "{out:?}");
assert_eq!(out[0].action, TriggerAction::Bell);
assert_eq!(out[0].message, "beep");
out.clear();
// A PTY's plain CRLF line ending completes the line — the CR just
// before the LF must NOT count as a rewrite (regression: every real
// shell line ends \r\n, so triggers never fired at all). Also holds
// when the CR is the last byte of a chunk.
sc.scan(b"beep one\r\n", &s, &mut out);
assert_eq!(out.len(), 1, "CRLF must complete the line: {out:?}");
out.clear();
sc.scan(b"beep two\r", &s, &mut out);
sc.scan(b"\n", &s, &mut out);
assert_eq!(out.len(), 1, "chunk-split CRLF must complete: {out:?}");
}
/// The scanner tracks alt-screen entry/exit POSITIONALLY through the
/// byte stream: alt-screen content never fires, primary text sharing a
/// chunk with an alt transition still does, and a partial primary line
/// interrupted by an alt round trip never splices with post-exit text.
#[test]
fn scanner_tracks_the_alt_screen_positionally() {
let s = set(r##"[
{ "regex": "SECRET", "action": "notify" },
{ "regex": "BUILD FAILED", "action": "notify" },
{ "regex": "ERROR: failed", "action": "notify" }
]"##);
let mut sc = TriggerScanner::new();
let mut out = Vec::new();
// (a) Content that only ever existed on the alt screen must not
// fire, even though the chunk ENDS back on the primary screen.
sc.scan(b"\x1b[?1049hSECRET\n\x1b[?1049l", &s, &mut out);
assert!(out.is_empty(), "alt-screen content fired: {out:?}");
// (b) Primary text in the same chunk as the alt ENTRY still fires.
sc.scan(b"BUILD FAILED\n\x1b[?1049h", &s, &mut out);
assert_eq!(out.len(), 1, "primary text before alt entry: {out:?}");
assert_eq!(out[0].line, "BUILD FAILED");
out.clear();
sc.scan(b"\x1b[?1049l", &s, &mut out);
// (c) A partial primary line interrupted by an alt round trip must
// not splice with post-exit output into a line never printed.
sc.scan(b"ERR", &s, &mut out);
sc.scan(b"\x1b[?1049halt stuff\x1b[?1049l", &s, &mut out);
sc.scan(b"OR: failed\n", &s, &mut out);
assert!(out.is_empty(), "spliced a line never printed: {out:?}");
// Multi-parameter DECSET lists count too (\x1b[?1002;1049h).
sc.scan(b"\x1b[?1002;1049hSECRET\n\x1b[?1049;1002l", &s, &mut out);
assert!(out.is_empty(), "combined DECSET alt entry missed: {out:?}");
// And RIS resets to the primary screen.
sc.scan(b"\x1b[?1049h\x1bcBUILD FAILED\n", &s, &mut out);
assert_eq!(out.len(), 1, "RIS must exit the alt screen: {out:?}");
}
/// CAN/SUB cancel an incomplete CSI and an ESC inside one starts a new
/// escape (VT100 semantics): retaining them as CSI parameters made the
/// malformed CSI swallow the following `ESC [?1049h`, so alt-screen
/// entry went unseen and full-screen content fired triggers.
#[test]
fn a_cancelled_csi_does_not_swallow_the_alt_screen_entry() {
let s = set(r##"[ { "regex": "SECRET", "action": "notify" } ]"##);
let mut sc = TriggerScanner::new();
let mut out = Vec::new();
// CAN aborts the dangling CSI; the alt entry after it must count.
sc.scan(b"\x1b[\x18\x1b[?1049hSECRET\n\x1b[?1049l", &s, &mut out);
assert!(
out.is_empty(),
"CAN-cancelled CSI ate the alt entry: {out:?}"
);
// SUB likewise.
sc.scan(b"\x1b[12\x1a\x1b[?1049hSECRET\n\x1b[?1049l", &s, &mut out);
assert!(
out.is_empty(),
"SUB-cancelled CSI ate the alt entry: {out:?}"
);
// An ESC inside an incomplete CSI begins a NEW escape sequence.
sc.scan(b"\x1b[12\x1b[?1049hSECRET\n\x1b[?1049l", &s, &mut out);
assert!(out.is_empty(), "ESC-in-CSI ate the alt entry: {out:?}");
}
/// CAN/SUB abort control strings too (ECMA-48): an unterminated OSC /
/// DCS / APC / PM / SOS cancelled by CAN or SUB used to keep the
/// scanner in its string state, swallowing ordinary output and the
/// alt-screen boundary until some unrelated BEL/ST arrived.
#[test]
fn can_and_sub_cancel_an_unterminated_control_string() {
let s = set(
r##"[ { "regex": "PRIMARY OK", "action": "notify" }, { "regex": "SECRET", "action": "notify" } ]"##,
);
for intro in [b"\x1b]".as_slice(), b"\x1bP", b"\x1b_", b"\x1b^", b"\x1bX"] {
for cancel in [0x18u8, 0x1a] {
let mut sc = TriggerScanner::new();
let mut out = Vec::new();
let mut bytes = Vec::new();
bytes.extend_from_slice(intro);
bytes.extend_from_slice(b"unterminated-body");
bytes.push(cancel);
bytes.extend_from_slice(b"PRIMARY OK\n\x1b[?1049hSECRET\n\x1b[?1049l");
sc.scan(&bytes, &s, &mut out);
assert_eq!(
out.len(),
1,
"intro {intro:?} cancel {cancel:#x}: the cancelled string must \
release the scanner: {out:?}"
);
assert_eq!(
out[0].line, "PRIMARY OK",
"intro {intro:?} cancel {cancel:#x}"
);
}
}
}
#[test]
fn scanner_caps_runaway_lines() {
let s = set(r#"[ { "regex": "needle", "action": "notify" } ]"#);
let mut sc = TriggerScanner::new();
let mut out = Vec::new();
let long = vec![b'x'; LINE_CAP + 512];
sc.scan(&long, &s, &mut out);
sc.scan(b"needle\n", &s, &mut out);
assert!(
out.is_empty(),
"bytes past the cap are dropped, the needle never enters the buffer: {out:?}"
);
}
#[test]
fn capture_action_parses_and_scanner_reports_the_full_line() {
let s = set(
r#"[ { "regex": "error\\[(\\w+)\\]", "action": "capture", "message": "rustc \\1" } ]"#,
);
assert!(s.has_events(), "capture is an event action");
let mut sc = TriggerScanner::new();
let mut out = Vec::new();
sc.scan(b"error[E0308]: mismatched types\r\n", &s, &mut out);
assert_eq!(out.len(), 1, "{out:?}");
assert_eq!(out[0].action, TriggerAction::Capture);
assert_eq!(out[0].message, "rustc E0308");
assert_eq!(
out[0].line, "error[E0308]: mismatched types",
"a capture hit carries the whole matched line for the panel"
);
}
#[test]
fn notify_without_a_template_reports_the_whole_match() {
let s = set(r#"[ { "regex": "deploy (ok|failed)", "action": "notify" } ]"#);
let mut sc = TriggerScanner::new();
let mut out = Vec::new();
sc.scan(b"deploy failed\n", &s, &mut out);
assert_eq!(out.len(), 1);
assert_eq!(out[0].message, "deploy failed");
}
}