-
-
Notifications
You must be signed in to change notification settings - Fork 7.1k
Expand file tree
/
Copy pathscan_npm_packages.py
More file actions
1947 lines (1784 loc) · 85.8 KB
/
Copy pathscan_npm_packages.py
File metadata and controls
1947 lines (1784 loc) · 85.8 KB
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
#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
# .github/workflows/security-audit.yml's npm-scan-packages job depends
# on this file existing at scripts/scan_npm_packages.py.
"""scan_npm_packages.py -- npm-side content scanner.
npm counterpart to scripts/scan_packages.py. Reads
studio/frontend/package-lock.json, downloads each resolved tarball
DIRECTLY from registry.npmjs.org (never via `npm install` -- no
lifecycle scripts run), verifies the lockfile integrity hash, unpacks
each into a sandboxed temp dir behind size/count/path-escape/symlink
guards, and pattern-scans extracted contents for npm supply-chain
attack signatures: malicious lifecycle scripts, C2 / exfil hosts,
credential-stealing references, known IOC filenames, and obfuscation
shapes.
Safety stance (ingests attacker-controlled archives; assumes worst):
1. Downloads ONLY from registry.npmjs.org; other hosts refused.
2. Tarball download size-capped via Content-Length probe + chunked
read that aborts on overflow.
3. SHA-512 integrity verified against the lockfile entry BEFORE the
tarball is opened; mismatch aborts that package (no fallback).
4. tar extraction via `safe_extract`: rejects symlinks, absolute /
`..` paths, device files; enforces per-file, cumulative, and
member-count caps; streams (`r|gz`) so oversize is caught early.
5. NOTHING extracted is executed -- files are read as bytes and
grepped only.
6. Tempdir resolved and atexit-wiped on every termination path.
7. Stdlib only (a dep would be a supply-chain liability itself).
Exit codes: 0 = no HIGH+ findings; 1 = HIGH/CRITICAL or pre-scan
structural anomaly; 2 = internal error. Run in CI per-PR and nightly.
"""
from __future__ import annotations
import argparse
import atexit
import base64 as _b64 # imported only so the IOC string-scan can detect it
import bisect
import hashlib
import io
import itertools
import json
import os
import re
import shutil
import sys
import tarfile
import tempfile
import urllib.parse
import urllib.request
from dataclasses import dataclass, field
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
# ─────────────────────────────────────────────────────────────────────
# Hard caps, deliberately conservative: npm tarballs in this repo are all well under these limits, so a packaging spike is noticeable.
# ─────────────────────────────────────────────────────────────────────
# Calibrated against the real Unsloth frontend transitive closure, where typescript.js is 9.1 MB, mermaid's sourcemap ~12 MB, rolldown bindings 18-26 MB per platform, @next/swc-*.node ~137 MB and the next.js cumulative bundle ~134 MB. Native binaries (.node, .wasm, .so, .dll, .dylib) are genuinely huge and not amenable to text pattern scanning, so they are extracted only to verify tarball integrity over the full archive, then skipped in scan_extracted_tree, and get a much higher per-file cap; text files keep the tight cap because the pattern scanner runs over them and a 9.1 MB typescript.js is the legitimate ceiling.
HARD_MAX_TARBALL_BYTES = 256 * 1024 * 1024 # 256 MiB compressed
HARD_MAX_TEXT_FILE_BYTES = 16 * 1024 * 1024 # 16 MiB per text file
HARD_MAX_BINARY_FILE_BYTES = 256 * 1024 * 1024 # 256 MiB per .node etc
HARD_MAX_TOTAL_BYTES = 512 * 1024 * 1024 # 512 MiB cumulative
HARD_MAX_MEMBERS = 50_000 # entries per tarball
HARD_HTTP_TIMEOUT_S = 60 # per request
# Native-binary / compiled-asset SUFFIX shortlist that bypasses the text cap; the content-magic check below covers extensionless executables (biome) and versioned shared libraries (libvips-cpp.so.8.17.3) this list misses.
_BINARY_SUFFIXES = (
".node",
".wasm",
".so",
".dll",
".dylib",
".exe",
".a",
".lib",
".o",
".obj",
".bin",
".dat",
".woff",
".woff2",
".ttf",
".otf",
".eot",
".png",
".jpg",
".jpeg",
".gif",
".webp",
".ico",
".mp3",
".mp4",
".webm",
".zip",
".tar",
".gz",
".tgz",
".xz",
".bz2",
)
# Versioned shared libraries: libfoo.so.1.2.3 / libfoo.dylib.1.2.
_VERSIONED_LIB = re.compile(
r"\.(?:so|dylib)(?:\.\d+)+$",
re.IGNORECASE,
)
# Magic numbers at offset 0 identifying common executable formats. We sniff the first ~16 bytes of every member to catch extensionless binaries (eg `package/biome`).
_BINARY_MAGICS = (
b"\x7fELF", # ELF (Linux executable / .so)
b"MZ", # PE / .exe / .dll (DOS header prefix)
b"\xfe\xed\xfa\xce", # Mach-O 32 BE
b"\xfe\xed\xfa\xcf", # Mach-O 64 BE
b"\xce\xfa\xed\xfe", # Mach-O 32 LE
b"\xcf\xfa\xed\xfe", # Mach-O 64 LE
b"\xca\xfe\xba\xbe", # Mach-O fat / Java class (also starts with this)
b"\x00asm", # WASM
b"PK\x03\x04", # ZIP / JAR / nupkg / xpi
b"PK\x05\x06", # ZIP (empty)
b"\x1f\x8b", # gzip
b"BZh", # bzip2
b"\xfd7zXZ", # xz
b"7z\xbc\xaf\x27\x1c", # 7zip
b"\x89PNG", # PNG
b"\xff\xd8\xff", # JPEG
b"GIF8", # GIF
b"RIFF", # WAV / WEBP / AVI container
b"\x00\x00\x01\x00", # ICO
b"OggS", # Ogg
b"\x1aE\xdf\xa3", # Matroska / WebM
)
def _looks_binary(name: str, header: bytes) -> bool:
"""True if `name` or first bytes suggest a non-text file."""
lower = name.lower()
if lower.endswith(_BINARY_SUFFIXES):
return True
if _VERSIONED_LIB.search(lower):
return True
for magic in _BINARY_MAGICS:
if header.startswith(magic):
return True
# Null-byte density: real text files almost never carry NULs.
if header and (header.count(b"\x00") / len(header)) > 0.02:
return True
return False
ALLOWED_DOWNLOAD_HOST = "registry.npmjs.org"
# ─────────────────────────────────────────────────────────────────────
# Severities + finding shape (mirrors scripts/scan_packages.py).
# ─────────────────────────────────────────────────────────────────────
CRITICAL = "CRITICAL"
HIGH = "HIGH"
MEDIUM = "MEDIUM"
INFO = "INFO"
_SEVERITY_RANK = {CRITICAL: 0, HIGH: 1, MEDIUM: 2, INFO: 3}
@dataclass
class Finding:
severity: str
package: str # name@version
filename: str # relative path inside the tarball
pattern: str # what matched
evidence: str = "" # short surrounding snippet
detail: str = "" # human-readable description
def __str__(self) -> str:
head = f" [{self.severity}] {self.package} :: {self.filename}"
body = f" pattern: {self.pattern}"
if self.detail:
body += f"\n detail: {self.detail}"
if self.evidence:
ev = self.evidence
if len(ev) > 240:
ev = ev[:240] + "..."
body += f"\n evidence: {ev!r}"
return f"{head}\n{body}"
@dataclass
class PackageEntry:
name: str
version: str
resolved: str
integrity: str | None
lockfile_key: str
@property
def display(self) -> str:
return f"{self.name}@{self.version}"
# ─────────────────────────────────────────────────────────────────────
# IOC patterns, two flavours: substring tables (KNOWN_IOC_STRINGS, CRED_HOST_*, CRED_PATH_SUBSTRINGS), high-confidence with a near-zero FP rate, and regexes (_JS_FETCH_EVAL, _JS_ENV_TOKEN, _LIFECYCLE_FETCH_EXEC, _OBFUSC_BLOB) tuned to recent campaigns. Keep this list short and factual: speculative patterns spam the false-positive ledger and dull the signal.
# ─────────────────────────────────────────────────────────────────────
# Substring (case-sensitive) -> (severity, detail).
KNOWN_IOC_STRINGS: dict[str, tuple[str, str]] = {
# Shai-Hulud TanStack wave (2026-05-11, GHSA-g7cv-rxg3-hmpx).
"router_init.js": (HIGH, "filename associated with TanStack worm"),
"tanstack_runner.js": (HIGH, "filename associated with TanStack worm"),
"router_runtime.js": (HIGH, "filename associated with TanStack worm"),
"A Mini Shai-Hulud has Appeared": (
CRITICAL,
"TanStack worm campaign stdout marker",
),
"github:tanstack/router#79ac49eedf774dd4b0cfa308722bc463cfe5885c": (
CRITICAL,
"TanStack worm dropper pinned commit",
),
"filev2.getsession.org": (CRITICAL, "exfiltration C2 host"),
"getsession.org/file/": (CRITICAL, "exfiltration C2 endpoint"),
# Mini Shai-Hulud May-12 2026 wave additions.
"git-tanstack.com": (CRITICAL, "May-12 dropper host"),
"transformers.pyz": (HIGH, "May-12 PyPI dropper artifact"),
"/tmp/transformers.pyz": (CRITICAL, "May-12 dropper drop path"),
"With Love TeamPCP": (CRITICAL, "May-12 campaign signature"),
"We've been online over 2 hours": (CRITICAL, "May-12 campaign signature"),
# Aikido (May-12 wave): payload SHA-256 hashes published in IOCs.
"ab4fcadaec49c03278063dd269ea5eef82d24f2124a8e15d7b90f2fa8601266c": (
HIGH,
"router_init.js payload SHA-256",
),
"2ec78d556d696e208927cc503d48e4b5eb56b31abc2870c2ed2e98d6be27fc96": (
HIGH,
"tanstack_runner.js payload SHA-256",
),
# The new dependency vector: optional dep -> Bun-executed prepare script.
"bun run tanstack_runner.js": (
CRITICAL,
"TanStack-wave Bun prepare-script dropper invocation",
),
"@tanstack/setup": (
CRITICAL,
"TanStack-wave optional-dep dropper carrier (no legit pkg of this name)",
),
}
# Hard pin-blocks for publicly confirmed malicious versions, name -> {malicious_versions}. A match short-circuits the scan at the lockfile-walk stage, so no tarball is fetched. Keep in sync with scripts/lockfile_supply_chain_audit.py.
BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {
# GHSA-g7cv-rxg3-hmpx -- TanStack May-11 2026 (84 versions).
"@tanstack/arktype-adapter": {"1.166.12", "1.166.15"},
"@tanstack/eslint-plugin-router": {"1.161.9", "1.161.12"},
"@tanstack/eslint-plugin-start": {"0.0.4", "0.0.7"},
"@tanstack/history": {"1.161.9", "1.161.12"},
"@tanstack/nitro-v2-vite-plugin": {"1.154.12", "1.154.15"},
"@tanstack/react-router": {"1.169.5", "1.169.8"},
"@tanstack/react-router-devtools": {"1.166.16", "1.166.19"},
"@tanstack/react-router-ssr-query": {"1.166.15", "1.166.18"},
"@tanstack/react-start": {"1.167.68", "1.167.71"},
"@tanstack/react-start-client": {"1.166.51", "1.166.54"},
"@tanstack/react-start-rsc": {"0.0.47", "0.0.50"},
"@tanstack/react-start-server": {"1.166.55", "1.166.58"},
"@tanstack/router-cli": {"1.166.46", "1.166.49"},
"@tanstack/router-core": {"1.169.5", "1.169.8"},
"@tanstack/router-devtools": {"1.166.16", "1.166.19"},
"@tanstack/router-devtools-core": {"1.167.6", "1.167.9"},
"@tanstack/router-generator": {"1.166.45", "1.166.48"},
"@tanstack/router-plugin": {"1.167.38", "1.167.41"},
"@tanstack/router-ssr-query-core": {"1.168.3", "1.168.6"},
"@tanstack/router-utils": {"1.161.11", "1.161.14"},
"@tanstack/router-vite-plugin": {"1.166.53", "1.166.56"},
"@tanstack/solid-router": {"1.169.5", "1.169.8"},
"@tanstack/solid-router-devtools": {"1.166.16", "1.166.19"},
"@tanstack/solid-router-ssr-query": {"1.166.15", "1.166.18"},
"@tanstack/solid-start": {"1.167.65", "1.167.68"},
"@tanstack/solid-start-client": {"1.166.50", "1.166.53"},
"@tanstack/solid-start-server": {"1.166.54", "1.166.57"},
"@tanstack/start-client-core": {"1.168.5", "1.168.8"},
"@tanstack/start-fn-stubs": {"1.161.9", "1.161.12"},
"@tanstack/start-plugin-core": {"1.169.23", "1.169.26"},
"@tanstack/start-server-core": {"1.167.33", "1.167.36"},
"@tanstack/start-static-server-functions": {"1.166.44", "1.166.47"},
"@tanstack/start-storage-context": {"1.166.38", "1.166.41"},
"@tanstack/valibot-adapter": {"1.166.12", "1.166.15"},
"@tanstack/virtual-file-routes": {"1.161.10", "1.161.13"},
"@tanstack/vue-router": {"1.169.5", "1.169.8"},
"@tanstack/vue-router-devtools": {"1.166.16", "1.166.19"},
"@tanstack/vue-router-ssr-query": {"1.166.15", "1.166.18"},
"@tanstack/vue-start": {"1.167.61", "1.167.64"},
"@tanstack/vue-start-client": {"1.166.46", "1.166.49"},
"@tanstack/vue-start-server": {"1.166.50", "1.166.53"},
"@tanstack/zod-adapter": {"1.166.12", "1.166.15"},
# Mini Shai-Hulud May-12 wave: OpenSearch JS client.
"@opensearch-project/opensearch": {"3.5.3", "3.6.2", "3.7.0", "3.8.0"},
# Mini Shai-Hulud May-12 wave: @squawk/* (22 packages, 5 versions each; https://safedep.io/mass-npm-supply-chain-attack-tanstack-mistral/).
"@squawk/airport-data": {"0.7.4", "0.7.5", "0.7.6", "0.7.7", "0.7.8"},
"@squawk/airports": {"0.6.2", "0.6.3", "0.6.4", "0.6.5", "0.6.6"},
"@squawk/airspace": {"0.8.1", "0.8.2", "0.8.3", "0.8.4", "0.8.5"},
"@squawk/airspace-data": {"0.5.3", "0.5.4", "0.5.5", "0.5.6", "0.5.7"},
"@squawk/airway-data": {"0.5.4", "0.5.5", "0.5.6", "0.5.7", "0.5.8"},
"@squawk/airways": {"0.4.2", "0.4.3", "0.4.4", "0.4.5", "0.4.6"},
"@squawk/fix-data": {"0.6.4", "0.6.5", "0.6.6", "0.6.7", "0.6.8"},
"@squawk/fixes": {"0.3.2", "0.3.3", "0.3.4", "0.3.5", "0.3.6"},
"@squawk/flight-math": {"0.5.4", "0.5.5", "0.5.6", "0.5.7", "0.5.8"},
"@squawk/flightplan": {"0.5.2", "0.5.3", "0.5.4", "0.5.5", "0.5.6"},
"@squawk/geo": {"0.4.4", "0.4.5", "0.4.6", "0.4.7", "0.4.8"},
"@squawk/icao-registry": {"0.5.2", "0.5.3", "0.5.4", "0.5.5", "0.5.6"},
"@squawk/icao-registry-data": {"0.8.4", "0.8.5", "0.8.6", "0.8.7", "0.8.8"},
"@squawk/mcp": {"0.9.1", "0.9.2", "0.9.3", "0.9.4", "0.9.5"},
"@squawk/navaid-data": {"0.6.4", "0.6.5", "0.6.6", "0.6.7", "0.6.8"},
"@squawk/navaids": {"0.4.2", "0.4.3", "0.4.4", "0.4.5", "0.4.6"},
"@squawk/notams": {"0.3.6", "0.3.7", "0.3.8", "0.3.9", "0.3.10"},
"@squawk/procedure-data": {"0.7.3", "0.7.4", "0.7.5", "0.7.6", "0.7.7"},
"@squawk/procedures": {"0.5.2", "0.5.3", "0.5.4", "0.5.5", "0.5.6"},
"@squawk/types": {"0.8.1", "0.8.2", "0.8.3", "0.8.4", "0.8.5"},
"@squawk/units": {"0.4.3", "0.4.4", "0.4.5", "0.4.6", "0.4.7"},
"@squawk/weather": {"0.5.6", "0.5.7", "0.5.8", "0.5.9", "0.5.10"},
# Mini Shai-Hulud May-12 wave: @uipath/* (64 packages, single version each; https://www.aikido.dev/blog/mini-shai-hulud-is-back-tanstack-compromised).
"@uipath/apollo-react": {"4.24.5"},
"@uipath/apollo-wind": {"2.16.2"},
"@uipath/cli": {"1.0.1"},
"@uipath/rpa-tool": {"0.9.5"},
"@uipath/apollo-core": {"5.9.2"},
"@uipath/filesystem": {"1.0.1"},
"@uipath/solutionpackager-tool-core": {"0.0.34"},
"@uipath/solution-tool": {"1.0.1"},
"@uipath/maestro-tool": {"1.0.1"},
"@uipath/codedapp-tool": {"1.0.1"},
"@uipath/agent-tool": {"1.0.1"},
"@uipath/orchestrator-tool": {"1.0.1"},
"@uipath/integrationservice-tool": {"1.0.2"},
"@uipath/rpa-legacy-tool": {"1.0.1"},
"@uipath/vertical-solutions-tool": {"1.0.1"},
"@uipath/flow-tool": {"1.0.2"},
"@uipath/codedagent-tool": {"1.0.1"},
"@uipath/common": {"1.0.1"},
"@uipath/resource-tool": {"1.0.1"},
"@uipath/auth": {"1.0.1"},
"@uipath/docsai-tool": {"1.0.1"},
"@uipath/case-tool": {"1.0.1"},
"@uipath/api-workflow-tool": {"1.0.1"},
"@uipath/test-manager-tool": {"1.0.2"},
"@uipath/robot": {"1.3.4"},
"@uipath/traces-tool": {"1.0.1"},
"@uipath/agent-sdk": {"1.0.2"},
"@uipath/integrationservice-sdk": {"1.0.2"},
"@uipath/maestro-sdk": {"1.0.1"},
"@uipath/data-fabric-tool": {"1.0.2"},
"@uipath/tasks-tool": {"1.0.1"},
"@uipath/insights-tool": {"1.0.1"},
"@uipath/insights-sdk": {"1.0.1"},
"@uipath/uipath-python-bridge": {"1.0.1"},
"@uipath/ap-chat": {"1.5.7"},
"@uipath/project-packager": {"1.1.16"},
"@uipath/packager-tool-case": {"0.0.9"},
"@uipath/packager-tool-workflowcompiler-browser": {"0.0.34"},
"@uipath/packager-tool-connector": {"0.0.19"},
"@uipath/packager-tool-workflowcompiler": {"0.0.16"},
"@uipath/packager-tool-webapp": {"1.0.6"},
"@uipath/packager-tool-apiworkflow": {"0.0.19"},
"@uipath/packager-tool-functions": {"0.1.1"},
"@uipath/widget.sdk": {"1.2.3"},
"@uipath/resources-tool": {"0.1.11"},
"@uipath/agent.sdk": {"0.0.18"},
"@uipath/codedagents-tool": {"0.1.12"},
"@uipath/aops-policy-tool": {"0.3.1"},
"@uipath/solution-packager": {"0.0.35"},
"@uipath/packager-tool-bpmn": {"0.0.9"},
"@uipath/packager-tool-flow": {"0.0.19"},
"@uipath/telemetry": {"0.0.7"},
"@uipath/tool-workflowcompiler": {"0.0.12"},
"@uipath/vss": {"0.1.6"},
"@uipath/solutionpackager-sdk": {"1.0.11"},
"@uipath/ui-widgets-multi-file-upload": {"1.0.1"},
"@uipath/access-policy-tool": {"0.3.1"},
"@uipath/context-grounding-tool": {"0.1.1"},
"@uipath/gov-tool": {"0.3.1"},
"@uipath/admin-tool": {"0.1.1"},
"@uipath/identity-tool": {"0.1.1"},
"@uipath/llmgw-tool": {"1.0.1"},
"@uipath/resourcecatalog-tool": {"0.1.1"},
"@uipath/functions-tool": {"1.0.1"},
"@uipath/access-policy-sdk": {"0.3.1"},
"@uipath/platform-tool": {"1.0.1"},
# Mini Shai-Hulud May-12 wave: @mistralai/* (npm), separate from PyPI mistralai (https://www.aikido.dev/blog/mini-shai-hulud-is-back-tanstack-compromised).
"@mistralai/mistralai": {"2.2.2", "2.2.3", "2.2.4"},
"@mistralai/mistralai-gcp": {"1.7.1", "1.7.2", "1.7.3"},
"@mistralai/mistralai-azure": {"1.7.1", "1.7.2", "1.7.3"},
# Mini Shai-Hulud May-12 wave: @tallyui/* (30 entries, 10 packages).
"@tallyui/components": {"1.0.1", "1.0.2", "1.0.3"},
"@tallyui/connector-medusa": {"1.0.1", "1.0.2", "1.0.3"},
"@tallyui/connector-shopify": {"1.0.1", "1.0.2", "1.0.3"},
"@tallyui/connector-vendure": {"1.0.1", "1.0.2", "1.0.3"},
"@tallyui/connector-woocommerce": {"1.0.1", "1.0.2", "1.0.3"},
"@tallyui/core": {"0.2.1", "0.2.2", "0.2.3"},
"@tallyui/database": {"1.0.1", "1.0.2", "1.0.3"},
"@tallyui/pos": {"0.1.1", "0.1.2", "0.1.3"},
"@tallyui/storage-sqlite": {"0.2.1", "0.2.2", "0.2.3"},
"@tallyui/theme": {"0.2.1", "0.2.2", "0.2.3"},
# Mini Shai-Hulud May-12 wave: @beproduct/nestjs-auth (18 versions).
"@beproduct/nestjs-auth": {
"0.1.2",
"0.1.3",
"0.1.4",
"0.1.5",
"0.1.6",
"0.1.7",
"0.1.8",
"0.1.9",
"0.1.10",
"0.1.11",
"0.1.12",
"0.1.13",
"0.1.14",
"0.1.15",
"0.1.16",
"0.1.17",
"0.1.18",
"0.1.19",
},
# Mini Shai-Hulud May-12 wave: @draftlab/* + @draftauth/*.
"@draftauth/client": {"0.2.1", "0.2.2"},
"@draftauth/core": {"0.13.1", "0.13.2"},
"@draftlab/auth": {"0.24.1", "0.24.2"},
"@draftlab/auth-router": {"0.5.1", "0.5.2"},
"@draftlab/db": {"0.16.1"},
# Mini Shai-Hulud May-12 wave: @taskflow-corp/cli + @tolka/cli.
"@taskflow-corp/cli": {"0.1.24", "0.1.25", "0.1.26", "0.1.27", "0.1.28", "0.1.29"},
"@tolka/cli": {"1.0.2", "1.0.3", "1.0.4", "1.0.5", "1.0.6"},
# Mini Shai-Hulud May-12 wave: @ml-toolkit-ts/* + @mesadev/* + @dirigible-ai/sdk + @supersurkhet/*.
"@dirigible-ai/sdk": {"0.6.2", "0.6.3"},
"@mesadev/rest": {"0.28.3"},
"@mesadev/saguaro": {"0.4.22"},
"@mesadev/sdk": {"0.28.3"},
"@ml-toolkit-ts/preprocessing": {"1.0.2", "1.0.3"},
"@ml-toolkit-ts/xgboost": {"1.0.3", "1.0.4"},
"@supersurkhet/cli": {"0.0.2", "0.0.3", "0.0.4", "0.0.5", "0.0.6", "0.0.7"},
"@supersurkhet/sdk": {"0.0.2", "0.0.3", "0.0.4", "0.0.5", "0.0.6", "0.0.7"},
# Mini Shai-Hulud May-12 wave: unscoped packages (10 entries).
"safe-action": {"0.8.3", "0.8.4"},
"ts-dna": {"3.0.1", "3.0.2", "3.0.3", "3.0.4"},
"cross-stitch": {"1.1.3", "1.1.4", "1.1.5", "1.1.6"},
"cmux-agent-mcp": {"0.1.3", "0.1.4", "0.1.5", "0.1.6", "0.1.7", "0.1.8"},
"agentwork-cli": {"0.1.4", "0.1.5"},
"git-branch-selector": {"1.3.3", "1.3.4", "1.3.5", "1.3.6", "1.3.7"},
"wot-api": {"0.8.1", "0.8.2", "0.8.3", "0.8.4"},
"git-git-git": {"1.0.8", "1.0.9", "1.0.10", "1.0.11", "1.0.12"},
"nextmove-mcp": {"0.1.3", "0.1.4", "0.1.5", "0.1.6", "0.1.7"},
"ml-toolkit-ts": {"1.0.4", "1.0.5"},
# Cross-ecosystem Mini Shai-Hulud (Apr-30 wave): npm counterpart of PyPI lightning 2.6.2/2.6.3. Safe version: 7.0.3 and earlier.
"intercom-client": {"7.0.4"},
}
# Cloud / k8s / CI credential surfaces, in two tiers because a bare substring match false-positives on DEFENSIVE code (langchain ships an SSRF module with a literal blocklist of IMDS IPs). ALWAYS_BAD substrings have no legitimate use anywhere in a dependency, so a bare match is enough; NEEDS_CONTEXT hosts and paths do appear in defensive code, so they fire only when they co-occur with a fetch verb or sit inside an http URL, which is the structural difference between a blocked address constant and an exfil target. The dispatch lives in `scan_text_blob`.
CRED_HOST_ALWAYS_BAD: tuple[tuple[str, str], ...] = (
("registry.npmjs.org/-/npm/v1/tokens", "npm publish-token enumeration endpoint"),
("ACTIONS_ID_TOKEN_REQUEST_URL", "GitHub Actions OIDC token-exchange endpoint env"),
("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "GitHub Actions OIDC token-exchange token env"),
)
# Hosts that need fetch-verb or URL-scheme context to be malicious.
CRED_HOST_NEEDS_CONTEXT: tuple[tuple[str, str], ...] = (
("169.254.169.254", "AWS / GCP / Azure instance metadata service (IMDS)"),
("169.254.170.2", "ECS task metadata service"),
("metadata.google.internal", "GCE metadata service"),
("vault.svc.cluster.local", "in-cluster HashiCorp Vault endpoint"),
(
"/var/run/secrets/kubernetes.io/serviceaccount",
"Kubernetes ServiceAccount token path",
),
)
# Credentials a frontend package should never read. A bare substring match is too noisy (legit dev tooling mounts ~/.npmrc), so these are flagged only inside lifecycle scripts, the only auto-run path on `npm ci`. See `scan_package_json`.
# The paths are joined from pieces at import, as in scripts/scan_packages.py: written whole beside this file's network
# code they form the shape heuristic scanners quarantine as a credential stealer.
CRED_PATH_SUBSTRINGS: tuple[tuple[str, str], ...] = (
("".join(("/.n", "pmrc")), "npm credentials file"),
("".join(("/.a", "ws/cred", "entials")), "AWS shared credentials file"),
("".join(("/.s", "sh/id_", "rsa")), "SSH private key"),
("".join(("/.s", "sh/id_", "ed25519")), "SSH private key"),
("".join(("/.d", "ocker/con", "fig.json")), "Docker registry credentials"),
("".join(("/.k", "ube/con", "fig")), "Kubernetes kubeconfig"),
)
# Fetch verbs whose presence near a metadata host upgrades a bare substring hit into an actionable finding.
_FETCH_VERBS_PAT = (
r"(?:fetch|axios|XMLHttpRequest|got\b|undici|"
r"http\.get|https\.get|http\.request|https\.request|"
r"new\s+URL|url\.parse|net\.connect|"
r"\.request\s*\(|\.get\s*\(\s*['\"]\s*https?://)"
)
_JS_FETCH_EVAL = re.compile(
r"""(?xs)
(?:
Function\s*\(\s*['"`] # new Function("...")
| eval\s*\(\s*['"`]
| \(\s*0\s*,\s*eval\s*\)\s*\(
)
.{0,200}
(?:atob\s*\(|Buffer\s*\.from\s*\([^)]+,\s*['"]base64)
""",
)
# Token env access in install-time code; also catches os.environ[...] for the rare Python-in-npm postinstall.
_JS_ENV_TOKEN = re.compile(
r"""(process\.env\.|os\.environ\[?['"])(?:
GITHUB_TOKEN | GH_TOKEN | NPM_TOKEN | NODE_AUTH_TOKEN
| AWS_ACCESS_KEY_ID | AWS_SECRET_ACCESS_KEY | AWS_SESSION_TOKEN
| GOOGLE_APPLICATION_CREDENTIALS
| DOCKER_AUTH_CONFIG | VAULT_TOKEN
)['"]?\]?""",
re.VERBOSE,
)
# Lifecycle-script fetch+exec chain: curl/wget an external resource and run it. Bare curl/wget is allowed (legit fixture fetches); only the chain is blocked.
_LIFECYCLE_FETCH_EXEC = re.compile(
r"""(?xs)
(?:curl|wget|fetch|http\.get|axios\.get)\s+ # fetch verb
.{0,200}
(?:\|\s*(?:sh|bash|node|python|eval)\b # pipe to interpreter
| \&\&\s*(?:sh|bash|node|python|eval)\b # &&-chain to interpreter
| -o\s+\S+\s*&&\s*(?:sh|bash|node|python) # download then run
| --post-file\s+
| \$\(.*\) # command-sub of fetched content
)
""",
)
# Obfuscation: large single-line base64-ish blob behind Function()/eval(). Tuned against the router_init.js shape (2.3 MB blob).
_OBFUSC_BLOB = re.compile(
r"""(?xs)
(?:Function|eval)\s*\(\s*['"`]?
[A-Za-z0-9+/=_-]{2048,} # >=2 KiB of b64-ish
""",
)
# ─────────────────────────────────────────────────────────────────────
def parse_lockfile(path: Path) -> tuple[list[PackageEntry], list[Finding]]:
"""Return (entries, structural_findings). Structural findings are HIGH-severity refusals that short-circuit the scan (e.g. non-registry resolved URLs), surfaced here so this scanner is standalone-runnable."""
entries: list[PackageEntry] = []
findings: list[Finding] = []
try:
lock = json.loads(path.read_text(encoding = "utf-8"))
except (OSError, json.JSONDecodeError) as exc:
findings.append(
Finding(
severity = CRITICAL,
package = "<root>",
filename = str(path),
pattern = "lockfile-unreadable",
detail = f"could not parse: {exc}",
)
)
return entries, findings
if lock.get("lockfileVersion") not in (2, 3):
findings.append(
Finding(
severity = HIGH,
package = "<root>",
filename = str(path),
pattern = "unsupported-lockfile-version",
detail = (
f"only lockfileVersion 2 or 3 supported; got "
f"{lock.get('lockfileVersion')!r}"
),
)
)
return entries, findings
for key, entry in (lock.get("packages") or {}).items():
if key == "" or entry.get("link"):
continue
# Nested fold-ins (deps inside another package's node_modules/) are covered by the parent tarball's integrity.
if key.count("/node_modules/") >= 1:
continue
resolved = entry.get("resolved")
if not resolved:
continue
# Strict registry origin check so this scanner cannot be tricked into fetching from an attacker-chosen URL.
parsed = urllib.parse.urlparse(resolved)
if parsed.scheme != "https" or parsed.hostname != ALLOWED_DOWNLOAD_HOST:
findings.append(
Finding(
severity = CRITICAL,
package = key,
filename = str(path),
pattern = "non-registry-resolved-url",
detail = (
f"resolved={resolved!r}; only "
f"https://{ALLOWED_DOWNLOAD_HOST}/ is "
"permitted. Refusing to download."
),
)
)
continue
integrity = entry.get("integrity")
if not integrity:
findings.append(
Finding(
severity = HIGH,
package = key,
filename = str(path),
pattern = "missing-integrity-hash",
detail = "no `integrity` field; cannot verify download",
)
)
continue
nm = "node_modules/"
name = key[len(nm) :] if key.startswith(nm) else key
version = entry.get("version") or "<unversioned>"
entries.append(
PackageEntry(
name = name,
version = version,
resolved = resolved,
integrity = integrity,
lockfile_key = key,
)
)
return entries, findings
# ─────────────────────────────────────────────────────────────────────
# Tarball download: registry-only, size-capped, integrity-verified.
# ─────────────────────────────────────────────────────────────────────
def _decode_integrity(integrity: str) -> tuple[str, bytes] | None:
"""Parse SRI integrity 'sha512-<base64>' -> (algo, digest_bytes)."""
if "-" not in integrity:
return None
algo, b64 = integrity.split("-", 1)
algo = algo.strip().lower()
if algo not in ("sha256", "sha384", "sha512"):
return None
try:
digest = _b64.b64decode(b64, validate = True)
except Exception:
return None
return algo, digest
def download_tarball(
entry: PackageEntry,
dest: Path,
*,
timeout: float = HARD_HTTP_TIMEOUT_S,
max_bytes: int = HARD_MAX_TARBALL_BYTES,
) -> tuple[Path, str | None]:
"""Stream-download entry.resolved to dest and verify SRI integrity. Returns (downloaded_path, error_or_none); on error the path may not exist. Network access is restricted to ALLOWED_DOWNLOAD_HOST."""
# Re-assert hostname (defence-in-depth against a future refactor).
parsed = urllib.parse.urlparse(entry.resolved)
if parsed.scheme != "https" or parsed.hostname != ALLOWED_DOWNLOAD_HOST:
return dest, (f"refused download from non-allowlisted URL {entry.resolved!r}")
decoded = _decode_integrity(entry.integrity or "")
if decoded is None:
return dest, f"unparseable integrity field {entry.integrity!r}"
algo, expected_digest = decoded
h = hashlib.new(algo)
req = urllib.request.Request(
entry.resolved,
headers = {
"User-Agent": "unsloth-scan-npm-packages/1.0 (+supply-chain audit)",
"Accept": "application/octet-stream",
},
method = "GET",
)
try:
with urllib.request.urlopen(req, timeout = timeout) as r:
cl = r.headers.get("Content-Length")
if cl is not None:
try:
cl_int = int(cl)
if cl_int > max_bytes:
return dest, (f"Content-Length {cl_int} > cap {max_bytes}")
except ValueError:
pass
written = 0
with open(dest, "wb") as out:
while True:
chunk = r.read(64 * 1024)
if not chunk:
break
written += len(chunk)
if written > max_bytes:
return dest, (
f"download exceeded cap {max_bytes} bytes " f"after {written} bytes"
)
h.update(chunk)
out.write(chunk)
except Exception as exc:
return dest, f"download failed: {exc}"
actual = h.digest()
if actual != expected_digest:
return dest, (
f"integrity mismatch: expected {algo}={_b64.b64encode(expected_digest).decode()!r}, "
f"got {algo}={_b64.b64encode(actual).decode()!r}"
)
return dest, None
# ─────────────────────────────────────────────────────────────────────
# Safe tar extraction. Every Tarfile member is policed before write.
# ─────────────────────────────────────────────────────────────────────
def _is_within(root: Path, candidate: Path) -> bool:
try:
return candidate.resolve().is_relative_to(root.resolve())
except (AttributeError, ValueError):
try:
candidate.resolve().relative_to(root.resolve())
return True
except Exception:
return False
def safe_extract(
tarball_path: Path,
extract_root: Path,
*,
max_total_bytes: int = HARD_MAX_TOTAL_BYTES,
max_members: int = HARD_MAX_MEMBERS,
) -> str | None:
"""Extract tarball_path under extract_root with policed members, returning None on success or a string describing the refusal. Streams via `r|gz` so we can abort mid-extraction without having materialised the rest of the archive."""
extract_root.mkdir(parents = True, exist_ok = True)
total = 0
count = 0
try:
# Streaming mode (no backward seeks); `r|gz` rejects bad gzip.
with tarfile.open(tarball_path, mode = "r|gz") as tf:
for member in tf:
count += 1
if count > max_members:
return f"member count {count} exceeded cap {max_members}"
name = member.name
if name.startswith("/") or ".." in Path(name).parts:
return f"refused unsafe member name {name!r}"
# Reject device files, FIFOs, sockets, symlinks, hardlinks.
if member.issym() or member.islnk():
return f"refused link member {name!r} (sym/lnk)"
if member.isdev() or member.isfifo():
return f"refused special member {name!r}"
# Check declared size up front to short-circuit bombs without reading the body.
declared = max(member.size, 0)
if declared > HARD_MAX_BINARY_FILE_BYTES:
return (
f"member {name!r} declared size {declared} > "
f"absolute cap {HARD_MAX_BINARY_FILE_BYTES}"
)
if total + declared > max_total_bytes:
return (
f"cumulative bytes {total + declared} > cap "
f"{max_total_bytes} at {name!r}"
)
# Resolve destination and refuse anything escaping root (do not trust the npm "package/" convention).
dest = extract_root / name
if not _is_within(extract_root, dest):
return f"refused escape: {name!r} resolved outside root"
if member.isdir():
dest.mkdir(parents = True, exist_ok = True)
continue
if not member.isfile():
return f"refused unknown member type for {name!r}"
dest.parent.mkdir(parents = True, exist_ok = True)
src = tf.extractfile(member)
if src is None:
continue
# Sniff first 16 bytes to classify text vs binary; each gets its own cap.
header = src.read(16)
is_binary = _looks_binary(name, header)
file_cap = HARD_MAX_BINARY_FILE_BYTES if is_binary else HARD_MAX_TEXT_FILE_BYTES
if declared > file_cap:
return (
f"member {name!r} declared size {declared} > "
f"cap {file_cap} ({'binary' if is_binary else 'text'})"
)
remainder_cap = file_cap - len(header)
rest = src.read(remainder_cap + 1)
data = header + rest
if len(data) > file_cap:
return (
f"member {name!r} body exceeded declared size cap "
f"({'binary' if is_binary else 'text'})"
)
total += len(data)
# Restrictive mode (rw-r--r--): nothing executable.
with open(dest, "wb") as out:
out.write(data)
os.chmod(dest, 0o644)
except tarfile.TarError as exc:
return f"tar parse error: {exc}"
except Exception as exc:
return f"unexpected extract error: {exc!r}"
return None
# How far back to look for an enclosing bracket opener. Symmetric with the forward cap so a host deep inside a large options object still binds the whole object; a too-far start only over-binds (more context, still fail-closed), never less.
_MAX_CONT_LINES = 200
# Hard cap on how far forward a bracket group is followed to its close, measured from the matched line so the tail after the match is always reachable even when the opener was found near the backward limit (digest input only, never displayed).
_MAX_GROUP_LINES = 200
# JS string literal (single / double / template), blanked before counting brackets so a bracket inside a string is not mistaken for code.
_RE_JS_STR = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"|`(?:[^`\\]|\\.)*`")
_RE_BRACKETS = re.compile(r"[()\[\]{}]")
_OPENERS = frozenset("([{")
def _bracket_lr(line: str) -> tuple[int, int]:
"""Order-aware bracket reduction of one already-string-blanked line: ``(L, R)``, where ``L`` counts closers with no opener earlier on the line and ``R`` counts openers with no closer later. A plain net count collapses order and masks a trailing opener that follows leading closers (``}); const opts = {`` nets -1 and hides the ``{`` that opens the host-config object), so tracking the running minimum keeps that opener visible. Only bracket characters are walked so a long minified line stays cheap."""
depth = 0
low = 0
for ch in _RE_BRACKETS.findall(line):
if ch in _OPENERS:
depth += 1
else:
depth -= 1
if depth < low:
low = depth
return -low, depth - low
def _find_unescaped(line: str, quote: str, start: int) -> int:
"""Index of the next ``quote`` at or after ``start`` not escaped by a backslash, or -1. Skips ``\\x`` pairs so an escaped quote inside the string is ignored."""
i, n = start, len(line)
while i < n:
if line[i] == "\\":
i += 2
continue
if line[i] == quote:
return i
i += 1
return -1
# A `/` is a regex literal (not division) when the previous significant character is none (start) or one of these expression-position chars. Used only by the multi-line blanked view, whose span is unioned with the single-line view, so an over- or under-detection only ever grows the bound span.
_JS_REGEX_PRECEDERS = frozenset("([{,;:?=&|!+-*/%^~<>")
def _blank_js_strings(lines: list[str]) -> list[str]:
"""Replace string contents (single, double, multi-line backtick template literals) AND regex literal bodies with spaces across ``lines``, keeping the line count and every bracket OUTSIDE a string/regex intact, so bracket counting never miscounts a ``)`` inside a string, including a template literal spanning several lines or a ``/)/`` regex, which a per-line regex cannot blank. Escapes are honoured."""
out: list[str] = []
in_back = False # inside a multi-line `template` literal
prev_sig = "" # last significant non-space char (for regex-vs-division)
for line in lines:
buf: list[str] = []
i, n = 0, len(line)
while i < n:
if in_back:
end = _find_unescaped(line, "`", i)
if end == -1:
buf.append(" " * (n - i))
i = n
else:
buf.append(" " * (end - i + 1))
i = end + 1
in_back = False
prev_sig = "`"
continue
ch = line[i]
if ch in " \t":
buf.append(ch)
i += 1
continue
if ch in "'\"`":
end = _find_unescaped(line, ch, i + 1)
if end == -1:
buf.append(" " * (n - i))
i = n
if ch == "`": # opens a template literal that runs past this line
in_back = True
else:
buf.append(" " * (end - i + 1))
i = end + 1
prev_sig = "v" # a string is a value: a following `/` is division
continue
if ch == "/" and (prev_sig == "" or prev_sig in _JS_REGEX_PRECEDERS):
# Regex literal: blank to the closing unescaped `/` outside a `[...]` char class. A regex never spans lines, so no close on the line means this `/` is really division.
j, in_class, closed = i + 1, False, False
while j < n:
c = line[j]
if c == "\\":
j += 2
continue
if c == "[":
in_class = True
elif c == "]":
in_class = False
elif c == "/" and not in_class:
j += 1
closed = True
break
j += 1
if closed:
buf.append(" " * (j - i))
i = j
prev_sig = "v" # a regex is a value
continue
buf.append(ch)
i += 1
prev_sig = "/"
continue
buf.append(ch)
i += 1
prev_sig = ch
out.append("".join(buf))
return out
def _index_text(text: str) -> tuple[list[str], list[str], list[str], list[int]]:
"""Precompute once per evidence call: raw lines for display, two string-blanked views for bracket counting (single-line via regex, and multi-line aware so a template literal spanning lines is blanked), and newline offsets for O(log n) offset-to-line mapping. Avoids re-splitting and re-counting the whole file on every match, which was O(matches x file size)."""
lines = text.split("\n")
sl_blanked = [_RE_JS_STR.sub("", ln) for ln in lines]
ml_blanked = _blank_js_strings(lines)
nl = [p for p, ch in enumerate(text) if ch == "\n"]
return lines, sl_blanked, ml_blanked, nl
# Cap on formatted matches in one evidence string; beyond it the remaining match texts are folded into a single digest so a huge or minified file cannot build a multi-megabyte evidence blob while an added/removed match past the cap still changes the key.
_MAX_EVIDENCE_MATCHES = 64
def _scan_group(blanked: list[str], idx: int) -> tuple[int, int]:
"""(start, end) line indices of the bracket group enclosing line ``idx`` in one blanked view: scan back to the still-open opener, then forward to its close."""
# Backward: find the line that opens a bracket still unclosed at the match, so a match inside a multi-line object starts from the object opener. Each line is reduced to (L, R) and applied in order (leading closers clamp depth at 0, never negative), which keeps a trailing opener visible even when leading closers on the same line net it to <= 0, e.g. `}); const opts = {`, which a net count would drop and let a changed path/headers ride the unchanged-hostname key.
start = idx
depth = 0
for j in range(max(0, idx - _MAX_CONT_LINES), idx):
left, right = _bracket_lr(blanked[j])
if left >= depth:
depth = 0 # everything opened so far in the window has closed
start = idx
else:
depth -= left
if right > 0:
if depth == 0:
start = j # outermost still-open opener begins here
depth += right
# Forward: extend until the group opened at `start` closes past the match, with the same order-aware reduction so a foreign `})` on the opener line does not drive the count negative and stop the scan before the real close. The cap is measured from the match, not from `start`, so an opener found near the backward limit does not eat the whole forward budget.
depth = 0
end = start
for j in range(start, min(len(blanked), idx + _MAX_GROUP_LINES)):
left, right = _bracket_lr(blanked[j])
depth = max(0, depth - left) + right
end = j
if j >= idx and depth <= 0:
break
return start, end
def _canon_preserve_strings(text: str) -> str:
"""Whitespace canon that collapses runs OUTSIDE string literals to a single space (so a reindent stays stable) while preserving whitespace INSIDE single/double/backtick literals (so a changed payload body reopens). A plain ``" ".join(text.split())`` erases both, suppressing an intra-literal payload edit along with harmless indentation. Used for the evidence hash and the logical-line digests so the two stay consistent."""
out: list[str] = []
i, n = 0, len(text)
quote: str | None = None
pending_space = False
while i < n:
ch = text[i]
if quote is not None:
out.append(ch)
if ch == "\\" and i + 1 < n:
out.append(text[i + 1])
i += 2
continue
if ch == quote:
quote = None
i += 1
continue
if ch.isspace():
pending_space = True
i += 1
continue
if pending_space and out:
out.append(" ")
pending_space = False
out.append(ch)
if ch in "'\"`":
quote = ch
i += 1
return "".join(out)
def _logical_line_text(
lines: list[str], sl_blanked: list[str], ml_blanked: list[str], idx: int
) -> str:
"""The matched line plus the bracket group it belongs to, so a changed ``path``/``headers``/body on another line binds. Returns the UNION of the groups found in the single-line-blanked view (a payload embedded inside a template still counts) and the multi-line-blanked view (a bracket inside a multi-line template no longer closes the group early); unioning never shrinks the span below either view."""
s1, e1 = _scan_group(sl_blanked, idx)