dart-decimate 0.0.29 → 0.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/Cargo.lock +1 -1
  2. package/Cargo.toml +1 -1
  3. package/README.md +36 -60
  4. package/npm/bin/runner.js +26 -14
  5. package/npm/scripts/postinstall.js +89 -63
  6. package/package.json +3 -2
  7. package/src/baseline.rs +38 -0
  8. package/src/cli/health_args.rs +36 -7
  9. package/src/cli/html_open.rs +4 -0
  10. package/src/cli/issue_filter_args.rs +1 -0
  11. package/src/cli/security_summary_run.rs +1 -0
  12. package/src/config/health.rs +22 -2
  13. package/src/config/rule_aliases.rs +43 -0
  14. package/src/config/rules.rs +46 -1
  15. package/src/config.rs +2 -1
  16. package/src/dart_parser/test_support.rs +51 -0
  17. package/src/dart_parser.rs +8 -0
  18. package/src/dependencies/analyze.rs +3 -1
  19. package/src/dependencies/tests.rs +111 -7
  20. package/src/dependencies/usage.rs +5 -1
  21. package/src/dependencies.rs +7 -3
  22. package/src/explain/flutter_style.rs +43 -0
  23. package/src/explain/misc.rs +72 -0
  24. package/src/explain.rs +23 -67
  25. package/src/flutter_style/scanner.rs +883 -0
  26. package/src/flutter_style/types.rs +90 -0
  27. package/src/flutter_style/usage.rs +349 -0
  28. package/src/flutter_style.rs +72 -0
  29. package/src/generated.rs +154 -0
  30. package/src/health/large_units.rs +49 -0
  31. package/src/health/tests.rs +212 -1
  32. package/src/health/threshold_types.rs +31 -1
  33. package/src/health/thresholds.rs +49 -0
  34. package/src/health/types.rs +35 -0
  35. package/src/health.rs +72 -6
  36. package/src/inspect.rs +8 -0
  37. package/src/lib.rs +17 -5
  38. package/src/manifest.rs +7 -3
  39. package/src/output/dependency_findings.rs +14 -1
  40. package/src/output/flutter_style.rs +189 -0
  41. package/src/output/health_findings.rs +93 -10
  42. package/src/output/health_inventory.rs +121 -0
  43. package/src/output/html/tests.rs +20 -0
  44. package/src/output/html.rs +10 -1
  45. package/src/output/human.rs +85 -1
  46. package/src/output/human_details.rs +93 -12
  47. package/src/output/scope.rs +62 -2
  48. package/src/output/security_findings.rs +101 -76
  49. package/src/output/security_sarif.rs +24 -13
  50. package/src/output/suppressions.rs +4 -0
  51. package/src/output/types.rs +38 -2
  52. package/src/output/verdict.rs +12 -0
  53. package/src/output.rs +77 -74
  54. package/src/report_schema/inventory.rs +268 -4
  55. package/src/report_schema.rs +94 -60
  56. package/src/security/catalogue.rs +103 -0
  57. package/src/security/detect/weak_randomness.rs +762 -0
  58. package/src/security/detect.rs +1535 -221
  59. package/src/security/security_matchers.toml +172 -0
  60. package/src/security/tests.rs +336 -2
  61. package/src/security.rs +292 -56
  62. package/src/security_gate.rs +28 -0
  63. package/src/semantic.rs +276 -0
  64. package/src/symbols/semantic_evidence.rs +342 -0
  65. package/src/symbols.rs +20 -10
  66. package/src/trace/rendering.rs +54 -0
  67. package/src/trace/semantic.rs +126 -0
  68. package/src/trace.rs +54 -62
  69. package/src/widgets/inheritance.rs +63 -0
  70. package/src/widgets.rs +33 -3
@@ -0,0 +1,762 @@
1
+ use std::collections::BTreeSet;
2
+ use std::path::Path;
3
+
4
+ use tree_sitter::Node;
5
+
6
+ use super::{blind_spot, detected, is_identifier_byte, line_at, match_indices, segment_indices};
7
+ use crate::dart_parser::parse_dart_source_lossy;
8
+ use crate::security::catalogue::MatcherCatalogue;
9
+ use crate::security::{
10
+ DetectionResult, SecurityBlindSpotReason, SecurityCategory, SecurityConfidence,
11
+ };
12
+
13
+ const SECURITY_SEGMENTS: [&str; 12] = [
14
+ "token",
15
+ "secret",
16
+ "nonce",
17
+ "salt",
18
+ "otp",
19
+ "session",
20
+ "key",
21
+ "password",
22
+ "passcode",
23
+ "auth",
24
+ "csrf",
25
+ "credential",
26
+ ];
27
+ const SECURITY_CODE_PREFIXES: [&str; 17] = [
28
+ "access",
29
+ "authentication",
30
+ "authorization",
31
+ "backup",
32
+ "challenge",
33
+ "confirmation",
34
+ "invite",
35
+ "login",
36
+ "mfa",
37
+ "pairing",
38
+ "pin",
39
+ "recovery",
40
+ "reset",
41
+ "security",
42
+ "totp",
43
+ "verification",
44
+ "verify",
45
+ ];
46
+
47
+ pub(super) fn detect(
48
+ path: &Path,
49
+ source: &str,
50
+ catalogue: &MatcherCatalogue,
51
+ result: &mut DetectionResult,
52
+ ) {
53
+ let matcher = catalogue.by_detector("weak-randomness");
54
+ if matcher.import_provenance != "dart:math"
55
+ || !matcher.callees.iter().any(|callee| callee == "Random")
56
+ {
57
+ return;
58
+ }
59
+ let Ok(parsed) = parse_dart_source_lossy(path, source) else {
60
+ return;
61
+ };
62
+ let root = parsed.tree().root_node();
63
+ let imports = dart_math_imports(source);
64
+ let random_aliases = confirmed_random_type_aliases(source, &imports);
65
+ let random_factories = confirmed_random_factories(source, root, &imports);
66
+ let mut known_factory_names = random_factories.clone();
67
+ known_factory_names.extend(confirmed_secure_random_factories(source, root, &imports));
68
+ let random_bindings =
69
+ confirmed_random_bindings(source, root, &imports, &random_aliases, &random_factories);
70
+ let mut direct_lines = BTreeSet::new();
71
+
72
+ for index in random_indices(source) {
73
+ if !identifier_node_at(root, index) || !random_constructor_at(source, index) {
74
+ continue;
75
+ }
76
+ if flutter_key_context(source, index)
77
+ || !security_shaped_flow_context(root, source, index)
78
+ || secure_constructor_at(source, index)
79
+ {
80
+ continue;
81
+ }
82
+ if random_has_provenance(source, index, &imports) {
83
+ direct_lines.insert(line_start(source, index));
84
+ result.candidates.push(detected(
85
+ path,
86
+ source,
87
+ index,
88
+ SecurityCategory::WeakRandomness,
89
+ "weak-randomness",
90
+ SecurityConfidence::Medium,
91
+ "Random",
92
+ ));
93
+ } else {
94
+ result.blind_spots.push(blind_spot(
95
+ path,
96
+ source,
97
+ index,
98
+ SecurityCategory::WeakRandomness,
99
+ "weak-randomness",
100
+ SecurityBlindSpotReason::AmbiguousRandomProvenance,
101
+ ));
102
+ }
103
+ }
104
+
105
+ for alias in &random_aliases {
106
+ for index in segment_indices(source, alias) {
107
+ if !identifier_node_named_at(root, index, alias)
108
+ || !source[index + alias.len()..].trim_start().starts_with('(')
109
+ || flutter_key_context(source, index)
110
+ {
111
+ continue;
112
+ }
113
+ if !security_shaped_flow_context(root, source, index) {
114
+ continue;
115
+ }
116
+ direct_lines.insert(line_start(source, index));
117
+ result.candidates.push(detected(
118
+ path,
119
+ source,
120
+ index,
121
+ SecurityCategory::WeakRandomness,
122
+ "weak-randomness",
123
+ SecurityConfidence::Medium,
124
+ "Random",
125
+ ));
126
+ }
127
+ }
128
+
129
+ let flows = RandomFlowFacts {
130
+ bindings: &random_bindings,
131
+ factories: &random_factories,
132
+ known_factory_names: &known_factory_names,
133
+ direct_lines: &direct_lines,
134
+ };
135
+ report_indirect_random_flows(path, source, root, &flows, result);
136
+ }
137
+
138
+ struct RandomFlowFacts<'facts> {
139
+ bindings: &'facts BTreeSet<String>,
140
+ factories: &'facts BTreeSet<String>,
141
+ known_factory_names: &'facts BTreeSet<String>,
142
+ direct_lines: &'facts BTreeSet<usize>,
143
+ }
144
+
145
+ fn report_indirect_random_flows(
146
+ path: &Path,
147
+ source: &str,
148
+ root: Node<'_>,
149
+ flows: &RandomFlowFacts<'_>,
150
+ result: &mut DetectionResult,
151
+ ) {
152
+ for (offset, line) in source_lines(source) {
153
+ if flows.direct_lines.contains(&offset) {
154
+ continue;
155
+ }
156
+ let binding_use = flows
157
+ .bindings
158
+ .iter()
159
+ .find_map(|binding| member_access_index(line, binding))
160
+ .map(|index| offset + index);
161
+ let factory_use = flows
162
+ .factories
163
+ .iter()
164
+ .find_map(|factory| constructor_call_index(line, factory))
165
+ .map(|index| offset + index);
166
+ let security_use = binding_use
167
+ .or(factory_use)
168
+ .is_some_and(|index| security_shaped_flow_context(root, source, index));
169
+ if security_use
170
+ && !non_security_enclosing_scope(root, source, offset + first_non_whitespace(line))
171
+ {
172
+ result.blind_spots.push(blind_spot(
173
+ path,
174
+ source,
175
+ offset + first_non_whitespace(line),
176
+ SecurityCategory::WeakRandomness,
177
+ "weak-randomness",
178
+ SecurityBlindSpotReason::UnflattenedRandomFlow,
179
+ ));
180
+ } else if security_shaped_context(line)
181
+ && ambiguous_random_constructor(line, flows.known_factory_names)
182
+ {
183
+ result.blind_spots.push(blind_spot(
184
+ path,
185
+ source,
186
+ offset + first_non_whitespace(line),
187
+ SecurityCategory::WeakRandomness,
188
+ "weak-randomness",
189
+ SecurityBlindSpotReason::AmbiguousRandomProvenance,
190
+ ));
191
+ }
192
+ }
193
+ }
194
+
195
+ #[derive(Debug, Default)]
196
+ struct DartMathImports {
197
+ unprefixed: bool,
198
+ prefixes: BTreeSet<String>,
199
+ }
200
+
201
+ fn dart_math_imports(source: &str) -> DartMathImports {
202
+ let mut imports = DartMathImports::default();
203
+ for (_, line) in source_lines(source) {
204
+ let trimmed = line.trim();
205
+ if !trimmed.starts_with("import ")
206
+ || !(trimmed.contains("'dart:math'") || trimmed.contains("\"dart:math\""))
207
+ || trimmed.contains("hide Random")
208
+ || (trimmed.contains(" show ") && !shown_name(trimmed, "Random"))
209
+ {
210
+ continue;
211
+ }
212
+ if let Some(prefix) = trimmed
213
+ .split_once(" as ")
214
+ .map(|(_, tail)| identifier_prefix(tail))
215
+ .filter(|prefix| !prefix.is_empty())
216
+ {
217
+ imports.prefixes.insert(prefix.to_owned());
218
+ } else {
219
+ imports.unprefixed = true;
220
+ }
221
+ }
222
+ imports
223
+ }
224
+
225
+ fn confirmed_random_bindings(
226
+ source: &str,
227
+ root: Node<'_>,
228
+ imports: &DartMathImports,
229
+ aliases: &BTreeSet<String>,
230
+ factories: &BTreeSet<String>,
231
+ ) -> BTreeSet<String> {
232
+ let mut bindings = BTreeSet::new();
233
+ for index in random_indices(source) {
234
+ if !identifier_node_at(root, index)
235
+ || !random_constructor_at(source, index)
236
+ || secure_constructor_at(source, index)
237
+ || !random_has_provenance(source, index, imports)
238
+ {
239
+ continue;
240
+ }
241
+ if let Some(binding) = initialized_binding_name(root, source, index)
242
+ && !security_shaped_identifier(&binding)
243
+ && !flutter_key_context(source, index)
244
+ {
245
+ bindings.insert(binding);
246
+ }
247
+ }
248
+ for constructor in aliases.iter().chain(factories) {
249
+ for index in segment_indices(source, constructor) {
250
+ if !identifier_node_named_at(root, index, constructor)
251
+ || !source[index + constructor.len()..]
252
+ .trim_start()
253
+ .starts_with('(')
254
+ {
255
+ continue;
256
+ }
257
+ if let Some(binding) = initialized_binding_name(root, source, index)
258
+ && !security_shaped_identifier(&binding)
259
+ && !flutter_key_context(source, index)
260
+ {
261
+ bindings.insert(binding);
262
+ }
263
+ }
264
+ }
265
+ bindings
266
+ }
267
+
268
+ fn confirmed_random_type_aliases(source: &str, imports: &DartMathImports) -> BTreeSet<String> {
269
+ let mut aliases = BTreeSet::new();
270
+ for (offset, line) in source_lines(source) {
271
+ let trimmed = line.trim();
272
+ let Some((declaration, target)) = trimmed
273
+ .strip_prefix("typedef ")
274
+ .and_then(|typedef| typedef.split_once('='))
275
+ else {
276
+ continue;
277
+ };
278
+ let alias = identifier_prefix(declaration);
279
+ let target = target.trim().trim_end_matches(';').trim();
280
+ let target_is_random =
281
+ (target == "Random" && imports.unprefixed && !local_random_declaration(source))
282
+ || target.split_once('.').is_some_and(|(prefix, name)| {
283
+ name == "Random"
284
+ && imports.prefixes.contains(prefix)
285
+ && !prefix_shadowed(source, prefix, offset)
286
+ });
287
+ if !alias.is_empty() && target_is_random {
288
+ aliases.insert(alias.to_owned());
289
+ }
290
+ }
291
+ aliases
292
+ }
293
+
294
+ fn confirmed_random_factories(
295
+ source: &str,
296
+ root: Node<'_>,
297
+ imports: &DartMathImports,
298
+ ) -> BTreeSet<String> {
299
+ let mut factories = BTreeSet::new();
300
+ for index in random_indices(source) {
301
+ if !identifier_node_at(root, index) || !random_has_provenance(source, index, imports) {
302
+ continue;
303
+ }
304
+ let tearoff = source[index + "Random".len()..]
305
+ .trim_start()
306
+ .starts_with(".new");
307
+ if tearoff && let Some(binding) = initialized_binding_name(root, source, index) {
308
+ factories.insert(binding);
309
+ }
310
+ if !secure_constructor_at(source, index)
311
+ && let Some(factory) = returned_random_factory_name(root, source, index)
312
+ {
313
+ factories.insert(factory);
314
+ }
315
+ }
316
+ factories
317
+ }
318
+
319
+ fn confirmed_secure_random_factories(
320
+ source: &str,
321
+ root: Node<'_>,
322
+ imports: &DartMathImports,
323
+ ) -> BTreeSet<String> {
324
+ let mut factories = BTreeSet::new();
325
+ for index in random_indices(source) {
326
+ if !identifier_node_at(root, index)
327
+ || !secure_constructor_at(source, index)
328
+ || !random_has_provenance(source, index, imports)
329
+ {
330
+ continue;
331
+ }
332
+ if let Some(binding) = initialized_binding_name(root, source, index) {
333
+ factories.insert(binding);
334
+ }
335
+ if let Some(factory) = returned_random_factory_name(root, source, index) {
336
+ factories.insert(factory);
337
+ }
338
+ }
339
+ factories
340
+ }
341
+
342
+ fn returned_random_factory_name(root: Node<'_>, source: &str, index: usize) -> Option<String> {
343
+ if !random_constructor_is_return_value(root, index) {
344
+ return None;
345
+ }
346
+ let mut node = root.descendant_for_byte_range(index, index.saturating_add(1))?;
347
+ let mut returned = false;
348
+ while let Some(parent) = node.parent() {
349
+ returned |= parent.kind() == "return_statement";
350
+ if matches!(
351
+ parent.kind(),
352
+ "function_declaration"
353
+ | "local_function_declaration"
354
+ | "method_declaration"
355
+ | "function_expression"
356
+ ) {
357
+ let text = parent.utf8_text(source.as_bytes()).ok()?;
358
+ let relative_index = index.checked_sub(parent.start_byte())?;
359
+ let expression_body = text[..relative_index.min(text.len())].contains("=>");
360
+ if !returned && !expression_body {
361
+ return None;
362
+ }
363
+ if parent.kind() == "function_expression" {
364
+ return initialized_binding_name(root, source, index);
365
+ }
366
+ let header_end = text.find('(')?;
367
+ return Some(identifier_suffix(&text[..header_end]).to_owned());
368
+ }
369
+ node = parent;
370
+ }
371
+ None
372
+ }
373
+
374
+ fn random_constructor_is_return_value(root: Node<'_>, index: usize) -> bool {
375
+ let mut node = root.descendant_for_byte_range(index, index.saturating_add(1));
376
+ if node.is_some_and(|identifier| {
377
+ identifier
378
+ .parent()
379
+ .is_some_and(|parent| parent.kind() == "function_expression_body")
380
+ }) {
381
+ return true;
382
+ }
383
+ while let Some(current) = node {
384
+ if current.kind() == "call_expression" {
385
+ node = Some(current);
386
+ break;
387
+ }
388
+ node = current.parent();
389
+ }
390
+ let Some(mut value) = node else {
391
+ return false;
392
+ };
393
+ while value.parent().is_some_and(|parent| {
394
+ matches!(
395
+ parent.kind(),
396
+ "parenthesized_expression" | "null_assertion_expression"
397
+ )
398
+ }) {
399
+ value = value.parent().unwrap_or(value);
400
+ }
401
+ value.parent().is_some_and(|parent| {
402
+ matches!(
403
+ parent.kind(),
404
+ "return_statement" | "function_body" | "function_expression_body"
405
+ )
406
+ })
407
+ }
408
+
409
+ fn initialized_binding_name(root: Node<'_>, source: &str, index: usize) -> Option<String> {
410
+ let mut node = root.descendant_for_byte_range(index, index.saturating_add(1))?;
411
+ loop {
412
+ if matches!(
413
+ node.kind(),
414
+ "initialized_identifier"
415
+ | "initialized_variable_definition"
416
+ | "static_final_declaration"
417
+ ) && node
418
+ .child_by_field_name("value")
419
+ .is_some_and(|value| value.start_byte() <= index && value.end_byte() >= index)
420
+ {
421
+ if let Some(binding) = node
422
+ .child_by_field_name("name")
423
+ .and_then(|name| name.utf8_text(source.as_bytes()).ok())
424
+ .map(str::to_owned)
425
+ {
426
+ return Some(binding);
427
+ }
428
+ }
429
+ let Some(parent) = node.parent() else {
430
+ break;
431
+ };
432
+ node = parent;
433
+ }
434
+ statement_binding_name(source, index)
435
+ }
436
+
437
+ fn statement_binding_name(source: &str, index: usize) -> Option<String> {
438
+ let start = source[..index]
439
+ .rfind([';', '{', '}'])
440
+ .map_or(0, |position| position + 1);
441
+ let declaration = source[start..index].split_once('=')?.0;
442
+ declaration
443
+ .split(|character: char| !character.is_ascii_alphanumeric() && character != '_')
444
+ .rfind(|segment| !segment.is_empty())
445
+ .map(str::to_owned)
446
+ }
447
+
448
+ fn random_has_provenance(source: &str, index: usize, imports: &DartMathImports) -> bool {
449
+ let prefix = source[..index]
450
+ .trim_end()
451
+ .strip_suffix('.')
452
+ .map(identifier_suffix)
453
+ .unwrap_or_default();
454
+ if prefix.is_empty() {
455
+ imports.unprefixed && !local_random_declaration(source)
456
+ } else {
457
+ imports.prefixes.contains(prefix) && !prefix_shadowed(source, prefix, index)
458
+ }
459
+ }
460
+
461
+ fn random_indices(source: &str) -> Vec<usize> {
462
+ match_indices(source, "Random")
463
+ .into_iter()
464
+ .filter(|index| {
465
+ index
466
+ .checked_sub(1)
467
+ .and_then(|position| source.as_bytes().get(position))
468
+ .is_none_or(|byte| !is_identifier_byte(*byte))
469
+ })
470
+ .collect()
471
+ }
472
+
473
+ fn shown_name(import_line: &str, name: &str) -> bool {
474
+ import_line
475
+ .split_once(" show ")
476
+ .map(|(_, shown)| shown)
477
+ .unwrap_or_default()
478
+ .split(|character: char| !character.is_ascii_alphanumeric() && character != '_')
479
+ .any(|shown| shown == name)
480
+ }
481
+
482
+ fn local_random_declaration(source: &str) -> bool {
483
+ source_lines(source).any(|(_, line)| {
484
+ let trimmed = line.trim_start();
485
+ [
486
+ "class Random",
487
+ "mixin Random",
488
+ "enum Random",
489
+ "typedef Random",
490
+ ]
491
+ .iter()
492
+ .any(|declaration| trimmed.starts_with(declaration))
493
+ })
494
+ }
495
+
496
+ fn prefix_shadowed(source: &str, prefix: &str, use_index: usize) -> bool {
497
+ source_lines(&source[..use_index]).any(|(_, line)| {
498
+ ["final", "var", "const"].iter().any(|keyword| {
499
+ line.split_whitespace()
500
+ .zip(line.split_whitespace().skip(1))
501
+ .any(|(left, right)| {
502
+ left == *keyword
503
+ && right.trim_matches(|character: char| {
504
+ !character.is_ascii_alphanumeric() && character != '_'
505
+ }) == prefix
506
+ })
507
+ })
508
+ })
509
+ }
510
+
511
+ fn random_constructor_at(source: &str, index: usize) -> bool {
512
+ let after = source[index + "Random".len()..].trim_start();
513
+ after.starts_with('(') || after.starts_with(".secure")
514
+ }
515
+
516
+ fn secure_constructor_at(source: &str, index: usize) -> bool {
517
+ source[index + "Random".len()..]
518
+ .trim_start()
519
+ .starts_with(".secure")
520
+ }
521
+
522
+ fn identifier_node_at(root: Node<'_>, index: usize) -> bool {
523
+ identifier_node_named_at(root, index, "Random")
524
+ }
525
+
526
+ fn identifier_node_named_at(root: Node<'_>, index: usize, name: &str) -> bool {
527
+ root.descendant_for_byte_range(index, index + name.len())
528
+ .is_some_and(|node| {
529
+ matches!(
530
+ node.kind(),
531
+ "identifier" | "identifier_dollar_escaped" | "type_identifier"
532
+ ) && node.start_byte() == index
533
+ && node.end_byte() == index + name.len()
534
+ })
535
+ }
536
+
537
+ fn security_shaped_statement_context(source: &str, index: usize) -> bool {
538
+ let natural_start = source[..index]
539
+ .rfind([';', '{', '}'])
540
+ .map_or(0, |position| position + 1);
541
+ let start = natural_start.max(index.saturating_sub(512));
542
+ let natural_end = source[index..]
543
+ .find([';', '{', '}'])
544
+ .map_or(source.len(), |relative| index + relative);
545
+ let end = natural_end.min(index.saturating_add(512));
546
+ source.get(start..end).is_some_and(security_shaped_context)
547
+ }
548
+
549
+ fn security_shaped_context(line: &str) -> bool {
550
+ line.split(|character: char| !character.is_ascii_alphanumeric() && character != '_')
551
+ .any(security_shaped_identifier)
552
+ }
553
+
554
+ fn security_shaped_flow_context(root: Node<'_>, source: &str, index: usize) -> bool {
555
+ if security_shaped_context(line_at(source, index))
556
+ || security_shaped_statement_context(source, index)
557
+ {
558
+ return true;
559
+ }
560
+ let Some(mut node) = root.descendant_for_byte_range(index, index.saturating_add(1)) else {
561
+ return false;
562
+ };
563
+ while let Some(parent) = node.parent() {
564
+ if parent
565
+ .child_by_field_name("name")
566
+ .and_then(|name| name.utf8_text(source.as_bytes()).ok())
567
+ .is_some_and(security_shaped_identifier)
568
+ {
569
+ return true;
570
+ }
571
+ if parent.kind().contains("function") || parent.kind().contains("method") {
572
+ let header = parent
573
+ .utf8_text(source.as_bytes())
574
+ .ok()
575
+ .map(|text| text.find(['{', '=']).map_or(text, |end| &text[..end]));
576
+ if header.is_some_and(security_shaped_context) {
577
+ return true;
578
+ }
579
+ }
580
+ if parent.kind() == "class_declaration" {
581
+ return false;
582
+ }
583
+ node = parent;
584
+ }
585
+ false
586
+ }
587
+
588
+ fn security_shaped_identifier(identifier: &str) -> bool {
589
+ let segments = identifier_segments(identifier);
590
+ if strong_security_segments(&segments) {
591
+ return true;
592
+ }
593
+ let ambiguous_security_segment = segments
594
+ .iter()
595
+ .any(|segment| matches!(segment.as_str(), "key" | "session"));
596
+ let ui_or_simulation_name = segments.first().is_some_and(|segment| {
597
+ matches!(
598
+ segment.as_str(),
599
+ "animation" | "game" | "keyboard" | "map" | "simulation" | "ui" | "widget"
600
+ )
601
+ }) || segments.as_slice() == ["key", "code"];
602
+ ambiguous_security_segment && !ui_or_simulation_name
603
+ }
604
+
605
+ fn strong_security_segments(segments: &[String]) -> bool {
606
+ let strong_security_segment = segments.iter().any(|segment| {
607
+ SECURITY_SEGMENTS.contains(&segment.as_str())
608
+ && !matches!(segment.as_str(), "key" | "session")
609
+ });
610
+ let security_code = segments
611
+ .windows(2)
612
+ .any(|pair| pair[1] == "code" && SECURITY_CODE_PREFIXES.contains(&pair[0].as_str()));
613
+ strong_security_segment || security_code
614
+ }
615
+
616
+ fn non_security_enclosing_scope(root: Node<'_>, source: &str, index: usize) -> bool {
617
+ let line_has_strong_security = line_at(source, index)
618
+ .split(|character: char| !character.is_ascii_alphanumeric() && character != '_')
619
+ .map(identifier_segments)
620
+ .any(|segments| strong_security_segments(&segments));
621
+ if line_has_strong_security {
622
+ return false;
623
+ }
624
+ let Some(mut node) = root.descendant_for_byte_range(index, index.saturating_add(1)) else {
625
+ return false;
626
+ };
627
+ while let Some(parent) = node.parent() {
628
+ let scope_name = parent
629
+ .child_by_field_name("name")
630
+ .and_then(|name| name.utf8_text(source.as_bytes()).ok());
631
+ if scope_name.is_some_and(non_security_scope_name) {
632
+ return true;
633
+ }
634
+ if parent.kind() == "class_declaration" {
635
+ let header = parent
636
+ .utf8_text(source.as_bytes())
637
+ .ok()
638
+ .map(|text| text.find('{').map_or(text, |end| &text[..end]));
639
+ return header.is_some_and(non_security_scope_name);
640
+ }
641
+ node = parent;
642
+ }
643
+ false
644
+ }
645
+
646
+ fn non_security_scope_name(name: &str) -> bool {
647
+ identifier_segments(name).iter().any(|segment| {
648
+ matches!(
649
+ segment.as_str(),
650
+ "animation" | "game" | "keyboard" | "map" | "simulation" | "ui" | "widget"
651
+ )
652
+ })
653
+ }
654
+
655
+ fn identifier_segments(identifier: &str) -> Vec<String> {
656
+ let mut segments = Vec::new();
657
+ let mut current = String::new();
658
+ let characters = identifier.chars().collect::<Vec<_>>();
659
+ for (index, character) in characters.iter().copied().enumerate() {
660
+ if character == '_' || character == '-' {
661
+ if !current.is_empty() {
662
+ segments.push(std::mem::take(&mut current));
663
+ }
664
+ } else if character.is_ascii_uppercase()
665
+ && !current.is_empty()
666
+ && (characters[index - 1].is_ascii_lowercase()
667
+ || characters
668
+ .get(index + 1)
669
+ .is_some_and(char::is_ascii_lowercase))
670
+ {
671
+ segments.push(std::mem::take(&mut current));
672
+ current.push(character.to_ascii_lowercase());
673
+ } else {
674
+ current.push(character.to_ascii_lowercase());
675
+ }
676
+ }
677
+ if !current.is_empty() {
678
+ segments.push(current);
679
+ }
680
+ segments
681
+ }
682
+
683
+ fn ambiguous_random_constructor(line: &str, known_factories: &BTreeSet<String>) -> bool {
684
+ match_indices(line, "Random").into_iter().any(|index| {
685
+ let before = index
686
+ .checked_sub(1)
687
+ .and_then(|position| line.as_bytes().get(position))
688
+ .copied();
689
+ if !before.is_some_and(is_identifier_byte)
690
+ || !line[index + "Random".len()..].trim_start().starts_with('(')
691
+ {
692
+ return false;
693
+ }
694
+ let identifier_start = line[..index]
695
+ .rfind(|character: char| !character.is_ascii_alphanumeric() && character != '_')
696
+ .map_or(0, |position| position + 1);
697
+ let identifier = &line[identifier_start..index + "Random".len()];
698
+ identifier
699
+ .chars()
700
+ .next()
701
+ .is_some_and(|character| character.is_ascii_uppercase())
702
+ && !known_factories.contains(identifier)
703
+ })
704
+ }
705
+
706
+ fn flutter_key_context(source: &str, index: usize) -> bool {
707
+ let start = source[..index]
708
+ .rfind([';', '{', '}', '\n'])
709
+ .map_or(0, |position| position + 1);
710
+ let context = &source[start..index];
711
+ ["ValueKey(", "PageStorageKey(", "ObjectKey("]
712
+ .iter()
713
+ .any(|constructor| context.contains(constructor))
714
+ }
715
+
716
+ fn member_access_index(line: &str, binding: &str) -> Option<usize> {
717
+ segment_indices(line, binding)
718
+ .into_iter()
719
+ .find(|index| line[index + binding.len()..].trim_start().starts_with('.'))
720
+ }
721
+
722
+ fn constructor_call_index(line: &str, constructor: &str) -> Option<usize> {
723
+ segment_indices(line, constructor)
724
+ .into_iter()
725
+ .find(|index| {
726
+ line[index + constructor.len()..]
727
+ .trim_start()
728
+ .starts_with('(')
729
+ })
730
+ }
731
+
732
+ fn source_lines(source: &str) -> impl Iterator<Item = (usize, &str)> {
733
+ source.split_inclusive('\n').scan(0, |offset, line| {
734
+ let start = *offset;
735
+ *offset += line.len();
736
+ Some((start, line.trim_end_matches('\n')))
737
+ })
738
+ }
739
+
740
+ fn line_start(source: &str, index: usize) -> usize {
741
+ source[..index]
742
+ .rfind('\n')
743
+ .map_or(0, |position| position + 1)
744
+ }
745
+
746
+ fn first_non_whitespace(line: &str) -> usize {
747
+ line.find(|character: char| !character.is_whitespace())
748
+ .unwrap_or(0)
749
+ }
750
+
751
+ fn identifier_prefix(text: &str) -> &str {
752
+ text.trim_start()
753
+ .split(|character: char| !character.is_ascii_alphanumeric() && character != '_')
754
+ .next()
755
+ .unwrap_or_default()
756
+ }
757
+
758
+ fn identifier_suffix(text: &str) -> &str {
759
+ text.rsplit(|character: char| !character.is_ascii_alphanumeric() && character != '_')
760
+ .next()
761
+ .unwrap_or_default()
762
+ }