decaloguex 0.3.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.
- decaloguex/__init__.py +16 -0
- decaloguex/__main__.py +12 -0
- decaloguex/blindspots.py +123 -0
- decaloguex/cli.py +405 -0
- decaloguex/engine.py +584 -0
- decaloguex/explain.py +328 -0
- decaloguex/languages.py +358 -0
- decaloguex/models.py +99 -0
- decaloguex/project.py +384 -0
- decaloguex/rules/__init__.py +29 -0
- decaloguex/rules/appsec.py +347 -0
- decaloguex/rules/async_.py +605 -0
- decaloguex/rules/auth.py +293 -0
- decaloguex/rules/common.py +134 -0
- decaloguex/rules/config_files.py +159 -0
- decaloguex/rules/errors.py +641 -0
- decaloguex/rules/fallbacks.py +229 -0
- decaloguex/rules/gitignore.py +371 -0
- decaloguex/rules/injection.py +452 -0
- decaloguex/rules/launch.py +288 -0
- decaloguex/rules/other_languages.py +1629 -0
- decaloguex/rules/secrets.py +632 -0
- decaloguex/rules/sql.py +1052 -0
- decaloguex/rules/supabase.py +109 -0
- decaloguex/rules/web.py +643 -0
- decaloguex/scenes.py +341 -0
- decaloguex/telemetry.py +366 -0
- decaloguex/ui.py +798 -0
- decaloguex/undo.py +185 -0
- decaloguex-0.3.0.dist-info/METADATA +452 -0
- decaloguex-0.3.0.dist-info/RECORD +35 -0
- decaloguex-0.3.0.dist-info/WHEEL +5 -0
- decaloguex-0.3.0.dist-info/entry_points.txt +2 -0
- decaloguex-0.3.0.dist-info/licenses/LICENSE +21 -0
- decaloguex-0.3.0.dist-info/top_level.txt +1 -0
decaloguex/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""
|
|
2
|
+
DecalogueX: the "Crash Doctor" scanner (Phase 0).
|
|
3
|
+
|
|
4
|
+
JAVA COMPARISON: a folder containing an __init__.py file is a Python
|
|
5
|
+
"package", the same idea as a Java package (com.decaloguex). This file runs
|
|
6
|
+
once, the first time anything inside the package is imported, a bit like a
|
|
7
|
+
static initializer block. Most packages leave it nearly empty.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
# The version string, readable from anywhere as decaloguex.__version__.
|
|
11
|
+
# Keep it in sync with the version in pyproject.toml.
|
|
12
|
+
__version__ = "0.3.0"
|
|
13
|
+
|
|
14
|
+
# Shown at the end of every scan, and included in the --json report so AI
|
|
15
|
+
# tools can pass it on. Change the wording here and it changes everywhere.
|
|
16
|
+
EARLY_ACCESS_NOTICE = "DecalogueX is in free early access. The full version is coming soon."
|
decaloguex/__main__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Lets you run the tool with: python -m decaloguex scan <path>
|
|
3
|
+
|
|
4
|
+
JAVA COMPARISON: `python -m decaloguex` is like `java -jar decaloguex.jar`.
|
|
5
|
+
Python looks for a __main__.py file inside the package and runs it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from decaloguex.cli import main
|
|
9
|
+
|
|
10
|
+
# SystemExit is how a Python program sets its exit code, the same as
|
|
11
|
+
# System.exit(code) in Java. main() returns 0 for success, 1 if problems remain.
|
|
12
|
+
raise SystemExit(main())
|
decaloguex/blindspots.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""
|
|
2
|
+
blindspots.py: an honest list of what DecalogueX could NOT check.
|
|
3
|
+
|
|
4
|
+
A security tool that quietly skips things gives people false confidence.
|
|
5
|
+
So every scan keeps track of its blind spots and shows them openly:
|
|
6
|
+
|
|
7
|
+
unsupported code files in languages DecalogueX can't read yet
|
|
8
|
+
("10 Rust files"). These tell you which language to add next.
|
|
9
|
+
tripped files where a rule hit something it didn't expect and had to
|
|
10
|
+
stop. The rest of the scan carries on; these show where a
|
|
11
|
+
rule needs improving.
|
|
12
|
+
too_big files too large to check quickly (usually generated code).
|
|
13
|
+
generated minified or machine-generated files (like app.min.js). People
|
|
14
|
+
don't edit these, so they aren't checked or changed.
|
|
15
|
+
test_files how many test, test-data and example files were found. These
|
|
16
|
+
are only checked for REAL key formats, and never changed:
|
|
17
|
+
they're full of made-up passwords on purpose.
|
|
18
|
+
manual problems DecalogueX found but can't fix safely, by rule
|
|
19
|
+
("SQL-001: 3"). These show where an automatic fix is worth adding.
|
|
20
|
+
reported_wrong findings the USER marked as wrong (the "w" key): a false
|
|
21
|
+
alarm, or a fix that looks wrong. Only a person can spot
|
|
22
|
+
these, and they show exactly which rule needs improving.
|
|
23
|
+
|
|
24
|
+
The report is saved in the project as .decaloguex/blind-spots.json so you
|
|
25
|
+
can look back at it, and (as anonymous counts only) it's part of the usage
|
|
26
|
+
stats, so you can see the most common blind spots across all users.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import json
|
|
32
|
+
from collections import Counter # a dict that counts things, like a HashMap<String, Integer>
|
|
33
|
+
from dataclasses import dataclass, field
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
|
|
36
|
+
# Code file types DecalogueX recognises but can't check yet.
|
|
37
|
+
# Extension -> the language's name.
|
|
38
|
+
UNSUPPORTED_CODE = {
|
|
39
|
+
".rs": "Rust", ".c": "C", ".h": "C", ".cpp": "C++", ".cc": "C++", ".hpp": "C++",
|
|
40
|
+
".dart": "Dart", ".scala": "Scala", ".lua": "Lua", ".pl": "Perl", ".r": "R",
|
|
41
|
+
".m": "Objective-C", ".mm": "Objective-C", ".ex": "Elixir", ".exs": "Elixir",
|
|
42
|
+
".erl": "Erlang", ".hs": "Haskell", ".clj": "Clojure", ".groovy": "Groovy",
|
|
43
|
+
".astro": "Astro",
|
|
44
|
+
".fs": "F#", ".vb": "Visual Basic", ".jl": "Julia", ".zig": "Zig", ".sol": "Solidity",
|
|
45
|
+
# (Shell and PowerShell scripts are checked for secrets in config_files.py,
|
|
46
|
+
# and Razor/ERB page templates are checked like HTML pages.)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
MAX_FILE_SIZE = 2_000_000 # bytes. Bigger files are skipped (and listed as a blind spot).
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class BlindSpots:
|
|
54
|
+
"""Everything a scan couldn't check, and why."""
|
|
55
|
+
|
|
56
|
+
unsupported: Counter = field(default_factory=Counter) # language -> number of files
|
|
57
|
+
tripped: list[dict] = field(default_factory=list) # {"path", "rule", "error"} per problem
|
|
58
|
+
too_big: list[str] = field(default_factory=list) # relative paths
|
|
59
|
+
manual: Counter = field(default_factory=Counter) # rule ID -> number of findings
|
|
60
|
+
# {"rule", "file", "line", "reason"} for each finding the user marked as wrong
|
|
61
|
+
reported_wrong: list[dict] = field(default_factory=list)
|
|
62
|
+
generated: list[str] = field(default_factory=list) # relative paths
|
|
63
|
+
test_files: int = 0
|
|
64
|
+
|
|
65
|
+
def is_empty(self) -> bool:
|
|
66
|
+
return not (self.unsupported or self.tripped or self.too_big or self.manual or self.reported_wrong
|
|
67
|
+
or self.generated or self.test_files)
|
|
68
|
+
|
|
69
|
+
def files_not_checked(self) -> int:
|
|
70
|
+
tripped_files = {t["path"] for t in self.tripped}
|
|
71
|
+
return sum(self.unsupported.values()) + len(self.too_big) + len(self.generated) + len(tripped_files)
|
|
72
|
+
|
|
73
|
+
def to_dict(self) -> dict:
|
|
74
|
+
return {
|
|
75
|
+
"unsupported_languages": dict(self.unsupported.most_common()),
|
|
76
|
+
"tripped": self.tripped,
|
|
77
|
+
"too_big": self.too_big,
|
|
78
|
+
"generated": self.generated,
|
|
79
|
+
"test_files_only_checked_for_real_keys": self.test_files,
|
|
80
|
+
"manual_steps_by_rule": dict(sorted(self.manual.items())),
|
|
81
|
+
"reported_wrong": self.reported_wrong,
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def unsupported_language(path: Path) -> str | None:
|
|
86
|
+
"""The language name if this is a code file DecalogueX can't check yet."""
|
|
87
|
+
name = path.name.lower()
|
|
88
|
+
for extension, language in UNSUPPORTED_CODE.items():
|
|
89
|
+
if name.endswith(extension):
|
|
90
|
+
return language
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def save(root: Path, spots: BlindSpots) -> Path | None:
|
|
95
|
+
"""Write the report to <project>/.decaloguex/blind-spots.json."""
|
|
96
|
+
folder = private_folder(root)
|
|
97
|
+
if folder is None:
|
|
98
|
+
return None
|
|
99
|
+
target = folder / "blind-spots.json"
|
|
100
|
+
try:
|
|
101
|
+
target.write_text(json.dumps(spots.to_dict(), indent=2), encoding="utf-8")
|
|
102
|
+
except OSError:
|
|
103
|
+
return None # a read-only folder, say. Never worth crashing over.
|
|
104
|
+
return target
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def private_folder(root: Path) -> Path | None:
|
|
108
|
+
"""DecalogueX's own folder inside the project: .decaloguex/
|
|
109
|
+
|
|
110
|
+
It holds the blind spots report and the undo backups. A .gitignore
|
|
111
|
+
INSIDE it ("*", meaning everything) keeps the whole folder out of Git,
|
|
112
|
+
without touching the project's own .gitignore. That matters because the
|
|
113
|
+
backups can contain the secrets that were just moved out of the code.
|
|
114
|
+
"""
|
|
115
|
+
folder = root / ".decaloguex"
|
|
116
|
+
try:
|
|
117
|
+
folder.mkdir(exist_ok=True)
|
|
118
|
+
ignore = folder / ".gitignore"
|
|
119
|
+
if not ignore.exists():
|
|
120
|
+
ignore.write_text("# DecalogueX's private files. Never upload these.\n*\n", encoding="utf-8")
|
|
121
|
+
except OSError:
|
|
122
|
+
return None
|
|
123
|
+
return folder
|
decaloguex/cli.py
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
"""
|
|
2
|
+
cli.py: the `decaloguex` command.
|
|
3
|
+
|
|
4
|
+
Usage:
|
|
5
|
+
decaloguex scan [path] scan, explain, then ask what to do
|
|
6
|
+
decaloguex scan [path] --yes fix everything without asking
|
|
7
|
+
decaloguex scan [path] --dry-run only show problems; never change anything
|
|
8
|
+
decaloguex scan [path] --json a report for AI tools (add --yes to also fix)
|
|
9
|
+
decaloguex scan [path] --no-animation no moving bars or spinners
|
|
10
|
+
decaloguex scan [path] --no-color plain text, no colours
|
|
11
|
+
decaloguex undo [path] put back everything the last fix changed
|
|
12
|
+
decaloguex telemetry [on|off|status] control the anonymous usage stats
|
|
13
|
+
|
|
14
|
+
Exit codes (what scripts and AI agents check):
|
|
15
|
+
0 nothing left to fix
|
|
16
|
+
1 problems remain (skipped, dry run, or needing a manual step)
|
|
17
|
+
2 bad arguments, or the path doesn't exist
|
|
18
|
+
130 stopped with Ctrl+C (the usual code for that)
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import argparse # reads the command-line options, like picocli in Java
|
|
24
|
+
import json
|
|
25
|
+
import sys
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
from decaloguex import EARLY_ACCESS_NOTICE, __version__, blindspots, engine, project, telemetry, ui, undo
|
|
29
|
+
from decaloguex.explain import explain
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def split_glued_command(argv: list[str]) -> list[str]:
|
|
33
|
+
"""Turn "scan/Users/me/project" back into "scan" + "/Users/me/project".
|
|
34
|
+
|
|
35
|
+
The instructions say: type the command, then drag a folder in. Copy and
|
|
36
|
+
paste often drops the space at the end, so the dragged location gets
|
|
37
|
+
glued straight onto the command word (a beta tester hit exactly this
|
|
38
|
+
on a Mac). If a word starts with a command and the rest looks like a
|
|
39
|
+
location, split it.
|
|
40
|
+
"""
|
|
41
|
+
if argv:
|
|
42
|
+
for command in ("scan", "undo"):
|
|
43
|
+
rest = argv[0][len(command):]
|
|
44
|
+
if argv[0].startswith(command) and rest[:1] in ("/", "\\", "~", ".", "'", '"') \
|
|
45
|
+
or argv[0].startswith(command) and len(rest) > 2 and rest[1] == ":": # C:\...
|
|
46
|
+
return [command, rest.strip("'\"")] + argv[1:]
|
|
47
|
+
return argv
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def main(argv: list[str] | None = None) -> int:
|
|
51
|
+
"""Entry point. argv=None means "use the real command line".
|
|
52
|
+
|
|
53
|
+
Taking argv as a parameter lets tests call main(["scan", "x"]), the
|
|
54
|
+
same way you'd call main(String[] args) from a JUnit test.
|
|
55
|
+
"""
|
|
56
|
+
parser = argparse.ArgumentParser(
|
|
57
|
+
prog="decaloguex",
|
|
58
|
+
description="Crash Doctor: finds and fixes the mistakes AI coding tools leave behind.",
|
|
59
|
+
)
|
|
60
|
+
parser.add_argument("--version", action="version", version=f"decaloguex {__version__}")
|
|
61
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
62
|
+
|
|
63
|
+
scan_cmd = commands.add_parser("scan", help="scan a file or folder")
|
|
64
|
+
scan_cmd.add_argument("path", nargs="?", default=".", help="file or folder to scan (default: this folder)")
|
|
65
|
+
scan_cmd.add_argument("-y", "--yes", action="store_true", help="fix everything without asking")
|
|
66
|
+
scan_cmd.add_argument("--dry-run", action="store_true", help="only show problems; change nothing")
|
|
67
|
+
scan_cmd.add_argument("--json", action="store_true", help="print a JSON report for AI tools")
|
|
68
|
+
scan_cmd.add_argument("--all", action="store_true", dest="show_all",
|
|
69
|
+
help="also show places that are only worth a look, not just sure problems")
|
|
70
|
+
scan_cmd.add_argument("--no-animation", action="store_true", help="no moving bars or spinners")
|
|
71
|
+
scan_cmd.add_argument("--no-color", action="store_true", help="plain text, no colours")
|
|
72
|
+
|
|
73
|
+
undo_cmd = commands.add_parser("undo", help="put back everything the last fix changed")
|
|
74
|
+
undo_cmd.add_argument("path", nargs="?", default=".", help="the project folder (default: this folder)")
|
|
75
|
+
undo_cmd.add_argument("-y", "--yes", action="store_true", help="don't ask, even if files changed since")
|
|
76
|
+
undo_cmd.add_argument("--no-color", action="store_true", help="plain text, no colours")
|
|
77
|
+
|
|
78
|
+
telemetry_cmd = commands.add_parser("telemetry", help="control the anonymous usage stats")
|
|
79
|
+
telemetry_cmd.add_argument("setting", nargs="?", choices=["on", "off", "status"], default="status")
|
|
80
|
+
|
|
81
|
+
args = parser.parse_args(split_glued_command(sys.argv[1:] if argv is None else argv))
|
|
82
|
+
try:
|
|
83
|
+
if args.command == "undo":
|
|
84
|
+
return run_undo(Path(args.path), assume_yes=args.yes, no_color=args.no_color)
|
|
85
|
+
if args.command == "telemetry":
|
|
86
|
+
return run_telemetry(args.setting)
|
|
87
|
+
if args.json:
|
|
88
|
+
return run_json(Path(args.path), assume_yes=args.yes, show_all=args.show_all)
|
|
89
|
+
# argparse turns "--dry-run" into the attribute name dry_run.
|
|
90
|
+
return run_scan(Path(args.path), assume_yes=args.yes, dry_run=args.dry_run,
|
|
91
|
+
no_color=args.no_color, no_animation=args.no_animation, show_all=args.show_all)
|
|
92
|
+
finally:
|
|
93
|
+
telemetry.finish() # let any usage stats finish sending (about a second; at most 4)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# ===========================================================================
|
|
97
|
+
# SCAN (the normal, human mode)
|
|
98
|
+
# ===========================================================================
|
|
99
|
+
|
|
100
|
+
def run_scan(
|
|
101
|
+
target: Path,
|
|
102
|
+
assume_yes: bool = False,
|
|
103
|
+
dry_run: bool = False,
|
|
104
|
+
no_color: bool = False,
|
|
105
|
+
no_animation: bool = False,
|
|
106
|
+
ask: ui.Ask = input,
|
|
107
|
+
show_all: bool = False,
|
|
108
|
+
) -> int:
|
|
109
|
+
"""Scan, explain, ask, fix. Returns the exit code.
|
|
110
|
+
|
|
111
|
+
`ask` defaults to Python's built-in input() (like Scanner.nextLine()).
|
|
112
|
+
Tests pass a fake function instead of typing at a keyboard. That's
|
|
113
|
+
dependency injection, with a function standing in for an interface.
|
|
114
|
+
"""
|
|
115
|
+
screen = ui.setup_screen(no_color, no_animation)
|
|
116
|
+
try:
|
|
117
|
+
return _run(screen, target, assume_yes, dry_run, ask, show_all)
|
|
118
|
+
except KeyboardInterrupt:
|
|
119
|
+
# Ctrl+C. Fixes are only written at the very end, so stopping
|
|
120
|
+
# before that leaves every file exactly as it was.
|
|
121
|
+
screen.settle("")
|
|
122
|
+
screen.say(screen.dim(" Stopped. Nothing was changed."))
|
|
123
|
+
return 130
|
|
124
|
+
finally:
|
|
125
|
+
screen.cursor(True) # never leave the cursor hidden
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def whole_computer_folder(target: Path) -> bool:
|
|
129
|
+
"""Is this someone's whole home folder, or a whole drive, rather than a project?
|
|
130
|
+
|
|
131
|
+
A new terminal window opens in the home folder, so "scan" with no
|
|
132
|
+
location (a beta tester pressed Enter before dragging a file in)
|
|
133
|
+
scanned every file the person had. That's slow, and "fix all" could
|
|
134
|
+
then change files that belong to no project. So these are refused.
|
|
135
|
+
"""
|
|
136
|
+
try:
|
|
137
|
+
place = target.resolve()
|
|
138
|
+
home = Path.home().resolve()
|
|
139
|
+
except (OSError, RuntimeError):
|
|
140
|
+
return False
|
|
141
|
+
is_drive = place.parent == place # "/" or "C:\"
|
|
142
|
+
holds_home = place == home or place in home.parents # home itself, "/Users", ...
|
|
143
|
+
return is_drive or holds_home
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
WHOLE_COMPUTER_MESSAGE = ("That's your whole {what}, not a project, so I won't scan it.\n"
|
|
147
|
+
"Type the scan command, press the spacebar, then drag your project folder in.")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _run(screen: ui.Screen, target: Path, assume_yes: bool, dry_run: bool, ask: ui.Ask,
|
|
151
|
+
show_all: bool = False) -> int:
|
|
152
|
+
if not target.exists():
|
|
153
|
+
screen.say(screen.coral(f" I can't find {target}. Check the spelling and try again."))
|
|
154
|
+
return 2
|
|
155
|
+
if whole_computer_folder(target):
|
|
156
|
+
what = "drive" if target.resolve().parent == target.resolve() else "home folder"
|
|
157
|
+
for line in WHOLE_COMPUTER_MESSAGE.format(what=what).splitlines():
|
|
158
|
+
screen.say(screen.coral(" " + line))
|
|
159
|
+
return 2
|
|
160
|
+
|
|
161
|
+
# 1 and 2: start-up, then scan with a live progress bar.
|
|
162
|
+
ui.show_start(screen)
|
|
163
|
+
# The one-time stats notice comes FIRST, before anything is sent, so the
|
|
164
|
+
# first run can be counted and people are still told beforehand.
|
|
165
|
+
notice = telemetry.take_notice()
|
|
166
|
+
if notice:
|
|
167
|
+
ui.show_notice(screen, notice)
|
|
168
|
+
progress = ui.ScanProgress(screen)
|
|
169
|
+
result = engine.scan(target, on_progress=progress.update)
|
|
170
|
+
progress.finish(result.files_checked, result.seconds)
|
|
171
|
+
if not dry_run:
|
|
172
|
+
blindspots.save(result.root, result.blind_spots)
|
|
173
|
+
# Only SURE problems, unless --all (see "CONFIDENCE" in engine.py).
|
|
174
|
+
worth_a_look = []
|
|
175
|
+
if not show_all:
|
|
176
|
+
result.findings, worth_a_look = engine.split_by_confidence(result.findings)
|
|
177
|
+
|
|
178
|
+
# 3: the report, one card per problem, then the blind spots.
|
|
179
|
+
ui.show_report(screen, result.findings, result.root)
|
|
180
|
+
ui.show_blind_spots(screen, result.blind_spots)
|
|
181
|
+
ui.show_worth_a_look(screen, len(worth_a_look))
|
|
182
|
+
fixable, manual = ui.sort_findings(result.findings)
|
|
183
|
+
|
|
184
|
+
if not result.findings or dry_run or not fixable:
|
|
185
|
+
if dry_run:
|
|
186
|
+
screen.say()
|
|
187
|
+
screen.say(screen.dim(" Dry run: nothing was changed."))
|
|
188
|
+
elif fixable == [] and manual:
|
|
189
|
+
# No question to ask: say why, or it looks like the choice went missing
|
|
190
|
+
# (a beta tester waited for "fix all", then typed "a" into the terminal).
|
|
191
|
+
screen.say()
|
|
192
|
+
screen.say(" " + screen.bold("Nothing here can be fixed automatically,")
|
|
193
|
+
+ " so there's nothing to choose.")
|
|
194
|
+
screen.say(" Each ✋ card above says what to do. Do those, then scan again.")
|
|
195
|
+
ui.show_summary(screen, len(result.findings), [], [], 0, manual)
|
|
196
|
+
if not result.findings:
|
|
197
|
+
# Clean code: the big finish.
|
|
198
|
+
ui.show_stamp(screen, result.files_checked, result.blind_spots.files_not_checked())
|
|
199
|
+
else:
|
|
200
|
+
screen.say()
|
|
201
|
+
finish_scan(screen, result, "dry_run" if dry_run else "none")
|
|
202
|
+
return 1 if result.findings else 0
|
|
203
|
+
|
|
204
|
+
# 4: the choice.
|
|
205
|
+
if assume_yes:
|
|
206
|
+
chosen, choice = fixable, "yes"
|
|
207
|
+
elif not sys.stdin.isatty() and ask is input:
|
|
208
|
+
# Never wait for an answer when no person is at the keyboard (an AI
|
|
209
|
+
# agent ran the command, say). Hanging forever would be worse.
|
|
210
|
+
screen.say()
|
|
211
|
+
screen.say(screen.dim(" No one is here to answer. Run again with --yes to fix everything."))
|
|
212
|
+
finish_scan(screen, result, "none")
|
|
213
|
+
return 1
|
|
214
|
+
else:
|
|
215
|
+
choice = ui.ask_how(screen, ask, len(fixable))
|
|
216
|
+
if choice == "all":
|
|
217
|
+
chosen = fixable
|
|
218
|
+
elif choice == "one":
|
|
219
|
+
chosen, reported_wrong = ui.ask_each(screen, ask, fixable, result.root)
|
|
220
|
+
if reported_wrong:
|
|
221
|
+
# Save the "this looks wrong" reports with the other blind spots.
|
|
222
|
+
result.blind_spots.reported_wrong += reported_wrong
|
|
223
|
+
blindspots.save(result.root, result.blind_spots)
|
|
224
|
+
else:
|
|
225
|
+
chosen = []
|
|
226
|
+
|
|
227
|
+
if not chosen:
|
|
228
|
+
screen.say()
|
|
229
|
+
screen.say(screen.dim(" OK, nothing was changed."))
|
|
230
|
+
screen.say()
|
|
231
|
+
finish_scan(screen, result, choice)
|
|
232
|
+
return 1
|
|
233
|
+
|
|
234
|
+
chosen = add_required_protection(screen, chosen, fixable)
|
|
235
|
+
|
|
236
|
+
# 5: apply the chosen fixes, then the summary.
|
|
237
|
+
ui.show_applying(screen, len(chosen))
|
|
238
|
+
outcome = engine.apply_fixes(chosen, result.root, result.fingerprints)
|
|
239
|
+
skipped = len(fixable) - len(chosen)
|
|
240
|
+
ui.show_summary(screen, len(result.findings), outcome.applied, outcome.rejected, skipped, manual)
|
|
241
|
+
if len(outcome.applied) == len(result.findings):
|
|
242
|
+
# Everything found was fixed: the big finish.
|
|
243
|
+
ui.show_stamp(screen, result.files_checked, result.blind_spots.files_not_checked())
|
|
244
|
+
finish_scan(screen, result, choice, chosen, outcome.applied, outcome.rejected)
|
|
245
|
+
|
|
246
|
+
problems_left = manual or outcome.rejected or skipped
|
|
247
|
+
return 1 if problems_left else 0
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def add_required_protection(screen: ui.Screen, chosen: list, fixable: list) -> list:
|
|
251
|
+
"""If secrets are moving into .env, the .gitignore fix MUST go in too.
|
|
252
|
+
|
|
253
|
+
Otherwise .env could be uploaded, which is worse than before.
|
|
254
|
+
"""
|
|
255
|
+
moves_secrets = any(append.path.name.startswith(".env") for f in chosen for append in f.fix.appends)
|
|
256
|
+
protection = [f for f in fixable if f.rule_id.startswith("GIT") and f not in chosen]
|
|
257
|
+
if moves_secrets and protection:
|
|
258
|
+
screen.say()
|
|
259
|
+
screen.say(screen.amber(" ⚠ ") + "I'm also adding .env to the \"never upload\" list, so the secrets "
|
|
260
|
+
"I move there stay private.")
|
|
261
|
+
return chosen + protection
|
|
262
|
+
return chosen
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def finish_scan(screen: ui.Screen, result, choice: str, chosen=(), applied=(), rejected=()) -> None:
|
|
266
|
+
"""The last steps of every scan: send the usage stats (the notice was
|
|
267
|
+
shown at the start), and end with the early-access line."""
|
|
268
|
+
telemetry.send("scan_completed", telemetry.scan_stats(result, choice, chosen, applied, rejected),
|
|
269
|
+
root=result.root)
|
|
270
|
+
ui.show_early_access(screen)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
# ===========================================================================
|
|
274
|
+
# SCAN --json (for AI tools)
|
|
275
|
+
# ===========================================================================
|
|
276
|
+
|
|
277
|
+
def run_json(target: Path, assume_yes: bool = False, show_all: bool = False) -> int:
|
|
278
|
+
"""Print one JSON report. No animations and no questions.
|
|
279
|
+
|
|
280
|
+
Without --yes nothing is changed. With --yes every fix is applied, and
|
|
281
|
+
the report says which ones worked.
|
|
282
|
+
"""
|
|
283
|
+
if not target.exists():
|
|
284
|
+
print(json.dumps({"error": f"path not found: {target}"}))
|
|
285
|
+
return 2
|
|
286
|
+
if whole_computer_folder(target):
|
|
287
|
+
print(json.dumps({"error": "this is a whole home folder or drive, not a project; "
|
|
288
|
+
"run the scan inside the project's folder"}))
|
|
289
|
+
return 2
|
|
290
|
+
result = engine.scan(target)
|
|
291
|
+
blindspots.save(result.root, result.blind_spots)
|
|
292
|
+
worth_a_look = []
|
|
293
|
+
if not show_all:
|
|
294
|
+
result.findings, worth_a_look = engine.split_by_confidence(result.findings)
|
|
295
|
+
|
|
296
|
+
fixable = [f for f in result.findings if f.fix]
|
|
297
|
+
applied, rejected = [], []
|
|
298
|
+
if assume_yes and fixable:
|
|
299
|
+
outcome = engine.apply_fixes(fixable, result.root, result.fingerprints)
|
|
300
|
+
applied, rejected = outcome.applied, outcome.rejected
|
|
301
|
+
|
|
302
|
+
report = {
|
|
303
|
+
"tool": "decaloguex",
|
|
304
|
+
"version": __version__,
|
|
305
|
+
"root": str(result.root),
|
|
306
|
+
"files_checked": result.files_checked,
|
|
307
|
+
"languages": dict(result.languages),
|
|
308
|
+
"seconds": round(result.seconds, 3),
|
|
309
|
+
"findings": [finding_json(f, result.root, applied, rejected) for f in result.findings],
|
|
310
|
+
"blind_spots": result.blind_spots.to_dict(),
|
|
311
|
+
# Places only a person can judge, hidden unless --all (see engine.py, CONFIDENCE).
|
|
312
|
+
"worth_a_look": len(worth_a_look),
|
|
313
|
+
"fixes_applied": len(applied),
|
|
314
|
+
"undo": "decaloguex undo" if applied else None,
|
|
315
|
+
# AI tools are asked (in SKILL.md) to pass this on to the user once.
|
|
316
|
+
"notice": EARLY_ACCESS_NOTICE,
|
|
317
|
+
}
|
|
318
|
+
# ensure_ascii=True writes characters like "…" as …, so the report
|
|
319
|
+
# is plain ASCII. Otherwise, on Windows, a report saved to a file came out
|
|
320
|
+
# in the old cp1252 encoding, which other programs (and AI tools) can't read.
|
|
321
|
+
print(json.dumps(report, indent=2, ensure_ascii=True))
|
|
322
|
+
|
|
323
|
+
notice = telemetry.take_notice() # told first, then sent
|
|
324
|
+
if notice:
|
|
325
|
+
print(notice, file=sys.stderr) # stderr, so it never breaks the JSON on stdout
|
|
326
|
+
telemetry.send("scan_completed", telemetry.scan_stats(result, "yes" if assume_yes else "json",
|
|
327
|
+
fixable if assume_yes else (), applied, rejected),
|
|
328
|
+
root=result.root)
|
|
329
|
+
|
|
330
|
+
remaining = len(result.findings) - len(applied)
|
|
331
|
+
return 1 if remaining else 0
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def finding_json(finding, root: Path, applied: list, rejected: list) -> dict:
|
|
335
|
+
"""One finding as plain data, for AI tools to read."""
|
|
336
|
+
info = explain(finding.rule_id)
|
|
337
|
+
if any(f is finding for f in applied):
|
|
338
|
+
status = "fixed"
|
|
339
|
+
elif any(f is finding for f in rejected):
|
|
340
|
+
status = "fix_failed_safety_check"
|
|
341
|
+
elif finding.fix:
|
|
342
|
+
status = "fixable"
|
|
343
|
+
else:
|
|
344
|
+
status = "manual"
|
|
345
|
+
return {
|
|
346
|
+
"rule": finding.rule_id,
|
|
347
|
+
"severity": finding.severity.value,
|
|
348
|
+
"title": finding.title,
|
|
349
|
+
"file": engine.relative(root, finding.path),
|
|
350
|
+
"line": finding.line,
|
|
351
|
+
"explanation": info.problem,
|
|
352
|
+
"status": status,
|
|
353
|
+
"fix": {"before": finding.fix.preview_before, "after": finding.fix.preview_after} if finding.fix else None,
|
|
354
|
+
"manual_step": finding.note or None,
|
|
355
|
+
"confidence": "worth_a_look" if engine.is_worth_a_look(finding) else "sure",
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
# ===========================================================================
|
|
360
|
+
# UNDO
|
|
361
|
+
# ===========================================================================
|
|
362
|
+
|
|
363
|
+
def run_undo(target: Path, assume_yes: bool = False, no_color: bool = False, ask: ui.Ask = input) -> int:
|
|
364
|
+
"""Put back every file the last round of fixes changed."""
|
|
365
|
+
screen = ui.setup_screen(no_color, no_animation=False)
|
|
366
|
+
root = project.find_root(target.resolve())
|
|
367
|
+
plan = undo.latest(root)
|
|
368
|
+
if plan is None:
|
|
369
|
+
screen.say(screen.dim(" Nothing to undo: no fixes have been applied in this project yet."))
|
|
370
|
+
return 1
|
|
371
|
+
|
|
372
|
+
if plan.edited_since and not assume_yes:
|
|
373
|
+
ui.show_undo_warning(screen, plan.edited_since)
|
|
374
|
+
if not sys.stdin.isatty() and ask is input:
|
|
375
|
+
screen.say(screen.dim(" No one is here to answer. Run again with --yes to undo anyway."))
|
|
376
|
+
return 1
|
|
377
|
+
if screen.ask(ask, screen.cyan(" Undo anyway? (y/n) ")) not in ("y", "yes"):
|
|
378
|
+
screen.say(screen.dim(" OK, nothing was changed."))
|
|
379
|
+
return 1
|
|
380
|
+
|
|
381
|
+
restored = undo.restore(plan)
|
|
382
|
+
ui.show_undo_done(screen, restored, plan.created)
|
|
383
|
+
telemetry.send("undo_used", {"files_restored": len(restored)}, root=root)
|
|
384
|
+
return 0
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
# ===========================================================================
|
|
388
|
+
# TELEMETRY SETTINGS
|
|
389
|
+
# ===========================================================================
|
|
390
|
+
|
|
391
|
+
def run_telemetry(setting: str) -> int:
|
|
392
|
+
screen = ui.setup_screen()
|
|
393
|
+
if setting in ("on", "off"):
|
|
394
|
+
telemetry.set_enabled(setting == "on")
|
|
395
|
+
ui.show_telemetry_status(screen, telemetry.is_enabled(), telemetry.will_send(),
|
|
396
|
+
log=telemetry.log_file(), in_ci=telemetry.running_in_ci())
|
|
397
|
+
if setting == "status" and telemetry.will_send():
|
|
398
|
+
# Actually try the connection, so "stats are on but never arrive" can be explained.
|
|
399
|
+
problem = telemetry.check_connection()
|
|
400
|
+
if problem is None:
|
|
401
|
+
screen.say(f" Connection to the stats server: {screen.mint('OK', bold=True)}")
|
|
402
|
+
else:
|
|
403
|
+
screen.say(f" Connection to the stats server: {screen.coral('NOT WORKING', bold=True)}: {problem}")
|
|
404
|
+
screen.say()
|
|
405
|
+
return 0
|