dexsect 4.1.0__py3-none-any.whl

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 (74) hide show
  1. dexsect/__init__.py +4 -0
  2. dexsect/__main__.py +5 -0
  3. dexsect/catalog/EXTRACTION_CATALOG.json +4057 -0
  4. dexsect/catalog/__init__.py +0 -0
  5. dexsect/cli.py +1272 -0
  6. dexsect/core/__init__.py +0 -0
  7. dexsect/core/config.py +177 -0
  8. dexsect/core/context.py +181 -0
  9. dexsect/core/i18n.py +40 -0
  10. dexsect/core/pipeline.py +153 -0
  11. dexsect/core/platform_utils.py +164 -0
  12. dexsect/core/runner.py +124 -0
  13. dexsect/core/theme.py +64 -0
  14. dexsect/core/ui.py +405 -0
  15. dexsect/core/utils.py +150 -0
  16. dexsect/inspectors/__init__.py +0 -0
  17. dexsect/inspectors/assets_db_inspector.py +235 -0
  18. dexsect/inspectors/base.py +46 -0
  19. dexsect/inspectors/bundle_inspector.py +55 -0
  20. dexsect/inspectors/code_inspector.py +341 -0
  21. dexsect/inspectors/custom_rules_inspector.py +178 -0
  22. dexsect/inspectors/dex_inspector.py +144 -0
  23. dexsect/inspectors/manifest_inspector.py +503 -0
  24. dexsect/inspectors/native_fw_inspector.py +167 -0
  25. dexsect/inspectors/resources_inspector.py +195 -0
  26. dexsect/inspectors/scanner_inspector.py +153 -0
  27. dexsect/inspectors/signing_inspector.py +423 -0
  28. dexsect/inspectors/text_scanner.py +336 -0
  29. dexsect/locales/__init__.py +0 -0
  30. dexsect/locales/ar.json +130 -0
  31. dexsect/locales/de.json +51 -0
  32. dexsect/locales/en.json +110 -0
  33. dexsect/locales/es.json +51 -0
  34. dexsect/locales/fr.json +51 -0
  35. dexsect/locales/ja.json +51 -0
  36. dexsect/locales/pt.json +51 -0
  37. dexsect/locales/ru.json +51 -0
  38. dexsect/locales/tr.json +51 -0
  39. dexsect/locales/zh.json +51 -0
  40. dexsect/parsers/__init__.py +0 -0
  41. dexsect/parsers/axml.py +264 -0
  42. dexsect/parsers/bundle.py +214 -0
  43. dexsect/parsers/elf.py +396 -0
  44. dexsect/phases/__init__.py +0 -0
  45. dexsect/phases/base.py +102 -0
  46. dexsect/phases/decode.py +507 -0
  47. dexsect/phases/decompile.py +408 -0
  48. dexsect/phases/fingerprint.py +341 -0
  49. dexsect/phases/frameworks.py +377 -0
  50. dexsect/phases/mapper.py +41 -0
  51. dexsect/phases/native.py +188 -0
  52. dexsect/plugins/__init__.py +0 -0
  53. dexsect/plugins/base.py +20 -0
  54. dexsect/plugins/diff.py +162 -0
  55. dexsect/plugins/inspect.py +172 -0
  56. dexsect/plugins/report.py +80 -0
  57. dexsect/plugins/trace.py +141 -0
  58. dexsect/reporting/__init__.py +0 -0
  59. dexsect/reporting/analysis_report.py +1190 -0
  60. dexsect/reporting/diff_report.py +144 -0
  61. dexsect/reporting/sarif_report.py +109 -0
  62. dexsect/reporting/unpack_map.py +149 -0
  63. dexsect/rules/__init__.py +0 -0
  64. dexsect/rules/anti_analysis.json +45 -0
  65. dexsect/rules/crypto_audit.json +41 -0
  66. dexsect/rules/secrets_extended.json +46 -0
  67. dexsect/storage/__init__.py +0 -0
  68. dexsect/storage/findings_db.py +460 -0
  69. dexsect-4.1.0.dist-info/METADATA +532 -0
  70. dexsect-4.1.0.dist-info/RECORD +74 -0
  71. dexsect-4.1.0.dist-info/WHEEL +5 -0
  72. dexsect-4.1.0.dist-info/entry_points.txt +2 -0
  73. dexsect-4.1.0.dist-info/licenses/LICENSE +21 -0
  74. dexsect-4.1.0.dist-info/top_level.txt +1 -0
dexsect/core/ui.py ADDED
@@ -0,0 +1,405 @@
1
+ import atexit
2
+ import os
3
+ import re
4
+ import shutil
5
+ import sys
6
+ import threading
7
+ import time
8
+ from collections import deque
9
+ from typing import Deque, Dict, List, Optional
10
+
11
+ from .platform_utils import enable_windows_vt100
12
+ from .theme import BrandColors
13
+ from .utils import format_bytes, format_duration
14
+
15
+
16
+ ANSI_RE = re.compile(r"(\033\[[0-9;]*m)")
17
+
18
+ Colors = BrandColors
19
+
20
+
21
+ def visible_len(text: str) -> int:
22
+ return len(ANSI_RE.sub("", text))
23
+
24
+
25
+ def ansi_clip(text: str, max_visible: int) -> str:
26
+ if max_visible <= 0:
27
+ return ""
28
+ tokens = ANSI_RE.split(text)
29
+ total_vis = sum(len(t) for idx, t in enumerate(tokens) if idx % 2 == 0)
30
+ if total_vis <= max_visible:
31
+ return text
32
+
33
+ target = max(0, max_visible - 3)
34
+ out = []
35
+ vis = 0
36
+ truncated = False
37
+ has_ansi = False
38
+
39
+ for idx, tok in enumerate(tokens):
40
+ if idx % 2 == 1:
41
+ out.append(tok)
42
+ has_ansi = True
43
+ continue
44
+ if vis >= target:
45
+ truncated = True
46
+ continue
47
+ take = target - vis
48
+ if len(tok) <= take:
49
+ out.append(tok)
50
+ vis += len(tok)
51
+ else:
52
+ out.append(tok[:take])
53
+ vis += take
54
+ truncated = True
55
+
56
+ if truncated and max_visible >= 3:
57
+ out.append("...")
58
+ if has_ansi:
59
+ out.append("\033[0m")
60
+ return "".join(out)
61
+
62
+
63
+ class TerminalDashboard:
64
+ SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
65
+ ASCII_SPINNER = ["|", "/", "-", "\\"]
66
+
67
+ def __init__(self, version: str, quiet: bool = False, no_color: bool = False) -> None:
68
+ enable_windows_vt100()
69
+ self.version = version
70
+ self.quiet = quiet
71
+ self.is_tty = (not quiet) and sys.stdout.isatty() and not os.environ.get("NO_COLOR")
72
+ self.c = BrandColors(enabled=self.is_tty and not no_color)
73
+ self.lock = threading.RLock()
74
+ self.started = False
75
+ self.pipeline_start = time.time()
76
+ self.phase_start = time.time()
77
+ self.task_start = time.time()
78
+ self.spin_idx = 0
79
+ self._last_render_ts = 0.0
80
+ self._stop_event = threading.Event()
81
+ self._ticker_thread: Optional[threading.Thread] = None
82
+
83
+ self.stage_order: List[str] = []
84
+ self.stage_states: Dict[str, Dict[str, str]] = {}
85
+ self.current_stage_key: str = ""
86
+
87
+ self.meta: Dict[str, str] = {
88
+ "phase_idx": "1/1",
89
+ "phase_name": "INIT",
90
+ "engine": "-",
91
+ "input": "-",
92
+ "type": "-",
93
+ "output": "-",
94
+ "jobs": "2",
95
+ "metric_label": "Files",
96
+ }
97
+ self.stats: Dict[str, int] = {
98
+ "total": 0,
99
+ "done": 0,
100
+ "success": 0,
101
+ "failed": 0,
102
+ "resumed": 0,
103
+ "duplicates": 0,
104
+ "skipped": 0,
105
+ "files_indexed": 0,
106
+ "bytes_indexed": 0,
107
+ }
108
+ self.active: Dict[str, str] = {
109
+ "id": "-",
110
+ "name": "Initializing...",
111
+ "role": "-",
112
+ "depth": "0",
113
+ "hash": "-",
114
+ "step": "IDLE",
115
+ }
116
+ self.stream_lines: Deque[str] = deque(maxlen=8)
117
+ self.events: Deque[str] = deque(maxlen=6)
118
+ atexit.register(self.stop)
119
+
120
+ def _ticker_loop(self) -> None:
121
+ while not self._stop_event.wait(0.25):
122
+ if self.started and self.is_tty:
123
+ self.render(force=True)
124
+
125
+ def start(self) -> None:
126
+ if self.started or self.quiet:
127
+ return
128
+ self.pipeline_start = time.time()
129
+ self.started = True
130
+ self._stop_event.clear()
131
+ if self.is_tty:
132
+ sys.stdout.write("\033[?1049h\033[?25l\033[2J\033[H")
133
+ sys.stdout.flush()
134
+ self._ticker_thread = threading.Thread(target=self._ticker_loop, daemon=True)
135
+ self._ticker_thread.start()
136
+
137
+ def stop(self) -> None:
138
+ self._stop_event.set()
139
+ if self._ticker_thread and threading.current_thread() is not self._ticker_thread:
140
+ self._ticker_thread.join(timeout=0.5)
141
+ self._ticker_thread = None
142
+ if self.is_tty and self.started:
143
+ sys.stdout.write("\033[?25h\033[?1049l")
144
+ sys.stdout.flush()
145
+ self.started = False
146
+
147
+ def set_pipeline_stages(self, stages: List[str]) -> None:
148
+ with self.lock:
149
+ self.stage_order = list(stages)
150
+ for s in stages:
151
+ self.stage_states.setdefault(s, {"status": "PENDING", "elapsed": ""})
152
+
153
+ def finish_stage(self, stage_key: str, status: str, duration_sec: float) -> None:
154
+ with self.lock:
155
+ self.stage_states[stage_key] = {
156
+ "status": status.upper(),
157
+ "elapsed": f"{int(duration_sec)}s" if duration_sec >= 1 else "<1s",
158
+ }
159
+ self.render(force=True)
160
+
161
+ def begin_phase(
162
+ self,
163
+ phase_idx: str,
164
+ phase_name: str,
165
+ engine: str,
166
+ metric_label: str = "Files",
167
+ stage_key: Optional[str] = None,
168
+ ) -> None:
169
+ with self.lock:
170
+ self.phase_start = time.time()
171
+ self.task_start = time.time()
172
+ self.meta["phase_idx"] = phase_idx
173
+ self.meta["phase_name"] = phase_name
174
+ self.meta["engine"] = engine
175
+ self.meta["metric_label"] = metric_label
176
+
177
+ inferred = (stage_key or phase_name.split()[0]).lower()
178
+ for known in self.stage_order:
179
+ if known == inferred or known in phase_name.lower():
180
+ inferred = known
181
+ break
182
+ self.current_stage_key = inferred
183
+ if not self.stage_order:
184
+ self.stage_order = [inferred]
185
+ elif inferred not in self.stage_order:
186
+ self.stage_order.append(inferred)
187
+ self.stage_states[inferred] = {"status": "RUNNING", "elapsed": ""}
188
+
189
+ for k in self.stats:
190
+ self.stats[k] = 0
191
+ self.stream_lines.clear()
192
+
193
+ if not self.is_tty and not self.quiet:
194
+ print(f"\n=== [{phase_idx}] {phase_name} ===", flush=True)
195
+ else:
196
+ self.render(force=True)
197
+
198
+ def set_meta(self, **kwargs: str) -> None:
199
+ with self.lock:
200
+ self.meta.update(kwargs)
201
+
202
+ def set_active(self, **kwargs: str) -> None:
203
+ with self.lock:
204
+ self.active.update(kwargs)
205
+
206
+ def reset_task_timer(self) -> None:
207
+ with self.lock:
208
+ self.task_start = time.time()
209
+ self.stream_lines.clear()
210
+
211
+ def update_stats(self, **kwargs: int) -> None:
212
+ with self.lock:
213
+ self.stats.update(kwargs)
214
+
215
+ def inc_stat(self, key: str, amount: int = 1) -> None:
216
+ with self.lock:
217
+ self.stats[key] = self.stats.get(key, 0) + amount
218
+
219
+ def push_stream(self, line: str) -> None:
220
+ clean = line.replace("\r", "").strip()
221
+ if not clean:
222
+ return
223
+ with self.lock:
224
+ self.stream_lines.append(clean)
225
+ if not self.is_tty and not self.quiet:
226
+ print(f" > {clean}", flush=True)
227
+
228
+ def push_event(self, level: str, msg: str) -> None:
229
+ ts = time.strftime("%H:%M:%S")
230
+ with self.lock:
231
+ self.events.append(f"[{ts}] [{level}] {msg}")
232
+ if not self.is_tty and not self.quiet:
233
+ print(f"[{ts}] [{level}] {msg}", flush=True)
234
+
235
+ def _compute_eta(self, now: float) -> str:
236
+ work = self.stats["success"] + self.stats["failed"]
237
+ rem = max(0, self.stats["total"] - self.stats["done"])
238
+ if rem == 0:
239
+ return "00:00:00"
240
+ if work <= 0:
241
+ return "--:--:--"
242
+ avg = (now - self.phase_start) / work
243
+ return "~" + format_duration(avg * rem)
244
+
245
+ def _format_stage_item(self, s: str, spin: str) -> str:
246
+ c = self.c
247
+ st = self.stage_states.get(s, {}).get("status", "PENDING")
248
+ el = self.stage_states.get(s, {}).get("elapsed", "")
249
+ if st == "RUNNING":
250
+ return f"{c.ORANGE}{c.BOLD}{spin} {s}{c.RESET}"
251
+ if st in ("COMPLETED", "SUCCESS"):
252
+ tag = f" ({el})" if el else ""
253
+ return f"{c.OK}✓ {s}{tag}{c.RESET}"
254
+ if st in ("FAILED", "INTERRUPTED"):
255
+ return f"{c.ERR}✗ {s}{c.RESET}"
256
+ if st == "SKIPPED":
257
+ return f"{c.MUTED}⊘ {s}{c.RESET}"
258
+ return f"{c.MUTED}○ {s}{c.RESET}"
259
+
260
+ def _build_header_box(self, box_w: int, use_utf8: bool) -> List[str]:
261
+ c = self.c
262
+ inner_w = max(20, box_w - 4)
263
+ tl, tr, bl, br, hz, vt = ("╭", "╮", "╰", "╯", "─", "│") if use_utf8 else ("+", "+", "+", "+", "-", "|")
264
+
265
+ title_vis = f" ◆ DexSect v{self.version} "
266
+ title_colored = f" {c.CRIMSON}◆ {c.ORANGE}{c.BOLD}Dex{c.CREAM}{c.BOLD}Sect{c.RESET} {c.MUTED}v{self.version}{c.RESET} "
267
+ rem_hz = max(1, (box_w - 2) - len(title_vis) - 1)
268
+ top_line = f"{c.CRIMSON}{tl}{hz}{c.RESET}{title_colored}{c.CRIMSON}{hz * rem_hz}{tr}{c.RESET}"
269
+
270
+ ws_name = os.path.basename(self.meta["output"].rstrip("/\\")) or self.meta["output"]
271
+ row1_raw = ansi_clip(
272
+ f"{c.MUTED}Target :{c.RESET} {c.CREAM}{self.meta['input']}{c.RESET} {c.MUTED}({self.meta['type']}){c.RESET}",
273
+ inner_w,
274
+ )
275
+ row2_raw = ansi_clip(
276
+ f"{c.MUTED}Workspace:{c.RESET} {c.CREAM}{ws_name}{c.RESET}",
277
+ inner_w,
278
+ )
279
+
280
+ pad1 = " " * max(0, inner_w - visible_len(row1_raw))
281
+ pad2 = " " * max(0, inner_w - visible_len(row2_raw))
282
+
283
+ mid1 = f"{c.CRIMSON}{vt}{c.RESET} {row1_raw}{pad1} {c.CRIMSON}{vt}{c.RESET}"
284
+ mid2 = f"{c.CRIMSON}{vt}{c.RESET} {row2_raw}{pad2} {c.CRIMSON}{vt}{c.RESET}"
285
+ bot_line = f"{c.CRIMSON}{bl}{hz * (box_w - 2)}{br}{c.RESET}"
286
+ return [top_line, mid1, mid2, bot_line]
287
+
288
+ def _render_stage_grid(self, max_w: int, spin: str) -> List[str]:
289
+ c = self.c
290
+ items = [self._format_stage_item(s, spin) for s in self.stage_order]
291
+ if max_w >= 88:
292
+ flow = f" {c.CRIMSON}›{c.RESET} ".join(items)
293
+ return [f" {c.MUTED}{'Pipeline':<10}{c.RESET}{flow}"]
294
+
295
+ cols_per_row = 3 if max_w >= 54 else 2
296
+ col_w = max(14, (max_w - 14) // cols_per_row)
297
+ rows: List[str] = []
298
+ for start_i in range(0, len(items), cols_per_row):
299
+ chunk = items[start_i : start_i + cols_per_row]
300
+ padded = []
301
+ for idx, it in enumerate(chunk):
302
+ if idx < len(chunk) - 1:
303
+ pad = " " * max(2, col_w - visible_len(it))
304
+ padded.append(it + pad)
305
+ else:
306
+ padded.append(it)
307
+ prefix = f" {c.MUTED}{'Pipeline':<10}{c.RESET}" if start_i == 0 else " " * 12
308
+ rows.append(prefix + "".join(padded))
309
+ return rows
310
+
311
+ def render(self, force: bool = False) -> None:
312
+ if not self.is_tty or self.quiet:
313
+ return
314
+ with self.lock:
315
+ now_mono = time.monotonic()
316
+ if not force and (now_mono - self._last_render_ts) < 0.12:
317
+ return
318
+ self._last_render_ts = now_mono
319
+
320
+ term = shutil.get_terminal_size((80, 24))
321
+ cols = max(40, term.columns)
322
+ rows = max(16, term.lines)
323
+ max_w = cols - 1
324
+ now = time.time()
325
+ c = self.c
326
+
327
+ use_utf8 = bool(sys.stdout.encoding and "utf" in sys.stdout.encoding.lower())
328
+ spin = (self.SPINNER_FRAMES if use_utf8 else self.ASCII_SPINNER)[self.spin_idx % (10 if use_utf8 else 4)]
329
+ self.spin_idx += 1
330
+
331
+ box_w = min(max_w, 72)
332
+ lines = self._build_header_box(box_w, use_utf8)
333
+
334
+ if rows >= 22:
335
+ lines.append("")
336
+ lines.extend(self._render_stage_grid(max_w, spin))
337
+ if rows >= 22:
338
+ lines.append("")
339
+
340
+ total = self.stats["total"]
341
+ done = self.stats["done"]
342
+ pct = int((done * 100) / total) if total > 0 else 0
343
+ bar_w = max(10, min(26, max_w - 30))
344
+ filled = int((pct / 100.0) * bar_w)
345
+ bar_ch_on, bar_ch_off = ("█", "░") if use_utf8 else ("#", "-")
346
+ bar = f"{c.ORANGE}{bar_ch_on * filled}{c.MUTED}{bar_ch_off * (bar_w - filled)}{c.RESET}"
347
+
348
+ metric_lbl = self.meta.get("metric_label", "Files")
349
+ metric_val = (
350
+ f"{self.stats['files_indexed']:,} ({format_bytes(self.stats['bytes_indexed'])})"
351
+ if self.stats.get("bytes_indexed", 0) > 0
352
+ else f"{self.stats['files_indexed']:,}"
353
+ )
354
+
355
+ lines.extend([
356
+ f" {c.MUTED}{'Progress':<10}{c.RESET}[{bar}] {c.ORANGE}{c.BOLD}{pct:3d}%{c.RESET} {c.MUTED}({done}/{total}){c.RESET}",
357
+ f" {c.MUTED}{'Timing':<10}{c.RESET}{c.CREAM}Elapsed {format_duration(now - self.pipeline_start)}{c.RESET} {c.MUTED}ETA {self._compute_eta(now)}{c.RESET}",
358
+ (
359
+ f" {c.MUTED}{'Summary':<10}{c.RESET}"
360
+ f"{c.OK}✓ {self.stats['success']}{c.RESET} "
361
+ f"{c.ERR}✗ {self.stats['failed']}{c.RESET} "
362
+ f"{c.INFO}↻ {self.stats['resumed']}{c.RESET} "
363
+ f"{c.MUTED}⊘ {self.stats['skipped'] + self.stats['duplicates']} "
364
+ f"{metric_lbl}: {metric_val}{c.RESET}"
365
+ ),
366
+ ])
367
+
368
+ if rows >= 22:
369
+ lines.append("")
370
+
371
+ lines.extend([
372
+ f" {c.MUTED}{'Active':<10}{c.RESET}{c.ORANGE}{spin} {c.CREAM}{c.BOLD}{self.active['name']}{c.RESET} {c.MUTED}({self.active['role']}){c.RESET}",
373
+ f" {c.MUTED}{self.active['step']} · {format_duration(now - self.task_start)}{c.RESET}",
374
+ ])
375
+
376
+ if rows >= 22:
377
+ lines.append("")
378
+
379
+ avail = max(2, (rows - 1) - (len(lines) + 2))
380
+ stream_slots = max(1, min(5, (avail * 2) // 3))
381
+ event_slots = max(1, min(3, avail - stream_slots))
382
+
383
+ lines.append(f" {c.ORANGE}{c.BOLD}Live Output{c.RESET}")
384
+ recent_stream = list(self.stream_lines)[-stream_slots:]
385
+ for i in range(stream_slots):
386
+ lines.append(f" {c.MUTED}› {recent_stream[i] if i < len(recent_stream) else ''}{c.RESET}")
387
+
388
+ lines.append(f" {c.CRIMSON}{c.BOLD}Events{c.RESET}")
389
+ recent_events = list(self.events)[-event_slots:]
390
+ for i in range(event_slots):
391
+ if i < len(recent_events):
392
+ ev = recent_events[i]
393
+ col = c.ERR if ("[FAIL]" in ev or "[ERR]" in ev) else (
394
+ c.OK if "[OK]" in ev else (c.ORANGE if ("[FOUND]" in ev or "[WARN]" in ev) else c.CREAM)
395
+ )
396
+ lines.append(f" {col}{ev}{c.RESET}")
397
+ else:
398
+ lines.append("")
399
+
400
+ buf = ["\033[H"]
401
+ for line in lines[: rows - 1]:
402
+ buf.append(f"{ansi_clip(line, max_w)}\033[K\n")
403
+ buf.append("\033[J")
404
+ sys.stdout.write("".join(buf))
405
+ sys.stdout.flush()
dexsect/core/utils.py ADDED
@@ -0,0 +1,150 @@
1
+ import hashlib
2
+ import os
3
+ import re
4
+ from pathlib import Path
5
+ from typing import List, Optional, Set, Tuple
6
+
7
+
8
+ ASCII_STR_RE = re.compile(rb"[\x20-\x7e]{5,}")
9
+ UTF8_WIDE_RE = re.compile(rb"(?:[\x20-\x7e]|[\xc2-\xf4][\x80-\xbf]{1,3}){5,}")
10
+ UTF16LE_STR_RE = re.compile(rb"(?:[\x20-\x7e]\x00){6,}")
11
+
12
+
13
+ def safe_slug(name: str, max_len: int = 56, fallback: str = "item") -> str:
14
+ cleaned = re.sub(r"[^a-zA-Z0-9._-]+", "_", name).strip("._-")
15
+ return cleaned[:max_len] if cleaned else fallback
16
+
17
+
18
+ def compute_sha256(path: Path) -> str:
19
+ h = hashlib.sha256()
20
+ with path.open("rb") as f:
21
+ while True:
22
+ chunk = f.read(1024 * 512)
23
+ if not chunk:
24
+ break
25
+ h.update(chunk)
26
+ return h.hexdigest()
27
+
28
+
29
+ def format_duration(seconds: float) -> str:
30
+ secs = max(0, int(seconds))
31
+ h, rem = divmod(secs, 3600)
32
+ m, s = divmod(rem, 60)
33
+ return f"{h:02d}:{m:02d}:{s:02d}"
34
+
35
+
36
+ def format_bytes(num_bytes: int) -> str:
37
+ val = float(num_bytes)
38
+ for unit in ("B", "KB", "MB", "GB"):
39
+ if val < 1024.0 or unit == "GB":
40
+ return f"{val:.1f} {unit}" if unit != "B" else f"{int(val)} B"
41
+ val /= 1024.0
42
+ return f"{num_bytes} B"
43
+
44
+
45
+ def count_tree(root: Path) -> Tuple[int, int]:
46
+ if not root.is_dir():
47
+ return 0, 0
48
+ count = 0
49
+ total_bytes = 0
50
+ stack = [root]
51
+ while stack:
52
+ cur = stack.pop()
53
+ try:
54
+ with os.scandir(cur) as it:
55
+ for entry in it:
56
+ try:
57
+ if entry.is_dir(follow_symlinks=False):
58
+ stack.append(Path(entry.path))
59
+ elif entry.is_file(follow_symlinks=False):
60
+ count += 1
61
+ total_bytes += entry.stat(follow_symlinks=False).st_size
62
+ except OSError:
63
+ continue
64
+ except OSError:
65
+ continue
66
+ return count, total_bytes
67
+
68
+
69
+ def extract_strings_chunked(file_path: Path, max_strings: int = 60000) -> List[str]:
70
+ """Extract ASCII, multi-byte UTF-8, and UTF-16LE wide strings in bounded 4MB chunks."""
71
+ results: List[str] = []
72
+ seen: Set[str] = set()
73
+ chunk_size = 4 * 1024 * 1024
74
+ tail = b""
75
+
76
+ def _add(val: str) -> None:
77
+ v = val.strip()
78
+ if len(v) >= 5 and v not in seen and len(results) < max_strings:
79
+ seen.add(v)
80
+ results.append(v)
81
+
82
+ try:
83
+ with file_path.open("rb") as f:
84
+ while len(results) < max_strings:
85
+ chunk = f.read(chunk_size)
86
+ if not chunk:
87
+ break
88
+ buf = tail + chunk
89
+ matches = UTF8_WIDE_RE.findall(buf)
90
+ if chunk and (0x20 <= chunk[-1] <= 0x7E or chunk[-1] >= 0x80) and matches:
91
+ tail = matches.pop()
92
+ if len(tail) > 512:
93
+ matches.append(tail)
94
+ tail = b""
95
+ else:
96
+ tail = b""
97
+
98
+ for m in matches:
99
+ try:
100
+ _add(m.decode("utf-8", errors="ignore"))
101
+ except Exception:
102
+ pass
103
+ if len(results) >= max_strings:
104
+ break
105
+
106
+ if len(results) < max_strings:
107
+ for wm in UTF16LE_STR_RE.findall(buf):
108
+ _add(wm.decode("utf-16-le", errors="ignore"))
109
+ if len(results) >= max_strings:
110
+ break
111
+
112
+ if tail and len(results) < max_strings:
113
+ _add(tail.decode("utf-8", errors="ignore"))
114
+ except OSError:
115
+ pass
116
+ return results
117
+
118
+
119
+ def pure_js_beautify(js_text: str, max_bytes: int = 8 * 1024 * 1024) -> str:
120
+ if len(js_text) > max_bytes:
121
+ return js_text
122
+ out: List[str] = []
123
+ indent = 0
124
+ in_str: Optional[str] = None
125
+ escaped = False
126
+
127
+ for ch in js_text:
128
+ if in_str is not None:
129
+ out.append(ch)
130
+ if escaped:
131
+ escaped = False
132
+ elif ch == "\\":
133
+ escaped = True
134
+ elif ch == in_str:
135
+ in_str = None
136
+ continue
137
+ if ch in ("'", '"', "`"):
138
+ in_str = ch
139
+ out.append(ch)
140
+ elif ch == "{":
141
+ indent += 1
142
+ out.append(" {\n" + (" " * indent))
143
+ elif ch == "}":
144
+ indent = max(0, indent - 1)
145
+ out.append("\n" + (" " * indent) + "}\n" + (" " * indent))
146
+ elif ch == ";":
147
+ out.append(";\n" + (" " * indent))
148
+ else:
149
+ out.append(ch)
150
+ return "".join(out)
File without changes