integrity-killswitch 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.
@@ -0,0 +1,426 @@
1
+ """Localhost Web UI dashboard and HTTP API for agent-killswitch.
2
+
3
+ All dynamic values in the dashboard are rendered via textContent (zero innerHTML
4
+ interpolation) to prevent stored XSS through audit reasons or vendor metadata.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import sys
12
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
13
+ from typing import Any
14
+ from urllib.parse import urlparse
15
+
16
+ from . import ancestry, core
17
+
18
+ HTML_DASHBOARD = """<!DOCTYPE html>
19
+ <html lang="en">
20
+ <head>
21
+ <meta charset="UTF-8">
22
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
23
+ <title>agent-killswitch — Local Control Dashboard</title>
24
+ <style>
25
+ :root {
26
+ --bg: #090b0f;
27
+ --card: #131822;
28
+ --border: #222a38;
29
+ --text: #e6edf5;
30
+ --muted: #8b97a8;
31
+ --green: #10b981;
32
+ --red: #ef4444;
33
+ --mono: ui-monospace, "JetBrains Mono", SFMono-Regular, Menlo, Consolas, monospace;
34
+ --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, sans-serif;
35
+ }
36
+ * { box-sizing: border-box; margin: 0; padding: 0; }
37
+ body {
38
+ background: var(--bg); color: var(--text); font-family: var(--sans);
39
+ padding: 28px; max-width: 920px; margin: 0 auto;
40
+ }
41
+ header {
42
+ display: flex; justify-content: space-between; align-items: center;
43
+ padding-bottom: 16px; margin-bottom: 24px; border-bottom: 1px solid var(--border); gap: 12px;
44
+ }
45
+ h1 { font-size: 19px; letter-spacing: -0.02em; }
46
+ .sub { color: var(--muted); font-size: 13px; margin-top: 4px; }
47
+ .badge {
48
+ font-family: var(--mono); font-size: 11.5px; font-weight: 700;
49
+ padding: 5px 10px; border-radius: 4px; border: 1px solid;
50
+ }
51
+ .badge-ok { background: rgba(16,185,129,.12); color: var(--green); border-color: rgba(16,185,129,.4); }
52
+ .badge-danger { background: rgba(239,68,68,.12); color: var(--red); border-color: rgba(239,68,68,.4); }
53
+ .panic-box {
54
+ background: rgba(239,68,68,.08); border: 1px solid rgba(239,68,68,.5); border-radius: 8px;
55
+ padding: 20px; margin-bottom: 24px; display: flex; justify-content: space-between;
56
+ align-items: center; gap: 16px;
57
+ }
58
+ .panic-box h2 { font-size: 15px; color: var(--red); margin-bottom: 4px; font-family: var(--mono); }
59
+ .panic-box p { font-size: 13px; color: var(--muted); }
60
+ .btn {
61
+ border: none; border-radius: 6px; padding: 10px 18px;
62
+ font-weight: 700; font-size: 13.5px; cursor: pointer; font-family: var(--sans);
63
+ }
64
+ .btn-panic { background: var(--red); color: #fff; }
65
+ .btn-resume { background: var(--green); color: #04130d; }
66
+ .sec-title {
67
+ font-family: var(--mono); font-size: 12px; text-transform: uppercase;
68
+ letter-spacing: .06em; color: var(--muted); margin-bottom: 12px;
69
+ }
70
+ .grid {
71
+ display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
72
+ gap: 12px; margin-bottom: 24px;
73
+ }
74
+ .card {
75
+ background: var(--card); border: 1px solid var(--border); border-radius: 8px;
76
+ padding: 14px 16px; display: flex; justify-content: space-between; align-items: center; gap: 12px;
77
+ }
78
+ .card.disabled { opacity: .65; border-color: rgba(239,68,68,.35); }
79
+ .v-title { font-size: 14.5px; font-weight: 600; }
80
+ .v-id { font-family: var(--mono); font-size: 11.5px; color: var(--muted); margin-top: 2px; }
81
+ .v-reason { font-size: 12px; color: #93c5fd; margin-top: 4px; word-break: break-word; }
82
+ .switch { position: relative; display: inline-block; width: 48px; height: 26px; flex-shrink: 0; }
83
+ .switch input { opacity: 0; width: 0; height: 0; }
84
+ .slider {
85
+ position: absolute; cursor: pointer; inset: 0;
86
+ background: #334155; border-radius: 26px; transition: .2s;
87
+ }
88
+ .slider:before {
89
+ position: absolute; content: ""; height: 20px; width: 20px;
90
+ left: 3px; bottom: 3px; background: #fff; border-radius: 50%; transition: .2s;
91
+ }
92
+ input:checked + .slider { background: var(--green); }
93
+ input:checked + .slider:before { transform: translateX(22px); }
94
+ input:disabled + .slider { opacity: .4; cursor: not-allowed; }
95
+ .audit-box { background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 16px; }
96
+ .log-list {
97
+ font-family: var(--mono); font-size: 12px; max-height: 210px;
98
+ overflow-y: auto; color: #cbd5e1; display: grid; gap: 6px;
99
+ }
100
+ .log-entry { padding-bottom: 6px; border-bottom: 1px solid rgba(255,255,255,.05); word-break: break-word; }
101
+ .log-entry.block { color: var(--red); }
102
+ .notice { font-family: var(--mono); font-size: 12px; color: var(--red); margin-bottom: 12px; min-height: 16px; }
103
+ </style>
104
+ </head>
105
+ <body>
106
+ <header>
107
+ <div>
108
+ <h1>agent-killswitch</h1>
109
+ <div class="sub">Local OS-enforced emergency stop for AI coding agents</div>
110
+ </div>
111
+ <div id="masterBadge" class="badge badge-ok">NORMAL</div>
112
+ </header>
113
+
114
+ <div class="notice" id="notice"></div>
115
+
116
+ <div class="panic-box">
117
+ <div>
118
+ <h2 id="panicHeader">MASTER KILLSWITCH</h2>
119
+ <p id="panicDesc">Immediately block all AI agents from gated scripts, SSH, secrets, and hooks.</p>
120
+ </div>
121
+ <div id="panicAction"></div>
122
+ </div>
123
+
124
+ <div class="sec-title">Per-Vendor Toggles</div>
125
+ <div class="grid" id="vendorGrid"></div>
126
+
127
+ <div class="audit-box">
128
+ <div class="sec-title">Recent Security Audit Events</div>
129
+ <div class="log-list" id="auditList"></div>
130
+ </div>
131
+
132
+ <script>
133
+ let currentState = null;
134
+
135
+ function setNotice(msg) {
136
+ document.getElementById("notice").textContent = msg || "";
137
+ }
138
+
139
+ async function loadStatus() {
140
+ try {
141
+ const res = await fetch("/api/status");
142
+ currentState = await res.json();
143
+ render();
144
+ } catch (err) {
145
+ setNotice("Failed to fetch status: " + err);
146
+ }
147
+ }
148
+
149
+ function render() {
150
+ if (!currentState) return;
151
+ const isPanic = Boolean(currentState.master_panic);
152
+ const badge = document.getElementById("masterBadge");
153
+ const panicHeader = document.getElementById("panicHeader");
154
+ const panicAction = document.getElementById("panicAction");
155
+ panicAction.textContent = "";
156
+
157
+ const btn = document.createElement("button");
158
+ if (isPanic) {
159
+ badge.className = "badge badge-danger";
160
+ badge.textContent = "ALL AGENTS BLOCKED";
161
+ panicHeader.textContent = "MASTER PANIC ACTIVE";
162
+ btn.className = "btn btn-resume";
163
+ btn.textContent = "Resume Access";
164
+ btn.addEventListener("click", () => togglePanic(false));
165
+ } else {
166
+ badge.className = "badge badge-ok";
167
+ badge.textContent = "NORMAL";
168
+ panicHeader.textContent = "MASTER KILLSWITCH";
169
+ btn.className = "btn btn-panic";
170
+ btn.textContent = "PANIC STOP";
171
+ btn.addEventListener("click", () => togglePanic(true));
172
+ }
173
+ panicAction.appendChild(btn);
174
+
175
+ const grid = document.getElementById("vendorGrid");
176
+ grid.textContent = "";
177
+ for (const [key, v] of Object.entries(currentState.vendors || {})) {
178
+ const card = document.createElement("div");
179
+ const active = Boolean(v.enabled) && !isPanic;
180
+ card.className = "card" + (active ? "" : " disabled");
181
+
182
+ const info = document.createElement("div");
183
+ const title = document.createElement("div");
184
+ title.className = "v-title";
185
+ title.textContent = v.title || key;
186
+ const vid = document.createElement("div");
187
+ vid.className = "v-id";
188
+ vid.textContent = "vendor: " + key;
189
+ const reason = document.createElement("div");
190
+ reason.className = "v-reason";
191
+ reason.textContent = v.reason || "";
192
+ info.append(title, vid, reason);
193
+
194
+ const label = document.createElement("label");
195
+ label.className = "switch";
196
+ const cb = document.createElement("input");
197
+ cb.type = "checkbox";
198
+ cb.checked = Boolean(v.enabled);
199
+ cb.disabled = isPanic;
200
+ cb.addEventListener("change", () => toggleVendor(key, cb.checked));
201
+ const slider = document.createElement("span");
202
+ slider.className = "slider";
203
+ label.append(cb, slider);
204
+
205
+ card.append(info, label);
206
+ grid.appendChild(card);
207
+ }
208
+
209
+ const logList = document.getElementById("auditList");
210
+ logList.textContent = "";
211
+ const logs = currentState.logs || [];
212
+ if (!logs.length) {
213
+ const empty = document.createElement("div");
214
+ empty.className = "log-entry";
215
+ empty.textContent = "No audit events recorded yet.";
216
+ logList.appendChild(empty);
217
+ return;
218
+ }
219
+ for (const entry of logs) {
220
+ const row = document.createElement("div");
221
+ const act = String(entry.action || "");
222
+ const isBlock = act === "block" || act === "panic_triggered" || act === "web_denied" || act === "admin_denied";
223
+ row.className = "log-entry" + (isBlock ? " block" : "");
224
+ const ts = String(entry.ts || "").replace("T", " ").slice(0, 19);
225
+ const vendor = entry.vendor ? " " + entry.vendor : "";
226
+ const target = entry.target ? " @" + entry.target : "";
227
+ const reason = entry.reason ? " - " + entry.reason : "";
228
+ row.textContent = "[" + ts + "] " + act.toUpperCase() + ":" + vendor + target + reason;
229
+ logList.appendChild(row);
230
+ }
231
+ }
232
+
233
+ async function postAction(path, payload) {
234
+ setNotice("");
235
+ const res = await fetch(path, {
236
+ method: "POST",
237
+ headers: { "Content-Type": "application/json" },
238
+ body: JSON.stringify(payload),
239
+ });
240
+ if (!res.ok) {
241
+ const data = await res.json().catch(() => ({}));
242
+ setNotice("Refused (" + res.status + "): " + (data.reason || "unauthorized"));
243
+ }
244
+ await loadStatus();
245
+ }
246
+
247
+ async function toggleVendor(vendor, enabled) {
248
+ await postAction("/api/toggle", { vendor, enabled, reason: "Toggled via Web UI" });
249
+ }
250
+
251
+ async function togglePanic(activate) {
252
+ if (activate && !confirm("Block ALL AI agents immediately?")) return;
253
+ await postAction(activate ? "/api/panic" : "/api/resume", { reason: "Toggled via Web UI" });
254
+ }
255
+
256
+ loadStatus();
257
+ setInterval(loadStatus, 2000);
258
+ </script>
259
+ </body>
260
+ </html>
261
+ """
262
+
263
+
264
+ class KillswitchHTTPHandler(BaseHTTPRequestHandler):
265
+ """Localhost-only HTTP handler with Same-Origin and OS peer-PID checks."""
266
+
267
+ def _send_json(self, code: int, doc: dict[str, Any]) -> None:
268
+ self.send_response(code)
269
+ self.send_header("Content-Type", "application/json; charset=utf-8")
270
+ self.send_header("Cache-Control", "no-store")
271
+ self.end_headers()
272
+ self.wfile.write(json.dumps(doc, ensure_ascii=False).encode("utf-8"))
273
+
274
+ def _same_origin(self) -> bool:
275
+ port = self.server.server_address[1]
276
+ hosts = {f"127.0.0.1:{port}", f"localhost:{port}"}
277
+ if self.headers.get("Host", "") not in hosts:
278
+ return False
279
+ origin = self.headers.get("Origin")
280
+ return origin is None or origin in {f"http://{h}" for h in hosts}
281
+
282
+ def _client_actor(self) -> tuple[str, list[str]]:
283
+ pid = ancestry.tcp_peer_pid(self.client_address[1], self.server.server_address[1])
284
+ names = ancestry.get_process_ancestor_names(pid) if pid else []
285
+ return ancestry.web_actor(names), names
286
+
287
+ def do_GET(self) -> None:
288
+ parsed = urlparse(self.path)
289
+ if parsed.path in ("/", "/index.html"):
290
+ self.send_response(200)
291
+ self.send_header("Content-Type", "text/html; charset=utf-8")
292
+ self.send_header("X-Content-Type-Options", "nosniff")
293
+ self.send_header("X-Frame-Options", "DENY")
294
+ self.end_headers()
295
+ self.wfile.write(HTML_DASHBOARD.encode("utf-8"))
296
+ return
297
+
298
+ if parsed.path == "/api/status":
299
+ state = core.load_state(core.state_path())
300
+ logs: list[dict[str, Any]] = []
301
+ lpath = core.log_path()
302
+ if lpath.exists():
303
+ try:
304
+ lines = lpath.read_text(encoding="utf-8", errors="replace").splitlines()
305
+ for line in reversed(lines[-20:]):
306
+ try:
307
+ item = json.loads(line)
308
+ if isinstance(item, dict):
309
+ logs.append(item)
310
+ except ValueError:
311
+ continue
312
+ except OSError:
313
+ logs = []
314
+ state["logs"] = logs
315
+ self._send_json(200, state)
316
+ return
317
+
318
+ self.send_response(404)
319
+ self.end_headers()
320
+
321
+ def do_POST(self) -> None:
322
+ parsed = urlparse(self.path)
323
+ if parsed.path not in ("/api/toggle", "/api/panic", "/api/resume"):
324
+ self.send_response(404)
325
+ self.end_headers()
326
+ return
327
+
328
+ try:
329
+ length = min(int(self.headers.get("Content-Length", 0) or 0), 65536)
330
+ except ValueError:
331
+ length = 0
332
+ body = self.rfile.read(length) if length else b"{}"
333
+ try:
334
+ payload = json.loads(body.decode("utf-8"))
335
+ except ValueError:
336
+ payload = {}
337
+ if not isinstance(payload, dict):
338
+ payload = {}
339
+
340
+ if not self._same_origin():
341
+ core.log_audit_event("web_denied", {"path": parsed.path, "reason": "cross-origin or foreign Host"})
342
+ self._send_json(403, {"status": "refused", "reason": "cross-origin request"})
343
+ return
344
+
345
+ actor, names = self._client_actor()
346
+ enabled = bool(payload.get("enabled", True))
347
+ restoring = parsed.path == "/api/resume" or (parsed.path == "/api/toggle" and enabled)
348
+ if restoring and actor != "owner":
349
+ core.log_audit_event(
350
+ "web_denied",
351
+ {
352
+ "path": parsed.path,
353
+ "actor": actor,
354
+ "ancestors": names,
355
+ "reason": "restoring access is owner-only",
356
+ },
357
+ )
358
+ self._send_json(
359
+ 403,
360
+ {"status": "refused", "reason": f"restoring access is owner-only (caller detected as {actor})"},
361
+ )
362
+ return
363
+
364
+ path = core.state_path()
365
+
366
+ if parsed.path == "/api/toggle":
367
+ vendor = str(payload.get("vendor", "")).lower().strip()
368
+ reason = str(payload.get("reason", "Web UI toggle"))[:200]
369
+ toggled = False
370
+
371
+ def _apply_toggle(state: dict[str, Any]) -> bool:
372
+ nonlocal toggled
373
+ if vendor not in state.get("vendors", {}):
374
+ return False
375
+ state["vendors"][vendor]["enabled"] = enabled
376
+ state["vendors"][vendor]["reason"] = reason
377
+ state["vendors"][vendor]["updated_at"] = core.utc_now()
378
+ toggled = True
379
+ return True
380
+
381
+ core.mutate_state(path, _apply_toggle, actor=f"{actor}-web-ui")
382
+ if toggled:
383
+ core.log_audit_event(
384
+ "vendor_toggle",
385
+ {"vendor": vendor, "enabled": enabled, "reason": reason, "actor": actor},
386
+ )
387
+ elif parsed.path == "/api/panic":
388
+ note = str(payload.get("reason", "Triggered from Web UI"))[:200]
389
+
390
+ def _apply_web_panic(state: dict[str, Any]) -> None:
391
+ state["master_panic"] = True
392
+ state["note"] = note
393
+
394
+ core.mutate_state(path, _apply_web_panic, actor=f"{actor}-web-ui")
395
+ core.log_audit_event("panic_triggered", {"reason": note, "actor": actor})
396
+ else:
397
+ note = str(payload.get("reason", "Resumed from Web UI"))[:200]
398
+
399
+ def _apply_web_resume(state: dict[str, Any]) -> None:
400
+ state["master_panic"] = False
401
+ state["note"] = note
402
+
403
+ core.mutate_state(path, _apply_web_resume, actor=f"{actor}-web-ui")
404
+ core.log_audit_event("panic_cleared", {"reason": note, "actor": actor})
405
+
406
+ self._send_json(200, {"status": "ok"})
407
+
408
+ def log_message(self, format: str, *args: Any) -> None:
409
+ return
410
+
411
+
412
+ def serve_dashboard(host: str = "127.0.0.1", port: int = 8787, state_override: str | None = None) -> int:
413
+ if state_override:
414
+ os.environ["AGENT_KILLSWITCH_STATE"] = state_override
415
+ if host not in ("127.0.0.1", "localhost", "::1"):
416
+ print("agent-killswitch: refusing to bind dashboard on non-loopback address", file=sys.stderr)
417
+ return 2
418
+ server = ThreadingHTTPServer((host, port), KillswitchHTTPHandler)
419
+ print(f"agent-killswitch dashboard listening on http://{host}:{server.server_address[1]}/")
420
+ try:
421
+ server.serve_forever()
422
+ except KeyboardInterrupt:
423
+ print("\nagent-killswitch dashboard stopped.")
424
+ finally:
425
+ server.server_close()
426
+ return 0