Merge branch 'feature/orchestrator-firewall' into unify/skills-20261112-night
# Conflicts: # orchestrator/Dockerfile # orchestrator/kvb_orchestrator/view.py # orchestrator/templates/index.html.j2 # orchestrator/templates/page-cleanup.js # scripts/orchestrator.sh
This commit is contained in:
commit
d364cfe55f
48 files changed
+3438
-106
No files matched your search
@@ -59,7 +59,7 @@ RUN chmod 0755 /opt/voices /opt/whisper
|
||||
|
||||
COPY server.py /app/server.py
|
||||
COPY kvb_orchestrator /app/kvb_orchestrator
|
||||
COPY client/hub_limits.py client/signing.py client/passkey.py client/verifier.py client/queue_live.py /app/client/
|
||||
COPY client/hub_limits.py client/signing.py client/emoji-variation.json client/passkey.py client/verifier.py client/queue_live.py /app/client/
|
||||
COPY templates /app/templates
|
||||
COPY vendor /app/vendor
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ def tree_facts(tree: Path) -> tuple[dict[str, str], bool]:
|
||||
data = json.loads(tree.read_text(encoding="utf-8"))
|
||||
known = {entry["path"]: entry.get("default") if isinstance(entry.get("default"), str) else "" for entry in data["repos"] if entry.get("known") is True and isinstance(entry.get("path"), str)}
|
||||
return known, data.get("delete_ready") is True
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
||||
except Exception: # noqa: BLE001
|
||||
return {}, False
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"source": "https://www.unicode.org/Public/16.0.0/ucd/emoji/emoji-variation-sequences.txt",
|
||||
"unicode": "16.0.0",
|
||||
"bases": [
|
||||
"00A9", "00AE", "203C", "2049", "2122", "2139", "2194", "2195", "2196", "2197", "2198", "2199", "21A9", "21AA", "231A", "231B", "2328", "23CF", "23E9", "23EA",
|
||||
"23EB", "23EC", "23ED", "23EE", "23EF", "23F0", "23F1", "23F2", "23F3", "23F8", "23F9", "23FA", "24C2", "25AA", "25AB", "25B6", "25C0", "25FB", "25FC", "25FD",
|
||||
"25FE", "2600", "2601", "2602", "2603", "2604", "260E", "2611", "2614", "2615", "2618", "261D", "2620", "2622", "2623", "2626", "262A", "262E", "262F", "2638",
|
||||
"2639", "263A", "2640", "2642", "2648", "2649", "264A", "264B", "264C", "264D", "264E", "264F", "2650", "2651", "2652", "2653", "265F", "2660", "2663", "2665",
|
||||
"2666", "2668", "267B", "267E", "267F", "2692", "2693", "2694", "2695", "2696", "2697", "2699", "269B", "269C", "26A0", "26A1", "26A7", "26AA", "26AB", "26B0",
|
||||
"26B1", "26BD", "26BE", "26C4", "26C5", "26C8", "26CE", "26CF", "26D1", "26D3", "26D4", "26E9", "26EA", "26F0", "26F1", "26F2", "26F3", "26F4", "26F5", "26F7",
|
||||
"26F8", "26F9", "26FA", "26FD", "2702", "2705", "2708", "2709", "270A", "270B", "270C", "270D", "270F", "2712", "2714", "2716", "271D", "2721", "2728", "2733",
|
||||
"2734", "2744", "2747", "274C", "274E", "2753", "2754", "2755", "2757", "2763", "2764", "2795", "2796", "2797", "27A1", "27B0", "27BF", "2934", "2935", "2B05",
|
||||
"2B06", "2B07", "2B1B", "2B1C", "2B50", "2B55", "3030", "303D", "3297", "3299", "1F004", "1F170", "1F171", "1F17E", "1F17F", "1F202", "1F21A", "1F22F", "1F237", "1F30D",
|
||||
"1F30E", "1F30F", "1F315", "1F31C", "1F321", "1F324", "1F325", "1F326", "1F327", "1F328", "1F329", "1F32A", "1F32B", "1F32C", "1F336", "1F378", "1F37D", "1F393", "1F396", "1F397",
|
||||
"1F399", "1F39A", "1F39B", "1F39E", "1F39F", "1F3A7", "1F3AC", "1F3AD", "1F3AE", "1F3C2", "1F3C4", "1F3C6", "1F3CA", "1F3CB", "1F3CC", "1F3CD", "1F3CE", "1F3D4", "1F3D5", "1F3D6",
|
||||
"1F3D7", "1F3D8", "1F3D9", "1F3DA", "1F3DB", "1F3DC", "1F3DD", "1F3DE", "1F3DF", "1F3E0", "1F3ED", "1F3F3", "1F3F5", "1F3F7", "1F408", "1F415", "1F41F", "1F426", "1F43F", "1F441",
|
||||
"1F442", "1F446", "1F447", "1F448", "1F449", "1F44D", "1F44E", "1F453", "1F46A", "1F47D", "1F4A3", "1F4B0", "1F4B3", "1F4BB", "1F4BF", "1F4CB", "1F4DA", "1F4DF", "1F4E4", "1F4E5",
|
||||
"1F4E6", "1F4EA", "1F4EB", "1F4EC", "1F4ED", "1F4F7", "1F4F9", "1F4FA", "1F4FB", "1F4FD", "1F508", "1F50D", "1F512", "1F513", "1F549", "1F54A", "1F550", "1F551", "1F552", "1F553",
|
||||
"1F554", "1F555", "1F556", "1F557", "1F558", "1F559", "1F55A", "1F55B", "1F55C", "1F55D", "1F55E", "1F55F", "1F560", "1F561", "1F562", "1F563", "1F564", "1F565", "1F566", "1F567",
|
||||
"1F56F", "1F570", "1F573", "1F574", "1F575", "1F576", "1F577", "1F578", "1F579", "1F587", "1F58A", "1F58B", "1F58C", "1F58D", "1F590", "1F5A5", "1F5A8", "1F5B1", "1F5B2", "1F5BC",
|
||||
"1F5C2", "1F5C3", "1F5C4", "1F5D1", "1F5D2", "1F5D3", "1F5DC", "1F5DD", "1F5DE", "1F5E1", "1F5E3", "1F5E8", "1F5EF", "1F5F3", "1F5FA", "1F610", "1F687", "1F68D", "1F691", "1F694",
|
||||
"1F698", "1F6AD", "1F6B2", "1F6B9", "1F6BA", "1F6BC", "1F6CB", "1F6CD", "1F6CE", "1F6CF", "1F6E0", "1F6E1", "1F6E2", "1F6E3", "1F6E4", "1F6E5", "1F6E9", "1F6F0", "1F6F3"
|
||||
]
|
||||
}
|
||||
@@ -30,9 +30,9 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
@@ -51,7 +51,6 @@ DENIED = "The operator denied this in the Agent Orchestrator."
|
||||
CHANGED = "staged tree changed since the preview"
|
||||
UNBOUND = "the staged tree cannot be read, so the allow is not bound to it"
|
||||
REASON_LIMIT = 2000
|
||||
CONTROL = re.compile(r"[\x00-\x1f\x7f]")
|
||||
FAILURES = (OSError, ValueError, staged_diff.DiffError)
|
||||
|
||||
|
||||
@@ -99,7 +98,26 @@ def commit_diff(ask: dict, rules: Path | None) -> tuple[str | None, dict]:
|
||||
|
||||
|
||||
def clean(text: str) -> str:
|
||||
return CONTROL.sub("?", text.strip())[:REASON_LIMIT]
|
||||
"""Returns:
|
||||
text on one line for the terminal and the agent: every character
|
||||
signing.unseen() names, a C0 or C1 control, a bidi or zero-width
|
||||
character among them, shown as ?, but a selector signing.presented()
|
||||
accepts; cut at REASON_LIMIT.
|
||||
"""
|
||||
stripped = text.strip()
|
||||
return "".join("?" if signing.unseen(char) and not signing.presented(stripped, index) else char for index, char in enumerate(stripped))[:REASON_LIMIT]
|
||||
|
||||
|
||||
def refusal(error: urllib.error.HTTPError) -> str:
|
||||
"""Returns:
|
||||
The reason the hub sent with an error status, on one line, or the
|
||||
status text when its body cannot be read.
|
||||
"""
|
||||
try:
|
||||
body = error.read().decode("utf-8", "replace")
|
||||
except OSError:
|
||||
body = ""
|
||||
return clean(body or str(error.reason))
|
||||
|
||||
|
||||
def bound(chosen: dict | None, ask: dict, pinned: str | None) -> dict | None:
|
||||
@@ -194,6 +212,9 @@ def main() -> int:
|
||||
answer = {"status": "pending"}
|
||||
while answer["status"] == "pending" and (left := deadline - time.monotonic()) > 0:
|
||||
answer = status(base, ask_id, min(left, POLL))
|
||||
except urllib.error.HTTPError as error:
|
||||
print(f"kvb-orchestrator: the hub answered {error.code}, Claude Code asks instead: {refusal(error)}", file=sys.stderr)
|
||||
return 0
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
||||
return 0
|
||||
chosen = bound(decision(answer, signing.ask_item(ask_id, ask["tool"], ask["command"], ask["cwd"], ask["session"]), trust), ask, pinned)
|
||||
|
||||
Executable
+365
@@ -0,0 +1,365 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Args:
|
||||
--port: port of the Agent Orchestrator; the signature's origin is
|
||||
http://localhost:<port>.
|
||||
--jobs: the directory the hub writes signed settings changes into, e.g.
|
||||
~/.local/state/kvb-orchestrator/firewall/jobs.
|
||||
--results: the directory each job's result goes to as <id>.json.
|
||||
--view: the file the Firewall reads, e.g.
|
||||
~/.local/state/kvb-orchestrator/firewall/view.json: per listed file
|
||||
its path, sha256 and only its permissions and sandbox sections.
|
||||
--approvers: the pinned passkeys, e.g. ~/.config/kvb-orchestrator/approvers.json.
|
||||
--replay: this writer's replay store, outside the hub's reach, e.g.
|
||||
~/.local/state/kvb-orchestrator-approvals/firewall.json.
|
||||
--tree: the tree file `pkgmgr branch tree` writes; the repositories it
|
||||
knows name the project settings files.
|
||||
|
||||
Returns:
|
||||
Exit code 2 without touching anything when CLAUDECODE or
|
||||
SANDBOX_RUNTIME is set: it runs only from its unit, never inside an
|
||||
agent or its sandbox. Else, as the operator on the host, per item of
|
||||
every job in --jobs: verifies the operator's passkey signature over
|
||||
file, base and changes with the replay store; refuses a file outside the
|
||||
fixed list (~/.claude/settings.json and <repository>/.claude/settings.json
|
||||
of every repository the tree file knows), a link or non-directory on its
|
||||
path, a file of another uid, a non-regular file and a file whose sha256
|
||||
is no longer the signed base; then applies exactly the signed changes to
|
||||
the parsed file, keeps every other key, copies the old bytes to
|
||||
<file>.before-firewall-<job id> beside it and replaces the file
|
||||
atomically, both with the file's mode (0600 for a new file). A refused
|
||||
item changes nothing; a failed one keeps the file's content. Writes each
|
||||
job's result, removes the job and rewrites --view, all through
|
||||
verifier.drain() and verifier.private_dir(): relative to open directory
|
||||
descriptors, never through a link, a linked or foreign jobs, results or
|
||||
view directory refused with one line on stderr. The exit code is 0.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import secrets
|
||||
import stat
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import signing
|
||||
import verifier
|
||||
from cleanup import tree_facts
|
||||
from offices import cycle
|
||||
|
||||
AGENT_MARKERS = ("CLAUDECODE", "SANDBOX_RUNTIME")
|
||||
DIRECTORY = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
|
||||
FILE = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC
|
||||
CREATE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC
|
||||
READ_LIMIT = 1 << 20
|
||||
NEW_MODE = 0o600
|
||||
BACKUP = "before-firewall"
|
||||
OUTSIDE = "an agent or its sandbox runs this: the settings writer runs only from the kvb-orchestrator-firewall unit"
|
||||
MISSING_DIRECTORY = "no directory: create it first"
|
||||
|
||||
|
||||
def listed(home: Path, tree: Path) -> list[str]:
|
||||
"""Returns:
|
||||
The fixed list of settings files: the operator's own and those of
|
||||
every repository the tree file knows.
|
||||
"""
|
||||
own = str(home / ".claude" / "settings.json")
|
||||
projects = sorted(f"{repository.rstrip('/')}{signing.SETTINGS_FILE}" for repository in tree_facts(tree)[0])
|
||||
return [own, *(path for path in projects if path != own)]
|
||||
|
||||
|
||||
def parent_of(path: str) -> int:
|
||||
"""Returns:
|
||||
The open directory holding path, reached from / without following a
|
||||
link on the way; the caller closes it.
|
||||
"""
|
||||
fd = os.open("/", DIRECTORY)
|
||||
try:
|
||||
for part in Path(path).parent.parts[1:]:
|
||||
child = os.open(part, DIRECTORY, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
except BaseException:
|
||||
os.close(fd)
|
||||
raise
|
||||
return fd
|
||||
|
||||
|
||||
def read_settings(parent: int, name: str) -> tuple[bytes | None, os.stat_result | None]:
|
||||
"""Returns:
|
||||
The file's bytes and status, None and None while it is missing.
|
||||
|
||||
Raises:
|
||||
signing.Refused for a link, a non-regular file or one over
|
||||
READ_LIMIT bytes.
|
||||
"""
|
||||
try:
|
||||
fd = os.open(name, FILE, dir_fd=parent)
|
||||
except FileNotFoundError:
|
||||
return None, None
|
||||
except OSError as error:
|
||||
raise signing.Refused(f"the file opens only through a link or not at all: {error.strerror}") from None
|
||||
with open(fd, "rb") as handle:
|
||||
found = os.fstat(fd)
|
||||
if not stat.S_ISREG(found.st_mode):
|
||||
raise signing.Refused("the file is no regular file")
|
||||
data = handle.read(READ_LIMIT + 1)
|
||||
if len(data) > READ_LIMIT:
|
||||
raise signing.Refused(f"the file is larger than {READ_LIMIT} bytes")
|
||||
return data, found
|
||||
|
||||
|
||||
def write_beside(parent: int, name: str, data: bytes, mode: int) -> str:
|
||||
"""Args:
|
||||
parent: the open directory.
|
||||
name: the file to replace or create in it.
|
||||
data: its new bytes.
|
||||
mode: its permission bits.
|
||||
|
||||
Returns:
|
||||
"" once the directory is synced, else why its sync failed after the
|
||||
file was already replaced.
|
||||
"""
|
||||
temporary = f".{name}.{secrets.token_hex(8)}"
|
||||
fd = os.open(temporary, CREATE, mode, dir_fd=parent)
|
||||
try:
|
||||
with open(fd, "wb") as handle:
|
||||
os.fchmod(fd, mode)
|
||||
handle.write(data)
|
||||
handle.flush()
|
||||
os.fsync(fd)
|
||||
os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent)
|
||||
except BaseException:
|
||||
os.unlink(temporary, dir_fd=parent)
|
||||
raise
|
||||
try:
|
||||
os.fsync(parent)
|
||||
except OSError as error:
|
||||
return error.strerror or type(error).__name__
|
||||
return ""
|
||||
|
||||
|
||||
class Unsafe(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def no_constant(name: str) -> float:
|
||||
raise Unsafe(f"the file holds {name}, which JSON readers reject")
|
||||
|
||||
|
||||
def finite(text: str) -> float:
|
||||
value = float(text)
|
||||
if not math.isfinite(value):
|
||||
raise Unsafe("the file holds a number beyond the double range, which JSON readers reject")
|
||||
return value
|
||||
|
||||
|
||||
def unique(pairs: list[tuple[str, object]]) -> dict:
|
||||
found = dict(pairs)
|
||||
if len(found) != len(pairs):
|
||||
raise Unsafe("the file repeats a key in one object")
|
||||
return found
|
||||
|
||||
|
||||
def parsed(data: bytes | None) -> dict:
|
||||
"""Returns:
|
||||
The settings object, {} while the file is missing.
|
||||
|
||||
Raises:
|
||||
Unsafe for anything but strict JSON every reader parses alike: no
|
||||
NaN, Infinity or overflowing number, no repeated key, no lone
|
||||
surrogate, at most signing.DEPTH_LIMIT levels, an object at the top.
|
||||
The reason never quotes the file.
|
||||
"""
|
||||
if data is None:
|
||||
return {}
|
||||
try:
|
||||
settings = json.loads(data.decode("utf-8"), parse_constant=no_constant, parse_float=finite, object_pairs_hook=unique)
|
||||
except Unsafe:
|
||||
raise
|
||||
except (ValueError, RecursionError) as error:
|
||||
raise Unsafe(f"the file holds no strict JSON: {type(error).__name__}") from None
|
||||
problem = signing.plain_problem(settings, 0) if isinstance(settings, dict) else "the file holds no JSON object"
|
||||
if problem:
|
||||
raise Unsafe(problem)
|
||||
return settings
|
||||
|
||||
|
||||
def digest(data: bytes | None) -> str:
|
||||
return "" if data is None else hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def view_of(path: str) -> dict:
|
||||
"""Returns:
|
||||
{"path", "exists", "sha256", "error", "settings"}: settings only the
|
||||
permissions and sandbox sections; error why the file was unreadable,
|
||||
for anything unforeseen only the exception's class, so one bad path
|
||||
never keeps the others or the view from being written.
|
||||
"""
|
||||
entry = {"path": path, "exists": False, "sha256": "", "error": "", "settings": {}}
|
||||
try:
|
||||
return read_view(path, entry)
|
||||
except Exception as error: # noqa: BLE001
|
||||
return {**entry, "error": f"unreadable: {type(error).__name__}"}
|
||||
|
||||
|
||||
def read_view(path: str, entry: dict) -> dict:
|
||||
try:
|
||||
parent = parent_of(path)
|
||||
except FileNotFoundError:
|
||||
return {**entry, "error": MISSING_DIRECTORY}
|
||||
except OSError as error:
|
||||
return {**entry, "error": f"a link or no directory on the path: {error.strerror}"}
|
||||
try:
|
||||
data, _ = read_settings(parent, Path(path).name)
|
||||
return {**entry, "exists": data is not None, "sha256": digest(data), "settings": signing.settings_view(parsed(data))}
|
||||
except (OSError, Unsafe, signing.Refused) as error:
|
||||
return {**entry, "error": str(error)[:300]}
|
||||
finally:
|
||||
os.close(parent)
|
||||
|
||||
|
||||
class Writer:
|
||||
def __init__(self, trust: verifier.Trust, home: Path, tree: Path) -> None:
|
||||
self.trust = trust
|
||||
self.home = home
|
||||
self.tree = tree
|
||||
|
||||
def view(self) -> dict:
|
||||
return {"written": time.time(), "files": [view_of(path) for path in listed(self.home, self.tree)]}
|
||||
|
||||
def apply(self, item: dict, job_id: str) -> dict:
|
||||
"""Args:
|
||||
item: one signed, well-formed settings change.
|
||||
job_id: the job's id, part of the backup's name.
|
||||
|
||||
Returns:
|
||||
{"backup", "sha256", "unsynced"}: the backup beside the file, ""
|
||||
for a file that was missing, the new content's sha256, and why
|
||||
the directory sync failed after a replace, "" when it did not.
|
||||
|
||||
Raises:
|
||||
signing.Refused or OSError when nothing was written.
|
||||
"""
|
||||
name = Path(item["file"]).name
|
||||
try:
|
||||
parent = parent_of(item["file"])
|
||||
except OSError as error:
|
||||
raise signing.Refused(f"a link or no directory on the path: {error.strerror}") from None
|
||||
try:
|
||||
data, found = read_settings(parent, name)
|
||||
if found is not None and found.st_uid != os.getuid():
|
||||
raise signing.Refused(f"the file belongs to uid {found.st_uid}, not {os.getuid()}")
|
||||
if digest(data) != item["base"]:
|
||||
raise signing.Refused("the file changed since the signature")
|
||||
text = (json.dumps(signing.apply_changes(parsed(data), item["changes"]), indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
|
||||
mode = NEW_MODE if found is None else stat.S_IMODE(found.st_mode)
|
||||
backup = unsynced = ""
|
||||
if data is not None:
|
||||
backup = f"{name}.{BACKUP}-{job_id}"
|
||||
unsynced = write_beside(parent, backup, data, mode)
|
||||
unsynced = write_beside(parent, name, text, mode) or unsynced
|
||||
finally:
|
||||
os.close(parent)
|
||||
return {"backup": str(Path(item["file"]).with_name(backup)) if backup else "", "sha256": digest(text), "unsynced": unsynced}
|
||||
|
||||
def item(self, item: dict, proof: object, job_id: str, now: float) -> dict:
|
||||
"""Args:
|
||||
item: one well-formed settings change.
|
||||
proof: the job's {"payload", "assertion"}.
|
||||
job_id: the job's id.
|
||||
now: the current time in epoch seconds.
|
||||
|
||||
Returns:
|
||||
The item with status done, refused or failed and the reason; a
|
||||
refused or failed item wrote nothing, and a failure's reason names
|
||||
only its kind, never the file's content.
|
||||
"""
|
||||
try:
|
||||
status, reason, written = self.outcome(item, proof, job_id, now)
|
||||
except OSError as error:
|
||||
status, reason, written = "failed", f"{error.strerror or error}; the file kept its content", {}
|
||||
except Exception as error: # noqa: BLE001
|
||||
status, reason, written = "failed", f"{error if isinstance(error, Unsafe) else type(error).__name__}; the file kept its content", {}
|
||||
return {**item, "status": status, "reason": reason, **written}
|
||||
|
||||
def outcome(self, item: dict, proof: object, job_id: str, now: float) -> tuple[str, str, dict]:
|
||||
try:
|
||||
verifier.check(proof, signing.settings_item(item["file"], item["base"], item["changes"]), "", self.trust, now)
|
||||
except (signing.Refused, OSError) as error:
|
||||
return "refused", f"no valid operator signature: {error}", {}
|
||||
if item["file"] not in listed(self.home, self.tree):
|
||||
return "refused", "unlisted file: only ~/.claude/settings.json and the .claude/settings.json of a repository pkgmgr knows", {}
|
||||
try:
|
||||
written = self.apply(item, job_id)
|
||||
except signing.Refused as error:
|
||||
return "refused", str(error)[:500], {}
|
||||
unsynced = written.pop("unsynced")
|
||||
return "done", f"written, but its directory sync failed: {unsynced}; the change may not survive a crash" if unsynced else "", written
|
||||
|
||||
def job(self, folder: int, path: Path, now: float) -> dict:
|
||||
"""Args:
|
||||
folder: the open jobs directory, as verifier.drain() passes it.
|
||||
path: the job's name in it.
|
||||
now: the current time in epoch seconds.
|
||||
|
||||
Returns:
|
||||
The job's result; whatever goes wrong in one job fails only that
|
||||
job, so the next job and the view still run.
|
||||
"""
|
||||
try:
|
||||
return self.checked_job(folder, path, now)
|
||||
except Exception as error: # noqa: BLE001
|
||||
return {"id": path.stem, "finished": now, "items": [], "error": f"failed: {type(error).__name__}; nothing changed"}
|
||||
|
||||
def checked_job(self, folder: int, path: Path, now: float) -> dict:
|
||||
try:
|
||||
job = json.loads(verifier.read_regular(path, folder))
|
||||
except (OSError, ValueError, RecursionError) as error:
|
||||
return {"id": path.stem, "finished": now, "items": [], "error": f"unreadable job: {error}"}
|
||||
items = job.get("items") if isinstance(job, dict) else None
|
||||
if not isinstance(items, list) or not items or any(signing.settings_problem(item) for item in items) or job.get("id") != path.stem:
|
||||
return {"id": path.stem, "finished": now, "items": [], "error": "malformed job: refused, nothing changed"}
|
||||
return {"id": path.stem, "finished": time.time(), "items": [self.item(item, job.get("proof"), path.stem, now) for item in items]}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if any(marker in os.environ for marker in AGENT_MARKERS):
|
||||
print(f"settings_writer: refused: {OUTSIDE}", file=sys.stderr)
|
||||
return 2
|
||||
parser = argparse.ArgumentParser(prog="settings_writer")
|
||||
parser.add_argument("--port", type=int, required=True)
|
||||
for name in ("--jobs", "--results", "--view", "--approvers", "--replay", "--tree"):
|
||||
parser.add_argument(name, type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
trust = verifier.Trust(approvers=args.approvers, replay=args.replay, origin=signing.origin_of(args.port))
|
||||
writer = Writer(trust, Path.home(), args.tree)
|
||||
try:
|
||||
cycle(args.jobs, args.results, writer)
|
||||
finally:
|
||||
write_view(args.view, writer.view())
|
||||
return 0
|
||||
|
||||
|
||||
def write_view(path: Path, view: dict) -> None:
|
||||
"""Args:
|
||||
path: the view file, written relative to its directory opened by
|
||||
verifier.private_dir(); a linked or foreign spool, or a write
|
||||
that fails, prints one line and raises nothing, so an error of
|
||||
the cycle before it still surfaces.
|
||||
view: Writer.view().
|
||||
"""
|
||||
try:
|
||||
with verifier.private_dir(path.parent, True) as folder:
|
||||
verifier.write_at(folder, path.name, view)
|
||||
except (signing.Refused, OSError) as error:
|
||||
print(f"view not written: {error}", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,10 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import copy
|
||||
import fnmatch
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
|
||||
RP_ID = "localhost"
|
||||
@@ -35,6 +37,28 @@ GATE_BRANCH = re.compile(r"(?![-/])(?!.*\.\.)(?!.*@\{)(?!.*//)[^\x00-\x20\x7f~^:
|
||||
TOKEN_FREE_MERGE = "ancestor"
|
||||
APPROVAL_KEYS = {"v", "kind", "items", "nonce", "expires"}
|
||||
RULE_KEYS = {"v", "kind", "id", "kinds", "tool", "pattern", "scope", "expires"}
|
||||
TARGET = "agents"
|
||||
ALL_AGENTS = "*"
|
||||
AGENT_LIMIT = 50
|
||||
SETTINGS_FILE = "/.claude/settings.json"
|
||||
SETTINGS_KEYS = ("file", "base", "changes")
|
||||
SETTINGS_SECTIONS = ("permissions", "sandbox")
|
||||
SETTINGS_LISTS = ("permissions.allow", "permissions.ask", "permissions.deny", "sandbox.filesystem.allowWrite", "sandbox.filesystem.denyRead", "sandbox.network.allowedDomains")
|
||||
SETTINGS_OPS = ("add", "remove")
|
||||
CHANGE_KEYS = ("list", "op", "entry")
|
||||
CHANGE_LIMIT = 50
|
||||
ENTRY = re.compile(r"(?=[^\x00-\x1f\x7f\ud800-\udfff]*\S)[^\x00-\x1f\x7f\ud800-\udfff]{1,500}")
|
||||
SETTINGS_PATH = re.compile(r"/[^\x00-\x1f\x7f\ud800-\udfff]{0,4095}")
|
||||
SURROGATE = re.compile(r"[\ud800-\udfff]")
|
||||
UNSEEN = ("Cc", "Cf", "Zl", "Zp")
|
||||
DEFAULT_IGNORABLE = ((0xAD, 0xAD), (0x34F, 0x34F), (0x61C, 0x61C), (0x115F, 0x1160), (0x17B4, 0x17B5), (0x180B, 0x180F), (0x200B, 0x200F), (0x202A, 0x202E), (0x2060, 0x206F), (0x3164, 0x3164), (0xFE00, 0xFE0F), (0xFEFF, 0xFEFF), (0xFFA0, 0xFFA0), (0xFFF0, 0xFFF8), (0x1BCA0, 0x1BCA3), (0x1D173, 0x1D17A), (0xE0000, 0xE0FFF))
|
||||
IGNORABLE = frozenset(code for start, end in DEFAULT_IGNORABLE for code in range(start, end + 1))
|
||||
EMOJI_TABLE = Path(__file__).with_name("emoji-variation.json")
|
||||
HEX_CODE = re.compile(r"[0-9A-F]{4,6}")
|
||||
PRESENTATION = (chr(0xFE0E), chr(0xFE0F))
|
||||
FREE_TEXT = ("command", "text", "reason", "question", "description")
|
||||
BREAKS = "\t\n"
|
||||
DEPTH_LIMIT = 64
|
||||
WARNINGS = (
|
||||
("deletes recursively", re.compile(r"\brm\s+(?:-\S+\s+)*-\S*[rR]")),
|
||||
("forces", re.compile(r"--force\b|\bpush\b.*\s-f\b")),
|
||||
@@ -284,6 +308,283 @@ def rule_payload(rule_id: str, kinds: list[str], tool: str, pattern: str, scope:
|
||||
return {"v": VERSION, "kind": "rule", "id": rule_id, "kinds": kinds, "tool": tool, "pattern": pattern, "scope": scope, "expires": expires}
|
||||
|
||||
|
||||
def targeted(rule: dict, agents: list[str]) -> dict:
|
||||
"""Args:
|
||||
rule: a rule_payload().
|
||||
agents: [ALL_AGENTS], or the sorted session ids of one agent or of a
|
||||
named group, resolved when the operator signs.
|
||||
|
||||
Returns:
|
||||
The rule payload limited to those agents.
|
||||
"""
|
||||
return {**rule, TARGET: agents}
|
||||
|
||||
|
||||
def enable_item(rule: dict) -> dict:
|
||||
"""Args:
|
||||
rule: the signed payload of a stored rule.
|
||||
|
||||
Returns:
|
||||
The item a fresh approval lists to turn exactly that rule on again.
|
||||
"""
|
||||
return {"kind": "enable", "rule": rule}
|
||||
|
||||
|
||||
def agents_problem(agents: object) -> str | None:
|
||||
"""Returns:
|
||||
Why agents is neither [ALL_AGENTS] nor 1 to AGENT_LIMIT sorted,
|
||||
distinct session ids, or None.
|
||||
"""
|
||||
if agents == [ALL_AGENTS]:
|
||||
return None
|
||||
if not isinstance(agents, list) or not 1 <= len(agents) <= AGENT_LIMIT or not all(isinstance(agent, str) and SESSION.fullmatch(agent) for agent in agents):
|
||||
return f'agents must be ["{ALL_AGENTS}"] or 1 to {AGENT_LIMIT} session ids'
|
||||
return None if agents == sorted(set(agents)) else "agents must be sorted and distinct"
|
||||
|
||||
|
||||
def checked_target(rule: dict) -> None:
|
||||
"""Raises:
|
||||
Refused when the rule carries agents that agents_problem() refuses.
|
||||
"""
|
||||
problem = agents_problem(rule[TARGET]) if TARGET in rule else None
|
||||
if problem:
|
||||
raise Refused(f"the rule names no target: {problem}")
|
||||
|
||||
|
||||
def item_sessions(item: dict) -> set[str]:
|
||||
"""Returns:
|
||||
The session an ask comes from; empty for every other item, which
|
||||
names none.
|
||||
"""
|
||||
return {item["session"]} if item["kind"] == "ask" else set()
|
||||
|
||||
|
||||
def reaches(rule: dict, sessions: set[str]) -> bool:
|
||||
"""Args:
|
||||
rule: a checked rule payload.
|
||||
sessions: the sessions the item comes from; empty when the item names
|
||||
none, which only a rule for every agent reaches.
|
||||
|
||||
Returns:
|
||||
True when the rule carries no agents or [ALL_AGENTS], or names one of
|
||||
the sessions.
|
||||
"""
|
||||
return TARGET not in rule or rule[TARGET] == [ALL_AGENTS] or bool(sessions & set(rule[TARGET]))
|
||||
|
||||
|
||||
def settings_item(file: str, base: str, changes: list[dict]) -> dict:
|
||||
return {"kind": "settings", "file": file, "base": base, "changes": changes}
|
||||
|
||||
|
||||
def unseen(char: str) -> bool:
|
||||
"""Returns:
|
||||
True for a character no prompt shows as itself: a category of UNSEEN,
|
||||
a space separator other than the space, or a code point of
|
||||
DEFAULT_IGNORABLE; page-reveal.js marks the same set.
|
||||
"""
|
||||
category = unicodedata.category(char)
|
||||
return category in UNSEEN or (category == "Zs" and char != " ") or ord(char) in IGNORABLE
|
||||
|
||||
|
||||
def emoji_base(code: int) -> bool:
|
||||
return 0x7F < code <= 0x10FFFF and not 0xD800 <= code <= 0xDFFF and not unseen(chr(code))
|
||||
|
||||
|
||||
def variation_table(path: Path) -> frozenset[int]:
|
||||
"""Args:
|
||||
path: the emoji variation table, a JSON object whose bases list the
|
||||
hex code points of emoji-variation-sequences.txt.
|
||||
|
||||
Returns:
|
||||
The bases as code points.
|
||||
|
||||
Raises:
|
||||
ValueError when bases is no list of hex strings, or names an ASCII
|
||||
code point, a surrogate or one unseen() names; like a missing file,
|
||||
this stops the module from loading, so no selector is ever accepted
|
||||
after an unchecked base.
|
||||
"""
|
||||
bases = json.loads(path.read_text(encoding="utf-8"))["bases"]
|
||||
if not isinstance(bases, list) or not all(isinstance(code, str) and HEX_CODE.fullmatch(code) for code in bases):
|
||||
raise ValueError(f"{path}: bases must be a list of hex code points")
|
||||
codes = frozenset(int(code, 16) for code in bases)
|
||||
wrong = sorted(code for code in codes if not emoji_base(code))
|
||||
if wrong:
|
||||
raise ValueError(f"{path}: U+{wrong[0]:04X} is no visible non-ASCII emoji base")
|
||||
return codes
|
||||
|
||||
|
||||
EMOJI_BASES = variation_table(EMOJI_TABLE)
|
||||
|
||||
|
||||
def presented(text: str, index: int) -> bool:
|
||||
"""Returns:
|
||||
True when text[index] is a variation selector of PRESENTATION right
|
||||
after a code point of EMOJI_BASES, a standardized emoji variation
|
||||
sequence such as the stopwatch of the score block that every prompt
|
||||
draws as the symbol itself; page-reveal.js skips the same pairs.
|
||||
"""
|
||||
return text[index] in PRESENTATION and index > 0 and ord(text[index - 1]) in EMOJI_BASES
|
||||
|
||||
|
||||
def hidden_char(text: str, name: str) -> str | None:
|
||||
"""Returns:
|
||||
The first character of text that unseen() names, a tab or a line
|
||||
break only outside the FREE_TEXT fields, and no presented() selector;
|
||||
None when there is none.
|
||||
"""
|
||||
allowed = BREAKS if name in FREE_TEXT else ""
|
||||
return next((char for index, char in enumerate(text) if unseen(char) and char not in allowed and not presented(text, index)), None)
|
||||
|
||||
|
||||
def removal(value: dict) -> bool:
|
||||
return set(value) == set(CHANGE_KEYS) and value["op"] == "remove" and value["list"] in SETTINGS_LISTS
|
||||
|
||||
|
||||
def hidden_problem(value: object, name: str) -> str | None:
|
||||
"""Args:
|
||||
value: a text, or an object or list of them, that reaches a signed
|
||||
payload or the approval prompt; an object's texts are named by
|
||||
their keys. Only the entry of a settings change of op remove is
|
||||
exempt: removing an allow entry narrows access, but removing a
|
||||
deny, ask or denyRead entry widens it, and that is safe only
|
||||
because the writer removes exactly the signed text and the page
|
||||
marks every character unseen() names.
|
||||
name: the field a text sits in.
|
||||
|
||||
Returns:
|
||||
Why the first text holding a character unseen() names (a bidi
|
||||
control, a zero-width character, a carriage return, a no-break space,
|
||||
a Hangul filler) is refused, since the prompt would show other text
|
||||
than what is signed; None when no text holds one.
|
||||
"""
|
||||
if isinstance(value, dict):
|
||||
named = {key: child for key, child in value.items() if not (key == "entry" and removal(value))}
|
||||
return next(filter(None, (hidden_problem(child, str(key)) for key, child in named.items())), None)
|
||||
if isinstance(value, list):
|
||||
return next(filter(None, (hidden_problem(child, name) for child in value)), None)
|
||||
hidden = hidden_char(value, name) if isinstance(value, str) else None
|
||||
return None if hidden is None else f"{name} must hold no invisible, format, control or look-alike character such as U+{ord(hidden):04X}, which shows other text than what is signed"
|
||||
|
||||
|
||||
def settings_file_problem(file: object) -> str | None:
|
||||
if not isinstance(file, str) or not SETTINGS_PATH.fullmatch(file) or not file.endswith(SETTINGS_FILE):
|
||||
return f"file must be the absolute path of a {SETTINGS_FILE.lstrip('/')}"
|
||||
if any(part in f"{file}/" for part in ("/../", "/./", "//")):
|
||||
return "file must name no . or .. and no empty part"
|
||||
return hidden_problem(file, "file")
|
||||
|
||||
|
||||
def change_problem(change: object) -> str | None:
|
||||
if not isinstance(change, dict) or set(change) != set(CHANGE_KEYS) or not all(isinstance(change[name], str) for name in CHANGE_KEYS):
|
||||
return "a change holds exactly list, op and entry as text"
|
||||
if change["list"] not in SETTINGS_LISTS or change["op"] not in SETTINGS_OPS:
|
||||
return f"list must be one of {', '.join(SETTINGS_LISTS)} and op one of {', '.join(SETTINGS_OPS)}"
|
||||
return hidden_problem(change, "change") if ENTRY.fullmatch(change["entry"]) else "entry must be one line of 1 to 500 characters"
|
||||
|
||||
|
||||
def settings_problem(item: object) -> str | None:
|
||||
"""Args:
|
||||
item: {"file", "base", "changes"}: file the absolute path of a
|
||||
.claude/settings.json, base the sha256 of its bytes or "" while it
|
||||
is missing, changes 1 to CHANGE_LIMIT {"list", "op", "entry"},
|
||||
each list and entry once.
|
||||
|
||||
Returns:
|
||||
Why the item is malformed, or None; the hub and the writer check it
|
||||
the same way.
|
||||
"""
|
||||
if not isinstance(item, dict) or set(item) != set(SETTINGS_KEYS):
|
||||
return "a settings change holds exactly file, base and changes"
|
||||
if not isinstance(item["base"], str) or not (item["base"] == "" or HASH.fullmatch(item["base"])):
|
||||
return "base must be the sha256 of the file, or empty for a missing file"
|
||||
return settings_file_problem(item["file"]) or changes_problem(item["changes"])
|
||||
|
||||
|
||||
def changes_problem(changes: object) -> str | None:
|
||||
if not isinstance(changes, list) or not 1 <= len(changes) <= CHANGE_LIMIT:
|
||||
return f"changes must list 1 to {CHANGE_LIMIT} changes"
|
||||
problem = next(filter(None, map(change_problem, changes)), None)
|
||||
if problem:
|
||||
return problem
|
||||
pairs = {(change["list"], change["entry"]) for change in changes}
|
||||
return None if len(pairs) == len(changes) else "each list and entry is changed once"
|
||||
|
||||
|
||||
def settings_view(settings: dict) -> dict:
|
||||
"""Returns:
|
||||
The permissions and sandbox sections of a settings object, the only
|
||||
part of the file the Agent Orchestrator receives.
|
||||
"""
|
||||
return {name: settings[name] for name in SETTINGS_SECTIONS if isinstance(settings.get(name), dict)}
|
||||
|
||||
|
||||
def plain_problem(value: object, depth: int) -> str | None:
|
||||
"""Args:
|
||||
value: a parsed JSON value.
|
||||
depth: how many objects and lists hold it.
|
||||
|
||||
Returns:
|
||||
Why value is unsafe to copy or write, a lone surrogate in any text or
|
||||
more than DEPTH_LIMIT levels, or None.
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
return "the file holds a lone surrogate" if SURROGATE.search(value) else None
|
||||
if not isinstance(value, (dict, list)):
|
||||
return None
|
||||
if depth >= DEPTH_LIMIT:
|
||||
return f"the file nests deeper than {DEPTH_LIMIT} levels"
|
||||
children = [*value, *value.values()] if isinstance(value, dict) else value
|
||||
return next(filter(None, (plain_problem(child, depth + 1) for child in children)), None)
|
||||
|
||||
|
||||
def plain_copy(settings: dict) -> dict:
|
||||
"""Raises:
|
||||
Refused for settings plain_problem() refuses, before deepcopy could
|
||||
recurse into them.
|
||||
"""
|
||||
problem = plain_problem(settings, 0)
|
||||
if problem:
|
||||
raise Refused(problem)
|
||||
return copy.deepcopy(settings)
|
||||
|
||||
|
||||
def apply_changes(settings: dict, changes: list[dict]) -> dict:
|
||||
"""Args:
|
||||
settings: the parsed settings object.
|
||||
changes: changes settings_problem() accepts.
|
||||
|
||||
Returns:
|
||||
A copy of settings with each change applied in order and every other
|
||||
key kept.
|
||||
|
||||
Raises:
|
||||
Refused when settings nest deeper than DEPTH_LIMIT or hold a lone
|
||||
surrogate, an object on a list's path is no object, a list holds
|
||||
anything but text, an added entry is listed already or a removed one
|
||||
is not.
|
||||
"""
|
||||
result = plain_copy(settings)
|
||||
for change in changes:
|
||||
*path, leaf = change["list"].split(".")
|
||||
node = result
|
||||
for name in path:
|
||||
node = node.setdefault(name, {})
|
||||
if not isinstance(node, dict):
|
||||
raise Refused(f"{name} is no object")
|
||||
entries = node.setdefault(leaf, [])
|
||||
if not isinstance(entries, list) or not all(isinstance(entry, str) for entry in entries):
|
||||
raise Refused(f"{change['list']} is no list of texts")
|
||||
listed = change["entry"] in entries
|
||||
if listed == (change["op"] == "add"):
|
||||
raise Refused(f"{change['list']} {'lists' if listed else 'does not list'} {change['entry']}")
|
||||
if listed:
|
||||
entries.remove(change["entry"])
|
||||
else:
|
||||
entries.append(change["entry"])
|
||||
return result
|
||||
|
||||
|
||||
def warnings(command: str) -> list[str]:
|
||||
return [label for label, pattern in WARNINGS if pattern.search(command)]
|
||||
|
||||
@@ -311,8 +612,9 @@ def checked_approval(payload: object, now: float) -> dict:
|
||||
|
||||
|
||||
def checked_rule(payload: object, now: float) -> dict:
|
||||
if not isinstance(payload, dict) or set(payload) != RULE_KEYS or payload["v"] != VERSION or payload["kind"] != "rule":
|
||||
if not isinstance(payload, dict) or set(payload) - {TARGET} != RULE_KEYS or payload["v"] != VERSION or payload["kind"] != "rule":
|
||||
raise Refused("the payload is no rule")
|
||||
checked_target(payload)
|
||||
if not isinstance(payload["id"], str) or not ID.fullmatch(payload["id"]):
|
||||
raise Refused("the rule holds no id")
|
||||
kinds = payload["kinds"]
|
||||
@@ -325,6 +627,10 @@ def checked_rule(payload: object, now: float) -> dict:
|
||||
|
||||
|
||||
def rule_allows(rule: dict, item: dict, gate: str, now: float) -> bool:
|
||||
return reaches(rule, item_sessions(item)) and pattern_allows(rule, item, gate, now)
|
||||
|
||||
|
||||
def pattern_allows(rule: dict, item: dict, gate: str, now: float) -> bool:
|
||||
if rule["expires"] <= now or item["kind"] not in rule["kinds"]:
|
||||
return False
|
||||
if item["kind"] == "ask":
|
||||
|
||||
@@ -8,12 +8,13 @@ from .choosing import answer_signed
|
||||
from .cleanup import cleanup_request
|
||||
from .denying import DENIABLE, DENY_KEYS, denial_note, request_status, request_words
|
||||
from .errors import Conflict, Missing, ToolError
|
||||
from .fields import decode, expect, field
|
||||
from .fields import decode, expect, field, visible
|
||||
from .firewall import settings_request
|
||||
from .gating import gate_request
|
||||
from .offices import office_request
|
||||
from .records import digest, shown
|
||||
from .register import REGISTER, adder, operator_rows, read_register, runnable
|
||||
from .rules import rule_matches, subject_of
|
||||
from .rules import enable_request, rule_matches, subject_of
|
||||
from .signed import (
|
||||
ask_signed,
|
||||
operator_signed,
|
||||
@@ -63,7 +64,12 @@ class Approving:
|
||||
"""Returns:
|
||||
The approval payload over the items, its WebAuthn challenge and the
|
||||
pinned credential ids; payload and challenge are None for no item.
|
||||
|
||||
Raises:
|
||||
ToolError from visible() for an item holding a text no prompt
|
||||
shows as signed, whatever source missed it.
|
||||
"""
|
||||
visible(items)
|
||||
credentials = [key["id"] for key in self.keys()]
|
||||
if not items:
|
||||
return {"payload": None, "challenge": None, "credentials": credentials}
|
||||
@@ -131,7 +137,7 @@ class Approving:
|
||||
|
||||
def automate(self, kind_name: str, record: dict) -> None:
|
||||
now = time.time()
|
||||
subject = subject_of(kind_name, record)
|
||||
subject = subject_of(kind_name, record, self.deciders(kind_name, record))
|
||||
rule = next((rule for rule in self.rules.listed() if rule_matches(rule, kind_name, subject, now)), None)
|
||||
if rule is None:
|
||||
return
|
||||
@@ -189,6 +195,27 @@ class Approving:
|
||||
raise Conflict({"id": raw["id"], "status": "recipient changed", "to": name})
|
||||
return name
|
||||
|
||||
def operator_entry(self, raw: dict, tasks: dict[str, dict]) -> dict:
|
||||
"""Args:
|
||||
raw: a checked inbox entry of kind operator.
|
||||
tasks: the register.
|
||||
|
||||
Returns:
|
||||
The signed item of the operator row raw names, once its task,
|
||||
command and directory pass visible().
|
||||
"""
|
||||
row = next((row for row in operator_rows(tasks) if row["task"] == raw["id"]), None)
|
||||
if row is None:
|
||||
raise Missing(str(raw["id"]))
|
||||
visible({name: row[name] for name in ("task", "command", "directory")})
|
||||
if raw["verb"] == "approve" and not runnable(row):
|
||||
raise ToolError("an operator row is approved only when it holds a directory and a command")
|
||||
if digest(row["command"]) != raw["sha256"]:
|
||||
raise Conflict({"id": row["task"], "status": "changed"})
|
||||
if row["task"] in self.open_jobs():
|
||||
raise Conflict({"id": row["task"], "status": "queued"})
|
||||
return inbox_item(raw, "", row["command"], "", operator_signed(row), self.requester(raw, adder(tasks[row["task"]])))
|
||||
|
||||
def item_of(self, raw: object, tasks: dict[str, dict]) -> dict:
|
||||
if not isinstance(raw, dict):
|
||||
raise ToolError("every item must be an object with kind, id, verb, label and sha256, and a denial also channel, reason and to")
|
||||
@@ -197,16 +224,7 @@ class Approving:
|
||||
if kind_name not in INBOX_KINDS or verb not in VERBS or not isinstance(raw["label"], str) or not isinstance(raw["sha256"], str):
|
||||
raise ToolError(f"kind must be one of {', '.join(INBOX_KINDS)}, verb approve or reject, label and sha256 text")
|
||||
if kind_name == "operator":
|
||||
row = next((row for row in operator_rows(tasks) if row["task"] == raw["id"]), None)
|
||||
if row is None:
|
||||
raise Missing(str(raw["id"]))
|
||||
if verb == "approve" and not runnable(row):
|
||||
raise ToolError("an operator row is approved only when it holds a directory and a command")
|
||||
if digest(row["command"]) != raw["sha256"]:
|
||||
raise Conflict({"id": row["task"], "status": "changed"})
|
||||
if row["task"] in self.open_jobs():
|
||||
raise Conflict({"id": row["task"], "status": "queued"})
|
||||
return inbox_item(raw, "", row["command"], "", operator_signed(row), self.requester(raw, adder(tasks[row["task"]])))
|
||||
return self.operator_entry(raw, tasks)
|
||||
if kind_name == "rule" and verb == "approve":
|
||||
raise ToolError("a rule request is accepted in its row, with the passkey signature over the rule itself")
|
||||
item_id = field(raw, "id")
|
||||
@@ -253,6 +271,11 @@ class Approving:
|
||||
signed = self.task_changes(raw)
|
||||
elif gate_request(raw):
|
||||
signed = self.gate_changes(raw)
|
||||
elif settings_request(raw):
|
||||
signed = self.settings_changes(raw)
|
||||
elif enable_request(raw):
|
||||
signed = self.enable_items(raw)
|
||||
return {**self.challenge_for(signed), "enables": signed[0]["rule"]}
|
||||
else:
|
||||
signed = [item["signed"] for item in self.checked(raw) if item["signed"] is not None]
|
||||
return self.challenge_for(signed)
|
||||
|
||||
@@ -16,6 +16,7 @@ from .fields import (
|
||||
instant,
|
||||
message_text,
|
||||
seconds,
|
||||
visible,
|
||||
)
|
||||
from .signed import ask_signed
|
||||
|
||||
@@ -55,7 +56,9 @@ def option_of(option: object) -> dict:
|
||||
raise ToolError("every option must be an object with label and description")
|
||||
expect(option, ("label", "description"))
|
||||
label = field(option, "label").strip()
|
||||
return {"label": label, "description": bounded(option, "description", DESCRIPTION_LIMIT).strip()}
|
||||
description = bounded(option, "description", DESCRIPTION_LIMIT).strip()
|
||||
visible({"description": description})
|
||||
return {"label": label, "description": description}
|
||||
|
||||
|
||||
class Asking:
|
||||
@@ -64,6 +67,7 @@ class Asking:
|
||||
diff = valid_diff(payload.pop("diff")) if "diff" in payload else None
|
||||
expect(payload, ("tool", *ASK_TEXTS, "timeout"))
|
||||
values = {name: bounded(payload, name, limit) for name, limit in ASK_TEXTS.items()}
|
||||
visible(values)
|
||||
lifetime = seconds(payload, "timeout", ASK_LIFETIME)
|
||||
created = time.time()
|
||||
fields = {**values, "tool": field(payload, "tool").strip(), "status": "pending", "decided": None, "proof": None, "diff_files": None if diff is None else len(diff)}
|
||||
@@ -104,6 +108,7 @@ class Asking:
|
||||
def decision_request(self, arguments: dict) -> dict:
|
||||
expect(arguments, ("question", "options", "agent", "recommended"))
|
||||
question = message_text(arguments, "question")
|
||||
visible({"question": question})
|
||||
options = arguments["options"]
|
||||
if not isinstance(options, list) or not 1 <= len(options) <= OPTION_LIMIT:
|
||||
raise ToolError(f"options must be a list of 1 to {OPTION_LIMIT} objects")
|
||||
|
||||
@@ -5,7 +5,7 @@ import math
|
||||
import re
|
||||
|
||||
from .errors import ToolError
|
||||
from .signed import limits
|
||||
from .signed import limits, signing
|
||||
|
||||
WAIT_CAP = 300
|
||||
TEXT_LIMIT = 20_000
|
||||
@@ -43,9 +43,25 @@ def field(arguments: dict, name: str) -> str:
|
||||
value = arguments[name]
|
||||
if not isinstance(value, str) or not pattern.fullmatch(value):
|
||||
raise ToolError(f"{name} must be {hint}")
|
||||
visible({name: value})
|
||||
return value
|
||||
|
||||
|
||||
def visible(value: object) -> None:
|
||||
"""Args:
|
||||
value: an object of named texts, or a list of them, that reaches a
|
||||
signed payload or the approval prompt.
|
||||
|
||||
Raises:
|
||||
ToolError with the reason signing.hidden_problem() gives for the
|
||||
first text holding an invisible, format, control or look-alike
|
||||
character.
|
||||
"""
|
||||
hidden = signing.hidden_problem(value, "value")
|
||||
if hidden:
|
||||
raise ToolError(hidden)
|
||||
|
||||
|
||||
def bounded(arguments: dict, name: str, limit: int) -> str:
|
||||
value = arguments[name]
|
||||
if not isinstance(value, str) or len(value) > limit:
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from .errors import Conflict, Missing, ToolError
|
||||
from .fields import decode, expect, visible
|
||||
from .ledger import Ledger
|
||||
from .records import read_json, stamp
|
||||
from .rules import EVERY_AGENT, RULE_KINDS
|
||||
from .signed import signing
|
||||
|
||||
VIEW = "view.json"
|
||||
JOB_VERSION = 1
|
||||
ITEM_LIMIT = 10
|
||||
SET_LIMIT = 50
|
||||
DAY_LIMIT = 366
|
||||
NAME = re.compile(r"(?=[^\x00-\x1f\x7f]*\S)[^\x00-\x1f\x7f]{1,80}")
|
||||
RULE_TEXT = re.compile(r"(?P<tool>[^()]+?)(?:\((?P<spec>.*)\))?", re.DOTALL)
|
||||
WORD = re.compile(r"[\s:]")
|
||||
HASH = re.compile(r"[0-9a-f]{64}")
|
||||
PERMISSION_LISTS = ("allow", "ask", "deny")
|
||||
SET_KEYS = ("kind", "tool", "pattern", "scope")
|
||||
CHAINED = "chains, pipes, redirects or substitutions"
|
||||
|
||||
|
||||
def settings_request(raw: object) -> bool:
|
||||
return isinstance(raw, list) and bool(raw) and all(isinstance(entry, dict) and entry.get("kind") == "settings" for entry in raw)
|
||||
|
||||
|
||||
def tool_and_prefix(entry: str) -> tuple[str, str]:
|
||||
"""Returns:
|
||||
The tool of a permission rule such as Bash(git push:*) and the first
|
||||
word of its specifier, for Bash the command; "" without specifier.
|
||||
"""
|
||||
found = RULE_TEXT.fullmatch(entry)
|
||||
if found is None:
|
||||
return entry.strip(), ""
|
||||
return found.group("tool").strip(), WORD.split((found.group("spec") or "").strip(), maxsplit=1)[0]
|
||||
|
||||
|
||||
def grouped(permissions: object) -> list[dict]:
|
||||
"""Returns:
|
||||
The allow, ask and deny entries of a permissions section grouped by
|
||||
tool and prefix, sorted: [{"tool", "prefix", "entries": [{"list",
|
||||
"entry"}]}].
|
||||
"""
|
||||
groups: dict[tuple[str, str], list[dict]] = {}
|
||||
lists = permissions if isinstance(permissions, dict) else {}
|
||||
for name in PERMISSION_LISTS:
|
||||
values = lists.get(name)
|
||||
for entry in values if isinstance(values, list) else []:
|
||||
if isinstance(entry, str):
|
||||
groups.setdefault(tool_and_prefix(entry), []).append({"list": name, "entry": entry})
|
||||
return [{"tool": tool, "prefix": prefix, "entries": entries} for (tool, prefix), entries in sorted(groups.items())]
|
||||
|
||||
|
||||
def sandbox_entries(section: object, path: str) -> list[dict]:
|
||||
"""Returns:
|
||||
Every leaf of a sandbox section under the dotted path, a list as
|
||||
{"key", "values"} and any other value as {"key", "value"}.
|
||||
"""
|
||||
found: list[dict] = []
|
||||
for name, value in section.items() if isinstance(section, dict) else ():
|
||||
key = f"{path}.{name}"
|
||||
if isinstance(value, dict):
|
||||
found += sandbox_entries(value, key)
|
||||
elif isinstance(value, list):
|
||||
found.append({"key": key, "values": [entry if isinstance(entry, str) else json.dumps(entry) for entry in value]})
|
||||
else:
|
||||
found.append({"key": key, "value": value})
|
||||
return found
|
||||
|
||||
|
||||
def shaped_file(entry: object) -> bool:
|
||||
if not isinstance(entry, dict) or not isinstance(entry.get("path"), str) or not isinstance(entry.get("exists"), bool):
|
||||
return False
|
||||
return isinstance(entry.get("settings"), dict) and isinstance(entry.get("sha256"), str) and (entry["sha256"] == "" or bool(HASH.fullmatch(entry["sha256"])))
|
||||
|
||||
|
||||
def section_diff(path: str, before: dict, after: dict) -> str:
|
||||
"""Returns:
|
||||
The unified diff of the permissions and sandbox sections before and
|
||||
after the change, as the host writer applies it.
|
||||
"""
|
||||
lines = difflib.unified_diff(json.dumps(before, indent=2).splitlines(), json.dumps(after, indent=2).splitlines(), fromfile=path, tofile=path, lineterm="", n=3)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def unique_name(payload: dict, ledger: Ledger) -> str:
|
||||
name = payload["name"]
|
||||
if not isinstance(name, str) or not NAME.fullmatch(name):
|
||||
raise ToolError("name must be one line of 1 to 80 characters")
|
||||
visible({"name": name})
|
||||
if any(record["name"] == name for record in ledger.listed()):
|
||||
raise Conflict({"name": name, "status": "exists"})
|
||||
return name
|
||||
|
||||
|
||||
def dropped(ledger: Ledger, record_id: str) -> dict:
|
||||
if not ledger.remove(record_id):
|
||||
raise Missing(record_id)
|
||||
return {"id": record_id, "deleted": True}
|
||||
|
||||
|
||||
def deny_patterns() -> list[dict]:
|
||||
"""Returns:
|
||||
The commands no ask rule ever grants, as {"label", "pattern"}.
|
||||
"""
|
||||
return [*({"label": label, "pattern": pattern.pattern} for label, pattern in signing.WARNINGS), {"label": CHAINED, "pattern": signing.CHAINED.pattern}]
|
||||
|
||||
|
||||
class Firewall:
|
||||
def settings_files(self) -> tuple[list[dict], dict]:
|
||||
"""Returns:
|
||||
The listed settings files the host writer last read, each
|
||||
{"path", "exists", "sha256", "error", "settings"} with settings
|
||||
only their permissions and sandbox sections, and the view's
|
||||
written time and error.
|
||||
"""
|
||||
view = read_json(self.firewall_spool.root / VIEW)
|
||||
files = view.get("files") if isinstance(view, dict) else None
|
||||
if not isinstance(files, list):
|
||||
return [], {"written": None, "error": "no settings view yet: the kvb-orchestrator-firewall unit writes it on the host"}
|
||||
shown = [{**entry, "settings": signing.settings_view(entry["settings"]), "error": str(entry.get("error") or "")} for entry in files if shaped_file(entry)]
|
||||
return shown, {"written": view.get("written"), "error": ""}
|
||||
|
||||
def firewall(self) -> dict:
|
||||
files, meta = self.settings_files()
|
||||
listed = [{key: entry[key] for key in ("path", "exists", "sha256", "error")} | {"groups": grouped(entry["settings"].get("permissions")), "sandbox": sandbox_entries(entry["settings"].get("sandbox"), "sandbox")} for entry in files]
|
||||
return {**meta, "files": listed, "lists": list(signing.SETTINGS_LISTS), "patterns": deny_patterns(), "groups": self.groups.listed(), "sets": self.rule_sets.listed()}
|
||||
|
||||
def settings_changes(self, raw: object) -> list[dict]:
|
||||
"""Args:
|
||||
raw: the page's items, each {"kind": "settings", "file", "base",
|
||||
"changes"} for one listed file at the sha256 the view shows.
|
||||
|
||||
Returns:
|
||||
The signed items, each one file whose changes apply to the
|
||||
sections the view shows.
|
||||
"""
|
||||
if not isinstance(raw, list) or not 1 <= len(raw) <= ITEM_LIMIT:
|
||||
raise ToolError(f"items must be a list of 1 to {ITEM_LIMIT} settings changes")
|
||||
files = {entry["path"]: entry for entry in self.settings_files()[0]}
|
||||
signed: list[dict] = []
|
||||
for entry in raw:
|
||||
if not isinstance(entry, dict):
|
||||
raise ToolError("every item must be an object with kind, file, base and changes")
|
||||
expect(entry, ("kind", *signing.SETTINGS_KEYS))
|
||||
order = {name: entry[name] for name in signing.SETTINGS_KEYS}
|
||||
problem = signing.settings_problem(order)
|
||||
if problem:
|
||||
raise ToolError(problem)
|
||||
self.applicable(files, order)
|
||||
if any(item["file"] == order["file"] for item in signed):
|
||||
raise ToolError("one item per file: list every change of a file in its changes")
|
||||
signed.append(signing.settings_item(**order))
|
||||
return signed
|
||||
|
||||
def applicable(self, files: dict[str, dict], order: dict) -> dict:
|
||||
shown = files.get(order["file"])
|
||||
if shown is None:
|
||||
raise ToolError(f"{order['file'][:300]} is no settings file the Firewall lists")
|
||||
if shown["sha256"] != order["base"]:
|
||||
raise Conflict({"file": order["file"], "status": "changed", "sha256": shown["sha256"]})
|
||||
try:
|
||||
return signing.apply_changes(shown["settings"], order["changes"])
|
||||
except signing.Refused as error:
|
||||
raise ToolError(str(error)) from None
|
||||
|
||||
def settings_preview(self, body: bytes) -> dict:
|
||||
payload = decode(body)
|
||||
expect(payload, ("items",))
|
||||
items = self.settings_changes(payload["items"])
|
||||
files = {entry["path"]: entry for entry in self.settings_files()[0]}
|
||||
return {"diffs": [{"file": item["file"], "diff": section_diff(item["file"], files[item["file"]]["settings"], self.applicable(files, item))} for item in items]}
|
||||
|
||||
def change_settings(self, body: bytes) -> dict:
|
||||
payload = decode(body)
|
||||
expect(payload, ("items", "proof"))
|
||||
items = self.settings_changes(payload["items"])
|
||||
proof = self.covered(payload["proof"], items, time.time())
|
||||
for item in items:
|
||||
self.operator_proven(proof, item)
|
||||
job_id = secrets.token_hex(8)
|
||||
job = {"v": JOB_VERSION, "id": job_id, "created": stamp(), "items": [{name: item[name] for name in signing.SETTINGS_KEYS} for item in items], "proof": proof}
|
||||
self.firewall_spool.put(job_id, job)
|
||||
lines = [f"{item['file']}: {change['op']} {change['list']} {change['entry']}" for item in items for change in item["changes"]]
|
||||
self.log.add({"kind": "run", "title": f"Settings change signed: {len(lines)}"[:200], "text": "\n".join(lines), "ref": {"firewall": job_id, "status": "queued"}})
|
||||
return {"id": job_id, "status": "queued", "items": job["items"]}
|
||||
|
||||
def settings_state(self, job_id: str) -> dict:
|
||||
result = read_json(self.firewall_spool.results / f"{job_id}.json")
|
||||
if isinstance(result, dict) and isinstance(result.get("items"), list):
|
||||
return {**result, "id": job_id, "status": "done"}
|
||||
if (self.firewall_spool.jobs / f"{job_id}.json").is_file():
|
||||
return {"id": job_id, "status": "queued", "items": []}
|
||||
raise Missing(job_id)
|
||||
|
||||
def add_group(self, body: bytes) -> dict:
|
||||
"""Args:
|
||||
body: {"name", "members"}: members 1 to signing.AGENT_LIMIT
|
||||
sorted session ids the Agent Orchestrator knows.
|
||||
"""
|
||||
payload = decode(body)
|
||||
expect(payload, ("name", "members"))
|
||||
members = payload["members"]
|
||||
problem = signing.agents_problem(members) if members != EVERY_AGENT else "members must name sessions, not every agent"
|
||||
if problem:
|
||||
raise ToolError(problem)
|
||||
self.known_agents(members)
|
||||
record = self.groups.add({"name": unique_name(payload, self.groups), "members": members})
|
||||
self.log.add({"kind": "rule", "title": f"Agent group {record['name']}: {len(members)} agents", "text": ", ".join(members), "ref": {"group": record["id"]}})
|
||||
return record
|
||||
|
||||
def add_set(self, body: bytes) -> dict:
|
||||
"""Args:
|
||||
body: {"name", "days", "rules"}: the ids of 1 to SET_LIMIT stored
|
||||
rules whose kind, tool, pattern and scope the set keeps, and
|
||||
the lifetime in days each rule gets when the set is taken
|
||||
over and signed for an agent, a group or every agent.
|
||||
"""
|
||||
payload = decode(body)
|
||||
expect(payload, ("name", "days", "rules"))
|
||||
days = payload["days"]
|
||||
if isinstance(days, bool) or not isinstance(days, int) or not 1 <= days <= DAY_LIMIT:
|
||||
raise ToolError(f"days must be a whole number from 1 to {DAY_LIMIT}")
|
||||
chosen = self.stored_rules(payload["rules"])
|
||||
record = self.rule_sets.add({"name": unique_name(payload, self.rule_sets), "days": days, "rules": [{key: rule[key] for key in SET_KEYS} for rule in chosen]})
|
||||
self.log.add({"kind": "rule", "title": f"Rule set {record['name']}: {len(chosen)} rules", "text": "\n".join(f"{rule['kind']} {rule['tool']} {rule['pattern']}".replace(" ", " ") for rule in chosen), "ref": {"set": record["id"]}})
|
||||
return record
|
||||
|
||||
def stored_rules(self, ids: object) -> list[dict]:
|
||||
if not isinstance(ids, list) or not 1 <= len(ids) <= SET_LIMIT or len(set(map(str, ids))) != len(ids):
|
||||
raise ToolError(f"rules must list 1 to {SET_LIMIT} distinct rule ids")
|
||||
chosen = [self.rules.get(rule_id) if isinstance(rule_id, str) else None for rule_id in ids]
|
||||
if None in chosen or any(rule["kind"] not in RULE_KINDS for rule in chosen):
|
||||
raise ToolError("rules must name stored rules")
|
||||
return chosen
|
||||
|
||||
def drop_group(self, group_id: str) -> dict:
|
||||
return dropped(self.groups, group_id)
|
||||
|
||||
def drop_set(self, set_id: str) -> dict:
|
||||
return dropped(self.rule_sets, set_id)
|
||||
@@ -64,8 +64,13 @@ SETTINGS_SIGN_ROUTE = "/api/settings/sign"
|
||||
CHOICES_ROUTE = "/api/choices"
|
||||
CHOICES_SIGN_ROUTE = "/api/choices/sign"
|
||||
DIFF_ROUTE = re.compile(r"/api/diffs/(review|ask)/([0-9a-f]{16})")
|
||||
FIREWALL_ROUTE = "/api/firewall"
|
||||
FIREWALL_POSTS = {"/api/firewall/preview": "settings_preview", "/api/firewall/settings": "change_settings", "/api/firewall/groups": "add_group", "/api/firewall/sets": "add_set"}
|
||||
FIREWALL_STATE = re.compile(r"/api/firewall/settings/([0-9a-f]{16})")
|
||||
FIREWALL_DROP = re.compile(r"/api/firewall/(groups|sets)/([0-9a-f]{16})/delete")
|
||||
FIREWALL_STATUS = {"settings_preview": HTTPStatus.OK, "change_settings": HTTPStatus.ACCEPTED, "add_group": HTTPStatus.CREATED, "add_set": HTTPStatus.CREATED}
|
||||
WAV_POSTS = (STT_ROUTE, VOICE_ROUTE)
|
||||
ACTION_POSTS = ("/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE)
|
||||
ACTION_POSTS = ("/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
|
||||
|
||||
|
||||
class Handler(Exchange):
|
||||
@@ -93,10 +98,13 @@ class Handler(Exchange):
|
||||
office = OFFICE_STATE.fullmatch(path)
|
||||
voice = VOICE_ITEM.fullmatch(path)
|
||||
diff = DIFF_ROUTE.fullmatch(path)
|
||||
firewall = self.firewall_reader(path)
|
||||
if self.host() is None:
|
||||
self.send_text(HTTPStatus.FORBIDDEN, "forbidden host")
|
||||
elif path == "/":
|
||||
self.index()
|
||||
elif firewall:
|
||||
self.answer(firewall, HTTPStatus.OK)
|
||||
elif diff:
|
||||
self.answer(lambda: hub.diff_of(diff.group(1), diff.group(2)), HTTPStatus.OK)
|
||||
elif vendored and vendored.group(1) in VENDOR:
|
||||
@@ -197,7 +205,7 @@ class Handler(Exchange):
|
||||
if path == "/api/rules":
|
||||
return lambda body: self.answer(lambda: hub.add_rule(body), HTTPStatus.CREATED)
|
||||
if rule:
|
||||
return lambda _body: self.answer(lambda: hub.rule_action(rule.group(1), rule.group(2)), HTTPStatus.OK)
|
||||
return lambda body: self.answer(lambda: hub.rule_action(rule.group(1), rule.group(2), body), HTTPStatus.OK)
|
||||
if path == "/api/nl":
|
||||
return lambda body: self.answer(lambda: hub.nl(body), HTTPStatus.OK)
|
||||
if path == SETTINGS_ROUTE:
|
||||
@@ -216,10 +224,28 @@ class Handler(Exchange):
|
||||
return lambda body: self.answer(lambda: hub.sign_choices(body), HTTPStatus.OK)
|
||||
if path == CHOICES_ROUTE:
|
||||
return lambda body: self.answer(lambda: hub.request_choices(body), HTTPStatus.CREATED)
|
||||
return self.firewall_action(path)
|
||||
|
||||
def firewall_reader(self, path: str) -> Callable[[], dict] | None:
|
||||
hub = self.server.hub
|
||||
job = FIREWALL_STATE.fullmatch(path)
|
||||
if path == FIREWALL_ROUTE:
|
||||
return hub.firewall
|
||||
return (lambda: hub.settings_state(job.group(1))) if job else None
|
||||
|
||||
def firewall_action(self, path: str) -> Callable[[bytes], None] | None:
|
||||
hub = self.server.hub
|
||||
drop = FIREWALL_DROP.fullmatch(path)
|
||||
if path in FIREWALL_POSTS:
|
||||
method = getattr(hub, FIREWALL_POSTS[path])
|
||||
return lambda body: self.answer(lambda: method(body), FIREWALL_STATUS[FIREWALL_POSTS[path]])
|
||||
if drop:
|
||||
remove = hub.drop_group if drop.group(1) == "groups" else hub.drop_set
|
||||
return lambda _body: self.answer(lambda: remove(drop.group(2)), HTTPStatus.OK)
|
||||
return None
|
||||
|
||||
def posted(self, path: str) -> bool:
|
||||
return any(pattern.fullmatch(path) for pattern in (INBOX_ROUTE, UNDO_ROUTE, RULE_ROUTE, REQUEST_ROUTE, RUNNER_ROUTE))
|
||||
return any(pattern.fullmatch(path) for pattern in (INBOX_ROUTE, UNDO_ROUTE, RULE_ROUTE, REQUEST_ROUTE, RUNNER_ROUTE, FIREWALL_DROP))
|
||||
|
||||
def runner(self, path: str, body: bytes) -> None:
|
||||
hub = self.server.hub
|
||||
|
||||
@@ -19,6 +19,7 @@ from .crons import History, queue_live
|
||||
from .denying import Denying
|
||||
from .engines import Engines, Speech
|
||||
from .events import Log, Watch
|
||||
from .firewall import Firewall
|
||||
from .gating import Gating
|
||||
from .icons import sheet
|
||||
from .inbox import Inbox
|
||||
@@ -43,7 +44,7 @@ from .redirects import Redirects
|
||||
from .requesting import Requesting
|
||||
from .resources import RESOURCES, SAMPLES
|
||||
from .reviewing import Reviewing
|
||||
from .rules import Rules
|
||||
from .rules import Offers, Rules
|
||||
from .settings import Settings
|
||||
from .signed import signing
|
||||
from .skill_scripts import Runner
|
||||
@@ -81,7 +82,7 @@ def environment(templates: Path) -> jinja2.Environment:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Hub(Mcp, Reviewing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Inbox, Rules, Jobs, Sources, Timeline, View, Language):
|
||||
class Hub(Mcp, Reviewing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Firewall, Inbox, Rules, Jobs, Sources, Timeline, View, Language):
|
||||
council: Path
|
||||
pages: Path
|
||||
public_port: int
|
||||
@@ -96,6 +97,7 @@ class Hub(Mcp, Reviewing, Asking, Messaging, Choosing, Approving, Denying, Reque
|
||||
scripts: Runner
|
||||
templates: jinja2.Environment
|
||||
rules: Ledger
|
||||
offers: Offers
|
||||
jobs: Ledger
|
||||
marks: Marks
|
||||
log: Log
|
||||
@@ -118,6 +120,9 @@ class Hub(Mcp, Reviewing, Asking, Messaging, Choosing, Approving, Denying, Reque
|
||||
icons: Markup
|
||||
spool: Spool
|
||||
office_spool: Spool
|
||||
firewall_spool: Spool
|
||||
groups: Ledger
|
||||
rule_sets: Ledger
|
||||
touched: Touched
|
||||
voice_notes: VoiceNotes
|
||||
replay: Path
|
||||
@@ -160,6 +165,9 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
|
||||
icons=sheet(places.vendor, templates),
|
||||
spool=Spool(places.cleanup).ready(),
|
||||
office_spool=Spool(places.offices).ready(),
|
||||
firewall_spool=Spool(state / "firewall").ready(),
|
||||
groups=Ledger(state / "groups.json"),
|
||||
rule_sets=Ledger(state / "rule-sets.json"),
|
||||
touched=Touched(reviews.stored),
|
||||
approvers=approvers,
|
||||
speech=speech,
|
||||
@@ -167,6 +175,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
|
||||
replay=state / "replay" / "messages.json",
|
||||
view_store=ViewStore(state / "view.json"),
|
||||
rules=Ledger(state / "rules.json"),
|
||||
offers=Offers(),
|
||||
jobs=Ledger(state / "jobs.json"),
|
||||
marks=Marks(state / "marks.json"),
|
||||
log=Log(state / "log.jsonl"),
|
||||
|
||||
@@ -6,7 +6,7 @@ from .denying import request_status, request_words, requester_of
|
||||
from .errors import Conflict, Missing, ToolError
|
||||
from .fields import WAIT_CAP, bounded, decode, expect, field, seconds
|
||||
from .records import iso_epoch
|
||||
from .rules import rule_fields, rule_matches, signed_fields, subject_of
|
||||
from .rules import EVERY_AGENT, rule_fields, rule_matches, signed_fields, subject_of
|
||||
from .signed import signing
|
||||
|
||||
# Trip-wire: MCP carries no caller identity, so an agent may name itself anew for each request; AGENT_CAP only spreads the queue, TOTAL_CAP is the bound.
|
||||
@@ -33,7 +33,7 @@ class Requesting:
|
||||
def rule_request(self, arguments: dict) -> dict:
|
||||
expect(arguments, (*RULE_FIELDS, "agent", "why"))
|
||||
now = time.time()
|
||||
fields = rule_fields(arguments, now)
|
||||
fields = {name: value for name, value in rule_fields(arguments, EVERY_AGENT, now).items() if name in RULE_FIELDS}
|
||||
if fields["kind"] == "decision" and fields["scope"] != "*":
|
||||
raise ToolError("a decision rule takes scope *, as the rules form does")
|
||||
name = field(arguments, "agent").strip()
|
||||
@@ -71,7 +71,7 @@ class Requesting:
|
||||
rule = {**{key: record[key] for key in RULE_FIELDS}, "enabled": True, "proof": {"payload": payload, "assertion": None}}
|
||||
ledger = {"ask": self.asks, "review": self.reviews, "decision": self.decisions}[kind_name]
|
||||
since = now - RECENT_DAYS * 86400
|
||||
subjects = [subject_of(kind_name, entry) for entry in ledger.listed() if created_of(entry) >= since]
|
||||
subjects = [subject_of(kind_name, entry, self.deciders(kind_name, entry)) for entry in ledger.listed() if created_of(entry) >= since]
|
||||
return {"matched": sum(rule_matches(rule, kind_name, subject, now) for subject in subjects), "total": len(subjects), "days": RECENT_DAYS}
|
||||
|
||||
def request_items(self, base: dict, now: float, claims: list[dict]) -> list[dict]:
|
||||
@@ -95,7 +95,7 @@ class Requesting:
|
||||
|
||||
def sign_request(self, request_id: str) -> dict:
|
||||
record = self.pending_request(request_id)
|
||||
return {**self.rule_offer(rule_fields(record, time.time())), "sign": True}
|
||||
return {**self.rule_offer(rule_fields(record, EVERY_AGENT, time.time())), "sign": True}
|
||||
|
||||
def accept_request(self, request_id: str, body: bytes) -> dict:
|
||||
payload = decode(body)
|
||||
@@ -106,9 +106,8 @@ class Requesting:
|
||||
fields = signed_fields(rule, now)
|
||||
if [fields[key] for key in RULE_FIELDS] != [record[key] for key in RULE_FIELDS]:
|
||||
raise ToolError("the signed rule must be exactly the requested one")
|
||||
if self.rules.get(rule["id"]) is not None:
|
||||
raise Conflict({"id": rule["id"], "status": "exists"})
|
||||
proof = self.proven_rule(rule, payload["assertion"])
|
||||
self.offered(rule, now)
|
||||
decided, changed = self.rule_requests.decide(request_id, {"status": "accepted", "rule": rule["id"]})
|
||||
if not changed:
|
||||
raise Conflict(request_state(decided, now))
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import fnmatch
|
||||
import threading
|
||||
import time
|
||||
|
||||
from .council import read_claims
|
||||
from .errors import Conflict, Missing, ToolError
|
||||
from .fields import COMMAND_LIMIT, PATH_LIMIT, bounded, decode, expect
|
||||
from .fields import COMMAND_LIMIT, PATH_LIMIT, bounded, decode, expect, visible
|
||||
from .names import Directory
|
||||
from .signed import ask_signed, passkey, review_signed, signing, verifier
|
||||
|
||||
RULE_KINDS = ("ask", "review", "decision")
|
||||
RULE_INPUT = ("kind", "tool", "pattern", "scope", "expires")
|
||||
EVERY_AGENT = [signing.ALL_AGENTS]
|
||||
OFFER_LIMIT = 1000
|
||||
|
||||
|
||||
def rule_matches(rule: dict, kind_name: str, subject: dict, now: float) -> bool:
|
||||
@@ -15,31 +21,73 @@ def rule_matches(rule: dict, kind_name: str, subject: dict, now: float) -> bool:
|
||||
if not rule["enabled"] or rule["expires"] <= now or rule["kind"] != kind_name or proof is None:
|
||||
return False
|
||||
if kind_name == "decision":
|
||||
return subject["recommended"] != "" and fnmatch.fnmatchcase(subject["agent"], rule["pattern"])
|
||||
named = subject["recommended"] != "" and fnmatch.fnmatchcase(subject["agent"], rule["pattern"])
|
||||
return named and signing.reaches(proof["payload"], subject["sessions"])
|
||||
return signing.rule_allows(proof["payload"], subject["item"], subject["gate"], now)
|
||||
|
||||
|
||||
def subject_of(kind_name: str, record: dict) -> dict:
|
||||
def subject_of(kind_name: str, record: dict, sessions: set[str]) -> dict:
|
||||
"""Args:
|
||||
kind_name: ask, review or decision.
|
||||
record: the ask, review or decision.
|
||||
sessions: for a decision, the sessions that held the asking agent's
|
||||
name; empty for an ask or review, whose signed item names its own.
|
||||
|
||||
Returns:
|
||||
What a rule of that kind is matched against.
|
||||
"""
|
||||
if kind_name == "ask":
|
||||
return {"item": ask_signed(record), "gate": ""}
|
||||
if kind_name == "review":
|
||||
return {"item": review_signed(record), "gate": record.get("gate", "")}
|
||||
return {"recommended": record["recommended"], "agent": record["agent"]}
|
||||
return {"recommended": record["recommended"], "agent": record["agent"], "sessions": sessions}
|
||||
|
||||
|
||||
def rule_fields(raw: dict, now: float) -> dict:
|
||||
def rule_fields(raw: dict, agents: object, now: float) -> dict:
|
||||
"""Args:
|
||||
raw: kind, tool, pattern, scope and expires of the rule.
|
||||
agents: EVERY_AGENT, or the sorted session ids of one agent or group.
|
||||
now: the current time in epoch seconds.
|
||||
|
||||
Returns:
|
||||
The checked fields with agents.
|
||||
"""
|
||||
kind_name, expires = raw["kind"], raw["expires"]
|
||||
if kind_name not in RULE_KINDS:
|
||||
raise ToolError(f"kind must be one of {', '.join(RULE_KINDS)}")
|
||||
tool_name, pattern, scope = rule_texts(raw, kind_name)
|
||||
if isinstance(expires, bool) or not isinstance(expires, int | float) or not now + 1 < expires <= now + signing.RULE_LIFETIME:
|
||||
raise ToolError("expires must be a moment within the next 366 days")
|
||||
return {"kind": kind_name, "tool": tool_name, "pattern": pattern, "scope": scope, "expires": int(expires), "agents": target_of(kind_name, agents)}
|
||||
|
||||
|
||||
def rule_texts(raw: dict, kind_name: str) -> tuple[str, str, str]:
|
||||
"""Returns:
|
||||
tool, pattern and scope of raw, once each is one line without a
|
||||
control, format, line or paragraph separator character, as visible()
|
||||
checks, and only an ask rule names a tool.
|
||||
"""
|
||||
tool_name = bounded(raw, "tool", 200).strip()
|
||||
if (kind_name == "ask") != bool(tool_name):
|
||||
raise ToolError("an ask rule names a tool; review and decision rules leave tool empty")
|
||||
pattern, scope = bounded(raw, "pattern", COMMAND_LIMIT), bounded(raw, "scope", PATH_LIMIT)
|
||||
if not pattern.strip() or not scope.strip() or "\n" in pattern or "\n" in scope:
|
||||
raise ToolError("pattern and scope must be one non-empty line each")
|
||||
if isinstance(expires, bool) or not isinstance(expires, int | float) or not now + 1 < expires <= now + signing.RULE_LIFETIME:
|
||||
raise ToolError("expires must be a moment within the next 366 days")
|
||||
return {"kind": kind_name, "tool": tool_name, "pattern": pattern, "scope": scope, "expires": int(expires)}
|
||||
visible({"tool": tool_name, "pattern": pattern, "scope": scope})
|
||||
return tool_name, pattern, scope
|
||||
|
||||
|
||||
def target_of(kind_name: str, agents: object) -> list[str]:
|
||||
"""Returns:
|
||||
agents, once signing.agents_problem() accepts it and a review rule
|
||||
names every agent, since a review names no session.
|
||||
"""
|
||||
problem = signing.agents_problem(agents)
|
||||
if problem:
|
||||
raise ToolError(problem)
|
||||
if kind_name == "review" and agents != EVERY_AGENT:
|
||||
raise ToolError("a review rule applies to every agent: a review names no session")
|
||||
return agents
|
||||
|
||||
|
||||
def signed_fields(rule: object, now: float) -> dict:
|
||||
@@ -49,17 +97,77 @@ def signed_fields(rule: object, now: float) -> dict:
|
||||
raise ToolError(f"rule: {error}") from None
|
||||
if len(rule["kinds"]) != 1:
|
||||
raise ToolError("a rule names exactly one kind")
|
||||
fields = rule_fields({**{name: rule[name] for name in ("tool", "pattern", "scope", "expires")}, "kind": rule["kinds"][0]}, now)
|
||||
agents = EVERY_AGENT
|
||||
if signing.TARGET in rule:
|
||||
agents = rule[signing.TARGET]
|
||||
fields = rule_fields({**{name: rule[name] for name in ("tool", "pattern", "scope", "expires")}, "kind": rule["kinds"][0]}, agents, now)
|
||||
if fields["tool"] != rule["tool"]:
|
||||
raise ToolError("tool must not carry surrounding blanks")
|
||||
return fields
|
||||
|
||||
|
||||
class Offers:
|
||||
def __init__(self) -> None:
|
||||
self.lock = threading.Lock()
|
||||
self.ids: dict[str, float] = {}
|
||||
|
||||
def offer(self, rule_id: str, now: float) -> None:
|
||||
"""Args:
|
||||
rule_id: an id the hub just put into a rule payload for the
|
||||
operator to sign; held in memory only, so a hub restart
|
||||
forgets every offer and refuses their proofs.
|
||||
now: the current time; offers older than signing.LIFETIME and
|
||||
beyond the newest OFFER_LIMIT are dropped.
|
||||
"""
|
||||
with self.lock:
|
||||
self.ids = {key: at for key, at in self.ids.items() if now - at <= signing.LIFETIME}
|
||||
self.ids[rule_id] = now
|
||||
while len(self.ids) > OFFER_LIMIT:
|
||||
del self.ids[next(iter(self.ids))]
|
||||
|
||||
def take(self, rule_id: str, now: float) -> bool:
|
||||
with self.lock:
|
||||
offered = self.ids.pop(rule_id, None)
|
||||
return offered is not None and now - offered <= signing.LIFETIME
|
||||
|
||||
|
||||
class Rules:
|
||||
def rule_offer(self, fields: dict) -> dict:
|
||||
rule = signing.rule_payload(self.rules.fresh(), [fields["kind"]], fields["tool"], fields["pattern"], fields["scope"], fields["expires"])
|
||||
rule = signing.targeted(signing.rule_payload(self.rules.fresh(), [fields["kind"]], fields["tool"], fields["pattern"], fields["scope"], fields["expires"]), fields["agents"])
|
||||
visible(rule)
|
||||
self.offers.offer(rule["id"], time.time())
|
||||
return {"payload": rule, "challenge": signing.challenge(rule), "credentials": [key["id"] for key in self.keys()]}
|
||||
|
||||
def offered(self, rule: dict, now: float) -> None:
|
||||
"""Raises:
|
||||
Conflict unless the hub offered the rule's id and stored no rule
|
||||
under it since, so a signed rule is stored once and never again
|
||||
after its deletion.
|
||||
"""
|
||||
if not self.offers.take(rule["id"], now):
|
||||
raise Conflict({"id": rule["id"], "status": "not offered or already stored: sign the rule anew"})
|
||||
|
||||
def deciders(self, kind_name: str, record: dict) -> set[str]:
|
||||
"""Returns:
|
||||
For a decision, the one session that holds its agent's name now,
|
||||
none when no session or several hold it; empty for every other
|
||||
kind.
|
||||
"""
|
||||
if kind_name != "decision":
|
||||
return set()
|
||||
directory = Directory(self.names.listed())
|
||||
holders = {session for session in directory.aliases(record["agent"]) if directory.now(session) == record["agent"]}
|
||||
return holders if len(holders) == 1 else set()
|
||||
|
||||
def known_agents(self, agents: list[str]) -> None:
|
||||
"""Raises:
|
||||
ToolError unless agents is EVERY_AGENT or every session in it is
|
||||
one the Agent Orchestrator knows.
|
||||
"""
|
||||
unknown = sorted(set(agents) - self.office_sessions(read_claims(self.council))) if agents != EVERY_AGENT else []
|
||||
if unknown:
|
||||
raise ToolError(f"agents must be sessions the Agent Orchestrator knows: {', '.join(unknown)[:200]}")
|
||||
|
||||
def proven_rule(self, rule: dict, assertion: object) -> dict:
|
||||
"""Args:
|
||||
rule: the rule payload, already checked by signed_fields.
|
||||
@@ -80,8 +188,11 @@ class Rules:
|
||||
|
||||
def sign_rule(self, body: bytes) -> dict:
|
||||
payload = decode(body)
|
||||
expect(payload, ("kind", "tool", "pattern", "scope", "expires"))
|
||||
return {**self.rule_offer(rule_fields(payload, time.time())), "sign": True}
|
||||
targeted = "agents" in payload
|
||||
expect(payload, (*RULE_INPUT, "agents") if targeted else RULE_INPUT)
|
||||
fields = rule_fields(payload, payload["agents"] if targeted else EVERY_AGENT, time.time())
|
||||
self.known_agents(fields["agents"])
|
||||
return {**self.rule_offer(fields), "sign": True}
|
||||
|
||||
def add_rule(self, body: bytes) -> dict:
|
||||
payload = decode(body)
|
||||
@@ -91,16 +202,49 @@ class Rules:
|
||||
fields = signed_fields(rule, now)
|
||||
if not isinstance(payload["enabled"], bool):
|
||||
raise ToolError("enabled must be true or false")
|
||||
if self.rules.get(rule["id"]) is not None:
|
||||
raise Conflict({"id": rule["id"], "status": "exists"})
|
||||
return self.store_rule(rule, fields, self.proven_rule(rule, payload["assertion"]), payload["enabled"], now)
|
||||
proof = self.proven_rule(rule, payload["assertion"])
|
||||
self.offered(rule, now)
|
||||
return self.store_rule(rule, fields, proof, payload["enabled"], now)
|
||||
|
||||
def rule_action(self, rule_id: str, verb: str) -> dict:
|
||||
def enable_items(self, raw: list[dict]) -> list[dict]:
|
||||
"""Args:
|
||||
raw: [{"kind": "enable", "rule"}] with the id of a stored rule.
|
||||
|
||||
Returns:
|
||||
The item a fresh approval signs to turn that rule on.
|
||||
"""
|
||||
expect(raw[0], ("kind", "rule"))
|
||||
return [self.enable_subject(raw[0]["rule"])]
|
||||
|
||||
def enable_subject(self, rule_id: object) -> dict:
|
||||
record = self.rules.get(rule_id) if isinstance(rule_id, str) else None
|
||||
if record is None:
|
||||
raise Missing(str(rule_id)[:40])
|
||||
if record.get("proof") is None:
|
||||
raise ToolError("an unsigned rule grants nothing: sign it anew")
|
||||
return signing.enable_item(record["proof"]["payload"])
|
||||
|
||||
def rule_action(self, rule_id: str, verb: str, body: bytes) -> dict:
|
||||
"""Args:
|
||||
rule_id: the stored rule.
|
||||
verb: delete, disable, or enable, which widens what agents may
|
||||
do and so needs {"proof"}: a fresh passkey approval listing
|
||||
signing.enable_item() of the rule.
|
||||
body: the request body.
|
||||
"""
|
||||
if verb == "delete":
|
||||
if not self.rules.remove(rule_id):
|
||||
raise Missing(rule_id)
|
||||
return {"id": rule_id, "deleted": True}
|
||||
if verb == "enable":
|
||||
payload = decode(body)
|
||||
expect(payload, ("proof",))
|
||||
self.operator_proven(payload["proof"], self.enable_subject(rule_id))
|
||||
record = self.rules.change(rule_id, {"enabled": verb == "enable"})
|
||||
if record is None:
|
||||
raise Missing(rule_id)
|
||||
return record
|
||||
|
||||
|
||||
def enable_request(raw: object) -> bool:
|
||||
return isinstance(raw, list) and len(raw) == 1 and isinstance(raw[0], dict) and raw[0].get("kind") == "enable"
|
||||
@@ -226,5 +226,5 @@ class View:
|
||||
def render(self, nonce: str) -> tuple[str, str]:
|
||||
now = time.time()
|
||||
state = self.state(now - RADIO_WINDOW, now, now, 0)
|
||||
page = self.templates.get_template("index.html.j2").render(nonce=nonce, state=state, view=self.view_store.get(), icons=self.icons)
|
||||
page = self.templates.get_template("index.html.j2").render(nonce=nonce, state=state, view=self.view_store.get(), icons=self.icons, emoji_bases=sorted(signing.EMOJI_BASES))
|
||||
return page, INDEX_CSP.format(nonce, " ".join(["'self'", *state["media"]]))
|
||||
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Agent Orchestrator firewall: wake on a signed settings change the Agent Orchestrator wrote
|
||||
|
||||
[Path]
|
||||
DirectoryNotEmpty=%h/.local/state/kvb-orchestrator/firewall/jobs
|
||||
MakeDirectory=true
|
||||
DirectoryMode=0700
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Agent Orchestrator firewall: verify the operator signature, then write exactly the signed change into a listed Claude settings file, and refresh the settings view the Firewall shows
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
Environment=PATH=/usr/bin:/bin
|
||||
EnvironmentFile=%h/.local/share/kvb-orchestrator/.env
|
||||
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/settings_writer.py --port ${KVB_ORCHESTRATOR_PORT} --jobs %h/.local/state/kvb-orchestrator/firewall/jobs --results %h/.local/state/kvb-orchestrator/firewall/results --view %h/.local/state/kvb-orchestrator/firewall/view.json --approvers %h/.config/kvb-orchestrator/approvers.json --replay %h/.local/state/kvb-orchestrator-approvals/firewall.json --tree %h/.local/state/pkgmgr/tree/branch-tree.json
|
||||
TimeoutStartSec=120
|
||||
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Agent Orchestrator firewall settings view a minute after its last run
|
||||
|
||||
[Timer]
|
||||
OnActiveSec=5s
|
||||
OnUnitInactiveSec=60s
|
||||
AccuracySec=5s
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -432,6 +432,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
{% include "style-ancestry.css" %}
|
||||
|
||||
{% include "style-home.css" %}
|
||||
|
||||
{% include "style-firewall.css" %}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -467,6 +469,7 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
<div class="bubbles" id="bubbles" aria-hidden="true" hidden><div class="bubble-bar"></div></div>
|
||||
<script nonce="{{ nonce }}" id="state" type="application/json">{{ state | tojson }}</script>
|
||||
<script nonce="{{ nonce }}" id="view" type="application/json">{{ view | tojson }}</script>
|
||||
<script nonce="{{ nonce }}" id="emoji-bases" type="application/json">{{ emoji_bases | tojson }}</script>
|
||||
<script nonce="{{ nonce }}">
|
||||
{% include "ambience.js" %}
|
||||
</script>
|
||||
@@ -520,6 +523,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
|
||||
{% include "page-state.js" %}
|
||||
|
||||
{% include "page-reveal.js" %}
|
||||
|
||||
{% include "page-dom.js" %}
|
||||
|
||||
{% include "page-api.js" %}
|
||||
@@ -610,6 +615,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
|
||||
{% include "page-rules.js" %}
|
||||
|
||||
{% include "page-firewall.js" %}
|
||||
|
||||
{% include "page-keyboard.js" %}
|
||||
|
||||
{% include "page-popup.js" %}
|
||||
|
||||
@@ -101,7 +101,7 @@
|
||||
edges.push({child: item.branch, parent: item.parent, source: "staged"});
|
||||
}
|
||||
}
|
||||
const plan = Ancestry.layout(repo.branches.map((entry) => ({id: entry.name, label: entry.name})), edges);
|
||||
const plan = Ancestry.layout(repo.branches.map((entry) => ({id: entry.name, label: revealed(entry.name)})), edges);
|
||||
const dropping = (link) => staged.some((item) => item.drop && item.branch === link.child && item.parent === link.parent);
|
||||
return ancestryChart(plan, `Ancestry of ${repo.name}`, {
|
||||
item: `ancestry:${repo.path}`,
|
||||
@@ -109,7 +109,7 @@
|
||||
class: ["ancestry-edge", link.derived ? "derived" : "", link.source === "staged" ? "pending" : "", dropping(link) ? "dropping" : ""].filter(Boolean).join(" "),
|
||||
d, "data-child": link.child, "data-parent": link.parent, "data-source": link.source,
|
||||
on: {click: () => stageParent(repo.path, link.child, link.parent, link.source !== "staged")},
|
||||
}, s("title", {}, `${link.parent} → ${link.child} · ${link.source}`)),
|
||||
}, s("title", {}, revealed(`${link.parent} → ${link.child} · ${link.source}`))),
|
||||
node: (node) => s("g", {
|
||||
class: "node a-branch ancestry-node", transform: `translate(${fixed(node.x)} ${fixed(node.y)})`, tabindex: 0, role: "button", "aria-label": node.label,
|
||||
"data-repo": repo.path, "data-branch": node.id, "data-generation": node.generation,
|
||||
|
||||
@@ -17,8 +17,8 @@
|
||||
const waits = locked.includes(item);
|
||||
const kept = held.includes(item);
|
||||
return h("li", {class: waits ? "dry-run locked" : kept ? "dry-run held" : "dry-run", "data-token": waits ? "needed" : null, "data-held": kept && entry ? entry.held : null},
|
||||
h("div", {class: "row"}, h("strong", {}, repo ? repo.name : item.repository), h("code", {}, item.branch), waits ? chip("bi-key", "token needed", "warn") : kept ? chip("bi-folder-symlink", "held by a worktree: not deleted here", "neutral") : null),
|
||||
h("pre", {}, (entry ? entry.plan : [`${item.branch} @ ${item.tip.slice(0, 12)}`]).join("\n")));
|
||||
h("div", {class: "row"}, h("strong", {}, revealed(repo ? repo.name : item.repository)), h("code", {}, revealed(item.branch)), waits ? chip("bi-key", "token needed", "warn") : kept ? chip("bi-folder-symlink", "held by a worktree: not deleted here", "neutral") : null),
|
||||
h("pre", {}, (entry ? entry.plan : [`${item.branch} @ ${item.tip.slice(0, 12)}`]).map(revealed).join("\n")));
|
||||
});
|
||||
const outcome = h("div", {class: "mini", "aria-live": "polite"});
|
||||
const confirm = h("button", {type: "button", class: "btn danger", ...named("Delete", "Delete: hand over to the host with your passkey signature")}, icon("bi-trash3"), "Delete");
|
||||
|
||||
@@ -24,15 +24,15 @@
|
||||
function patchRow(row) {
|
||||
const number = row.new || row.old || null;
|
||||
if (row.kind === "hunk") {
|
||||
return h("tr", {class: "hunk"}, h("td", {colspan: 3}), h("td", {class: "code"}, row.text));
|
||||
return h("tr", {class: "hunk"}, h("td", {colspan: 3}), h("td", {class: "code"}, revealed(row.text)));
|
||||
}
|
||||
return h("tr", {class: row.kind, "data-line": number},
|
||||
h("td", {class: "num"}, row.old), h("td", {class: "num"}, row.new), h("td", {class: "sign"}, SIGNS[row.kind] || " "), h("td", {class: "code"}, row.text));
|
||||
h("td", {class: "num"}, row.old), h("td", {class: "num"}, row.new), h("td", {class: "sign"}, SIGNS[row.kind] || " "), h("td", {class: "code"}, revealed(row.text)));
|
||||
}
|
||||
|
||||
function diffBlock(file) {
|
||||
const tone = DIFF_TONES[file.status] || "neutral";
|
||||
const head = [h("span", {class: "letter", "data-tone": tone}, file.status), h("code", {class: "path"}, file.path),
|
||||
const head = [h("span", {class: "letter", "data-tone": tone}, file.status), h("code", {class: "path"}, revealed(file.path)),
|
||||
file.mode && file.mode !== "100644" ? h("code", {class: "mode", title: `mode: ${file.mode}`}, file.mode) : null, h("span", {class: "spacer"}),
|
||||
file.note ? h("span", {class: "note", title: file.note}, icon("bi-eye-slash"), file.note) : null,
|
||||
file.status === "B" ? icon("bi-file-earmark-binary") : h("span", {class: "stat"}, h("span", {class: "add"}, `+${file.additions}`), h("span", {class: "del"}, `-${file.deletions}`))];
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
const status = (value) => pill((STATUS[value] || [value])[0], (STATUS[value] || [value, "neutral"])[1]);
|
||||
const klass = (value) => pill(CLASSES[value] || value, PILLS[value] || "neutral");
|
||||
const counter = (value) => h("span", {class: "count"}, String(value));
|
||||
const meta = (pairs) => h("dl", {class: "meta"}, pairs.map(([label, value, title]) => h("div", {}, h("dt", {}, label), h("dd", {}, h("code", {title: title || null}, dash(value))))));
|
||||
const meta = (pairs) => h("dl", {class: "meta"}, pairs.map(([label, value, title]) => h("div", {}, h("dt", {}, label), h("dd", {}, h("code", {title: title ? revealed(title) : null}, revealed(dash(value)))))));
|
||||
const emptyState = (title, text) => h("div", {class: "empty"}, h("div", {class: "empty-mark", "aria-hidden": "true"}), h("h2", {}, title), h("p", {}, text));
|
||||
const live = () => ui.preset !== -1 && ui.asOf === null;
|
||||
const alarmRows = () => state.radio.filter((row) => (row.class === "mayday" || row.class === "pan-pan") && row.ts >= state.alarm_since).reverse();
|
||||
@@ -89,7 +89,7 @@
|
||||
s("title", {}, PRESENCE[value][0]), s("rect", {class: "presence-dot", x: fixed(-size * 0.65), y: fixed(-size * 0.65), width: fixed(size * 1.3), height: fixed(size * 1.3), rx: fixed(size * 0.65)}),
|
||||
s("g", {class: "glyph"}, s("use", {href: `#${PRESENCE[value][1]}`, x: fixed(-size / 2), y: fixed(-size / 2), width: fixed(size), height: fixed(size)}))) : null;
|
||||
};
|
||||
const person = (name) => (name && name !== "-" && name !== "all" && name !== HUMAN ? h("button", {type: "button", class: "linkish", title: `Open ${name}`, on: {click: () => openAgent(name)}}, name) : dash(name));
|
||||
const person = (name) => (name && name !== "-" && name !== "all" && name !== HUMAN ? h("button", {type: "button", class: "linkish", title: revealed(`Open ${name}`), on: {click: () => openAgent(name)}}, revealed(name)) : dash(name));
|
||||
const people = () => state.people || {};
|
||||
const labelOf = (key) => (people()[key] || {name: String(key).replace(/^name:/, "")}).name;
|
||||
const nameOf = (key) => (people()[key] || {now: String(key).replace(/^name:/, "")}).now;
|
||||
@@ -147,8 +147,9 @@
|
||||
|
||||
function openSheet(title, body, wide) {
|
||||
const sheet = document.getElementById("sheet");
|
||||
sheet.replaceChildren(h("div", {class: `sheet-box${wide ? " wide" : ""}`, role: "dialog", "aria-modal": "true", "aria-label": title},
|
||||
h("div", {class: "sheet-head"}, h("h2", {class: "panel-title"}, title), h("span", {class: "spacer"}), iconBtn("bi-x-lg", "Close", "btn small ghost", closeSheet)),
|
||||
const shown = revealed(title);
|
||||
sheet.replaceChildren(h("div", {class: `sheet-box${wide ? " wide" : ""}`, role: "dialog", "aria-modal": "true", "aria-label": shown},
|
||||
h("div", {class: "sheet-head"}, h("h2", {class: "panel-title"}, shown), h("span", {class: "spacer"}), iconBtn("bi-x-lg", "Close", "btn small ghost", closeSheet)),
|
||||
h("div", {class: "sheet-body"}, body)));
|
||||
sheet.hidden = false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
const FIREWALL_LISTS = {"permissions.allow": "Allow", "permissions.ask": "Ask", "permissions.deny": "Deny", "sandbox.filesystem.allowWrite": "Sandbox: write", "sandbox.filesystem.denyRead": "Sandbox: no read", "sandbox.network.allowedDomains": "Sandbox: domain"};
|
||||
const LIST_TONES = {allow: "ok", ask: "warn", deny: "bad"};
|
||||
const SETTINGS_RESULTS = {done: ["written", "ok"], refused: ["refused", "bad"], failed: ["failed", "bad"]};
|
||||
const EVERY_AGENT = "*";
|
||||
const TARGET_GONE = "gone";
|
||||
const TARGET_PICK = "";
|
||||
const SESSION_KEY = /^(?!-)[A-Za-z0-9_-]{1,128}$/;
|
||||
const firewall = {data: null, busy: false, staged: {}, dom: null, targets: new Set(), picks: {}};
|
||||
|
||||
const knownAgents = () => Object.keys(people()).filter((key) => key !== HUMAN && SESSION_KEY.test(key)).sort();
|
||||
const firewallGroups = () => (firewall.data ? firewall.data.groups : []);
|
||||
const settingsFile = (path) => (firewall.data ? firewall.data.files.find((file) => file.path === path) : null);
|
||||
const everyAgent = (agents) => !agents || (agents.length === 1 && agents[0] === EVERY_AGENT);
|
||||
const groupOf = (agents) => firewallGroups().find((entry) => entry.members.join(",") === [...agents].sort().join(","));
|
||||
const firewallPickOf = (key) => (Object.hasOwn(firewall.picks, key) ? firewall.picks[key] : TARGET_PICK);
|
||||
|
||||
function targetLabel(agents) {
|
||||
if (everyAgent(agents)) {
|
||||
return "all agents";
|
||||
}
|
||||
const group = groupOf(agents);
|
||||
return revealed(group ? `group ${group.name}` : agents.map(labelOf).join(", "));
|
||||
}
|
||||
|
||||
const signedMembers = (agents) => agents.map((key) => `${labelOf(key)} (${key})`).join(", ");
|
||||
|
||||
/**
|
||||
* @param {string[]} agents the session ids a payload is signed for.
|
||||
* @returns {string} the scope the passkey prompt names with every session id the signature covers: for all agents, for group X: A (s1), B (s2), for agent A (s1) or for agents A (s1), B (s2).
|
||||
*/
|
||||
function scopeLabel(agents) {
|
||||
if (everyAgent(agents)) {
|
||||
return "for all agents";
|
||||
}
|
||||
const group = groupOf(agents);
|
||||
return group ? `for group ${group.name}: ${signedMembers(agents)}` : `for ${agents.length === 1 ? "agent" : "agents"} ${signedMembers(agents)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} rule a rule as signed: kinds, tool, pattern, scope, expires in epoch seconds and agents.
|
||||
* @returns {string[]} the lines the passkey prompt shows for it: what it grants, in which directory, until when and for which sessions.
|
||||
*/
|
||||
function ruleLines(rule) {
|
||||
const end = new Date(rule.expires * 1000).toISOString().slice(0, 16).replace("T", " ");
|
||||
const days = (Math.max(rule.expires - nowSeconds(), 0) / DAY).toFixed(1);
|
||||
return [`${rule.kinds.join(", ")}${rule.tool ? ` ${rule.tool}` : ""}: ${rule.pattern}`, `in ${rule.scope}`, `until ${end} UTC, in ${days} days`, scopeLabel(Object.hasOwn(rule, "agents") ? rule.agents : [EVERY_AGENT])];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} label what the operator signs.
|
||||
* @param {Object} prepared the hub's offer: payload, the signed rule itself or an approval, and enables, the signed rule an approval turns on.
|
||||
* @returns {string} the passkey prompt's text, with every line of ruleLines() for the rule that takes effect, each line through revealed().
|
||||
*/
|
||||
function promptText(label, prepared) {
|
||||
const rule = prepared.payload && prepared.payload.kind === "rule" ? prepared.payload : prepared.enables;
|
||||
return [label, ...(rule ? ruleLines(rule) : [])].map(revealed).join("\n");
|
||||
}
|
||||
|
||||
const targetPill = (agents) => h("span", {class: "pill", "data-tone": "neutral", "data-agents": JSON.stringify(agents === undefined ? [EVERY_AGENT] : agents), title: "Applies to"}, targetLabel(agents));
|
||||
|
||||
function targetOptions(keyed) {
|
||||
return [
|
||||
...(keyed ? [h("option", {value: TARGET_PICK, disabled: true}, "Pick a target")] : []),
|
||||
h("option", {value: "all"}, "All agents"),
|
||||
...knownAgents().map((key) => h("option", {value: `agent:${key}`}, revealed(`Agent ${labelOf(key)}`))),
|
||||
...firewallGroups().map((group) => h("option", {value: `group:${group.id}`}, revealed(`Group ${group.name}`))),
|
||||
];
|
||||
}
|
||||
|
||||
function fillTargets(select) {
|
||||
const keyed = "targetKey" in select.dataset;
|
||||
const value = keyed ? firewallPickOf(select.dataset.targetKey) : select.value;
|
||||
select.replaceChildren(...targetOptions(keyed));
|
||||
const gone = value !== TARGET_PICK && ![...select.options].some((option) => option.value === value);
|
||||
if (gone) {
|
||||
select.append(h("option", {value: TARGET_GONE, disabled: true}, "Target gone: pick again"));
|
||||
select.value = TARGET_GONE;
|
||||
} else if (value !== TARGET_PICK || keyed) {
|
||||
select.value = value;
|
||||
}
|
||||
const waiting = keyed && value === TARGET_PICK;
|
||||
select.setCustomValidity(gone ? "The chosen group or agent is gone: pick the target again" : waiting ? "Pick a target first" : "");
|
||||
const scope = select.form || select.parentElement;
|
||||
for (const button of scope ? scope.querySelectorAll("[data-sign]") : []) {
|
||||
button.disabled = (gone || waiting) && !select.disabled;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} label the select's accessible name.
|
||||
* @param {string|null} key the rule set whose pick the page keeps across redraws, with no default until the operator picks; null for a select that starts on all agents.
|
||||
* @returns {HTMLSelectElement} the target select.
|
||||
*/
|
||||
function targetSelect(label, key) {
|
||||
const select = h("select", {class: "field", "aria-label": label, "data-target-key": key});
|
||||
fillTargets(select);
|
||||
select.addEventListener("change", () => {
|
||||
if (key !== null) {
|
||||
firewall.picks[key] = select.value;
|
||||
}
|
||||
fillTargets(select);
|
||||
});
|
||||
firewall.targets.add(select);
|
||||
return select;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} value the target select's value: all, agent:<session>, group:<id> or gone.
|
||||
* @returns {string[]|null} the sorted session ids the rule is signed for, ["*"] only for all, null for a gone or unknown target.
|
||||
*/
|
||||
function agentsOf(value) {
|
||||
if (value.startsWith("agent:")) {
|
||||
return [value.slice("agent:".length)];
|
||||
}
|
||||
if (value.startsWith("group:")) {
|
||||
const group = firewallGroups().find((entry) => entry.id === value.slice("group:".length));
|
||||
return group ? group.members : null;
|
||||
}
|
||||
return value === "all" ? [EVERY_AGENT] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} kind the rule kind; a review rule always applies to every agent.
|
||||
* @param {string} value the target select's value.
|
||||
* @returns {string[]|null} the agents to sign; null for a group that is gone, which the hub refuses.
|
||||
*/
|
||||
const ruleAgents = (kind, value) => (kind === "review" ? [EVERY_AGENT] : agentsOf(value));
|
||||
|
||||
async function fetchFirewall() {
|
||||
if (firewall.busy) {
|
||||
return;
|
||||
}
|
||||
firewall.busy = true;
|
||||
try {
|
||||
const response = await fetch("/api/firewall", {cache: "no-store"});
|
||||
if (response.ok) {
|
||||
firewall.data = await response.json();
|
||||
}
|
||||
} catch {
|
||||
ui.offline = true;
|
||||
}
|
||||
firewall.busy = false;
|
||||
drawFirewall();
|
||||
}
|
||||
|
||||
function drawFirewall() {
|
||||
const dom = firewall.dom;
|
||||
if (!dom || !dom.settings.isConnected) {
|
||||
return;
|
||||
}
|
||||
for (const select of [...firewall.targets]) {
|
||||
if (select.isConnected) {
|
||||
fillTargets(select);
|
||||
} else {
|
||||
firewall.targets.delete(select);
|
||||
}
|
||||
}
|
||||
for (const node of document.querySelectorAll("#main [data-agents]")) {
|
||||
node.textContent = targetLabel(JSON.parse(node.dataset.agents));
|
||||
}
|
||||
dom.groups.replaceChildren(groupsCard());
|
||||
dom.sets.replaceChildren(setsCard());
|
||||
dom.patterns.replaceChildren(patternsCard());
|
||||
dom.settings.replaceChildren(settingsCard());
|
||||
}
|
||||
|
||||
function firewallSections() {
|
||||
firewall.dom = {groups: h("div", {}), sets: h("div", {}), patterns: h("div", {}), settings: h("div", {})};
|
||||
window.setTimeout(() => {
|
||||
drawFirewall();
|
||||
fetchFirewall();
|
||||
}, 0);
|
||||
return [firewall.dom.settings, firewall.dom.groups, firewall.dom.sets, firewall.dom.patterns];
|
||||
}
|
||||
|
||||
async function firewallPost(path, payload, label) {
|
||||
const result = await sendJson(path, payload);
|
||||
toast(result.ok ? label : `${label}: not possible`, result.ok ? [] : fail(result), result.ok);
|
||||
await fetchFirewall();
|
||||
return result.ok;
|
||||
}
|
||||
|
||||
function groupsCard() {
|
||||
const name = h("input", {class: "field", type: "text", placeholder: "builders", "aria-label": "Group name"});
|
||||
const members = h("select", {class: "field", multiple: true, size: Math.min(Math.max(knownAgents().length, 2), 6), "aria-label": "Members"}, knownAgents().map((key) => h("option", {value: key}, labelOf(key))));
|
||||
const form = h("form", {class: "fw-form", "aria-label": "New agent group"}, h("label", {}, "Name", name), h("label", {}, "Members", members),
|
||||
h("button", {type: "submit", class: "btn soft", ...named("Add group", "Add group: name the chosen agents as one rule target")}, icon("bi-people"), "Add group"));
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const chosen = [...members.selectedOptions].map((option) => option.value).sort();
|
||||
await firewallPost("/api/firewall/groups", {name: name.value.trim(), members: chosen}, "Group added");
|
||||
});
|
||||
const rows = firewallGroups().map((group) => h("div", {class: "rule-row", "data-group": group.name}, h("strong", {}, revealed(group.name)), h("span", {class: "muted"}, revealed(group.members.map(labelOf).join(", "))), h("span", {class: "spacer"}),
|
||||
iconBtn("bi-trash3", "Delete group", "btn small danger", () => firewallPost(`/api/firewall/groups/${encodeURIComponent(group.id)}/delete`, {}, "Group deleted"), `Delete group ${group.name}: rules signed for it keep their agents`)));
|
||||
return h("section", {class: "card stack-tight", "aria-label": "Agent groups"}, h("h3", {}, "Agent groups"),
|
||||
h("p", {class: "muted"}, "A rule applies to one agent, a group or all agents. A group's members are signed into each rule when you sign it."),
|
||||
rows.length ? h("div", {class: "mini"}, rows) : h("p", {class: "muted"}, "No group yet."), form);
|
||||
}
|
||||
|
||||
function setsCard() {
|
||||
const name = h("input", {class: "field", type: "text", placeholder: "ci", "aria-label": "Set name"});
|
||||
const days = h("input", {class: "field", type: "number", min: 1, max: 366, value: 7, "aria-label": "Days"});
|
||||
const chosen = h("select", {class: "field", multiple: true, size: Math.min(Math.max(state.rules.length, 2), 6), "aria-label": "Rules"}, state.rules.map((rule) => h("option", {value: rule.id}, `${rule.kind} ${rule.tool} ${rule.pattern}`.replace(" ", " "))));
|
||||
const form = h("form", {class: "fw-form", "aria-label": "New rule set"}, h("label", {}, "Name", name), h("label", {}, "Days", days), h("label", {}, "Rules", chosen),
|
||||
h("button", {type: "submit", class: "btn soft", ...named("Save set", "Save set: keep the chosen rules as one named rule set")}, icon("bi-collection"), "Save set"));
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
await firewallPost("/api/firewall/sets", {name: name.value.trim(), days: Number(days.value), rules: [...chosen.selectedOptions].map((option) => option.value)}, "Rule set saved");
|
||||
});
|
||||
const sets = firewall.data ? firewall.data.sets : [];
|
||||
const rows = sets.map((set) => setRow(set));
|
||||
return h("section", {class: "card stack-tight", "aria-label": "Rule sets"}, h("h3", {}, "Rule sets"),
|
||||
h("p", {class: "muted"}, "Take a set over as a whole for one agent, a group or all agents: each of its rules is signed with your passkey for that target."),
|
||||
rows.length ? h("div", {class: "mini"}, rows) : h("p", {class: "muted"}, "No rule set yet."), form);
|
||||
}
|
||||
|
||||
function setRow(set) {
|
||||
const target = targetSelect(`Take over ${set.name} for`, set.id);
|
||||
const take = h("button", {type: "button", class: "btn small soft", "data-sign": "", ...named("Take over", `Take over: sign the ${set.rules.length} rules of ${set.name} for the chosen agents`)}, icon("bi-box-arrow-in-down"), "Take over");
|
||||
take.addEventListener("click", async () => {
|
||||
take.disabled = true;
|
||||
await takeOver(set, agentsOf(target.value));
|
||||
fillTargets(target);
|
||||
});
|
||||
const row = h("div", {class: "rule-row", "data-set": set.name}, h("strong", {}, revealed(set.name)), h("span", {class: "muted"}, `${set.rules.length} rules, ${set.days} days`), h("span", {class: "spacer"}), target, take,
|
||||
iconBtn("bi-trash3", "Delete set", "btn small danger", () => firewallPost(`/api/firewall/sets/${encodeURIComponent(set.id)}/delete`, {}, "Rule set deleted"), `Delete set ${set.name}: its signed rules stay`));
|
||||
fillTargets(target);
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} set the rule set to take over: name, days and rules.
|
||||
* @param {string[]|null} agents the target from agentsOf().
|
||||
*/
|
||||
async function takeOver(set, agents) {
|
||||
if (!agents) {
|
||||
toast(`${set.name}: not taken over`, ["No target picked, or the picked group or agent is gone"], false);
|
||||
return;
|
||||
}
|
||||
const expires = Math.floor(nowSeconds()) + set.days * DAY;
|
||||
let created = 0;
|
||||
for (const rule of set.rules) {
|
||||
const prepared = await sendJson("/api/rules/sign", {...rule, expires, agents: rule.kind === "review" ? [EVERY_AGENT] : agents});
|
||||
const signed = prepared.ok && prepared.data ? await assertion(prepared.data, `Rule set ${set.name}`) : null;
|
||||
const result = signed ? await sendJson("/api/rules", {rule: prepared.data.payload, assertion: signed, enabled: true}) : prepared;
|
||||
created += signed && result.ok ? 1 : 0;
|
||||
}
|
||||
toast(`${set.name}: ${created} of ${set.rules.length} rules signed for ${targetLabel(agents)}`, [], created === set.rules.length);
|
||||
await load();
|
||||
}
|
||||
|
||||
function patternsCard() {
|
||||
const patterns = firewall.data ? firewall.data.patterns : [];
|
||||
return h("section", {class: "card stack-tight", "aria-label": "Never granted"}, h("h3", {}, "Never granted by a rule"),
|
||||
h("p", {class: "muted"}, "An ask rule never grants a command that matches one of these patterns; Claude Code asks instead."),
|
||||
h("ul", {class: "mini fw-patterns"}, patterns.map((pattern) => h("li", {}, h("div", {class: "row"}, pill(pattern.label, "bad"), h("code", {}, pattern.pattern))))));
|
||||
}
|
||||
|
||||
function stageChange(path, change) {
|
||||
const changes = (firewall.staged[path] || []).filter((entry) => !(entry.list === change.list && entry.entry === change.entry));
|
||||
firewall.staged[path] = [...changes, change];
|
||||
drawFirewall();
|
||||
}
|
||||
|
||||
function unstageChange(path, change) {
|
||||
firewall.staged[path] = (firewall.staged[path] || []).filter((entry) => entry !== change);
|
||||
if (!firewall.staged[path].length) {
|
||||
delete firewall.staged[path];
|
||||
}
|
||||
drawFirewall();
|
||||
}
|
||||
|
||||
function entryRow(path, list, entry) {
|
||||
const last = list.split(".").pop();
|
||||
const tone = Object.hasOwn(LIST_TONES, last) ? LIST_TONES[last] : "neutral";
|
||||
const editable = Object.hasOwn(FIREWALL_LISTS, list);
|
||||
return h("li", {"data-entry": entry, "data-list": list}, h("div", {class: "row"}, pill(FIREWALL_LISTS[list] || list, tone), h("code", {}, revealed(entry)), h("span", {class: "spacer"}),
|
||||
editable ? iconBtn("bi-dash-circle", "Remove", "btn small ghost", () => stageChange(path, {list, op: "remove", entry}), `Remove: stage the removal of ${revealed(entry)} from ${list}`) : null));
|
||||
}
|
||||
|
||||
function fileCard(file) {
|
||||
const groups = file.groups.map((group) => h("details", {class: "fw-group", open: true, "data-tool": group.tool, "data-prefix": group.prefix},
|
||||
h("summary", {}, h("strong", {}, group.tool), group.prefix ? h("code", {}, group.prefix) : null, counter(group.entries.length)),
|
||||
h("ul", {class: "mini"}, group.entries.map((entry) => entryRow(file.path, `permissions.${entry.list}`, entry.entry)))));
|
||||
const sandbox = file.sandbox.map((entry) => (entry.values
|
||||
? h("details", {class: "fw-group", "data-key": entry.key}, h("summary", {}, h("strong", {}, entry.key), counter(entry.values.length)), h("ul", {class: "mini"}, entry.values.map((value) => entryRow(file.path, entry.key, value))))
|
||||
: h("div", {class: "rule-row", "data-key": entry.key}, h("strong", {}, entry.key), h("code", {}, JSON.stringify(entry.value)))));
|
||||
const status = file.error ? pill(file.error, "bad") : file.exists ? pill(`sha256 ${file.sha256.slice(0, 12)}`, "neutral") : pill("missing: a change creates it", "warn");
|
||||
return h("section", {class: "fw-file", "data-file": file.path, "aria-label": file.path}, h("div", {class: "row"}, h("code", {class: "fw-path"}, file.path), status),
|
||||
groups.length ? groups : h("p", {class: "muted"}, "No permission entries."), sandbox.length ? h("h4", {}, "Sandbox") : null, sandbox);
|
||||
}
|
||||
|
||||
function addForm(files) {
|
||||
const file = h("select", {class: "field", "aria-label": "Settings file"}, files.map((entry) => h("option", {value: entry.path}, entry.path)));
|
||||
const list = h("select", {class: "field", "aria-label": "List"}, Object.entries(FIREWALL_LISTS).map(([value, label]) => h("option", {value}, `${label} (${value})`)));
|
||||
const entry = h("input", {class: "field", type: "text", placeholder: "Bash(make test:*)", "aria-label": "Entry"});
|
||||
const form = h("form", {class: "fw-form", "aria-label": "Stage a settings change"}, h("label", {}, "File", file), h("label", {}, "List", list), h("label", {}, "Entry", entry),
|
||||
h("button", {type: "submit", class: "btn soft", ...named("Stage", "Stage: add the entry to the list; nothing is written before you sign")}, icon("bi-plus-lg"), "Stage"));
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
if (entry.value.trim()) {
|
||||
stageChange(file.value, {list: list.value, op: "add", entry: entry.value.trim()});
|
||||
}
|
||||
});
|
||||
return form;
|
||||
}
|
||||
|
||||
const settingsItems = () => Object.entries(firewall.staged).filter(([file]) => settingsFile(file)).map(([file, changes]) => ({kind: "settings", file, base: settingsFile(file).sha256, changes}));
|
||||
|
||||
function stagedList() {
|
||||
const rows = Object.entries(firewall.staged).flatMap(([path, changes]) => changes.map((change) => h("li", {"data-staged": `${change.op} ${change.entry}`}, h("div", {class: "row"},
|
||||
pill(change.op === "add" ? "add" : "remove", change.op === "add" ? "ok" : "bad"), h("code", {}, revealed(`${change.list}: ${change.entry}`)), h("span", {class: "muted"}, revealed(path)), h("span", {class: "spacer"}),
|
||||
iconBtn("bi-x-circle", "Unstage", "btn small ghost", () => unstageChange(path, change), "Unstage: drop this change")))));
|
||||
if (!rows.length) {
|
||||
return h("p", {class: "muted"}, "No staged change.");
|
||||
}
|
||||
const review = h("button", {type: "button", class: "btn primary", ...named("Review and sign", "Review and sign: show the diff, then sign it with your passkey")}, icon("bi-file-diff"), "Review and sign");
|
||||
review.addEventListener("click", reviewSettings);
|
||||
return h("div", {class: "stack-tight"}, h("ul", {class: "mini", "aria-label": "Staged changes"}, rows), h("div", {class: "actions"}, review));
|
||||
}
|
||||
|
||||
function settingsCard() {
|
||||
const data = firewall.data;
|
||||
if (!data) {
|
||||
return h("section", {class: "card"}, h("p", {class: "muted"}, "Loading the settings …"));
|
||||
}
|
||||
const files = data.files;
|
||||
return h("section", {class: "card stack-tight", "aria-label": "Claude settings"}, h("h3", {}, "Claude settings"),
|
||||
h("p", {class: "muted"}, "Permissions and sandbox entries of the listed settings files, grouped by tool and prefix as the host read them. A change shows as a diff, is signed with your passkey and is written by the host, never by an agent."),
|
||||
data.error ? h("p", {class: "muted"}, data.error) : null,
|
||||
files.map(fileCard), files.length ? addForm(files) : null, stagedList());
|
||||
}
|
||||
|
||||
function diffLines(text) {
|
||||
return h("pre", {class: "fw-diff"}, text.split("\n").map((line) => h("span", {class: line.startsWith("+") && !line.startsWith("+++") ? "add" : line.startsWith("-") && !line.startsWith("---") ? "del" : null}, `${revealed(line)}\n`)));
|
||||
}
|
||||
|
||||
async function reviewSettings() {
|
||||
const items = settingsItems();
|
||||
const preview = await sendJson("/api/firewall/preview", {items});
|
||||
if (!preview.ok || !preview.data) {
|
||||
toast("Settings: not possible", fail(preview), false);
|
||||
await fetchFirewall();
|
||||
return;
|
||||
}
|
||||
const outcome = h("div", {class: "mini", "aria-live": "polite"});
|
||||
const confirm = h("button", {type: "button", class: "btn primary", ...named("Sign and apply", "Sign and apply: hand exactly this diff to the host with your passkey signature")}, icon("bi-pen"), "Sign and apply");
|
||||
confirm.addEventListener("click", async () => {
|
||||
confirm.disabled = true;
|
||||
if (!await applySettings(items, outcome)) {
|
||||
confirm.disabled = false;
|
||||
}
|
||||
});
|
||||
openSheet("Settings change", [
|
||||
h("p", {class: "muted"}, "The host writer checks your signature, refuses a file that changed since and writes exactly this change; it keeps every other key and a backup beside the file."),
|
||||
h("div", {class: "stack-tight", "aria-label": "Diff"}, preview.data.diffs.map((entry) => h("div", {"data-diff": entry.file}, h("code", {}, revealed(entry.file)), diffLines(entry.diff)))),
|
||||
outcome,
|
||||
h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), confirm),
|
||||
], true);
|
||||
}
|
||||
|
||||
async function applySettings(items, outcome) {
|
||||
const signed = await proofFor(items, "Settings");
|
||||
if (signed === null) {
|
||||
outcome.replaceChildren(h("p", {class: "muted"}, "Not signed: nothing was handed over."));
|
||||
return false;
|
||||
}
|
||||
const result = await sendJson("/api/firewall/settings", {items, proof: signed.proof});
|
||||
if (!result.ok || !result.data) {
|
||||
toast("Settings: not possible", fail(result), false);
|
||||
outcome.replaceChildren(h("p", {class: "muted"}, `${result.status} ${result.text}`.trim()));
|
||||
return false;
|
||||
}
|
||||
outcome.replaceChildren(h("p", {class: "muted", "data-firewall": result.data.id}, `Signed and handed to the host (job ${result.data.id}); the firewall unit writes now.`));
|
||||
followJob(`/api/firewall/settings/${encodeURIComponent(result.data.id)}`, outcome, Date.now(), (data) => {
|
||||
const {good, lines} = showJob(data, outcome, "file", SETTINGS_RESULTS);
|
||||
toast(`Settings: ${good ? "written" : "not everything written"}`, lines, good);
|
||||
if (good) {
|
||||
firewall.staged = {};
|
||||
}
|
||||
fetchFirewall();
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -75,11 +75,11 @@
|
||||
return;
|
||||
}
|
||||
const rows = usable.map((item) => h("li", {},
|
||||
h("div", {class: "row"}, pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), item.kind === "decision" && !deny ? h("span", {class: "muted"}, `→ ${item.recommended}`) : null),
|
||||
h("strong", {}, item.title),
|
||||
item.kind === "operator" ? h("div", {class: "command"}, h("code", {}, item.command)) : null,
|
||||
item.kind === "operator" ? h("span", {class: "muted"}, `in ${item.directory}`) : null,
|
||||
item.kind === "ask" ? h("div", {class: "command"}, h("code", {}, item.command)) : null));
|
||||
h("div", {class: "row"}, pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), item.kind === "decision" && !deny ? h("span", {class: "muted"}, revealed(`→ ${item.recommended}`)) : null),
|
||||
h("strong", {}, revealed(item.title)),
|
||||
item.kind === "operator" ? h("div", {class: "command"}, h("code", {}, revealed(item.command))) : null,
|
||||
item.kind === "operator" ? h("span", {class: "muted"}, revealed(`in ${item.directory}`)) : null,
|
||||
item.kind === "ask" ? h("div", {class: "command"}, h("code", {}, revealed(item.command))) : null));
|
||||
const confirm = h("button", {type: "button", class: deny ? "btn danger" : "btn primary"}, `${deny ? "Deny" : "Grant"} ${usable.length}`);
|
||||
confirm.addEventListener("click", () => {
|
||||
closeSheet();
|
||||
@@ -135,7 +135,7 @@
|
||||
} else if (item.kind === "ask") {
|
||||
buttons.push(iconBtn("bi-check-lg", "Grant", "btn small primary", () => approveOne(item)));
|
||||
} else if (item.kind === "decision" && item.recommended) {
|
||||
buttons.push(h("button", {type: "button", class: "btn small primary", ...named(`Recommendation: ${item.recommended}`), on: {click: () => approveOne(item)}}, icon("bi-check-lg"), item.recommended));
|
||||
buttons.push(h("button", {type: "button", class: "btn small primary", ...named(revealed(`Recommendation: ${item.recommended}`)), on: {click: () => approveOne(item)}}, icon("bi-check-lg"), revealed(item.recommended)));
|
||||
} else if (item.kind === "operator" && item.runnable) {
|
||||
buttons.push(iconBtn("bi-play-fill", "Run", "btn small primary", () => approveOne(item)));
|
||||
} else if (item.kind === "rule") {
|
||||
@@ -166,18 +166,18 @@
|
||||
item.until ? pill(`until ${absolute.format(stampOf(item.until))}`, "neutral") : null),
|
||||
h("div", {class: "entry-body"},
|
||||
h("div", {class: "route"},
|
||||
h("button", {type: "button", class: "linkish headline", title: "Open", on: {click: () => openItem(item)}}, item.kind === "operator" ? item.id : item.kind === "ask" ? item.title.split(": ")[0] : item.title),
|
||||
h("button", {type: "button", class: "linkish headline", title: "Open", on: {click: () => openItem(item)}}, revealed(item.kind === "operator" ? item.id : item.kind === "ask" ? item.title.split(": ")[0] : item.title)),
|
||||
item.agent ? [face(item.agent, false), person(item.agent)] : null),
|
||||
item.kind === "review" ? h("div", {class: "muted"}, item.detail, item.score ? ` · ${item.score}` : "") : null,
|
||||
commanded ? h("div", {class: "command", "data-path": item.directory || "-"}, h("code", {}, item.command), copyButton(item.command)) : null,
|
||||
commanded ? h("span", {class: "muted"}, `in ${dash(item.directory)}`) : null,
|
||||
item.kind === "operator" && item.detail && item.detail !== "-" ? h("p", {class: "text reason"}, item.detail) : null,
|
||||
item.kind === "review" ? h("div", {class: "muted"}, revealed(item.detail), item.score ? revealed(` · ${item.score}`) : "") : null,
|
||||
commanded ? h("div", {class: "command", "data-path": item.directory || "-"}, h("code", {}, revealed(item.command)), copyButton(item.command)) : null,
|
||||
commanded ? h("span", {class: "muted"}, revealed(`in ${dash(item.directory)}`)) : null,
|
||||
item.kind === "operator" && item.detail && item.detail !== "-" ? h("p", {class: "text reason"}, revealed(item.detail)) : null,
|
||||
diffBlocks(item),
|
||||
item.job ? consoleOf(item.job) : null,
|
||||
item.kind === "rule" ? ruleRequestBody(item) : null,
|
||||
item.kind === "decision" ? h("div", {class: "options"}, item.options.map((option) => h("button", {
|
||||
type: "button", class: `option${option.label === item.recommended ? " recommended" : ""}`, title: `${option.label}: your passkey signs this answer, a post to ${item.agent}`, disabled: item.held, on: {click: () => chooseOne(item, option.label)},
|
||||
}, h("strong", {}, option.label), option.description ? h("span", {}, option.description) : null))) : null,
|
||||
type: "button", class: `option${option.label === item.recommended ? " recommended" : ""}`, title: revealed(`${option.label}: your passkey signs this answer, a post to ${item.agent}`), disabled: item.held, on: {click: () => chooseOne(item, option.label)},
|
||||
}, h("strong", {}, revealed(option.label)), option.description ? h("span", {}, revealed(option.description)) : null))) : null,
|
||||
feedbackList(keyOf(item))),
|
||||
h("div", {class: "item-actions line-actions"},
|
||||
actionsFor(item),
|
||||
@@ -246,8 +246,8 @@
|
||||
}
|
||||
const body = [
|
||||
h("div", {class: "who"}, pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), item.agent ? face(item.agent, false) : null, item.agent ? person(item.agent) : null, when(item.ts)),
|
||||
h("p", {class: "text"}, item.title),
|
||||
item.command ? h("div", {class: "command"}, h("code", {}, item.command), copyButton(item.command)) : null,
|
||||
h("p", {class: "text"}, revealed(item.title)),
|
||||
item.command ? h("div", {class: "command"}, h("code", {}, revealed(item.command)), copyButton(item.command)) : null,
|
||||
item.kind === "rule" ? ruleRequestBody(item) : null,
|
||||
meta([["Directory", item.directory], ["Warnings", item.warnings.join(", ")], ["Id", item.id]]),
|
||||
item.kind === "decision" ? h("div", {class: "options"}, item.options.map((option) => h("button", {
|
||||
@@ -255,7 +255,7 @@
|
||||
closeSheet();
|
||||
chooseOne(item, option.label);
|
||||
}},
|
||||
}, h("strong", {}, option.label), option.description ? h("span", {}, option.description) : null))) : null,
|
||||
}, h("strong", {}, revealed(option.label)), option.description ? h("span", {}, revealed(option.description)) : null))) : null,
|
||||
h("div", {class: "actions"}, h("span", {class: "spacer"}), actionsFor(item).map((node) => {
|
||||
node.addEventListener("click", closeSheet);
|
||||
return node;
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
toast(`${label}: not signed`, ["No passkey pinned: Settings → Register passkey"], false);
|
||||
return null;
|
||||
}
|
||||
const prompt = h("div", {class: "toast wait passkey-prompt", id: "passkey-prompt", role: "status", "aria-live": "polite"}, h("strong", {}, "Passkey signs"), h("pre", {}, promptText(label, prepared)));
|
||||
document.body.append(prompt);
|
||||
try {
|
||||
const credential = await navigator.credentials.get({publicKey: {
|
||||
challenge: unb64url(prepared.challenge),
|
||||
@@ -29,6 +31,8 @@
|
||||
} catch (error) {
|
||||
toast(`${label}: not signed`, [`${(error && error.name) || error}: KeePassXC locked or canceled; nothing was sent.`], false);
|
||||
return null;
|
||||
} finally {
|
||||
prompt.remove();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
const UNSEEN = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Zs}\p{Default_Ignorable_Code_Point}]/gu;
|
||||
const EMOJI_BASES = new Set(JSON.parse(document.getElementById("emoji-bases").textContent));
|
||||
const PRESENTATION = new Set([0xFE0E, 0xFE0F]);
|
||||
|
||||
/**
|
||||
* @param {string} text the text a match sits in.
|
||||
* @param {number} offset the UTF-16 index of the match.
|
||||
* @returns {number} the code point right before offset, NaN at the start.
|
||||
*/
|
||||
const codePointBefore = (text, offset) => {
|
||||
const pair = offset > 1 ? text.codePointAt(offset - 2) : 0;
|
||||
return pair > 0xFFFF ? pair : text.charCodeAt(offset - 1);
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {string} text a text a passkey prompt, a signed-item preview or an inbox diff shows.
|
||||
* @returns {string} the text with every control, format, line or paragraph separator, space separator but the space and default-ignorable character but the tab shown as ⟨U+XXXX⟩, the set signing.unseen() refuses, except a variation selector right after a code point of EMOJI_BASES, the pair signing.presented() accepts, so no text hides, reorders or splits what the passkey signs.
|
||||
*/
|
||||
const revealed = (text) => String(text).replace(UNSEEN, (char, offset, whole) => (char === "\t" || char === " " || (PRESENTATION.has(char.codePointAt(0)) && EMOJI_BASES.has(codePointBefore(whole, offset))) ? char : `⟨U+${char.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}⟩`));
|
||||
|
||||
/**
|
||||
* @param {string} text a text of several lines a signed-item preview shows.
|
||||
* @returns {string} each line through revealed(), joined by real line breaks.
|
||||
*/
|
||||
const revealedLines = (text) => String(text).split("\n").map(revealed).join("\n");
|
||||
@@ -44,7 +44,7 @@
|
||||
const head = h("article", {class: "card"},
|
||||
h("div", {class: "card-head"}, h("div", {}, h("p", {class: "muted"}, "submitted ", when(review.created_ts))), h("div", {class: "who"}, status(review.status || "pending"), review.gate ? pill(review.gate === "pass" ? "Gate green" : "Gate red", review.gate === "pass" ? "ok" : "bad") : null)),
|
||||
meta([["Repo", review.worktree], ["Branch", review.branch], ["Tree", (review.tree || "").slice(0, 12), review.tree], ["Score", review.score]]),
|
||||
review.notes ? h("pre", {class: "notes"}, review.notes) : null,
|
||||
review.notes ? h("pre", {class: "notes"}, revealedLines(review.notes)) : null,
|
||||
h("div", {class: "actions"},
|
||||
h("a", {class: "btn ghost icon-only", href: `/reviews/${encodeURIComponent(review.id)}/page`, target: "_blank", rel: "noopener noreferrer", ...named("Open full page", "Open full page (new tab)")}, icon("bi-box-arrow-up-right")),
|
||||
h("span", {class: "spacer"}),
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
const dry = item.dry_run;
|
||||
const pairs = [["Kind", RULE_KINDS[rule.kind]], rule.kind === "ask" ? ["Tool (glob)", rule.tool] : null, ["Pattern (glob)", rule.pattern], rule.kind === "decision" ? null : ["Directory (glob)", rule.scope], ["Expires on", absolute.format(stampOf(rule.expires))]];
|
||||
return h("div", {class: "rule-request"},
|
||||
item.detail ? h("p", {class: "text"}, item.detail) : null,
|
||||
item.detail ? h("p", {class: "text"}, revealed(item.detail)) : null,
|
||||
meta(pairs.filter(Boolean)),
|
||||
h("p", {class: "muted dry-run-count"}, "Dry run: the rule would have granted ", h("strong", {}, `${dry.matched} of ${dry.total}`), ` ${COUNTED[rule.kind]} from the last ${dry.days} days.`),
|
||||
h("p", {class: "muted"}, RULE_HINTS[rule.kind]));
|
||||
|
||||
@@ -1,12 +1,23 @@
|
||||
const RULE_KINDS = {ask: "Ask: tool + command pattern", review: "Review: branch pattern + gate green", decision: "Decision: take the recommendation"};
|
||||
const RULE_HINTS = {
|
||||
ask: "Grants matching asks in matching directories, never a command with a warning (rm -r, push, --force, sudo, pipes into a shell …). The passkey signs the rule once; the hook checks signature and pattern itself.",
|
||||
review: "Grants reviews of matching branches and worktrees, only when their gate is green. The passkey signs the rule once; the commit skill checks signature and pattern itself.",
|
||||
ask: "Grants matching asks in matching directories, never a command with a warning (rm -r, push, --force, sudo, pipes into a shell …). The passkey signs the rule and the agents it applies to once; the hook checks signature, pattern and agent itself.",
|
||||
review: "Grants reviews of matching branches and worktrees, only when their gate is green, for every agent: a review names no session. The passkey signs the rule once; the commit skill checks signature and pattern itself.",
|
||||
decision: "Takes the recommended option in decisions of matching agents. The passkey signs the rule once; the decisions themselves stay unsigned.",
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {Object} rule the stored rule to turn on again, which widens what agents may do.
|
||||
* @returns {Promise<Object|null>} the hub's answer, null when the operator did not sign.
|
||||
*/
|
||||
async function turnOn(rule) {
|
||||
const signed = await proofFor([{kind: "enable", rule: rule.id}], "Turn on rule");
|
||||
return signed ? sendJson(`/api/rules/${encodeURIComponent(rule.id)}/enable`, {proof: signed.proof}) : null;
|
||||
}
|
||||
|
||||
function rulesScreen() {
|
||||
const kind = h("select", {class: "field", "aria-label": "Kind"}, Object.entries(RULE_KINDS).map(([value, label]) => h("option", {value}, label)));
|
||||
const target = targetSelect("Applies to", null);
|
||||
const targetField = h("label", {}, "Applies to", target);
|
||||
const tool = h("input", {class: "field", type: "text", placeholder: "Bash", value: "Bash"});
|
||||
const pattern = h("input", {class: "field", type: "text", placeholder: "make test*"});
|
||||
const scope = h("input", {class: "field", type: "text", value: "*", placeholder: "/home/…/Repositories/*"});
|
||||
@@ -19,12 +30,15 @@
|
||||
const sync = () => {
|
||||
toolField.hidden = kind.value !== "ask";
|
||||
scopeField.hidden = kind.value === "decision";
|
||||
targetField.hidden = kind.value === "review";
|
||||
target.disabled = targetField.hidden;
|
||||
fillTargets(target);
|
||||
pattern.placeholder = {ask: "make test*", review: "feature/*", decision: "* (agent pattern)"}[kind.value];
|
||||
hint.textContent = RULE_HINTS[kind.value];
|
||||
};
|
||||
kind.addEventListener("change", sync);
|
||||
sync();
|
||||
const form = h("form", {class: "rule-form"}, h("label", {}, "Kind", kind), toolField, h("label", {}, "Pattern (glob)", pattern), scopeField, h("label", {}, "Expires on", expires), h("label", {class: "check"}, enabled, "active"), h("button", {type: "submit", class: "btn primary"}, "Create rule"));
|
||||
const form = h("form", {class: "rule-form"}, h("label", {}, "Kind", kind), targetField, toolField, h("label", {}, "Pattern (glob)", pattern), scopeField, h("label", {}, "Expires on", expires), h("label", {class: "check"}, enabled, "active"), h("button", {type: "submit", class: "btn primary", "data-sign": ""}, "Create rule"));
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const end = Date.parse(`${expires.value}T23:59:59`) / 1000;
|
||||
@@ -34,6 +48,7 @@
|
||||
pattern: pattern.value.trim() || (kind.value === "decision" ? "*" : ""),
|
||||
scope: kind.value === "decision" ? "*" : scope.value.trim(),
|
||||
expires: Number.isFinite(end) ? end : 0,
|
||||
agents: ruleAgents(kind.value, target.value),
|
||||
};
|
||||
const prepared = await sendJson("/api/rules/sign", fields);
|
||||
if (!prepared.ok || !prepared.data) {
|
||||
@@ -49,18 +64,19 @@
|
||||
await load();
|
||||
});
|
||||
const change = async (rule, verb) => {
|
||||
const result = await send(`/api/rules/${encodeURIComponent(rule.id)}/${verb}`, "", "application/json");
|
||||
if (!result.ok) {
|
||||
toast("Rule not changed", [`${result.status} ${result.text}`.trim()], false);
|
||||
const result = verb === "enable" ? await turnOn(rule) : await send(`/api/rules/${encodeURIComponent(rule.id)}/${verb}`, "", "application/json");
|
||||
if (result && !result.ok) {
|
||||
toast("Rule not changed", fail(result), false);
|
||||
}
|
||||
await load();
|
||||
};
|
||||
const now = nowSeconds();
|
||||
const list = state.rules.length ? h("div", {class: "mini"}, state.rules.map((rule) => h("div", {class: "rule-row"},
|
||||
pill(rule.kind, KIND_TONES[rule.kind]),
|
||||
rule.tool ? h("code", {}, rule.tool) : null,
|
||||
h("code", {}, rule.pattern),
|
||||
rule.kind === "decision" ? null : h("code", {title: "Directory"}, rule.scope || "–"),
|
||||
targetPill(rule.agents),
|
||||
rule.tool ? h("code", {}, revealed(rule.tool)) : null,
|
||||
h("code", {}, revealed(rule.pattern)),
|
||||
rule.kind === "decision" ? null : h("code", {title: "Directory"}, rule.scope ? revealed(rule.scope) : "–"),
|
||||
pill(rule.signed ? "signed" : "unsigned: has no effect", rule.signed ? "ok" : "bad"),
|
||||
rule.expires <= now ? pill("expired", "bad") : h("span", {class: "muted"}, `until ${absolute.format(stampOf(rule.expires))}`),
|
||||
rule.enabled ? pill("active", "ok") : pill("off", "neutral"),
|
||||
@@ -71,5 +87,5 @@
|
||||
change(rule, "delete");
|
||||
}
|
||||
})))) : h("p", {class: "muted"}, "No rule yet. Every automatic grant shows up in the stream and can be undone for 3 s.");
|
||||
return h("div", {class: "stack"}, h("h2", {class: "title"}, "Firewall rules for automatic grants"), list, h("div", {class: "card"}, hint, form));
|
||||
return h("div", {class: "stack"}, h("h2", {class: "title"}, "Firewall"), h("h3", {}, "Hub rules for automatic grants"), list, h("div", {class: "card"}, hint, form), ...firewallSections());
|
||||
}
|
||||
@@ -51,9 +51,9 @@
|
||||
const setValue = h("button", {type: "button", class: "btn small primary", ...named("Set business value", "Set the business value as Operator, signed with the passkey; WSJF uses it instead of the median")}, icon("bi-gem"), "Set business value");
|
||||
const sync = () => {
|
||||
pin.disabled = !prioText(prio.value);
|
||||
pinCode.textContent = pin.disabled ? `Enter a priority from 1 to ${PRIO_MAX}` : shownArgv(prioArgv());
|
||||
estimateCode.textContent = shownArgv(estimateArgv());
|
||||
valueCode.textContent = shownArgv(valueArgv());
|
||||
pinCode.textContent = pin.disabled ? `Enter a priority from 1 to ${PRIO_MAX}` : revealed(shownArgv(prioArgv()));
|
||||
estimateCode.textContent = revealed(shownArgv(estimateArgv()));
|
||||
valueCode.textContent = revealed(shownArgv(valueArgv()));
|
||||
};
|
||||
for (const field of [prio, value, complexity, alone]) {
|
||||
field.addEventListener("input", sync);
|
||||
@@ -96,7 +96,7 @@
|
||||
function taskJobs(row) {
|
||||
const jobs = state.jobs.filter((job) => job.kind === "task" && job.task === row.task).slice(-5).reverse();
|
||||
return jobs.length ? [h("h3", {}, "Signed changes", counter(jobs.length)), h("ul", {class: "mini"}, jobs.map((job) => h("li", {"data-job": job.status},
|
||||
h("div", {class: "row"}, h("code", {}, job.command), status(job.status)),
|
||||
h("div", {class: "row"}, h("code", {}, revealed(job.command)), status(job.status)),
|
||||
job.status === "refused" || job.status === "failed" ? h("pre", {class: "notes"}, job.output) : null)))] : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
.stack-tight { display: grid; gap: 10px; min-width: 0; }
|
||||
.fw-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 200px), 1fr)); gap: 10px; align-items: end; }
|
||||
.fw-form label { display: grid; gap: 4px; min-width: 0; color: var(--muted); font-size: var(--fs-sm); }
|
||||
.fw-form .field { width: 100%; min-width: 0; }
|
||||
.fw-file { display: grid; gap: 8px; min-width: 0; padding: 10px; border: 1px solid var(--line); border-radius: 10px; }
|
||||
.fw-file > .row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.fw-path { overflow-wrap: anywhere; }
|
||||
.fw-group > summary { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; cursor: pointer; }
|
||||
.fw-group code, .fw-patterns code { overflow-wrap: anywhere; }
|
||||
.fw-diff { max-height: 50vh; margin: 4px 0 0; padding: 8px; overflow: auto; border-radius: 8px; background: var(--sunken); font-size: var(--fs-sm); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.fw-diff .add { color: var(--ok); }
|
||||
.fw-diff .del { color: var(--bad); }
|
||||
.rule-row select.field { width: auto; max-width: 100%; min-width: 0; }
|
||||
.passkey-prompt { position: fixed; top: 18px; left: 50%; z-index: 60; width: min(440px, calc(100vw - 36px)); transform: translateX(-50%); }
|
||||
Reference in new issue
Block a user