rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! Tauri rules: the security configuration, the commands that connect the Rust side to the
//! webview, and the crate/package versions that must move together.

use std::collections::BTreeSet;

use super::*;
use crate::review::diff::{Kind, Status};

pub fn run(cx: &Cx, out: &mut Vec<Finding>) {
    let Some(t) = cx.tauri() else { return };
    config(cx, &t, out);
    capabilities(cx, &t, out);
    commands(cx, &t, out);
    invokes(cx, &t, out);
    versions(cx, &t, out);
}

fn dev_cmd(cx: &Cx, t: &Tauri) -> String {
    t.cli(cx.node(), "dev")
}

// --- tauri.conf.json -----------------------------------------------------------------------

fn is_conf(t: &Tauri, path: &str) -> bool {
    ["tauri.conf.json", "tauri.conf.json5", "Tauri.toml"].iter().any(|n| path == t.path(n))
}

fn config(cx: &Cx, t: &Tauri, out: &mut Vec<Finding>) {
    for f in cx.diff.files.iter().filter(|f| is_conf(t, &f.path) && f.status != Status::Deleted) {
        let mut bundle_hit = None;
        for l in f.added() {
            let text = &l.text;
            if let Some(i) = text.find("\"csp\"")
                && text[i + 5..].trim_start().trim_start_matches(':').trim_start().starts_with("null")
            {
                out.push(
                    Finding::new("TAU001", Level::Risk, "the Content-Security-Policy is switched off")
                        .at(&f.path, l, "null", "no CSP: the webview will load and run anything")
                        .note("a CSP is what limits the damage of an XSS bug in the webview, where it could otherwise call every Tauri command the app allows")
                        .check("DevTools console after launching: CSP violations show as `Refused to load ...`; each one is either a real hole or a source to allow on purpose")
                        .test(format!("`{}`, open DevTools, and use every screen that loads images, fonts or remote APIs", dev_cmd(cx, t)))
                        .help("set a policy such as `default-src 'self'; connect-src ipc: http://ipc.localhost` and add only the sources the app needs"),
                );
            }
            for needle in ["unsafe-eval", "unsafe-inline"] {
                if let Some(i) = text.find(needle) {
                    out.push(
                        Finding::new("TAU001", Level::Warn, format!("the Content-Security-Policy allows `{needle}`"))
                            .at_range(&f.path, l, i, i + needle.len(), "weakens the policy")
                            .note("inline or eval'd script is exactly what an injected payload uses")
                            .check("is it needed for a dev server only? Tauri adds nonces and hashes to its own scripts, so production rarely needs it")
                            .test(format!("`{}`: remove it and confirm the app still renders and every feature works", t.cli(cx.node(), "build"))),
                    );
                }
            }
            if let Some(i) = text.find("\"all\"")
                && text[i + 5..].trim_start().trim_start_matches(':').trim_start().starts_with("true")
            {
                out.push(
                    Finding::new("TAU002", Level::Risk, "the allowlist enables every API in a group")
                        .at_range(&f.path, l, i, text.len(), "grants all of it to the webview")
                        .help("enable only the individual APIs the app uses"),
                );
            }
            if ["\"pubkey\"", "\"endpoints\"", "\"updater\"", "createUpdaterArtifacts", "\"bundle\""]
                .iter()
                .any(|k| text.contains(k))
                && bundle_hit.is_none()
            {
                bundle_hit = Some(l);
            }
        }
        // Renaming the identifier moves the app's data folder: users appear to lose their data.
        for key in ["\"identifier\"", "\"productName\""] {
            let (a, r) = (f.added().find(|l| l.text.contains(key)), f.removed().find(|l| l.text.contains(key)));
            if let (Some(a), Some(r)) = (a, r) {
                out.push(
                    Finding::new("TAU006", Level::Warn, format!("{key} changed", key = key.trim_matches('"')))
                        .at(&f.path, a, key, "this changes where the app keeps its data")
                        .note(format!("was `{}`; the app data, config and cache folders are named after the identifier, so existing installs start with nothing and the updater may treat it as another app", r.text.trim()))
                        .test("install the previous release, create some data, then install this build over it and check the data is still there")
                        .help("keep the old identifier, or migrate the old folder on first start"),
                );
            }
        }
        if let Some(l) = bundle_hit {
            out.push(
                Finding::new("TAU008", Level::Note, "bundle or updater settings changed")
                    .at(&f.path, l, "", "affects the installer or auto-update")
                    .check("installer icons, targets, `endpoints` URL and the public key that must match the key the release is signed with")
                    .test(format!("`{}`, then install the result on a clean machine or VM and launch it", t.cli(cx.node(), "build")))
                    .test("for the updater: run an older version and confirm it finds, downloads and installs this one"),
            );
        }
    }
}

// --- capabilities (Tauri 2) ----------------------------------------------------------------

fn broad_permission(perm: &str) -> Option<&'static str> {
    let any = |ps: &[&str]| ps.iter().any(|p| perm.starts_with(p));
    if any(&["shell:allow-execute", "shell:allow-spawn", "shell:allow-kill"]) {
        Some("lets the webview run programs")
    } else if any(&[
        "fs:allow-write",
        "fs:allow-remove",
        "fs:allow-rename",
        "fs:allow-mkdir",
        "fs:allow-copy",
        "fs:allow-create",
        "fs:allow-truncate",
    ]) {
        Some("lets the webview change files")
    } else if any(&["http:default", "http:allow-fetch"]) {
        Some("lets the webview call any allowed URL")
    } else if any(&["process:allow-exit", "process:allow-restart"]) {
        Some("lets the webview quit or restart the app")
    } else if any(&["shell:allow-open", "opener:allow-open", "opener:default"]) {
        Some("lets the webview open files, folders and URLs")
    } else {
        None
    }
}

/// Permission names like `fs:allow-read-file` in a line of a capability file.
fn permissions_in(text: &str) -> Vec<(usize, usize, String)> {
    let mut found = Vec::new();
    let mut from = 0;
    while let Some((s, e, q)) = string_at(text, from) {
        from = e;
        if q != '"' && q != '\'' {
            continue;
        }
        let inner = &text[s + 1..e - 1];
        let shaped = inner.contains(':')
            && inner.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == ':')
            && !inner.starts_with("http");
        if shaped {
            found.push((s + 1, e - 1, inner.to_string()));
        }
    }
    found
}

fn capabilities(cx: &Cx, t: &Tauri, out: &mut Vec<Finding>) {
    let prefix = t.path("capabilities/");
    for f in cx.diff.files.iter().filter(|f| f.path.starts_with(&prefix) && f.status != Status::Deleted) {
        let mut others: Vec<String> = Vec::new();
        let mut first_other = None;
        for l in f.added() {
            for (s, e, perm) in permissions_in(&l.text) {
                if let Some(why) = broad_permission(&perm) {
                    out.push(
                        Finding::new("TAU002", Level::Warn, format!("broad permission `{perm}`"))
                            .at_range(&f.path, l, s, e, why)
                            .note("every window this capability applies to gets it, including any page that window loads")
                            .check("does the window only ever load your own bundled pages? is the scope as narrow as it can be (one folder, one command)?")
                            .test(format!("use the feature that needs it, then delete `{perm}` and repeat: the call must now be rejected with a \"not allowed\" error in DevTools, which proves this file is what grants it"))
                            .help("grant the narrowest permission with an explicit `allow` scope instead"),
                    );
                } else {
                    first_other.get_or_insert(l);
                    others.push(perm);
                }
            }
            for wide in ["\"**\"", "\"$HOME/**\"", "\"/**\"", "\"$APPDATA/**\""] {
                if let Some(i) = l.text.find(wide) {
                    out.push(
                        Finding::new("TAU002", Level::Warn, format!("scope {wide} covers every file below it"))
                            .at_range(&f.path, l, i, i + wide.len(), "a wildcard scope")
                            .check("which folder does the feature really need? scope to that")
                            .test("try to read or write a path outside the intended folder from DevTools: it should be refused"),
                    );
                }
            }
            if let Some(i) = l.text.find("\"remote\"") {
                out.push(
                    Finding::new("TAU002", Level::Warn, "capability applies to remote content")
                        .at_range(&f.path, l, i, i + 8, "remote URLs get these permissions")
                        .note("pages you do not ship (and anything injected into them) can then use the permissions listed in this file"),
                );
            }
        }
        if let (Some(l), false) = (first_other, others.is_empty()) {
            let list = others.iter().map(|p| format!("`{p}`")).collect::<Vec<_>>().join(", ");
            out.push(
                Finding::new("TAU002", Level::Note, format!("{} permission(s) added: {list}", others.len()))
                    .at(&f.path, l, "", "new permission")
                    .test("use each feature that needs one of them once; a missing permission shows as a \"not allowed\" error in the DevTools console")
                    .check("is each one needed by a window that really has this capability?"),
            );
        }
    }
}

// --- commands ------------------------------------------------------------------------------

/// The name of the function declared on a line, if it is one.
fn fn_name(text: &str) -> Option<&str> {
    let mut rest = text.trim_start();
    'outer: loop {
        for q in ["pub(crate) ", "pub(super) ", "pub ", "async ", "unsafe ", "const "] {
            if let Some(r) = rest.strip_prefix(q) {
                rest = r;
                continue 'outer;
            }
        }
        break;
    }
    let rest = rest.strip_prefix("fn ")?;
    let end = rest.find(|c: char| !(c.is_alphanumeric() || c == '_')).unwrap_or(rest.len());
    (end > 0).then(|| &rest[..end])
}

fn is_command_attr(text: &str) -> bool {
    let t = text.trim_start();
    t.starts_with("#[tauri::command") || t.starts_with("#[command")
}

/// Commands declared in Rust source text: the functions right after a command attribute.
fn commands_in(text: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut pending = false;
    for line in text.lines() {
        let t = line.trim();
        if is_command_attr(t) {
            pending = true;
        } else if pending {
            if let Some(n) = fn_name(t) {
                out.push(n.to_string());
                pending = false;
            } else if !(t.is_empty() || t.starts_with("#[") || t.starts_with("//")) {
                pending = false;
            }
        }
    }
    out
}

/// A command and where the diff declares it.
struct Declared<'a> {
    name: String,
    file: &'a FileDiff,
    line: &'a Line,
    /// The old declaration line, if the function already existed in this hunk.
    was: Option<&'a Line>,
}

fn declared_commands<'a>(cx: &'a Cx, t: &Tauri) -> Vec<Declared<'a>> {
    let mut found = Vec::new();
    for f in cx.diff.files.iter().filter(|f| {
        ext(&f.path) == "rs" && f.status != Status::Deleted && (t.dir == "." || f.path.starts_with(&t.path("")))
    }) {
        for h in &f.hunks {
            for (i, l) in h.lines.iter().enumerate() {
                if l.kind != Kind::Added {
                    continue;
                }
                let Some(name) = fn_name(&l.text) else { continue };
                // Walk back over attributes, doc comments and blank lines to find the command attribute.
                let is_cmd = h.lines[..i]
                    .iter()
                    .rev()
                    .filter(|p| p.kind != Kind::Removed)
                    .map(|p| p.text.trim())
                    .take_while(|p| p.is_empty() || p.starts_with("#[") || p.starts_with("//"))
                    .any(is_command_attr);
                if !is_cmd {
                    continue;
                }
                let was = h.lines.iter().find(|r| r.kind == Kind::Removed && fn_name(&r.text) == Some(name));
                found.push(Declared { name: name.to_string(), file: f, line: l, was });
            }
        }
    }
    found
}

/// The commands listed in `generate_handler![...]`, and where that list is.
fn registered(cx: &Cx, t: &Tauri) -> Option<(BTreeSet<String>, String)> {
    let mut names = BTreeSet::new();
    let mut place = None;
    for (path, text) in cx.scan(&t.path("src"), &["rs"]) {
        if text.contains("collect_commands!") {
            return None; // tauri-specta builds the list another way
        }
        let mut from = 0;
        while let Some(i) = text[from..].find("generate_handler!") {
            let at = from + i;
            from = at + 17;
            let Some(open) = text[from..].find(['[', '(']).map(|o| from + o) else { continue };
            let close_ch = if text.as_bytes()[open] == b'[' { ']' } else { ')' };
            let Some(close) = text[open..].find(close_ch).map(|c| open + c) else { continue };
            place.get_or_insert_with(|| format!("{path}:{}", text[..at].matches('\n').count() + 1));
            for item in text[open + 1..close].split(',') {
                let item: String =
                    item.lines().filter(|l| !l.trim_start().starts_with("//")).collect::<Vec<_>>().join(" ");
                let name = item.trim().rsplit("::").next().unwrap_or("").trim();
                if !name.is_empty() {
                    names.insert(name.to_string());
                }
            }
        }
    }
    place.map(|p| (names, p))
}

fn call_sites(cx: &Cx, name: &str) -> Vec<String> {
    let mut sites = Vec::new();
    for dir in ["src", "app", "frontend", "ui", "resources/js"] {
        for (path, text) in cx.scan(dir, &["js", "jsx", "ts", "tsx", "vue", "svelte", "mjs"]) {
            for (i, line) in text.lines().enumerate() {
                if invoke_calls(line).iter().any(|c| c.2 == name) {
                    sites.push(format!("{path}:{}", i + 1));
                }
            }
        }
    }
    sites
}

fn commands(cx: &Cx, t: &Tauri, out: &mut Vec<Finding>) {
    let declared = declared_commands(cx, t);
    if declared.is_empty() {
        return;
    }
    let reg = registered(cx, t);
    for d in &declared {
        let path = &d.file.path;
        let mut f = match d.was {
            None => Finding::new("TAU004", Level::Note, format!("new Tauri command `{}`", d.name))
                .at(path, d.line, &format!("fn {}", d.name), "callable from the webview once registered")
                .check("the argument names: Rust `snake_case` parameters are `camelCase` keys on the JS side unless `rename_all` is set")
                .check("the error type must implement `Serialize`, or the call cannot return it to JS")
                .check("slow work belongs in an `async` command, or the call blocks the main thread"),
            Some(old) => {
                let mut f = Finding::new("TAU004", Level::Warn, format!("Tauri command `{}` changed", d.name))
                    .at(path, d.line, &format!("fn {}", d.name), "JS callers pass arguments the old way")
                    .note(format!("was `{}`", old.text.trim()))
                    .check("every `invoke()` call site: renamed or retyped parameters are `camelCase` keys, a changed return type changes what `await invoke()` resolves to");
                let sites = call_sites(cx, &d.name);
                if !sites.is_empty() {
                    f = f.note(format!("called from {}", sites.iter().take(6).cloned().collect::<Vec<_>>().join(", ")));
                }
                f
            }
        };
        f = f.test(if t.major >= 2 {
            format!("in the app's DevTools console: `await window.__TAURI_INTERNALS__.invoke('{}', {{ /* args */ }})`; try valid input and one that makes it fail", d.name)
        } else {
            format!("call `invoke('{}', {{ /* args */ }})` from the frontend; try valid input and one that makes it fail", d.name)
        });
        out.push(f);
        if let Some((names, place)) = &reg
            && !names.contains(&d.name)
        {
            out.push(
                Finding::new("TAU003", Level::Risk, format!("command `{}` is not registered", d.name))
                    .at(path, d.line, &format!("fn {}", d.name), "missing from `generate_handler!`")
                    .note(format!("`invoke('{}')` will fail at runtime with \"Command {} not found\"; the compiler does not catch it", d.name, d.name))
                    .help(format!("add `{}` to the `tauri::generate_handler![...]` list at {place}", d.name)),
            );
        }
    }
}

// --- invoke() calls in the frontend --------------------------------------------------------

/// `invoke('name'` and `invoke<T>("name"` calls in a line: (start, end, name) of the string.
fn invoke_calls(text: &str) -> Vec<(usize, usize, String)> {
    let mut found = Vec::new();
    for (i, _) in text.match_indices("invoke") {
        if text[..i].chars().next_back().is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$') {
            continue;
        }
        let mut j = i + 6;
        let rest = &text[j..];
        if rest.starts_with('<') {
            let mut depth = 0;
            let mut end = None;
            for (k, c) in rest.char_indices() {
                match c {
                    '<' => depth += 1,
                    '>' => {
                        depth -= 1;
                        if depth == 0 {
                            end = Some(k + 1);
                            break;
                        }
                    }
                    _ => {}
                }
            }
            let Some(end) = end else { continue };
            j += end;
        }
        let after = text[j..].trim_start();
        let Some(args) = after.strip_prefix('(') else { continue };
        let args_start = text.len() - args.len();
        let trimmed = args.trim_start();
        let q_at = args_start + (args.len() - trimmed.len());
        if !trimmed.starts_with(['"', '\'', '`']) {
            continue;
        }
        let Some((s, e, _)) = string_at(text, q_at) else { continue };
        found.push((s, e, text[s + 1..e - 1].to_string()));
    }
    found
}

fn edit_distance(a: &str, b: &str) -> usize {
    let b: Vec<char> = b.chars().collect();
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    for (i, ca) in a.chars().enumerate() {
        let mut cur = vec![i + 1];
        for (j, cb) in b.iter().enumerate() {
            cur.push((prev[j] + usize::from(ca != *cb)).min(prev[j + 1] + 1).min(cur[j] + 1));
        }
        prev = cur;
    }
    prev[b.len()]
}

/// The known command closest to `name`, if any is close enough to be a typo.
fn did_you_mean<'a>(name: &str, known: &'a BTreeSet<String>) -> Option<&'a str> {
    let norm = |s: &str| s.replace('_', "").to_lowercase();
    known
        .iter()
        .map(|k| (k.as_str(), if norm(k) == norm(name) { 0 } else { edit_distance(&norm(k), &norm(name)) }))
        .filter(|&(_, d)| d <= 2.max(name.len() / 5))
        .min_by_key(|&(_, d)| d)
        .map(|(k, _)| k)
}

fn invokes(cx: &Cx, t: &Tauri, out: &mut Vec<Finding>) {
    let mut known: BTreeSet<String> = BTreeSet::new();
    for (_, text) in cx.scan(&t.path("src"), &["rs"]) {
        known.extend(commands_in(&text));
    }
    known.extend(declared_commands(cx, t).into_iter().map(|d| d.name));
    if known.is_empty() {
        return; // the Rust sources are not available: cannot tell
    }
    for f in cx
        .diff
        .files
        .iter()
        .filter(|f| f.status != Status::Deleted && (t.dir == "." || !f.path.starts_with(&t.path(""))))
    {
        if !matches!(ext(&f.path).as_str(), "js" | "jsx" | "ts" | "tsx" | "vue" | "svelte" | "mjs")
            || f.path.contains("node_modules/")
        {
            continue;
        }
        for l in f.added() {
            for (s, e, name) in invoke_calls(&l.text) {
                if name.starts_with("plugin:") || name.contains("${") || known.contains(&name) {
                    continue;
                }
                let mut finding = Finding::new("TAU005", Level::Risk, format!("no Tauri command named `{name}`"))
                    .at_range(&f.path, l, s, e, "not defined on the Rust side")
                    .note(format!("`invoke` rejects at runtime with \"Command {name} not found\""));
                finding = match did_you_mean(&name, &known) {
                    Some(k) => finding.help(format!(
                        "a command named `{k}` exists: did you mean it? (Rust `snake_case` names are called as written)"
                    )),
                    None => finding.help("define it with `#[tauri::command]` and register it in `generate_handler!`"),
                };
                out.push(finding);
            }
        }
    }
}

// --- crate and package versions ------------------------------------------------------------

fn versions(cx: &Cx, t: &Tauri, out: &mut Vec<Finding>) {
    let cargo_path = t.path("Cargo.toml");
    let crate_line = cx.file(&cargo_path).and_then(|f| {
        f.added().find(|l| {
            let tt = l.text.trim_start();
            (tt.starts_with("tauri =") || tt.starts_with("tauri-build =") || tt.starts_with("tauri-plugin-"))
                && tt.contains(|c: char| c.is_ascii_digit())
        })
    });
    let pkg = cx.diff.files.iter().find(|f| file_name(&f.path) == "package.json" && f.status != Status::Deleted);
    let js_line = pkg.and_then(|f| {
        f.added().find(|l| l.text.contains("\"@tauri-apps/") && l.text.contains(|c: char| c.is_ascii_digit()))
    });
    let info = t.cli(cx.node(), "info");
    match (crate_line, js_line) {
        (Some(l), None) => out.push(
            Finding::new("TAU007", Level::Warn, "a `tauri` crate changed but no `@tauri-apps` package did")
                .at(&cargo_path, l, "", "version changed here")
                .note("the Rust crates and the JS packages are a matched set: a different minor version can break the IPC between them")
                .test(format!("`{info}` lists both versions and warns when they do not match")),
        ),
        (None, Some(l)) => out.push(
            Finding::new("TAU007", Level::Warn, "an `@tauri-apps` package changed but no `tauri` crate did")
                .at(&pkg.unwrap().path, l, "", "version changed here")
                .note("the Rust crates and the JS packages are a matched set: a different minor version can break the IPC between them")
                .test(format!("`{info}` lists both versions and warns when they do not match")),
        ),
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::super::testing::*;
    use super::*;
    use crate::review::project::Project;
    use crate::review::testutil::Scratch;

    #[test]
    fn disabled_csp_is_a_risk_and_unsafe_eval_a_warning() {
        let f = review(&[edit(
            "src-tauri/tauri.conf.json",
            &["\"security\": {", "-\"csp\": \"default-src 'self'\"", "+\"csp\": null"],
        )]);
        let g = get(&f, "TAU001");
        assert_eq!(g.level, Level::Risk);
        assert_eq!(g.span.as_ref().unwrap().len, 4);
        let w = review(&[edit("src-tauri/tauri.conf.json", &["+\"csp\": \"script-src 'self' 'unsafe-eval'\""])]);
        assert_eq!(get(&w, "TAU001").level, Level::Warn);
    }

    #[test]
    fn broad_and_ordinary_permissions() {
        let f = review(&[add(
            "src-tauri/capabilities/main.json",
            &[
                "{",
                "  \"permissions\": [",
                "    \"core:default\",",
                "    \"shell:allow-execute\",",
                "    \"fs:allow-write-file\"",
                "  ]",
                "}",
            ],
        )]);
        let t2: Vec<_> = f.iter().filter(|f| f.code == "TAU002").collect();
        assert_eq!(t2.iter().filter(|f| f.level == Level::Warn).count(), 2);
        assert!(t2.iter().any(|f| f.level == Level::Note && f.title.contains("`core:default`")));
    }

    #[test]
    fn identifier_change_is_flagged_but_adding_one_is_not() {
        let f = review(&[edit(
            "src-tauri/tauri.conf.json",
            &["-\"identifier\": \"com.old.app\",", "+\"identifier\": \"com.new.app\","],
        )]);
        assert!(get(&f, "TAU006").note[0].contains("com.old.app"));
        assert!(!has(&review(&[add("src-tauri/tauri.conf.json", &["\"identifier\": \"com.new.app\""])]), "TAU006"));
    }

    #[test]
    fn new_and_changed_commands() {
        let f = review(&[edit(
            "src-tauri/src/lib.rs",
            &[
                "#[tauri::command]",
                "+async fn save_note(note_id: u32) -> Result<(), String> {",
                "-fn rename(a: u32) {",
                "+fn rename(a: u32, b: u32) {",
                "}",
            ],
        )]);
        assert_eq!(f.iter().filter(|f| f.code == "TAU004").count(), 1); // rename is not a command: attribute is above save_note only
        let g = get(&f, "TAU004");
        assert!(g.title.contains("save_note") && g.level == Level::Note);
        assert!(g.test[0].contains("invoke('save_note'"));

        let changed = review(&[edit(
            "src-tauri/src/lib.rs",
            &["#[tauri::command]", "-fn load(id: u32) -> String {", "+fn load(id: u32, deep: bool) -> String {"],
        )]);
        let c = get(&changed, "TAU004");
        assert_eq!(c.level, Level::Warn);
        assert!(c.note[0].contains("fn load(id: u32)"));
    }

    #[test]
    fn unregistered_command_and_unknown_invoke_are_found_on_disk() {
        let s = Scratch::new("tauri-cmds");
        s.write("src-tauri/tauri.conf.json", "{}");
        s.write("src-tauri/Cargo.toml", "[dependencies]\ntauri = \"2\"\n");
        s.write(
            "src-tauri/src/lib.rs",
            "mod cmds;\n#[tauri::command]\nfn save_note() {}\n#[tauri::command]\nfn forgotten() {}\npub fn run() {\n    tauri::Builder::default().invoke_handler(tauri::generate_handler![\n        save_note,\n        cmds::other,\n    ]);\n}\n",
        );
        let project = Project::detect(&s.0);
        let f = review_with(
            &[
                edit("src-tauri/src/lib.rs", &["#[tauri::command]", "+fn forgotten() {}"]),
                add(
                    "src/api.ts",
                    &[
                        "await invoke('save_notes', { id: 1 });",
                        "await invoke<string>(\"save_note\");",
                        "await invoke('plugin:fs|read');",
                        "invoke(`dyn_${x}`)",
                    ],
                ),
            ],
            &project,
            None,
        );
        let unreg = get(&f, "TAU003");
        assert!(unreg.title.contains("forgotten"));
        assert!(unreg.help[0].contains("src-tauri/src/lib.rs:7"));
        let unknown: Vec<_> = f.iter().filter(|f| f.code == "TAU005").collect();
        assert_eq!(unknown.len(), 1);
        assert!(unknown[0].help[0].contains("`save_note`"));
        let s = unknown[0].span.as_ref().unwrap();
        assert_eq!((s.line, s.col), (1, 14));
    }

    #[test]
    fn version_skew_between_crate_and_npm_packages() {
        let f = review(&[edit("src-tauri/Cargo.toml", &["-tauri = \"2.0\"", "+tauri = \"2.2\""])]);
        assert!(has(&f, "TAU007"));
        let both = review(&[
            edit("src-tauri/Cargo.toml", &["-tauri = \"2.0\"", "+tauri = \"2.2\""]),
            edit("package.json", &["-\"@tauri-apps/api\": \"^2.0.0\"", "+\"@tauri-apps/api\": \"^2.2.0\""]),
        ]);
        assert!(!has(&both, "TAU007"));
    }

    #[test]
    fn invoke_parsing_handles_generics_and_quotes() {
        let c = invoke_calls("const a = await invoke<Array<string>>('list_all', {}); core.invoke(\"x\")");
        let names: Vec<_> = c.iter().map(|c| c.2.as_str()).collect();
        assert_eq!(names, vec!["list_all", "x"]);
        assert!(invoke_calls("reinvoke('a')").is_empty());
        assert!(invoke_calls("invoke(name)").is_empty());
    }
}