litmus-cli 0.3.0__tar.gz → 0.5.0__tar.gz

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 (87) hide show
  1. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/.gitignore +12 -0
  2. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/PKG-INFO +70 -7
  3. litmus_cli-0.5.0/README.md +136 -0
  4. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/pyproject.toml +6 -2
  5. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/__init__.py +7 -1
  6. litmus_cli-0.5.0/src/litmus/api.py +216 -0
  7. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/artifact.py +19 -3
  8. litmus_cli-0.5.0/src/litmus/cli.py +632 -0
  9. litmus_cli-0.5.0/src/litmus/excerpt.py +90 -0
  10. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/exif.py +36 -1
  11. litmus_cli-0.5.0/src/litmus/image_structure.py +2086 -0
  12. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/inspectors/__init__.py +6 -0
  13. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/inspectors/c2pa.py +10 -0
  14. litmus_cli-0.5.0/src/litmus/inspectors/file_metadata.py +329 -0
  15. litmus_cli-0.5.0/src/litmus/inspectors/image_threats.py +475 -0
  16. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/inspectors/office_metadata.py +3 -1
  17. litmus_cli-0.5.0/src/litmus/inspectors/pdf_metadata.py +76 -0
  18. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/io.py +17 -1
  19. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/model.py +37 -2
  20. litmus_cli-0.5.0/src/litmus/pdf.py +306 -0
  21. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/pipeline.py +178 -47
  22. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/reporting.py +29 -1
  23. litmus_cli-0.5.0/src/litmus/rules/README.md +35 -0
  24. litmus_cli-0.5.0/src/litmus/rules/image_threats.yar +218 -0
  25. litmus_cli-0.5.0/src/litmus/security.py +111 -0
  26. litmus_cli-0.5.0/src/litmus/security_report.py +583 -0
  27. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/server.py +37 -5
  28. litmus_cli-0.5.0/src/litmus/signatures.py +276 -0
  29. litmus_cli-0.5.0/src/litmus/transform/file_strip.py +319 -0
  30. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/validate/binary.py +35 -8
  31. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/validate/code.py +14 -0
  32. litmus_cli-0.5.0/src/litmus/validate/pdf.py +82 -0
  33. litmus_cli-0.5.0/src/litmus/validate/svg.py +141 -0
  34. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/validate/treesitter_code.py +9 -1
  35. litmus_cli-0.5.0/src/litmus/watch.py +435 -0
  36. litmus_cli-0.5.0/src/litmus/web_ui.py +863 -0
  37. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/conftest.py +59 -0
  38. litmus_cli-0.5.0/tests/test_api.py +236 -0
  39. litmus_cli-0.5.0/tests/test_bugfixes.py +239 -0
  40. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_cli.py +2 -1
  41. litmus_cli-0.5.0/tests/test_cli_threat.py +421 -0
  42. litmus_cli-0.5.0/tests/test_excerpt.py +70 -0
  43. litmus_cli-0.5.0/tests/test_gif_webp_clean.py +395 -0
  44. litmus_cli-0.5.0/tests/test_image_formats.py +957 -0
  45. litmus_cli-0.5.0/tests/test_image_threats.py +574 -0
  46. litmus_cli-0.5.0/tests/test_pdf_metadata.py +261 -0
  47. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_registry_and_report.py +10 -2
  48. litmus_cli-0.5.0/tests/test_security_report.py +373 -0
  49. litmus_cli-0.5.0/tests/test_security_verdict.py +167 -0
  50. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_server.py +95 -1
  51. litmus_cli-0.5.0/tests/test_signatures.py +354 -0
  52. litmus_cli-0.5.0/tests/test_svg_active_content.py +406 -0
  53. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_transform_and_validate.py +4 -1
  54. litmus_cli-0.5.0/tests/test_watch.py +639 -0
  55. litmus_cli-0.5.0/tests/test_web_ui.py +388 -0
  56. litmus_cli-0.5.0/tests/test_yara_rules.py +330 -0
  57. litmus_cli-0.3.0/README.md +0 -76
  58. litmus_cli-0.3.0/src/litmus/cli.py +0 -342
  59. litmus_cli-0.3.0/src/litmus/inspectors/file_metadata.py +0 -210
  60. litmus_cli-0.3.0/src/litmus/transform/file_strip.py +0 -148
  61. litmus_cli-0.3.0/src/litmus/web_ui.py +0 -728
  62. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/LICENSE +0 -0
  63. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/SECURITY.md +0 -0
  64. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/detectors/__init__.py +0 -0
  65. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/detectors/base.py +0 -0
  66. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/inspectors/base.py +0 -0
  67. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/inspectors/text_markers.py +0 -0
  68. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/inspectors/unicode_scan.py +0 -0
  69. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/office.py +0 -0
  70. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/providers/__init__.py +0 -0
  71. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/providers/registry.py +0 -0
  72. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/transform/__init__.py +0 -0
  73. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/transform/base.py +0 -0
  74. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/transform/code_structural.py +0 -0
  75. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/transform/text_normalize.py +0 -0
  76. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/validate/__init__.py +0 -0
  77. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/validate/office.py +0 -0
  78. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/validate/structural.py +0 -0
  79. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/src/litmus/validate/text.py +0 -0
  80. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_code_treesitter.py +0 -0
  81. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_exif_location.py +0 -0
  82. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_file_inspectors.py +0 -0
  83. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_office_metadata.py +0 -0
  84. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_removal.py +0 -0
  85. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_structural_imports.py +0 -0
  86. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_unicode_inspector.py +0 -0
  87. {litmus_cli-0.3.0 → litmus_cli-0.5.0}/tests/test_visible_content_invariant.py +0 -0
@@ -21,3 +21,15 @@ venv/
21
21
 
22
22
  # Artifacts a run may leave behind
23
23
  *.bak
24
+
25
+ # Local-only working files (never committed)
26
+ FEATURES.md
27
+ CLAUDE.md
28
+ RULES.md
29
+ .claude/
30
+ .githooks/
31
+
32
+ # Local secrets
33
+ .env
34
+ .env.*
35
+ !.env.example
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: litmus-cli
3
- Version: 0.3.0
3
+ Version: 0.5.0
4
4
  Summary: AI provenance inspector and quality-preserving transformation system
5
5
  Project-URL: Homepage, https://github.com/LastDev-coder/litmus
6
6
  Project-URL: Repository, https://github.com/LastDev-coder/litmus
@@ -28,13 +28,16 @@ Requires-Dist: pytest>=8.0; extra == 'dev'
28
28
  Requires-Dist: ruff>=0.5; extra == 'dev'
29
29
  Requires-Dist: tree-sitter-language-pack>=0.9; extra == 'dev'
30
30
  Requires-Dist: tree-sitter>=0.23; extra == 'dev'
31
+ Requires-Dist: yara-python>=4.3; extra == 'dev'
32
+ Provides-Extra: yara
33
+ Requires-Dist: yara-python>=4.3; extra == 'yara'
31
34
  Description-Content-Type: text/markdown
32
35
 
33
36
  # litmus
34
37
 
35
38
  **See what's hiding in your files — and remove it, safely.**
36
39
 
37
- ![litmus — a local web app that reveals and removes hidden content from your files](assets/screenshot.png)
40
+ ![litmus — a local web app that reveals and removes hidden content from your files](https://raw.githubusercontent.com/LastDev-coder/litmus/main/assets/screenshot.png)
38
41
 
39
42
  litmus is a private, fully local tool that reveals invisible characters, hidden
40
43
  file information and content credentials in your documents, code and images —
@@ -47,9 +50,33 @@ your original untouched.
47
50
  - **Trust** — nothing is saved unless the result is verified safe
48
51
  - **Private** — 100% offline; your files never leave your machine
49
52
 
50
- Works with text, source code, PNG, JPEG and SVG files.
53
+ Works with text, source code, PNG, JPEG, GIF, WebP, SVG, BMP, ICO, TIFF,
54
+ HEIC / AVIF, PDF and Office files (docx / xlsx / pptx). Cleaning is available
55
+ for text, code, PNG, JPEG, GIF, WebP, SVG, PDF and Office files; the other image
56
+ types are checked but not changed.
51
57
 
52
- ## Get started in one minute
58
+ ## Install
59
+
60
+ With [uv](https://docs.astral.sh/uv/) — works even if your system Python is
61
+ old or `pip` is missing (the default on macOS):
62
+
63
+ ```bash
64
+ uv tool install litmus-cli
65
+ litmus serve # opens the web app in your browser
66
+ ```
67
+
68
+ Or with pip, if you already have Python 3.11+:
69
+
70
+ ```bash
71
+ pip install litmus-cli # or: python3 -m pip install litmus-cli
72
+ ```
73
+
74
+ Either way the package installs the `litmus` command; see
75
+ [Command line](#command-line) below for terminal usage. If `litmus` isn't
76
+ found after a uv install, run `uv tool update-shell` once and open a new
77
+ terminal.
78
+
79
+ ### Or run from source
53
80
 
54
81
  ```bash
55
82
  git clone https://github.com/LastDev-coder/litmus
@@ -59,9 +86,8 @@ cd litmus
59
86
  ```
60
87
 
61
88
  That's the whole setup — it prepares everything and opens the app in your
62
- browser. Drop a file in, choose **Check** or **Clean**, and download the clean
63
- result. Requires Python 3.11+ (or [uv](https://docs.astral.sh/uv/), which
64
- fetches Python for you).
89
+ browser — no Python setup needed if you have
90
+ [uv](https://docs.astral.sh/uv/), which fetches everything for you.
65
91
 
66
92
  ## Using the app
67
93
 
@@ -97,6 +123,43 @@ For source-code files, litmus is deliberately strict: it saves a cleaned code
97
123
  file only when it can verify the program still behaves the same. If it can't
98
124
  verify, it refuses and tells you why.
99
125
 
126
+ ## Image security checks
127
+
128
+ litmus also looks for structural signs that an image hides something harmful,
129
+ and gives each file a verdict: **high**, **suspicious** or **none found**.
130
+
131
+ - Data hidden after the end of the image (for example a PHP web shell
132
+ appended to a JPEG), and file or script signatures inside the image
133
+ - Files whose content does not match their extension (a ".jpg" that is a ZIP)
134
+ - SVG files with scripts, event handlers, `javascript:` links or risky XML
135
+ entities — the SVG clean removes scripts and handlers, behind a proof that
136
+ the drawing is unchanged
137
+ - Images that declare huge dimensions (decompression bombs) and damaged files
138
+ - Optional: known-signature scanning with YARA (bundled rules for image
139
+ exploits) or your own local ClamAV
140
+
141
+ ```bash
142
+ litmus inspect uploads/ --fail-on-threat suspicious # CI / batch gate
143
+ litmus guard avatar.jpg # one JSON verdict; exit 1 = blocked
144
+ litmus watch uploads/ --quarantine quarantine/ # scan new files, move high-threat ones
145
+ litmus inspect uploads/ --security-report report.html # plain-language report: what, why, what to do
146
+ pip install "litmus-cli[yara]" # then: --signatures yara
147
+ ```
148
+
149
+ From Python, `litmus.scan_upload(data, filename)` returns a verdict before you
150
+ save an upload. In the web app, **Export report (PDF)** opens the detailed report
151
+ and your browser's print dialog — choose "Save as PDF". **litmus is not an antivirus.** "None found" means none of its
152
+ checks matched — it is not proof that a file is safe.
153
+
154
+ ## What litmus won't claim
155
+
156
+ Honesty is the point of this tool, so two limits are stated up front:
157
+
158
+ - litmus finds *hidden content* — it does **not** detect statistical AI
159
+ watermarks in plain text (no public tool can), and it never labels a file
160
+ "AI-generated" or "human-written".
161
+ - Finding nothing is not proof there is nothing. litmus reports only what it
162
+ can actually verify.
100
163
 
101
164
  ## Privacy
102
165
 
@@ -0,0 +1,136 @@
1
+ # litmus
2
+
3
+ **See what's hiding in your files — and remove it, safely.**
4
+
5
+ ![litmus — a local web app that reveals and removes hidden content from your files](https://raw.githubusercontent.com/LastDev-coder/litmus/main/assets/screenshot.png)
6
+
7
+ litmus is a private, fully local tool that reveals invisible characters, hidden
8
+ file information and content credentials in your documents, code and images —
9
+ then strips them out without changing anything you can see. Every clean-up is
10
+ checked before it is saved: if a change cannot be confirmed safe, litmus keeps
11
+ your original untouched.
12
+
13
+ - **Check** — see what's hidden: invisible characters, embedded file info, content credentials
14
+ - **Clean** — remove it, while what you see stays exactly the same
15
+ - **Trust** — nothing is saved unless the result is verified safe
16
+ - **Private** — 100% offline; your files never leave your machine
17
+
18
+ Works with text, source code, PNG, JPEG, GIF, WebP, SVG, BMP, ICO, TIFF,
19
+ HEIC / AVIF, PDF and Office files (docx / xlsx / pptx). Cleaning is available
20
+ for text, code, PNG, JPEG, GIF, WebP, SVG, PDF and Office files; the other image
21
+ types are checked but not changed.
22
+
23
+ ## Install
24
+
25
+ With [uv](https://docs.astral.sh/uv/) — works even if your system Python is
26
+ old or `pip` is missing (the default on macOS):
27
+
28
+ ```bash
29
+ uv tool install litmus-cli
30
+ litmus serve # opens the web app in your browser
31
+ ```
32
+
33
+ Or with pip, if you already have Python 3.11+:
34
+
35
+ ```bash
36
+ pip install litmus-cli # or: python3 -m pip install litmus-cli
37
+ ```
38
+
39
+ Either way the package installs the `litmus` command; see
40
+ [Command line](#command-line) below for terminal usage. If `litmus` isn't
41
+ found after a uv install, run `uv tool update-shell` once and open a new
42
+ terminal.
43
+
44
+ ### Or run from source
45
+
46
+ ```bash
47
+ git clone https://github.com/LastDev-coder/litmus
48
+ cd litmus
49
+ ./start.sh # macOS / Linux
50
+ ./start.ps1 # Windows (PowerShell)
51
+ ```
52
+
53
+ That's the whole setup — it prepares everything and opens the app in your
54
+ browser — no Python setup needed if you have
55
+ [uv](https://docs.astral.sh/uv/), which fetches everything for you.
56
+
57
+ ## Using the app
58
+
59
+ 1. **Drop a file** onto the page.
60
+ 2. **Check** shows what's hiding inside, explained in plain language.
61
+ 3. **Clean** removes it and hands you the cleaned file. Your original is never
62
+ modified.
63
+
64
+ Pick a cleaning level to control how much is done:
65
+
66
+ | Level | What it does |
67
+ |---|---|
68
+ | Minimal | Remove invisible characters only |
69
+ | Standard *(default)* | Also normalize unusual spaces, line endings and letterforms |
70
+ | Tidy | Also neaten extra blank lines |
71
+ | Code-aware | Also remove unused Python imports |
72
+
73
+ ## Command line
74
+
75
+ Prefer a terminal? After setup, the same features are available as commands:
76
+
77
+ ```bash
78
+ source .venv/bin/activate
79
+
80
+ litmus inspect myfile.txt # what's hidden? (read-only)
81
+ litmus transform myfile.txt # print the cleaned version
82
+ litmus transform myfile.txt --in-place --backup # save it, keep a .bak
83
+ litmus serve # open the web app
84
+ litmus --help # everything else
85
+ ```
86
+
87
+ For source-code files, litmus is deliberately strict: it saves a cleaned code
88
+ file only when it can verify the program still behaves the same. If it can't
89
+ verify, it refuses and tells you why.
90
+
91
+ ## Image security checks
92
+
93
+ litmus also looks for structural signs that an image hides something harmful,
94
+ and gives each file a verdict: **high**, **suspicious** or **none found**.
95
+
96
+ - Data hidden after the end of the image (for example a PHP web shell
97
+ appended to a JPEG), and file or script signatures inside the image
98
+ - Files whose content does not match their extension (a ".jpg" that is a ZIP)
99
+ - SVG files with scripts, event handlers, `javascript:` links or risky XML
100
+ entities — the SVG clean removes scripts and handlers, behind a proof that
101
+ the drawing is unchanged
102
+ - Images that declare huge dimensions (decompression bombs) and damaged files
103
+ - Optional: known-signature scanning with YARA (bundled rules for image
104
+ exploits) or your own local ClamAV
105
+
106
+ ```bash
107
+ litmus inspect uploads/ --fail-on-threat suspicious # CI / batch gate
108
+ litmus guard avatar.jpg # one JSON verdict; exit 1 = blocked
109
+ litmus watch uploads/ --quarantine quarantine/ # scan new files, move high-threat ones
110
+ litmus inspect uploads/ --security-report report.html # plain-language report: what, why, what to do
111
+ pip install "litmus-cli[yara]" # then: --signatures yara
112
+ ```
113
+
114
+ From Python, `litmus.scan_upload(data, filename)` returns a verdict before you
115
+ save an upload. In the web app, **Export report (PDF)** opens the detailed report
116
+ and your browser's print dialog — choose "Save as PDF". **litmus is not an antivirus.** "None found" means none of its
117
+ checks matched — it is not proof that a file is safe.
118
+
119
+ ## What litmus won't claim
120
+
121
+ Honesty is the point of this tool, so two limits are stated up front:
122
+
123
+ - litmus finds *hidden content* — it does **not** detect statistical AI
124
+ watermarks in plain text (no public tool can), and it never labels a file
125
+ "AI-generated" or "human-written".
126
+ - Finding nothing is not proof there is nothing. litmus reports only what it
127
+ can actually verify.
128
+
129
+ ## Privacy
130
+
131
+ Everything runs on your machine. No accounts, no uploads, no telemetry, no
132
+ network access. The web app binds to `127.0.0.1` and analyses files in memory.
133
+
134
+ ## License
135
+
136
+ [MIT](LICENSE)
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "litmus-cli"
3
- version = "0.3.0"
3
+ version = "0.5.0"
4
4
  description = "AI provenance inspector and quality-preserving transformation system"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -26,12 +26,16 @@ c2pa = ["c2pa-python>=0.5"]
26
26
  # Multi-language structural code validation (JS/TS/Java/Kotlin/Swift). Python
27
27
  # is validated with the stdlib and needs nothing here.
28
28
  code = ["tree-sitter>=0.23", "tree-sitter-language-pack>=0.9"]
29
+ # Opt-in YARA signature scanning (bundled rules plus your own). ClamAV needs no
30
+ # Python package: litmus calls your locally installed clamscan.
31
+ yara = ["yara-python>=4.3"]
29
32
  dev = [
30
33
  "pytest>=8.0",
31
34
  "mypy>=1.10",
32
35
  "ruff>=0.5",
33
36
  "tree-sitter>=0.23",
34
37
  "tree-sitter-language-pack>=0.9",
38
+ "yara-python>=4.3",
35
39
  ]
36
40
 
37
41
  [project.urls]
@@ -68,7 +72,7 @@ packages = ["litmus"]
68
72
  [[tool.mypy.overrides]]
69
73
  # Optional dependencies with no type stubs. Listed here so the type check is
70
74
  # clean whether or not the extra happens to be installed.
71
- module = ["tree_sitter_language_pack.*", "tree_sitter.*", "c2pa.*"]
75
+ module = ["tree_sitter_language_pack.*", "tree_sitter.*", "c2pa.*", "yara"]
72
76
  ignore_missing_imports = true
73
77
 
74
78
  [tool.ruff]
@@ -8,8 +8,9 @@ watermarks; no public detector exists for them.
8
8
 
9
9
  from __future__ import annotations
10
10
 
11
+ from .api import Scanner, UploadVerdict, scan_path, scan_upload
11
12
  from .artifact import Artifact, load_bytes, load_path
12
- from .model import TOOL_VERSION, Report
13
+ from .model import TOOL_VERSION, Report, ThreatLevel
13
14
  from .pipeline import TransformOptions, analyze, inspect, transform
14
15
 
15
16
  __version__ = TOOL_VERSION
@@ -17,11 +18,16 @@ __version__ = TOOL_VERSION
17
18
  __all__ = [
18
19
  "Artifact",
19
20
  "Report",
21
+ "Scanner",
22
+ "ThreatLevel",
20
23
  "TransformOptions",
24
+ "UploadVerdict",
21
25
  "__version__",
22
26
  "analyze",
23
27
  "inspect",
24
28
  "load_bytes",
25
29
  "load_path",
30
+ "scan_path",
31
+ "scan_upload",
26
32
  "transform",
27
33
  ]
@@ -0,0 +1,216 @@
1
+ """Upload-gate API: scan bytes or a file and get an allow/block verdict.
2
+
3
+ The verdict summarises structural threat indicators (and, if enabled, known
4
+ signature matches). It is never a statement that a file is safe: a verdict of
5
+ ``none_found`` only means no listed indicator was found by the checks that ran
6
+ (see :data:`litmus.security.NOT_PROOF_OF_SAFETY`).
7
+
8
+ Errors are not verdicts. :func:`scan_upload` and :func:`scan_path` raise
9
+ :class:`litmus.artifact.ArtifactError` for input that cannot be scanned (for
10
+ example above the 32 MiB limit), and the signature module raises
11
+ ``SignatureEngineError`` when an engine cannot be loaded. Callers should treat
12
+ any exception as *blocked* (fail closed).
13
+
14
+ Example, inside a web upload handler (framework-agnostic)::
15
+
16
+ from litmus import Scanner, ThreatLevel
17
+
18
+ SCANNER = Scanner() # build once; reuse for every request
19
+
20
+ def handle_upload(request):
21
+ upload = request.files["file"]
22
+ try:
23
+ verdict = SCANNER.scan_upload(upload.read(), upload.filename)
24
+ except Exception:
25
+ return "upload rejected", 400 # fail closed
26
+ if not verdict.allowed:
27
+ return f"upload rejected: {verdict.threat_level.value}", 400
28
+ ... # store the file; verdict.note explains what was not checked
29
+
30
+ Everything runs in memory: :meth:`Scanner.scan_upload` writes nothing to disk.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ from collections.abc import Collection, Sequence
36
+ from dataclasses import dataclass
37
+ from pathlib import Path
38
+
39
+ from .artifact import MAX_DEFAULT_BYTES, Artifact, ArtifactError, load_bytes, load_path
40
+ from .inspectors import Inspector, default_inspectors
41
+ from .model import Report, SecurityReason, ThreatLevel
42
+ from .pipeline import analyze
43
+ from .security import assess, at_least
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class UploadVerdict:
48
+ """The outcome of one scan.
49
+
50
+ ``allowed`` is True only when the scan is ``complete`` and the threat level
51
+ is below ``block_at``. A scan is incomplete (fail closed) when a requested
52
+ signature engine did not run on this file or any inspector crashed.
53
+ """
54
+
55
+ allowed: bool
56
+ threat_level: ThreatLevel
57
+ reasons: tuple[SecurityReason, ...]
58
+ engines: tuple[str, ...]
59
+ #: Always the "not proof of safety" wording; show it next to any allow.
60
+ note: str
61
+ report: Report
62
+ complete: bool
63
+ incomplete_reasons: tuple[str, ...]
64
+
65
+
66
+ def incomplete_reasons(report: Report, requested: Collection[str]) -> tuple[str, ...]:
67
+ """Why a scan did not check everything it should have; empty when complete.
68
+
69
+ Counts a crashed inspector (``InspectorStatus.error``) and a requested
70
+ signature engine that did not run on this file. A normal skip ("not
71
+ applicable") of an inspector nobody asked for does not count.
72
+ """
73
+ reasons: list[str] = []
74
+ for status in report.inspection.inspectors:
75
+ if status.error:
76
+ reasons.append(f"inspector {status.name} crashed: {status.reason}")
77
+ elif status.name in requested and not status.ran:
78
+ reasons.append(f"signature engine {status.name} did not run: {status.reason}")
79
+ return tuple(reasons)
80
+
81
+
82
+ def normalize_engines(values: Sequence[str]) -> tuple[str, ...]:
83
+ """Split comma-separated engine names, drop blanks and duplicates, keep order."""
84
+ names: list[str] = []
85
+ for value in values:
86
+ for part in value.split(","):
87
+ name = part.strip()
88
+ if name and name not in names:
89
+ names.append(name)
90
+ return tuple(names)
91
+
92
+
93
+ def _signature_inspectors(names: tuple[str, ...], yara_rules: Path | None) -> list[Inspector]:
94
+ """Build the signature-engine inspectors. The single seam tests replace."""
95
+ if not names and yara_rules is None:
96
+ return []
97
+ from .signatures import SignatureEngineError, build_signature_inspectors
98
+
99
+ if yara_rules is not None and "yara" not in names:
100
+ raise SignatureEngineError("custom YARA rules need the 'yara' signature engine enabled")
101
+ return build_signature_inspectors(names, yara_rules=yara_rules)
102
+
103
+
104
+ class Scanner:
105
+ """Holds the inspectors (including compiled signature rules) for many scans.
106
+
107
+ Build one and reuse it: constructing a scanner with signature engines loads
108
+ and compiles their rules, which is the expensive part.
109
+ """
110
+
111
+ def __init__(self, *, signatures: Sequence[str] = (), yara_rules: Path | None = None) -> None:
112
+ engines = normalize_engines(signatures)
113
+ self.requested_engines = frozenset(engines)
114
+ self._inspectors = default_inspectors() + _signature_inspectors(engines, yara_rules)
115
+
116
+ @property
117
+ def inspectors(self) -> list[Inspector]:
118
+ return list(self._inspectors)
119
+
120
+ def scan_artifact(
121
+ self, artifact: Artifact, *, block_at: ThreatLevel = ThreatLevel.SUSPICIOUS
122
+ ) -> UploadVerdict:
123
+ report, _ = analyze(artifact, inspectors=self._inspectors)
124
+ security = report.security if report.security is not None else assess(report)
125
+ gaps = incomplete_reasons(report, self.requested_engines)
126
+ return UploadVerdict(
127
+ allowed=not gaps and not at_least(security.threat_level, block_at),
128
+ threat_level=security.threat_level,
129
+ reasons=tuple(security.reasons),
130
+ engines=tuple(security.engines),
131
+ note=security.note,
132
+ report=report,
133
+ complete=not gaps,
134
+ incomplete_reasons=gaps,
135
+ )
136
+
137
+ def scan_upload(
138
+ self,
139
+ data: bytes,
140
+ filename: str | None = None,
141
+ *,
142
+ block_at: ThreatLevel = ThreatLevel.SUSPICIOUS,
143
+ ) -> UploadVerdict:
144
+ """Scan bytes in memory. ``filename`` only informs type routing and the report.
145
+
146
+ Raises :class:`ArtifactError` above the 32 MiB limit; treat it as blocked.
147
+ """
148
+ if len(data) > MAX_DEFAULT_BYTES:
149
+ raise ArtifactError(
150
+ f"{filename or '<upload>'} is {len(data)} bytes, "
151
+ f"above the {MAX_DEFAULT_BYTES} byte limit"
152
+ )
153
+ artifact = load_bytes(data, path=Path(filename) if filename else None)
154
+ return self.scan_artifact(artifact, block_at=block_at)
155
+
156
+ def scan_path(
157
+ self, path: Path | str, *, block_at: ThreatLevel = ThreatLevel.SUSPICIOUS
158
+ ) -> UploadVerdict:
159
+ """Read and scan one file. Raises :class:`ArtifactError` if it cannot be read."""
160
+ return self.scan_artifact(load_path(Path(path)), block_at=block_at)
161
+
162
+
163
+ def scan_upload(
164
+ data: bytes,
165
+ filename: str | None = None,
166
+ *,
167
+ block_at: ThreatLevel = ThreatLevel.SUSPICIOUS,
168
+ signatures: Sequence[str] = (),
169
+ yara_rules: Path | None = None,
170
+ ) -> UploadVerdict:
171
+ """One-off :meth:`Scanner.scan_upload`. Builds the inspectors on every call;
172
+ reuse a :class:`Scanner` when scanning many uploads."""
173
+ scanner = Scanner(signatures=signatures, yara_rules=yara_rules)
174
+ return scanner.scan_upload(data, filename, block_at=block_at)
175
+
176
+
177
+ def scan_path(
178
+ path: Path | str,
179
+ *,
180
+ block_at: ThreatLevel = ThreatLevel.SUSPICIOUS,
181
+ signatures: Sequence[str] = (),
182
+ yara_rules: Path | None = None,
183
+ ) -> UploadVerdict:
184
+ """One-off :meth:`Scanner.scan_path`. Reuse a :class:`Scanner` for many files."""
185
+ scanner = Scanner(signatures=signatures, yara_rules=yara_rules)
186
+ return scanner.scan_path(path, block_at=block_at)
187
+
188
+
189
+ def verdict_json(verdict: UploadVerdict, path: str | None) -> dict[str, object]:
190
+ """The compact JSON shape shared by ``litmus guard`` and ``litmus watch --json``."""
191
+ return {
192
+ "path": path,
193
+ "allowed": verdict.allowed,
194
+ "threat_level": verdict.threat_level.value,
195
+ "reasons": [
196
+ {
197
+ "level": r.level.value,
198
+ "detector": r.detector,
199
+ "category": r.category,
200
+ "summary": r.summary,
201
+ }
202
+ for r in verdict.reasons
203
+ ],
204
+ "engines": list(verdict.engines),
205
+ "note": verdict.note,
206
+ }
207
+
208
+
209
+ __all__ = [
210
+ "Scanner",
211
+ "UploadVerdict",
212
+ "incomplete_reasons",
213
+ "normalize_engines",
214
+ "scan_path",
215
+ "scan_upload",
216
+ ]
@@ -24,7 +24,7 @@ _LANGUAGE_BY_SUFFIX: dict[str, str] = {
24
24
  ".java": "java",
25
25
  ".swift": "swift",
26
26
  ".ts": "typescript",
27
- ".tsx": "typescript",
27
+ ".tsx": "tsx",
28
28
  ".js": "javascript",
29
29
  ".jsx": "javascript",
30
30
  ".mjs": "javascript",
@@ -40,6 +40,15 @@ _MEDIA_TYPE_BY_SUFFIX: dict[str, str] = {
40
40
  ".svg": "image/svg+xml",
41
41
  ".webp": "image/webp",
42
42
  ".gif": "image/gif",
43
+ ".bmp": "image/bmp",
44
+ ".dib": "image/bmp",
45
+ ".ico": "image/vnd.microsoft.icon",
46
+ ".cur": "image/vnd.microsoft.icon",
47
+ ".tif": "image/tiff",
48
+ ".tiff": "image/tiff",
49
+ ".heic": "image/heic",
50
+ ".heif": "image/heif",
51
+ ".avif": "image/avif",
43
52
  ".pdf": "application/pdf",
44
53
  ".md": "text/markdown",
45
54
  ".txt": "text/plain",
@@ -112,8 +121,15 @@ def _decode(data: bytes) -> tuple[str | None, str | None]:
112
121
  return text, "utf-8-sig" if data.startswith(codecs.BOM_UTF8) else "utf-8"
113
122
 
114
123
 
124
+ def _suffix(path: Path | None) -> str:
125
+ """Lower-case suffix, ignoring trailing dots/spaces (Windows drops them on save)."""
126
+ if path is None:
127
+ return ""
128
+ return Path(path.name.rstrip(". ")).suffix.lower()
129
+
130
+
115
131
  def classify(path: Path | None, data: bytes, text: str | None) -> tuple[ArtifactKind, str | None]:
116
- language = _LANGUAGE_BY_SUFFIX.get(path.suffix.lower()) if path else None
132
+ language = _LANGUAGE_BY_SUFFIX.get(_suffix(path))
117
133
  if text is None:
118
134
  return ArtifactKind.BINARY, None
119
135
  if language is not None:
@@ -124,7 +140,7 @@ def classify(path: Path | None, data: bytes, text: str | None) -> tuple[Artifact
124
140
  def load_bytes(data: bytes, *, path: Path | None = None) -> Artifact:
125
141
  text, encoding = _decode(data)
126
142
  kind, language = classify(path, data, text)
127
- media_type = _MEDIA_TYPE_BY_SUFFIX.get(path.suffix.lower()) if path else None
143
+ media_type = _MEDIA_TYPE_BY_SUFFIX.get(_suffix(path))
128
144
  ref = ArtifactRef(
129
145
  path=str(path) if path else None,
130
146
  kind=kind,