sealwright 0.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.
- sealwright/__init__.py +21 -0
- sealwright/__main__.py +5 -0
- sealwright/_util.py +64 -0
- sealwright/_version.py +1 -0
- sealwright/cli.py +306 -0
- sealwright/config.py +105 -0
- sealwright/engine.py +117 -0
- sealwright/hooks.py +61 -0
- sealwright/lockfile.py +230 -0
- sealwright/probe.py +262 -0
- sealwright/py.typed +0 -0
- sealwright/report.py +120 -0
- sealwright/scan.py +348 -0
- sealwright/sources.py +352 -0
- sealwright-0.1.0.dist-info/METADATA +202 -0
- sealwright-0.1.0.dist-info/RECORD +20 -0
- sealwright-0.1.0.dist-info/WHEEL +4 -0
- sealwright-0.1.0.dist-info/entry_points.txt +2 -0
- sealwright-0.1.0.dist-info/licenses/LICENSE +202 -0
- sealwright-0.1.0.dist-info/licenses/NOTICE +2 -0
sealwright/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Sealwright: lock, verify and scan the extensions AI agents load."""
|
|
2
|
+
|
|
3
|
+
from ._version import __version__
|
|
4
|
+
from .config import Config, ConfigError, Project
|
|
5
|
+
from .engine import Result, check
|
|
6
|
+
from .scan import Finding, scan
|
|
7
|
+
from .sources import Extension, Source, discover
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"__version__",
|
|
11
|
+
"Config",
|
|
12
|
+
"ConfigError",
|
|
13
|
+
"Extension",
|
|
14
|
+
"Finding",
|
|
15
|
+
"Project",
|
|
16
|
+
"Result",
|
|
17
|
+
"Source",
|
|
18
|
+
"check",
|
|
19
|
+
"discover",
|
|
20
|
+
"scan",
|
|
21
|
+
]
|
sealwright/__main__.py
ADDED
sealwright/_util.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Internal helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import tempfile
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
# Control characters, C1 controls, bidi overrides and isolates. Built from
|
|
15
|
+
# code points so the source file itself contains no invisible characters.
|
|
16
|
+
_CTRL_RANGES = [(0x00, 0x08), (0x0B, 0x1F), (0x7F, 0x9F), (0x202A, 0x202E), (0x2066, 0x2069)]
|
|
17
|
+
_CONTROL = re.compile("[" + "".join(f"{re.escape(chr(a))}-{re.escape(chr(b))}" for a, b in _CTRL_RANGES) + "]")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def utc_now() -> str:
|
|
21
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def canonical_json(obj: Any) -> bytes:
|
|
25
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def sha256_bytes(data: bytes) -> str:
|
|
29
|
+
return hashlib.sha256(data).hexdigest()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def sha256_json(obj: Any) -> str:
|
|
33
|
+
return sha256_bytes(canonical_json(obj))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def atomic_write(path: Path, data: bytes, mode: int = 0o644) -> None:
|
|
37
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".tmp-", suffix=path.suffix)
|
|
39
|
+
try:
|
|
40
|
+
with os.fdopen(fd, "wb") as fh:
|
|
41
|
+
fh.write(data)
|
|
42
|
+
try:
|
|
43
|
+
os.chmod(tmp, mode)
|
|
44
|
+
except OSError: # pragma: no cover - advisory on Windows
|
|
45
|
+
pass
|
|
46
|
+
os.replace(tmp, path)
|
|
47
|
+
except BaseException:
|
|
48
|
+
try:
|
|
49
|
+
os.unlink(tmp)
|
|
50
|
+
except OSError:
|
|
51
|
+
pass
|
|
52
|
+
raise
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def safe_term(value: object, limit: int = 300) -> str:
|
|
56
|
+
"""Render attacker-influenced text safely in a terminal."""
|
|
57
|
+
text = str(value).replace(chr(10), " ")
|
|
58
|
+
text = _CONTROL.sub(lambda m: f"\\x{ord(m.group(0)):02x}", text)
|
|
59
|
+
return text if len(text) <= limit else text[:limit] + "..."
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def expand(path: str, base: Path) -> Path:
|
|
63
|
+
p = Path(os.path.expandvars(os.path.expanduser(path)))
|
|
64
|
+
return p if p.is_absolute() else (base / p)
|
sealwright/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
sealwright/cli.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"""``sealwright`` command-line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from ._util import safe_term
|
|
11
|
+
from ._version import __version__
|
|
12
|
+
from .config import CONFIG_NAME, Config, ConfigError, Project
|
|
13
|
+
from .engine import Result, check, inventory, make_lock
|
|
14
|
+
from .lockfile import LockError, fingerprint, load_or_create_key, public_b64, read_lock, sign, write_lock
|
|
15
|
+
from .probe import ProbeError
|
|
16
|
+
from .report import sarif, text, to_json
|
|
17
|
+
from .scan import RANK, SEVERITIES, scan
|
|
18
|
+
from .sources import SOURCE_KINDS, Source
|
|
19
|
+
|
|
20
|
+
EXIT_OK, EXIT_ERROR, EXIT_FINDING = 0, 2, 3
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _project(args) -> Project:
|
|
24
|
+
if getattr(args, "project", None):
|
|
25
|
+
return Project.load(Path(args.project))
|
|
26
|
+
return Project.find(Path.cwd())
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _emit(result: Result, fmt: str, output: str | None, verbose: bool) -> None:
|
|
30
|
+
body = {
|
|
31
|
+
"text": lambda: text(result, verbose=verbose),
|
|
32
|
+
"json": lambda: to_json(result),
|
|
33
|
+
"sarif": lambda: sarif(result),
|
|
34
|
+
}[fmt]()
|
|
35
|
+
if output:
|
|
36
|
+
Path(output).write_text(body + "\n", encoding="utf-8")
|
|
37
|
+
print(f"wrote {output}", file=sys.stderr)
|
|
38
|
+
else:
|
|
39
|
+
print(body)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# -- commands ---------------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def cmd_init(args) -> int:
|
|
46
|
+
root = Path(args.project or ".").resolve()
|
|
47
|
+
if (root / CONFIG_NAME).exists() and not args.force:
|
|
48
|
+
raise ConfigError(f"{root / CONFIG_NAME} already exists (use --force to overwrite)")
|
|
49
|
+
project = Project(root, Config())
|
|
50
|
+
project.save()
|
|
51
|
+
key = load_or_create_key(create=True)
|
|
52
|
+
print(f"created {project.config_path}")
|
|
53
|
+
print(f"signing key {fingerprint(key.public_key())} (stored in your home directory, never in the repo)")
|
|
54
|
+
print("\nNext:")
|
|
55
|
+
print(" sealwright sources add skills-dir <dir> # add your agent's skills/plugins/hooks locations")
|
|
56
|
+
print(" sealwright check # review what is installed")
|
|
57
|
+
print(" sealwright lock # approve it")
|
|
58
|
+
return EXIT_OK
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def cmd_sources(args) -> int:
|
|
62
|
+
project = _project(args)
|
|
63
|
+
srcs = project.config.sources
|
|
64
|
+
if args.action == "list":
|
|
65
|
+
base = project.root
|
|
66
|
+
for s in srcs:
|
|
67
|
+
from ._util import expand
|
|
68
|
+
|
|
69
|
+
exists = "ok" if expand(s.path, base).exists() else ("missing" if not s.optional else "absent")
|
|
70
|
+
print(f"{s.kind:<13} {s.path:<50} {exists}{'' if s.optional else ' (required)'}")
|
|
71
|
+
return EXIT_OK
|
|
72
|
+
if args.action == "add":
|
|
73
|
+
if any(s.kind == args.kind and s.path == args.path for s in srcs):
|
|
74
|
+
print("already configured")
|
|
75
|
+
return EXIT_OK
|
|
76
|
+
srcs.append(Source(args.kind, args.path, optional=not args.required))
|
|
77
|
+
elif args.action == "remove":
|
|
78
|
+
before = len(srcs)
|
|
79
|
+
project.config.sources = [s for s in srcs if s.path != args.path]
|
|
80
|
+
if len(project.config.sources) == before:
|
|
81
|
+
raise ConfigError(f"no source with path {args.path}")
|
|
82
|
+
project.save()
|
|
83
|
+
print("sources updated")
|
|
84
|
+
return EXIT_OK
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def cmd_scan(args) -> int:
|
|
88
|
+
project = _project(args)
|
|
89
|
+
exts, warnings = inventory(project, do_probe=args.probe)
|
|
90
|
+
from .engine import _filter
|
|
91
|
+
|
|
92
|
+
result = Result(
|
|
93
|
+
exts,
|
|
94
|
+
_filter(scan(exts), project),
|
|
95
|
+
[],
|
|
96
|
+
warnings,
|
|
97
|
+
lock_present=True,
|
|
98
|
+
signature=(None, "lock not consulted by `scan`"),
|
|
99
|
+
probed=args.probe,
|
|
100
|
+
)
|
|
101
|
+
_emit(result, args.format, args.output, False)
|
|
102
|
+
return (
|
|
103
|
+
EXIT_FINDING
|
|
104
|
+
if any(RANK[f.severity] >= RANK[args.fail_on or project.config.fail_on] for f in result.findings)
|
|
105
|
+
else EXIT_OK
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def cmd_check(args) -> int:
|
|
110
|
+
project = _project(args)
|
|
111
|
+
result = check(project, do_probe=args.probe or None)
|
|
112
|
+
_emit(result, args.format, args.output, args.verbose)
|
|
113
|
+
if not result.lock_present:
|
|
114
|
+
return EXIT_FINDING
|
|
115
|
+
return EXIT_FINDING if result.failing(args.fail_on or project.config.fail_on) else EXIT_OK
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _write(project: Project, doc: dict) -> None:
|
|
119
|
+
key = load_or_create_key(create=True)
|
|
120
|
+
write_lock(project.lock_path, sign(doc, key))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def cmd_lock(args) -> int:
|
|
124
|
+
project = _project(args)
|
|
125
|
+
probed = args.probe or project.config.probe
|
|
126
|
+
exts, warnings = inventory(project, do_probe=probed)
|
|
127
|
+
for w in warnings:
|
|
128
|
+
print(f"warning: {safe_term(w)}", file=sys.stderr)
|
|
129
|
+
from .engine import _filter
|
|
130
|
+
|
|
131
|
+
findings = _filter(scan(exts), project)
|
|
132
|
+
serious = [f for f in findings if RANK[f.severity] >= RANK[project.config.fail_on]]
|
|
133
|
+
if serious and not args.accept_findings:
|
|
134
|
+
for f in serious:
|
|
135
|
+
print(
|
|
136
|
+
f"[{f.severity.upper()}] {f.rule} {safe_term(f.extension)} @ {safe_term(f.location)}: {f.message}",
|
|
137
|
+
file=sys.stderr,
|
|
138
|
+
)
|
|
139
|
+
print(
|
|
140
|
+
f"\nrefusing to approve {len(serious)} finding(s) at or above '{project.config.fail_on}'. Review them, "
|
|
141
|
+
"fix or ignore them in sealwright.json, or pass --accept-findings.",
|
|
142
|
+
file=sys.stderr,
|
|
143
|
+
)
|
|
144
|
+
return EXIT_FINDING
|
|
145
|
+
doc = make_lock(project, exts, probed=probed)
|
|
146
|
+
_write(project, doc)
|
|
147
|
+
print(
|
|
148
|
+
f"locked {len(doc['extensions'])} extension(s) in {project.lock_path.name}"
|
|
149
|
+
+ (" including tool surfaces" if probed else "")
|
|
150
|
+
)
|
|
151
|
+
return EXIT_OK
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def cmd_approve(args) -> int:
|
|
155
|
+
project = _project(args)
|
|
156
|
+
if read_lock(project.lock_path) is None:
|
|
157
|
+
raise ConfigError("no lockfile yet; run `sealwright lock` first")
|
|
158
|
+
probed = args.probe or project.config.probe
|
|
159
|
+
exts, _ = inventory(project, do_probe=probed)
|
|
160
|
+
known = {e.id for e in exts} | set((read_lock(project.lock_path) or {}).get("extensions", {}))
|
|
161
|
+
unknown = [i for i in args.ids if i not in known]
|
|
162
|
+
if unknown:
|
|
163
|
+
raise ConfigError(f"unknown extension id(s): {', '.join(unknown)}")
|
|
164
|
+
doc = make_lock(project, exts, approve=set(args.ids), probed=probed)
|
|
165
|
+
_write(project, doc)
|
|
166
|
+
print(f"approved {', '.join(args.ids)}")
|
|
167
|
+
return EXIT_OK
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def cmd_trust(args) -> int:
|
|
171
|
+
project = _project(args)
|
|
172
|
+
keys = project.config.trusted_keys
|
|
173
|
+
if args.add_self:
|
|
174
|
+
key = load_or_create_key(create=True)
|
|
175
|
+
b64 = public_b64(key.public_key())
|
|
176
|
+
if b64 not in keys:
|
|
177
|
+
keys.append(b64)
|
|
178
|
+
elif args.add:
|
|
179
|
+
from .lockfile import load_public
|
|
180
|
+
|
|
181
|
+
load_public(args.add) # validate
|
|
182
|
+
if args.add not in keys:
|
|
183
|
+
keys.append(args.add)
|
|
184
|
+
elif args.remove:
|
|
185
|
+
project.config.trusted_keys = [k for k in keys if k != args.remove]
|
|
186
|
+
else:
|
|
187
|
+
for k in keys:
|
|
188
|
+
print(k)
|
|
189
|
+
return EXIT_OK
|
|
190
|
+
project.save()
|
|
191
|
+
print(f"{len(project.config.trusted_keys)} trusted key(s)")
|
|
192
|
+
return EXIT_OK
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def cmd_keys(args) -> int:
|
|
196
|
+
key = load_or_create_key(create=args.create)
|
|
197
|
+
if key is None:
|
|
198
|
+
print("no signing key yet (run `sealwright init` or `sealwright keys --create`)")
|
|
199
|
+
return EXIT_OK
|
|
200
|
+
print(f"fingerprint {fingerprint(key.public_key())}")
|
|
201
|
+
print(f"public key {public_b64(key.public_key())}")
|
|
202
|
+
return EXIT_OK
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def cmd_hook(args) -> int:
|
|
206
|
+
"""Session-start hook: warn the user about unapproved changes. Never blocks."""
|
|
207
|
+
from .hooks import hook_config, run_hook
|
|
208
|
+
|
|
209
|
+
if args.print_config:
|
|
210
|
+
print(json.dumps(hook_config(args.project), indent=2))
|
|
211
|
+
return EXIT_OK
|
|
212
|
+
return run_hook(args.project)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def cmd_rules(args) -> int:
|
|
216
|
+
from .scan import RULES
|
|
217
|
+
|
|
218
|
+
for rid, desc in RULES.items():
|
|
219
|
+
print(f"{rid} {desc}")
|
|
220
|
+
return EXIT_OK
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# -- parser -----------------------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
227
|
+
p = argparse.ArgumentParser(
|
|
228
|
+
prog="sealwright",
|
|
229
|
+
description="Lock, verify and scan the extensions your AI agents load: MCP servers, skills, hooks, plugins.",
|
|
230
|
+
)
|
|
231
|
+
p.add_argument("--version", action="version", version=f"sealwright {__version__}")
|
|
232
|
+
p.add_argument("--project", help="project directory holding sealwright.json (default: search upward from cwd)")
|
|
233
|
+
sub = p.add_subparsers(dest="cmd", required=True, metavar="command")
|
|
234
|
+
|
|
235
|
+
s = sub.add_parser("init", help="create sealwright.json with default sources")
|
|
236
|
+
s.add_argument("--force", action="store_true")
|
|
237
|
+
s.set_defaults(fn=cmd_init)
|
|
238
|
+
|
|
239
|
+
s = sub.add_parser("sources", help="list, add or remove sources")
|
|
240
|
+
a = s.add_subparsers(dest="action", required=True)
|
|
241
|
+
a.add_parser("list")
|
|
242
|
+
x = a.add_parser("add")
|
|
243
|
+
x.add_argument("kind", choices=SOURCE_KINDS)
|
|
244
|
+
x.add_argument("path", help="relative to the project, or absolute, ~ and $VARS expanded")
|
|
245
|
+
x.add_argument("--required", action="store_true", help="fail if the source is missing")
|
|
246
|
+
x = a.add_parser("remove")
|
|
247
|
+
x.add_argument("path")
|
|
248
|
+
s.set_defaults(fn=cmd_sources)
|
|
249
|
+
|
|
250
|
+
def outputs(sp):
|
|
251
|
+
sp.add_argument("--format", choices=("text", "json", "sarif"), default="text")
|
|
252
|
+
sp.add_argument("-o", "--output")
|
|
253
|
+
sp.add_argument("--fail-on", choices=SEVERITIES)
|
|
254
|
+
sp.add_argument("--probe", action="store_true", help="start MCP servers and pin their live tool surface")
|
|
255
|
+
|
|
256
|
+
s = sub.add_parser("check", help="compare against the lock and scan (exit 3 on drift or findings)")
|
|
257
|
+
outputs(s)
|
|
258
|
+
s.add_argument("-v", "--verbose", action="store_true", help="show text diffs of changes")
|
|
259
|
+
s.set_defaults(fn=cmd_check)
|
|
260
|
+
|
|
261
|
+
s = sub.add_parser("scan", help="scan installed extensions without consulting the lock")
|
|
262
|
+
outputs(s)
|
|
263
|
+
s.set_defaults(fn=cmd_scan)
|
|
264
|
+
|
|
265
|
+
s = sub.add_parser("lock", help="approve everything currently installed and write a signed lock")
|
|
266
|
+
s.add_argument("--probe", action="store_true")
|
|
267
|
+
s.add_argument("--accept-findings", action="store_true", help="lock even with findings at or above fail_on")
|
|
268
|
+
s.set_defaults(fn=cmd_lock)
|
|
269
|
+
|
|
270
|
+
s = sub.add_parser("approve", help="approve the current state of specific extensions")
|
|
271
|
+
s.add_argument("ids", nargs="+")
|
|
272
|
+
s.add_argument("--probe", action="store_true")
|
|
273
|
+
s.set_defaults(fn=cmd_approve)
|
|
274
|
+
|
|
275
|
+
s = sub.add_parser("trust", help="manage public keys whose lock signatures are trusted")
|
|
276
|
+
g = s.add_mutually_exclusive_group()
|
|
277
|
+
g.add_argument("--add-self", action="store_true", help="trust your own signing key")
|
|
278
|
+
g.add_argument("--add", metavar="PUBKEY")
|
|
279
|
+
g.add_argument("--remove", metavar="PUBKEY")
|
|
280
|
+
s.set_defaults(fn=cmd_trust)
|
|
281
|
+
|
|
282
|
+
s = sub.add_parser("keys", help="show your signing key")
|
|
283
|
+
s.add_argument("--create", action="store_true")
|
|
284
|
+
s.set_defaults(fn=cmd_keys)
|
|
285
|
+
|
|
286
|
+
s = sub.add_parser("hook", help="session-start hook for coding agents (warns, never blocks)")
|
|
287
|
+
s.add_argument("--print-config", action="store_true")
|
|
288
|
+
s.set_defaults(fn=cmd_hook)
|
|
289
|
+
|
|
290
|
+
sub.add_parser("rules", help="list scanner rules").set_defaults(fn=cmd_rules)
|
|
291
|
+
return p
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def main(argv: list[str] | None = None) -> int:
|
|
295
|
+
args = build_parser().parse_args(argv)
|
|
296
|
+
try:
|
|
297
|
+
return int(args.fn(args) or 0)
|
|
298
|
+
except (ConfigError, LockError, ProbeError, OSError, ValueError) as exc:
|
|
299
|
+
print(f"sealwright: error: {safe_term(exc)}", file=sys.stderr)
|
|
300
|
+
return EXIT_ERROR
|
|
301
|
+
except KeyboardInterrupt: # pragma: no cover
|
|
302
|
+
return 130
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
if __name__ == "__main__": # pragma: no cover
|
|
306
|
+
sys.exit(main())
|
sealwright/config.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Project configuration (``sealwright.json``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from ._util import atomic_write
|
|
11
|
+
from .scan import SEVERITIES
|
|
12
|
+
from .sources import DEFAULT_SOURCES, SOURCE_KINDS, Source
|
|
13
|
+
|
|
14
|
+
CONFIG_NAME = "sealwright.json"
|
|
15
|
+
LOCK_NAME = "sealwright.lock"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ConfigError(Exception):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Config:
|
|
24
|
+
sources: list[Source] = field(default_factory=lambda: list(DEFAULT_SOURCES))
|
|
25
|
+
trusted_keys: list[str] = field(default_factory=list)
|
|
26
|
+
fail_on: str = "high"
|
|
27
|
+
ignore_rules: list[str] = field(default_factory=list)
|
|
28
|
+
ignore_findings: list[str] = field(default_factory=list)
|
|
29
|
+
probe: bool = False
|
|
30
|
+
probe_timeout: float = 20.0
|
|
31
|
+
|
|
32
|
+
def validate(self) -> None:
|
|
33
|
+
if self.fail_on not in SEVERITIES:
|
|
34
|
+
raise ConfigError(f"fail_on must be one of {SEVERITIES}")
|
|
35
|
+
for s in self.sources:
|
|
36
|
+
if s.kind not in SOURCE_KINDS:
|
|
37
|
+
raise ConfigError(f"unknown source kind {s.kind!r}; choose from {SOURCE_KINDS}")
|
|
38
|
+
|
|
39
|
+
def to_dict(self) -> dict[str, Any]:
|
|
40
|
+
return {
|
|
41
|
+
"version": 1,
|
|
42
|
+
"sources": [s.to_dict() for s in self.sources],
|
|
43
|
+
"trusted_keys": self.trusted_keys,
|
|
44
|
+
"fail_on": self.fail_on,
|
|
45
|
+
"ignore_rules": self.ignore_rules,
|
|
46
|
+
"ignore_findings": self.ignore_findings,
|
|
47
|
+
"probe": self.probe,
|
|
48
|
+
"probe_timeout": self.probe_timeout,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def from_dict(cls, d: dict[str, Any]) -> Config:
|
|
53
|
+
try:
|
|
54
|
+
cfg = cls(
|
|
55
|
+
sources=[
|
|
56
|
+
Source(str(s["kind"]), str(s["path"]), bool(s.get("optional", True))) for s in d.get("sources", [])
|
|
57
|
+
],
|
|
58
|
+
trusted_keys=[str(k) for k in d.get("trusted_keys", [])],
|
|
59
|
+
fail_on=str(d.get("fail_on", "high")),
|
|
60
|
+
ignore_rules=[str(r) for r in d.get("ignore_rules", [])],
|
|
61
|
+
ignore_findings=[str(r) for r in d.get("ignore_findings", [])],
|
|
62
|
+
probe=bool(d.get("probe", False)),
|
|
63
|
+
probe_timeout=float(d.get("probe_timeout", 20.0)),
|
|
64
|
+
)
|
|
65
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
66
|
+
raise ConfigError(f"invalid {CONFIG_NAME}: {exc}") from exc
|
|
67
|
+
cfg.validate()
|
|
68
|
+
return cfg
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class Project:
|
|
73
|
+
root: Path
|
|
74
|
+
config: Config
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def config_path(self) -> Path:
|
|
78
|
+
return self.root / CONFIG_NAME
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def lock_path(self) -> Path:
|
|
82
|
+
return self.root / LOCK_NAME
|
|
83
|
+
|
|
84
|
+
@classmethod
|
|
85
|
+
def find(cls, start: Path) -> Project:
|
|
86
|
+
"""Walk up from ``start`` to the nearest ``sealwright.json``."""
|
|
87
|
+
start = start.resolve()
|
|
88
|
+
for d in (start, *start.parents):
|
|
89
|
+
if (d / CONFIG_NAME).exists():
|
|
90
|
+
return cls.load(d)
|
|
91
|
+
raise ConfigError(f"no {CONFIG_NAME} found in {start} or its parents; run `sealwright init`")
|
|
92
|
+
|
|
93
|
+
@classmethod
|
|
94
|
+
def load(cls, root: Path) -> Project:
|
|
95
|
+
try:
|
|
96
|
+
data = json.loads((root / CONFIG_NAME).read_text(encoding="utf-8"))
|
|
97
|
+
except (OSError, ValueError) as exc:
|
|
98
|
+
raise ConfigError(f"cannot read {root / CONFIG_NAME}: {exc}") from exc
|
|
99
|
+
if not isinstance(data, dict):
|
|
100
|
+
raise ConfigError(f"{CONFIG_NAME} must be a JSON object")
|
|
101
|
+
return cls(root.resolve(), Config.from_dict(data))
|
|
102
|
+
|
|
103
|
+
def save(self) -> None:
|
|
104
|
+
self.config.validate()
|
|
105
|
+
atomic_write(self.config_path, (json.dumps(self.config.to_dict(), indent=2) + "\n").encode("utf-8"))
|
sealwright/engine.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Orchestration: discover, probe, scan, and compare against the lock."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import fnmatch
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .config import Project
|
|
10
|
+
from .lockfile import Change, build_lock, diff, read_lock, verify_signature
|
|
11
|
+
from .probe import ProbeError, probe
|
|
12
|
+
from .scan import RANK, Finding, scan
|
|
13
|
+
from .sources import Extension, discover
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Result:
|
|
18
|
+
extensions: list[Extension]
|
|
19
|
+
findings: list[Finding]
|
|
20
|
+
changes: list[Change]
|
|
21
|
+
warnings: list[str] = field(default_factory=list)
|
|
22
|
+
lock_present: bool = False
|
|
23
|
+
signature: tuple[bool | None, str] = (None, "")
|
|
24
|
+
probed: bool = False
|
|
25
|
+
|
|
26
|
+
def failing(self, threshold: str) -> bool:
|
|
27
|
+
"""True if anything at or above ``threshold`` needs attention."""
|
|
28
|
+
limit = RANK[threshold]
|
|
29
|
+
if self.signature[0] is False:
|
|
30
|
+
return True
|
|
31
|
+
return any(RANK[f.severity] >= limit for f in self.findings) or any(
|
|
32
|
+
RANK[c.severity] >= limit for c in self.changes
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
def to_dict(self) -> dict[str, Any]:
|
|
36
|
+
return {
|
|
37
|
+
"extensions": [{"id": e.id, "kind": e.kind, "name": e.name, "source": e.source} for e in self.extensions],
|
|
38
|
+
"findings": [f.to_dict() for f in self.findings],
|
|
39
|
+
"changes": [c.to_dict() for c in self.changes],
|
|
40
|
+
"warnings": self.warnings,
|
|
41
|
+
"lock_present": self.lock_present,
|
|
42
|
+
"signature": {"ok": self.signature[0], "message": self.signature[1]},
|
|
43
|
+
"probed": self.probed,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _filter(findings: list[Finding], project: Project) -> list[Finding]:
|
|
48
|
+
rules = set(project.config.ignore_rules)
|
|
49
|
+
patterns = project.config.ignore_findings
|
|
50
|
+
out = []
|
|
51
|
+
for f in findings:
|
|
52
|
+
if f.rule in rules:
|
|
53
|
+
continue
|
|
54
|
+
key = f"{f.rule}:{f.extension}:{f.location}"
|
|
55
|
+
if any(fnmatch.fnmatchcase(key, p) for p in patterns):
|
|
56
|
+
continue
|
|
57
|
+
out.append(f)
|
|
58
|
+
return out
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def inventory(project: Project, *, do_probe: bool) -> tuple[list[Extension], list[str]]:
|
|
62
|
+
exts, warnings = discover(project.config.sources, project.root)
|
|
63
|
+
if do_probe:
|
|
64
|
+
for ext in exts:
|
|
65
|
+
if ext.kind != "mcp_server":
|
|
66
|
+
continue
|
|
67
|
+
try:
|
|
68
|
+
ext.tools = probe(ext, timeout=project.config.probe_timeout)
|
|
69
|
+
except ProbeError as exc:
|
|
70
|
+
warnings.append(f"probe {ext.id}: {exc}")
|
|
71
|
+
return exts, warnings
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def check(project: Project, *, do_probe: bool | None = None) -> Result:
|
|
75
|
+
do_probe = project.config.probe if do_probe is None else do_probe
|
|
76
|
+
exts, warnings = inventory(project, do_probe=do_probe)
|
|
77
|
+
lock = read_lock(project.lock_path)
|
|
78
|
+
findings = _filter(scan(exts), project)
|
|
79
|
+
if lock is None:
|
|
80
|
+
return Result(exts, findings, [], warnings, False, (None, "no lockfile yet"), do_probe)
|
|
81
|
+
_carry_tools(exts, lock, probed=do_probe)
|
|
82
|
+
changes = diff(exts, lock, probed=do_probe)
|
|
83
|
+
sig = verify_signature(lock, project.config.trusted_keys)
|
|
84
|
+
return Result(exts, findings, changes, warnings, True, sig, do_probe)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _carry_tools(exts: list[Extension], lock: dict[str, Any], *, probed: bool) -> None:
|
|
88
|
+
"""Without probing, keep the previously pinned tool surface for unchanged servers."""
|
|
89
|
+
if probed:
|
|
90
|
+
return
|
|
91
|
+
locked = lock.get("extensions", {})
|
|
92
|
+
for ext in exts:
|
|
93
|
+
old = locked.get(ext.id)
|
|
94
|
+
if old and "tools" in old and old.get("content_hash") == ext.content_hash:
|
|
95
|
+
ext.tools = old["tools"]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def make_lock(
|
|
99
|
+
project: Project, exts: list[Extension], *, approve: set[str] | None = None, probed: bool
|
|
100
|
+
) -> dict[str, Any]:
|
|
101
|
+
"""Build a new lock. With ``approve``, only those ids take their current
|
|
102
|
+
state; everything else keeps its previously approved entry."""
|
|
103
|
+
previous = read_lock(project.lock_path)
|
|
104
|
+
if previous:
|
|
105
|
+
_carry_tools(exts, previous, probed=probed)
|
|
106
|
+
if approve is None or previous is None:
|
|
107
|
+
return build_lock(exts, previous)
|
|
108
|
+
current = {e.id: e for e in exts}
|
|
109
|
+
doc = build_lock([e for e in exts if e.id in approve], previous)
|
|
110
|
+
for ext_id, entry in previous.get("extensions", {}).items():
|
|
111
|
+
if ext_id not in approve and ext_id not in doc["extensions"]:
|
|
112
|
+
doc["extensions"][ext_id] = entry
|
|
113
|
+
for ext_id in approve:
|
|
114
|
+
if ext_id not in current:
|
|
115
|
+
doc["extensions"].pop(ext_id, None) # approving a removal
|
|
116
|
+
doc["extensions"] = dict(sorted(doc["extensions"].items()))
|
|
117
|
+
return doc
|
sealwright/hooks.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Session-start hook for coding agents.
|
|
2
|
+
|
|
3
|
+
Runs ``check`` when an agent session starts and, if anything changed since
|
|
4
|
+
approval or a serious finding exists, prints ``{"systemMessage": ...}`` so the
|
|
5
|
+
user sees it before the agent loads the changed extension's instructions.
|
|
6
|
+
It always exits 0: a broken checker must never stop someone working.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .config import ConfigError, Project
|
|
17
|
+
from .engine import check
|
|
18
|
+
from .scan import RANK
|
|
19
|
+
|
|
20
|
+
MAX_EVENT_BYTES = 1024 * 1024
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def run_hook(project_dir: str | None, stdin=None) -> int:
|
|
24
|
+
stdin = stdin or sys.stdin
|
|
25
|
+
try:
|
|
26
|
+
raw = stdin.read(MAX_EVENT_BYTES)
|
|
27
|
+
event = json.loads(raw) if raw.strip() else {}
|
|
28
|
+
if not isinstance(event, dict):
|
|
29
|
+
event = {}
|
|
30
|
+
if project_dir:
|
|
31
|
+
project = Project.load(Path(project_dir))
|
|
32
|
+
else:
|
|
33
|
+
try:
|
|
34
|
+
project = Project.find(Path(str(event.get("cwd") or ".")))
|
|
35
|
+
except ConfigError:
|
|
36
|
+
return 0 # project does not use sealwright
|
|
37
|
+
result = check(project, do_probe=False)
|
|
38
|
+
threshold = RANK[project.config.fail_on]
|
|
39
|
+
changes = [c for c in result.changes if RANK[c.severity] >= RANK["medium"]]
|
|
40
|
+
findings = [f for f in result.findings if RANK[f.severity] >= threshold]
|
|
41
|
+
parts = []
|
|
42
|
+
if not result.lock_present:
|
|
43
|
+
parts.append("no sealwright.lock yet: installed agent extensions have not been reviewed")
|
|
44
|
+
if result.signature[0] is False:
|
|
45
|
+
parts.append(f"lockfile signature problem: {result.signature[1]}")
|
|
46
|
+
if changes:
|
|
47
|
+
names = ", ".join(c.id for c in changes[:5]) + (" …" if len(changes) > 5 else "")
|
|
48
|
+
parts.append(f"{len(changes)} extension(s) changed since approval: {names}")
|
|
49
|
+
if findings:
|
|
50
|
+
parts.append(f"{len(findings)} finding(s) at or above '{project.config.fail_on}'")
|
|
51
|
+
if parts:
|
|
52
|
+
msg = "Sealwright: " + "; ".join(parts) + ". Run `sealwright check -v` to review."
|
|
53
|
+
print(json.dumps({"systemMessage": msg}))
|
|
54
|
+
except Exception as exc: # noqa: BLE001
|
|
55
|
+
print(f"sealwright hook error: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
56
|
+
return 0
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def hook_config(project_dir: str | None = None) -> dict[str, Any]:
|
|
60
|
+
cmd = "sealwright" + (f' --project "{Path(project_dir).resolve()}"' if project_dir else "") + " hook"
|
|
61
|
+
return {"hooks": {"SessionStart": [{"hooks": [{"type": "command", "command": cmd, "timeout": 60}]}]}}
|