divan-cli 0.2.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.
- divan/SKILL.md +12 -0
- divan/__init__.py +1 -0
- divan/__main__.py +3 -0
- divan/agent.py +281 -0
- divan/check.py +182 -0
- divan/cli.py +415 -0
- divan/config.py +278 -0
- divan/doc.py +90 -0
- divan/hooks.py +475 -0
- divan/index.py +229 -0
- divan/join.py +213 -0
- divan/land.py +271 -0
- divan/privdir.py +53 -0
- divan/safe.py +27 -0
- divan/settings.py +123 -0
- divan/tomledit.py +97 -0
- divan/write.py +72 -0
- divan_cli-0.2.0.dist-info/METADATA +202 -0
- divan_cli-0.2.0.dist-info/RECORD +22 -0
- divan_cli-0.2.0.dist-info/WHEEL +4 -0
- divan_cli-0.2.0.dist-info/entry_points.txt +2 -0
- divan_cli-0.2.0.dist-info/licenses/LICENSE +202 -0
divan/SKILL.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: divan
|
|
3
|
+
description: Search and write the user's markdown knowledge bases (corpora) with the divan CLI. Use before researching a topic, and when saving findings.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# divan
|
|
7
|
+
|
|
8
|
+
1. Search before you research: `divan find "<query>"` (add `--json` to parse). Results are grouped per corpus; read the hits before redoing work. `divan corpora` shows what this profile can see.
|
|
9
|
+
2. Before writing to a corpus, run `divan guide <corpus>` and follow it. To save a finding: `divan new --title "..." [--collection X]` prints a new file path. Fill it in, then `divan land <file> -m "<message>"`. Land only the files you wrote. `land` builds its commit directly, so repo commit hooks do not run; if the corpus regenerates committed files in a hook, use plain git instead.
|
|
10
|
+
3. Never write to a shared corpus unless `divan check` passes (`divan land` enforces it). Fix the errors; do not edit the corpus's `divan.toml` to silence them.
|
|
11
|
+
4. Findings are about the world. Do not copy private paths, hostnames, emails or secrets into a shared corpus.
|
|
12
|
+
5. Do not use `--corpus` to reach a corpus outside the active profile; if it is refused, the refusal is the answer.
|
divan/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.0"
|
divan/__main__.py
ADDED
divan/agent.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""`divan agent setup`: install divan's plugin into each detected agent through that agent's own CLI.
|
|
2
|
+
|
|
3
|
+
divan never writes an agent's settings files. It runs the agent's documented
|
|
4
|
+
plugin commands (marketplace add, plugin install) and nothing else.
|
|
5
|
+
"""
|
|
6
|
+
import contextlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from .config import ConfigError
|
|
16
|
+
from .tomledit import locked
|
|
17
|
+
|
|
18
|
+
SOURCE = "tnunamak/divan"
|
|
19
|
+
SOURCE_URL = "https://github.com/tnunamak/divan"
|
|
20
|
+
PLUGIN = "divan@divan"
|
|
21
|
+
FALLBACK = f"npx skills add {SOURCE} -g"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
CODEX_TRUST = ("IMPORTANT: Codex keeps the divan hooks inactive until you approve them. Open Codex, go to "
|
|
25
|
+
"/hooks and trust the divan hooks. Until then the search-first and save-after checks do nothing "
|
|
26
|
+
"in Codex (the skill still works).")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def owned_path() -> Path:
|
|
30
|
+
base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state")
|
|
31
|
+
return Path(base) / "divan" / "agent-setup.json"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def read_owned() -> dict:
|
|
35
|
+
"""What `divan agent setup` itself added, per agent: {"claude": ["marketplace", "plugin"]}."""
|
|
36
|
+
try:
|
|
37
|
+
d = json.loads(owned_path().read_text())
|
|
38
|
+
return d if isinstance(d, dict) else {}
|
|
39
|
+
except (OSError, ValueError):
|
|
40
|
+
return {}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
LOCK_TIMEOUT = 120.0 # seconds a second setup waits for the first (DIVAN_SETUP_LOCK_TIMEOUT overrides)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _write_locked(change) -> None:
|
|
47
|
+
p = owned_path()
|
|
48
|
+
d = read_owned()
|
|
49
|
+
if not change(d):
|
|
50
|
+
return
|
|
51
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
tmp = p.with_name(p.name + f".{os.getpid()}.tmp")
|
|
53
|
+
tmp.write_text(json.dumps(d, indent=1))
|
|
54
|
+
os.replace(tmp, p)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _update_owned(change, held: bool = False) -> bool:
|
|
58
|
+
"""Read, change and write the ownership record. Unless the caller already holds the ledger lock
|
|
59
|
+
(`held`), take it for this update. False if the record could not be written."""
|
|
60
|
+
try:
|
|
61
|
+
if held:
|
|
62
|
+
_write_locked(change)
|
|
63
|
+
else:
|
|
64
|
+
with locked(owned_path()):
|
|
65
|
+
_write_locked(change)
|
|
66
|
+
return True
|
|
67
|
+
except OSError:
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def mark_owned(client: str, kind: str, held: bool = False) -> bool:
|
|
72
|
+
def add(d):
|
|
73
|
+
if kind in d.get(client, []):
|
|
74
|
+
return False
|
|
75
|
+
d[client] = [*d.get(client, []), kind]
|
|
76
|
+
return True
|
|
77
|
+
return _update_owned(add, held)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def unmark_owned(client: str, kind: str, held: bool = False) -> bool:
|
|
81
|
+
def drop(d):
|
|
82
|
+
if kind not in d.get(client, []):
|
|
83
|
+
return False
|
|
84
|
+
d[client] = [k for k in d[client] if k != kind]
|
|
85
|
+
if not d[client]:
|
|
86
|
+
del d[client]
|
|
87
|
+
return True
|
|
88
|
+
return _update_owned(drop, held)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class Client:
|
|
92
|
+
"""`add` and `remove` are lists of (kind, args); kind is "marketplace" or "plugin"."""
|
|
93
|
+
def __init__(self, name, binary, add, remove, note=""):
|
|
94
|
+
self.name, self.binary, self.add, self.remove, self.note = name, binary, add, remove, note
|
|
95
|
+
|
|
96
|
+
def cmd(self, *args):
|
|
97
|
+
return [self.binary, *args]
|
|
98
|
+
|
|
99
|
+
def installed(self) -> bool | None:
|
|
100
|
+
"""True/False from the agent's own listing; None when it cannot be read."""
|
|
101
|
+
try:
|
|
102
|
+
if self.name in ("claude", "antigravity"):
|
|
103
|
+
r = subprocess.run(self.cmd("plugin", "list", "--json"), capture_output=True, text=True, timeout=30)
|
|
104
|
+
if r.returncode != 0:
|
|
105
|
+
return False
|
|
106
|
+
key, want = ("id", PLUGIN) if self.name == "claude" else ("name", "divan")
|
|
107
|
+
return any(p.get(key) == want for p in json.loads(r.stdout))
|
|
108
|
+
# `codex plugin list` queries remote marketplaces and can hang for minutes offline,
|
|
109
|
+
# so read the install cache instead (a read, never a write).
|
|
110
|
+
home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
|
|
111
|
+
return (home / "plugins" / "cache" / "divan" / "divan").is_dir()
|
|
112
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
CLIENTS = {
|
|
117
|
+
"claude": Client("claude", "claude",
|
|
118
|
+
add=[("marketplace", ["plugin", "marketplace", "add", SOURCE]), ("plugin", ["plugin", "install", PLUGIN])],
|
|
119
|
+
remove=[("plugin", ["plugin", "uninstall", PLUGIN]),
|
|
120
|
+
("marketplace", ["plugin", "marketplace", "remove", "divan"])],
|
|
121
|
+
note="Start a new Claude Code session to load the hooks."),
|
|
122
|
+
"codex": Client("codex", "codex",
|
|
123
|
+
add=[("marketplace", ["plugin", "marketplace", "add", SOURCE]), ("plugin", ["plugin", "add", PLUGIN])],
|
|
124
|
+
remove=[("plugin", ["plugin", "remove", PLUGIN]),
|
|
125
|
+
("marketplace", ["plugin", "marketplace", "remove", "divan"])],
|
|
126
|
+
note=CODEX_TRUST),
|
|
127
|
+
"antigravity": Client("antigravity", "agy",
|
|
128
|
+
add=[("plugin", ["plugin", "install", SOURCE_URL])],
|
|
129
|
+
remove=[("plugin", ["plugin", "uninstall", "divan"])],
|
|
130
|
+
note="Start a new Antigravity session to load the hooks."),
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def remove_steps(c: Client, inst, owned: dict) -> list[tuple[str, list[str]]]:
|
|
135
|
+
"""Undo only what divan's own setup added, from its ownership record. A plugin or
|
|
136
|
+
marketplace you installed yourself is left alone."""
|
|
137
|
+
mine = owned.get(c.name, [])
|
|
138
|
+
return [(k, a) for k, a in c.remove if k in mine]
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def plan(remove: bool, only: list[str] | None) -> list[dict]:
|
|
142
|
+
names = only or list(CLIENTS)
|
|
143
|
+
owned = read_owned()
|
|
144
|
+
out = []
|
|
145
|
+
for n in names:
|
|
146
|
+
c = CLIENTS[n]
|
|
147
|
+
detected = shutil.which(c.binary) is not None
|
|
148
|
+
inst = c.installed() if detected else None
|
|
149
|
+
steps = remove_steps(c, inst, owned) if remove else c.add
|
|
150
|
+
if not detected:
|
|
151
|
+
action = "skip"
|
|
152
|
+
elif remove:
|
|
153
|
+
action = "remove" if steps else "none"
|
|
154
|
+
else:
|
|
155
|
+
action = "none" if inst else "install"
|
|
156
|
+
out.append({"name": n, "detected": detected, "installed": inst, "action": action,
|
|
157
|
+
"commands": [c.cmd(*a) for _, a in steps] if action in ("install", "remove") else [],
|
|
158
|
+
"kinds": [k for k, _ in steps] if action in ("install", "remove") else [],
|
|
159
|
+
"notice": c.note})
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# What each agent's CLI prints, with a non-zero exit, when the thing is already there.
|
|
164
|
+
ALREADY = {
|
|
165
|
+
"claude": re.compile(r"already (?:exists|installed|added|configured|declared|registered)", re.I),
|
|
166
|
+
"codex": re.compile(r"already (?:exists|installed|added|configured|registered)", re.I),
|
|
167
|
+
"antigravity": re.compile(r"already (?:exists|installed|added|registered)", re.I),
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _run(cmd: list[str], client: str) -> tuple[bool, bool]:
|
|
172
|
+
"""(succeeded, divan_did_it). Exit 0 with no mention of "already" is divan's doing. Anything
|
|
173
|
+
ambiguous (exit 0 that says "already", or a client-specific "already there" reply) counts as
|
|
174
|
+
success but is not recorded as ours, so --remove will not undo it."""
|
|
175
|
+
print("$ " + " ".join(cmd))
|
|
176
|
+
r = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
|
177
|
+
text = (r.stdout + r.stderr).strip()
|
|
178
|
+
if text:
|
|
179
|
+
print(" " + text.replace("\n", "\n "))
|
|
180
|
+
mentions = "already" in text.lower()
|
|
181
|
+
if r.returncode == 0:
|
|
182
|
+
return True, not mentions
|
|
183
|
+
return bool(ALREADY[client].search(text)), False
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@contextlib.contextmanager
|
|
187
|
+
def _setup_lock(timeout: float):
|
|
188
|
+
"""The run-wide ledger lock. If it cannot be taken, stop before any agent CLI call: setup never
|
|
189
|
+
acts (and never writes the record as if it held the lock) without it. A timeout is an error too."""
|
|
190
|
+
cm = locked(owned_path(), timeout=timeout)
|
|
191
|
+
try:
|
|
192
|
+
cm.__enter__()
|
|
193
|
+
except OSError as e:
|
|
194
|
+
raise ConfigError(f"divan could not lock its state folder {owned_path().parent}: {e}; "
|
|
195
|
+
"nothing was changed") from e
|
|
196
|
+
try:
|
|
197
|
+
yield
|
|
198
|
+
finally:
|
|
199
|
+
cm.__exit__(None, None, None)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def setup(status: bool, as_json: bool, client: list[str] | None, yes: bool, remove: bool) -> int:
|
|
203
|
+
for n in client or []:
|
|
204
|
+
if n not in CLIENTS:
|
|
205
|
+
raise ConfigError(f"unknown client '{n}' (choose from {', '.join(CLIENTS)})")
|
|
206
|
+
p = plan(remove, client)
|
|
207
|
+
if client:
|
|
208
|
+
missing = [x["name"] for x in p if not x["detected"]]
|
|
209
|
+
if missing:
|
|
210
|
+
raise ConfigError(f"{', '.join(missing)} not found on PATH")
|
|
211
|
+
if as_json:
|
|
212
|
+
print(json.dumps({"source": SOURCE, "plugin": PLUGIN, "remove": remove, "clients": p,
|
|
213
|
+
"fallback": None if remove else FALLBACK}, indent=2))
|
|
214
|
+
return 0
|
|
215
|
+
if status:
|
|
216
|
+
for x in p:
|
|
217
|
+
state = ("not installed on this machine" if not x["detected"]
|
|
218
|
+
else "unknown" if x["installed"] is None
|
|
219
|
+
else "divan plugin installed" if x["installed"] else "divan plugin not installed")
|
|
220
|
+
print(f"{x['name']}: {state}")
|
|
221
|
+
if x["installed"] and CLIENTS[x["name"]].name == "codex":
|
|
222
|
+
print(" " + CODEX_TRUST.replace("Codex keeps the divan hooks inactive until you approve them.",
|
|
223
|
+
"Unless you already did, Codex keeps the divan hooks inactive until you approve them.", 1))
|
|
224
|
+
return 0
|
|
225
|
+
todo = [x for x in p if x["action"] in ("install", "remove")]
|
|
226
|
+
for x in p:
|
|
227
|
+
if x["action"] == "skip":
|
|
228
|
+
print(f"{x['name']}: not installed on this machine, skipped")
|
|
229
|
+
elif x["action"] == "none" and remove and x["installed"]:
|
|
230
|
+
print(f"{x['name']}: the divan plugin was not installed by `divan agent setup`; left alone")
|
|
231
|
+
elif x["action"] == "none":
|
|
232
|
+
print(f"{x['name']}: already {'removed' if remove else 'set up'}")
|
|
233
|
+
if not todo:
|
|
234
|
+
if not remove:
|
|
235
|
+
print(f"Other agents: {FALLBACK} (installs the skill only)")
|
|
236
|
+
return 0
|
|
237
|
+
print("This runs each agent's own plugin commands:")
|
|
238
|
+
for x in todo:
|
|
239
|
+
for c in x["commands"]:
|
|
240
|
+
print(" " + " ".join(c))
|
|
241
|
+
if not yes:
|
|
242
|
+
if not sys.stdin.isatty():
|
|
243
|
+
print("Not a terminal: re-run with -y to go ahead.", file=sys.stderr)
|
|
244
|
+
return 1
|
|
245
|
+
if input("Go ahead? [y/N] ").strip().lower() not in ("y", "yes"):
|
|
246
|
+
print("Nothing changed.")
|
|
247
|
+
return 1
|
|
248
|
+
# One exclusive lock for the whole run, from reading the ledger through every agent CLI call to
|
|
249
|
+
# the last ledger write; a second concurrent run waits here. Plan again under the lock, since
|
|
250
|
+
# the ledger and the agents may have changed while we waited or asked.
|
|
251
|
+
timeout = float(os.environ.get("DIVAN_SETUP_LOCK_TIMEOUT") or LOCK_TIMEOUT)
|
|
252
|
+
with _setup_lock(timeout):
|
|
253
|
+
todo = [x for x in plan(remove, client) if x["action"] in ("install", "remove")]
|
|
254
|
+
return _execute(todo, remove)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _execute(todo: list[dict], remove: bool) -> int:
|
|
258
|
+
rc = 0
|
|
259
|
+
for x in todo:
|
|
260
|
+
ok = True
|
|
261
|
+
for kind, c in zip(x["kinds"], x["commands"]):
|
|
262
|
+
good, did = _run(c, x["name"])
|
|
263
|
+
if not good:
|
|
264
|
+
ok = False
|
|
265
|
+
break
|
|
266
|
+
if remove:
|
|
267
|
+
if not unmark_owned(x["name"], kind, held=True):
|
|
268
|
+
print(f"divan could not update its record after removing {x['name']} {kind}", file=sys.stderr)
|
|
269
|
+
elif did and not mark_owned(x["name"], kind, held=True): # recorded at once, so a later failure still leaves a trail
|
|
270
|
+
print(f"divan could not record that it installed {x['name']} {kind}; `--remove` will leave it",
|
|
271
|
+
file=sys.stderr)
|
|
272
|
+
if ok:
|
|
273
|
+
print(f"{x['name']}: {'removed' if remove else 'installed'}.")
|
|
274
|
+
if not remove and CLIENTS[x["name"]].note:
|
|
275
|
+
print(" " + CLIENTS[x["name"]].note)
|
|
276
|
+
else:
|
|
277
|
+
print(f"{x['name']}: failed (see above)", file=sys.stderr)
|
|
278
|
+
rc = 1
|
|
279
|
+
if not remove:
|
|
280
|
+
print(f"Other agents: {FALLBACK} (installs the skill only)")
|
|
281
|
+
return rc
|
divan/check.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""divan check: frontmatter, required fields, and strict leak rules for shared corpora."""
|
|
2
|
+
import fnmatch
|
|
3
|
+
import math
|
|
4
|
+
import re
|
|
5
|
+
from dataclasses import asdict, dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .config import ConfigError, Context, Corpus
|
|
9
|
+
from .doc import parse
|
|
10
|
+
from .index import walk_md
|
|
11
|
+
from .safe import contain
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class Finding:
|
|
16
|
+
corpus: str
|
|
17
|
+
path: str
|
|
18
|
+
line: int
|
|
19
|
+
severity: str # "error" | "warn"
|
|
20
|
+
rule: str
|
|
21
|
+
message: str
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _red(s: str) -> str:
|
|
25
|
+
return s[:4] + "..." if len(s) > 8 else "..."
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
LOCAL_PATH = re.compile(r"(?<![\w/.:~-])(?:/home/[\w.-]+|/Users/[\w.-]+|~/[\w.-]*)")
|
|
29
|
+
IPV4 = re.compile(r"(?<![\w.])((?:\d{1,3})\.(?:\d{1,3})\.(?:\d{1,3})\.(?:\d{1,3}))(?![\w.]*\d)")
|
|
30
|
+
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}(?![\w-])")
|
|
31
|
+
SAFE_EMAIL = ["*@example.com", "*@*.example.com", "*@example.org", "*@*.example.org",
|
|
32
|
+
"*@example.net", "*@*.example.net", "*.example", "*.test", "*.invalid"]
|
|
33
|
+
# generic by default (documentation often says ~/.claude or 192.168.1.1); the denylist catches real ones
|
|
34
|
+
DEFAULT_SEVERITY = {"local-path": "warn", "private-ip": "warn"}
|
|
35
|
+
SECRETS = [
|
|
36
|
+
("private key", re.compile(r"-----BEGIN (?:[A-Z]+ )*PRIVATE KEY-----")),
|
|
37
|
+
("GitHub token", re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})")),
|
|
38
|
+
("AWS access key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),
|
|
39
|
+
("Slack token", re.compile(r"\bxox[abposr]-[A-Za-z0-9-]{10,}")),
|
|
40
|
+
("OpenAI/Anthropic-style key", re.compile(r"\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}")),
|
|
41
|
+
("assigned credential", re.compile(r"(?i)(?:password|token)\s*=\s*[\"']?([^\s\"']{16,})")),
|
|
42
|
+
]
|
|
43
|
+
PLACEHOLDER = re.compile(r"(?i)example|your|secret|passw|hunter|dummy|sample|fake|test|demo|xxx|changeme|placeholder|redacted|[<>{}$.…*]|^(.)\1+$")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _entropy(s: str) -> float:
|
|
47
|
+
return -sum(s.count(c) / len(s) * math.log2(s.count(c) / len(s)) for c in set(s))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _real_secret(what: str, m) -> bool:
|
|
51
|
+
if what == "assigned credential":
|
|
52
|
+
v = m.group(1)
|
|
53
|
+
return (not PLACEHOLDER.search(v) and any(c.isdigit() for c in v)
|
|
54
|
+
and any(c.isalpha() for c in v) and _entropy(v) >= 3.5)
|
|
55
|
+
if what.startswith("OpenAI"):
|
|
56
|
+
return any(c.isdigit() for c in m.group(0))
|
|
57
|
+
return True
|
|
58
|
+
CORPUS_LINK = re.compile(
|
|
59
|
+
r"(?<![\w/:.-])([A-Za-z][\w-]*):((?:[\w.-]+/)*[\w.-]+\.md)\b|\]\(\s*([A-Za-z][\w-]*):([^)\s]+)\s*\)")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _private_ip(m) -> bool:
|
|
63
|
+
try:
|
|
64
|
+
o = [int(x) for x in m.split(".")]
|
|
65
|
+
except ValueError:
|
|
66
|
+
return False
|
|
67
|
+
if len(o) != 4 or any(x > 255 for x in o):
|
|
68
|
+
return False
|
|
69
|
+
return (o[0] == 10 or (o[0] == 172 and 16 <= o[1] <= 31)
|
|
70
|
+
or (o[0] == 192 and o[1] == 168) or (o[0] == 169 and o[1] == 254))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def load_denylist(path: Path | None):
|
|
74
|
+
if not path or not path.is_file():
|
|
75
|
+
return []
|
|
76
|
+
out = []
|
|
77
|
+
for i, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
|
|
78
|
+
s = line.strip()
|
|
79
|
+
if not s or s.startswith("#"):
|
|
80
|
+
continue
|
|
81
|
+
try:
|
|
82
|
+
rx = re.compile(s, re.I)
|
|
83
|
+
except re.error:
|
|
84
|
+
rx = None
|
|
85
|
+
out.append((i, s.lower(), rx))
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def leak_findings(corpus: str, rel: str, text: str, allow_emails, corpus_names, shared_names,
|
|
90
|
+
denylist, severity=None):
|
|
91
|
+
out = []
|
|
92
|
+
sev = {**DEFAULT_SEVERITY, **(severity or {})}
|
|
93
|
+
|
|
94
|
+
def add(line, rule, msg):
|
|
95
|
+
level = "error" if rule == "denylist" else sev.get(rule, "error")
|
|
96
|
+
if level != "off":
|
|
97
|
+
out.append(Finding(corpus, rel, line, level, rule, msg))
|
|
98
|
+
|
|
99
|
+
for ln, line in enumerate(text.splitlines(), 1):
|
|
100
|
+
for m in LOCAL_PATH.finditer(line):
|
|
101
|
+
add(ln, "local-path", f"absolute local path '{m.group(0)}'")
|
|
102
|
+
for m in IPV4.finditer(line):
|
|
103
|
+
if _private_ip(m.group(1)):
|
|
104
|
+
add(ln, "private-ip", f"private-range IP address {m.group(1)}")
|
|
105
|
+
for m in EMAIL.finditer(line):
|
|
106
|
+
e = m.group(0)
|
|
107
|
+
if not any(fnmatch.fnmatch(e.lower(), a.lower()) for a in [*SAFE_EMAIL, *allow_emails]):
|
|
108
|
+
add(ln, "email", f"email address {e} (allow it in divan.toml [check] allow_emails)")
|
|
109
|
+
for what, rx in SECRETS:
|
|
110
|
+
m = rx.search(line)
|
|
111
|
+
if m and _real_secret(what, m):
|
|
112
|
+
add(ln, "secret", f"possible {what}: {_red(m.group(0))}")
|
|
113
|
+
for m in CORPUS_LINK.finditer(line):
|
|
114
|
+
name = m.group(1) or m.group(3)
|
|
115
|
+
if name not in corpus_names or name in shared_names:
|
|
116
|
+
continue
|
|
117
|
+
add(ln, "private-corpus-link",
|
|
118
|
+
f"link to corpus '{name}', which is not marked shared (links are corpus:path)")
|
|
119
|
+
for i, lit, rx in denylist:
|
|
120
|
+
if lit in line.lower() or (rx and rx.search(line)):
|
|
121
|
+
add(ln, "denylist", f"matches denylist entry #{i}")
|
|
122
|
+
return out
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def expand_files(root: Path, files: list[str]):
|
|
126
|
+
"""Corpus-relative file list; directories expand recursively to their .md files."""
|
|
127
|
+
out = {}
|
|
128
|
+
for f in files:
|
|
129
|
+
full = root / f
|
|
130
|
+
if full.is_dir():
|
|
131
|
+
for rel, p in walk_md(full, only_indexable=False):
|
|
132
|
+
r = (full / rel).relative_to(root).as_posix()
|
|
133
|
+
out[r] = root / r
|
|
134
|
+
else:
|
|
135
|
+
out[f] = full
|
|
136
|
+
return list(out.items())
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def check_corpus(ctx: Context, corpus: Corpus, files: list[str] | None = None,
|
|
140
|
+
explain: bool = False, read=None):
|
|
141
|
+
"""Return (findings, explain_rows). files are paths relative to the corpus root.
|
|
142
|
+
read(rel) -> bytes lets a caller hand over the exact bytes to inspect."""
|
|
143
|
+
cfg = corpus.cfg
|
|
144
|
+
denylist = load_denylist(ctx.denylist_file) if cfg.shared else []
|
|
145
|
+
shared = ctx.shared_names() | ({corpus.name} if cfg.shared else set())
|
|
146
|
+
known = set(ctx.corpora) | set(cfg.private_corpora)
|
|
147
|
+
if files is None:
|
|
148
|
+
targets = [(rel, full) for rel, full in walk_md(corpus.root, only_indexable=False)]
|
|
149
|
+
else:
|
|
150
|
+
targets = expand_files(corpus.root, files)
|
|
151
|
+
findings, rows = [], []
|
|
152
|
+
for rel, full in sorted(targets):
|
|
153
|
+
try:
|
|
154
|
+
data = read(rel) if read else contain(corpus.root, full, "file").read_bytes()
|
|
155
|
+
text = data.decode("utf-8", errors="replace")
|
|
156
|
+
except (OSError, ConfigError) as e:
|
|
157
|
+
findings.append(Finding(corpus.name, rel, 0, "error", "unreadable", str(e)))
|
|
158
|
+
continue
|
|
159
|
+
d = parse(text, full.name)
|
|
160
|
+
if d.error:
|
|
161
|
+
findings.append(Finding(corpus.name, rel, 1, "error", "frontmatter", d.error))
|
|
162
|
+
matched = cfg.resolve(rel)
|
|
163
|
+
rows.append({"path": rel, "collection": matched[0].name if matched else None,
|
|
164
|
+
"all": [c.name for c in matched]})
|
|
165
|
+
if len(matched) > 1:
|
|
166
|
+
findings.append(Finding(corpus.name, rel, 1, "warn", "multiple-collections",
|
|
167
|
+
"matched by several collections: " + ", ".join(c.name for c in matched)
|
|
168
|
+
+ f" (using {matched[0].name})"))
|
|
169
|
+
if matched and not d.error:
|
|
170
|
+
col = matched[0]
|
|
171
|
+
missing = [k for k in col.required
|
|
172
|
+
if d.fm.get(k) in (None, "", []) ]
|
|
173
|
+
if missing:
|
|
174
|
+
findings.append(Finding(corpus.name, rel, 1, col.severity, "required",
|
|
175
|
+
f"collection '{col.name}' requires: {', '.join(missing)}"))
|
|
176
|
+
if cfg.shared:
|
|
177
|
+
findings += leak_findings(corpus.name, rel, text, cfg.allow_emails, known, shared, denylist, cfg.severity)
|
|
178
|
+
return findings, rows
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def findings_json(fs):
|
|
182
|
+
return [asdict(f) for f in fs]
|