feat(hub): Controls page switches MCP servers, plugins and Artifacts
The Firewall page becomes Controls with three tabs: Tools lists every MCP server, plugin and feature switch of ~/.claude/settings.json with each other settings file that sets it differently, Rules keeps the settings lists and the hub rule form, Groups the groups and sets. A flip stages a change in one shared Apply bar; Apply shows the diff and signs it with the passkey as before. The signer writes deniedMcpServers rules, enabledPlugins entries and switches only in the own file and refuses wrong types and no-op flips; switching, the capability views and the per-item checks are one function each. 🎯 Fix: 88 % 💥 Break: 6 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 83 🚦 Gate: ⛔ fix 88 % < 90, break 6 % > 5 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
78f2fec339
commit
50363b1a33
16 files changed
+645
-78
No files matched your search
@@ -7,7 +7,9 @@
|
||||
--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.
|
||||
its path, sha256, whether it is ~/.claude/settings.json and only the
|
||||
part signing.settings_view() keeps, and the names of the MCP servers
|
||||
and plugins known() finds.
|
||||
--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.
|
||||
@@ -21,7 +23,8 @@ Returns:
|
||||
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
|
||||
of every repository the tree file knows), an MCP server, plugin or switch
|
||||
change outside ~/.claude/settings.json, 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
|
||||
@@ -57,18 +60,23 @@ 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
|
||||
CONFIG_LIMIT = 16 << 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 own_file(home: Path) -> str:
|
||||
return str(home / ".claude" / "settings.json")
|
||||
|
||||
|
||||
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")
|
||||
own = own_file(home)
|
||||
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)]
|
||||
|
||||
@@ -90,13 +98,18 @@ def parent_of(path: str) -> int:
|
||||
return fd
|
||||
|
||||
|
||||
def read_settings(parent: int, name: str) -> tuple[bytes | None, os.stat_result | None]:
|
||||
"""Returns:
|
||||
def read_settings(parent: int, name: str, limit: int) -> tuple[bytes | None, os.stat_result | None]:
|
||||
"""Args:
|
||||
parent: the open directory holding the file.
|
||||
name: the file's name in it.
|
||||
limit: the most bytes the file may hold.
|
||||
|
||||
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.
|
||||
signing.Refused for a link, a non-regular file or one over limit
|
||||
bytes.
|
||||
"""
|
||||
try:
|
||||
fd = os.open(name, FILE, dir_fd=parent)
|
||||
@@ -108,9 +121,9 @@ def read_settings(parent: int, name: str) -> tuple[bytes | None, os.stat_result
|
||||
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")
|
||||
data = handle.read(limit + 1)
|
||||
if len(data) > limit:
|
||||
raise signing.Refused(f"the file is larger than {limit} bytes")
|
||||
return data, found
|
||||
|
||||
|
||||
@@ -216,7 +229,7 @@ def read_view(path: str, entry: dict) -> dict:
|
||||
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)
|
||||
data, _ = read_settings(parent, Path(path).name, READ_LIMIT)
|
||||
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]}
|
||||
@@ -224,6 +237,45 @@ def read_view(path: str, entry: dict) -> dict:
|
||||
os.close(parent)
|
||||
|
||||
|
||||
def loaded(path: Path) -> dict:
|
||||
"""Returns:
|
||||
The JSON object in path, read as read_settings() reads a settings
|
||||
file but up to CONFIG_LIMIT bytes; {} for a file that is missing,
|
||||
linked, no regular file, too large, unreadable or no object.
|
||||
"""
|
||||
try:
|
||||
parent = parent_of(str(path))
|
||||
except OSError:
|
||||
return {}
|
||||
try:
|
||||
data, _ = read_settings(parent, path.name, CONFIG_LIMIT)
|
||||
value = json.loads(data) if data else {}
|
||||
except (OSError, ValueError, RecursionError, signing.Refused):
|
||||
return {}
|
||||
finally:
|
||||
os.close(parent)
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def known(home: Path) -> dict:
|
||||
"""Returns:
|
||||
{"servers", "plugins"}: the names of the MCP servers ~/.claude.json
|
||||
configures for the user or a project or that claude.ai connected
|
||||
once, and the ids of the installed plugins; names only, never a
|
||||
value, and nothing from a file that is missing or unreadable.
|
||||
"""
|
||||
config = loaded(home / ".claude.json")
|
||||
projects = config.get("projects")
|
||||
scopes = [config, *(projects.values() if isinstance(projects, dict) else [])]
|
||||
servers = [name for scope in scopes if isinstance(scope, dict) and isinstance(scope.get("mcpServers"), dict) for name in scope["mcpServers"]]
|
||||
connected = config.get("claudeAiMcpEverConnected")
|
||||
plugins = loaded(home / ".claude" / "plugins" / "installed_plugins.json").get("plugins")
|
||||
return {
|
||||
"servers": signing.names_of([*servers, *(connected if isinstance(connected, list) else [])], signing.MCP_NAME),
|
||||
"plugins": signing.names_of(plugins, signing.PLUGIN_ID),
|
||||
}
|
||||
|
||||
|
||||
class Writer:
|
||||
def __init__(self, trust: verifier.Trust, home: Path, tree: Path) -> None:
|
||||
self.trust = trust
|
||||
@@ -231,7 +283,8 @@ class Writer:
|
||||
self.tree = tree
|
||||
|
||||
def view(self) -> dict:
|
||||
return {"written": time.time(), "files": [view_of(path) for path in listed(self.home, self.tree)]}
|
||||
own = own_file(self.home)
|
||||
return {"written": time.time(), "files": [view_of(path) | {"own": path == own} for path in listed(self.home, self.tree)], "known": known(self.home)}
|
||||
|
||||
def apply(self, item: dict, job_id: str) -> dict:
|
||||
"""Args:
|
||||
@@ -252,7 +305,7 @@ class Writer:
|
||||
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)
|
||||
data, found = read_settings(parent, name, READ_LIMIT)
|
||||
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"]:
|
||||
@@ -295,6 +348,8 @@ class Writer:
|
||||
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", {}
|
||||
if item["file"] != own_file(self.home) and any(change["list"] in signing.CAPABILITIES for change in item["changes"]):
|
||||
return "refused", "MCP servers, plugins and switches change only in ~/.claude/settings.json", {}
|
||||
try:
|
||||
written = self.apply(item, job_id)
|
||||
except signing.Refused as error:
|
||||
|
||||
+119
-20
@@ -46,6 +46,10 @@ 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")
|
||||
MCP_NAME = re.compile(r"(?=.{1,128}\Z)[A-Za-z0-9]+(?:[ ._:-][A-Za-z0-9]+)*")
|
||||
PLUGIN_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}@[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
|
||||
SWITCHES = ("enableArtifact",)
|
||||
CAPABILITIES = {"deniedMcpServers": MCP_NAME, "enabledPlugins": PLUGIN_ID, "switches": re.compile("|".join(SWITCHES))}
|
||||
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}")
|
||||
@@ -516,8 +520,11 @@ def settings_file_problem(file: object) -> str | None:
|
||||
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)}"
|
||||
lists = (*SETTINGS_LISTS, *CAPABILITIES)
|
||||
if change["list"] not in lists or change["op"] not in SETTINGS_OPS:
|
||||
return f"list must be one of {', '.join(lists)} and op one of {', '.join(SETTINGS_OPS)}"
|
||||
if change["list"] in CAPABILITIES:
|
||||
return None if CAPABILITIES[change["list"]].fullmatch(change["entry"]) else f"entry is no valid {change['list']} name"
|
||||
return hidden_problem(change, "change") if ENTRY.fullmatch(change["entry"]) else "entry must be one line of 1 to 500 characters"
|
||||
|
||||
|
||||
@@ -551,10 +558,39 @@ def changes_problem(changes: object) -> str | None:
|
||||
|
||||
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.
|
||||
The only part of a settings object the Agent Orchestrator receives:
|
||||
the permissions and sandbox sections, the deniedMcpServers rules that
|
||||
name a server and nothing else, the enabledPlugins entries of a
|
||||
PLUGIN_ID and the SWITCHES. A capability key of the wrong type and a
|
||||
plugin or switch value that is no boolean show as null, so the hub
|
||||
refuses a change to it as switch_capability() refuses it in the file.
|
||||
"""
|
||||
return {name: settings[name] for name in SETTINGS_SECTIONS if isinstance(settings.get(name), dict)}
|
||||
view = {name: settings[name] for name in SETTINGS_SECTIONS if isinstance(settings.get(name), dict)}
|
||||
if "deniedMcpServers" in settings:
|
||||
view["deniedMcpServers"] = denied_view(settings["deniedMcpServers"])
|
||||
if "enabledPlugins" in settings:
|
||||
view["enabledPlugins"] = plugins_view(settings["enabledPlugins"])
|
||||
return view | {name: settings[name] if isinstance(settings[name], bool) else None for name in SWITCHES if name in settings}
|
||||
|
||||
|
||||
def denied_view(denied: object) -> list[dict] | None:
|
||||
if not isinstance(denied, list):
|
||||
return None
|
||||
return [rule for rule in denied if isinstance(rule, dict) and list(rule) == ["serverName"] and isinstance(rule["serverName"], str) and MCP_NAME.fullmatch(rule["serverName"])]
|
||||
|
||||
|
||||
def plugins_view(plugins: object) -> dict | None:
|
||||
if not isinstance(plugins, dict):
|
||||
return None
|
||||
return {name: on if isinstance(on, bool) else None for name, on in plugins.items() if PLUGIN_ID.fullmatch(name)}
|
||||
|
||||
|
||||
def names_of(found: object, pattern: re.Pattern) -> list[str]:
|
||||
"""Returns:
|
||||
The texts among found (a list, or a dict's keys) that pattern fully
|
||||
matches, sorted and each once; anything else is dropped.
|
||||
"""
|
||||
return sorted({name for name in found if isinstance(name, str) and pattern.fullmatch(name)}) if isinstance(found, (list, dict)) else []
|
||||
|
||||
|
||||
def plain_problem(value: object, depth: int) -> str | None:
|
||||
@@ -604,25 +640,88 @@ def apply_changes(settings: dict, changes: list[dict]) -> dict:
|
||||
"""
|
||||
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"])
|
||||
if change["list"] in CAPABILITIES:
|
||||
switch_capability(result, change["list"], change["entry"], change["op"] == "add")
|
||||
else:
|
||||
entries.append(change["entry"])
|
||||
change_list(result, change)
|
||||
return result
|
||||
|
||||
|
||||
def change_list(settings: dict, change: dict) -> None:
|
||||
*path, leaf = change["list"].split(".")
|
||||
node = settings
|
||||
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"])
|
||||
|
||||
|
||||
def switch_capability(settings: dict, name: str, entry: str, add: bool) -> None:
|
||||
"""Args:
|
||||
settings: the settings copy, changed in place.
|
||||
name: a CAPABILITIES key; add lists entry in it: a deniedMcpServers
|
||||
rule {"serverName": entry} blocks the server before it loads, an
|
||||
enabledPlugins entry turns true, a switch drops its false and
|
||||
falls back to its default, on.
|
||||
entry: the server name, plugin id or switch.
|
||||
add: True for op add, False for op remove.
|
||||
|
||||
Raises:
|
||||
Refused when the key or entry holds the wrong type or entry is in
|
||||
the state already; removing a blocked server drops every copy of its
|
||||
rule.
|
||||
"""
|
||||
if name == "switches":
|
||||
switch_feature(settings, entry, add)
|
||||
return
|
||||
blocked = name == "deniedMcpServers"
|
||||
held = settings.setdefault(name, [] if blocked else {})
|
||||
if not isinstance(held, list if blocked else dict):
|
||||
raise Refused(f"{name} holds the wrong type")
|
||||
(block_server if blocked else switch_plugin)(held, entry, add)
|
||||
|
||||
|
||||
def switch_feature(settings: dict, entry: str, add: bool) -> None:
|
||||
held = entry in settings
|
||||
if held and not isinstance(settings[entry], bool):
|
||||
raise Refused(f"{entry} holds the wrong type")
|
||||
if (not held or settings[entry]) == add:
|
||||
raise Refused(f"{entry} is {'on' if add else 'off'} already")
|
||||
if add:
|
||||
del settings[entry]
|
||||
else:
|
||||
settings[entry] = False
|
||||
|
||||
|
||||
def switch_plugin(held: dict, entry: str, add: bool) -> None:
|
||||
enabled = held.get(entry, False)
|
||||
if not isinstance(enabled, bool):
|
||||
raise Refused(f"{entry} holds the wrong type")
|
||||
if enabled == add:
|
||||
raise Refused(f"{entry} is {'enabled' if add else 'disabled'} already")
|
||||
held[entry] = add
|
||||
|
||||
|
||||
def block_server(held: list, entry: str, add: bool) -> None:
|
||||
rule = {"serverName": entry}
|
||||
if (rule in held) == add:
|
||||
raise Refused(f"{entry} is {'blocked' if add else 'not blocked'} already")
|
||||
if add:
|
||||
held.append(rule)
|
||||
else:
|
||||
held[:] = [kept for kept in held if kept != rule]
|
||||
|
||||
|
||||
def warnings(command: str) -> list[str]:
|
||||
return [label for label, pattern in WARNINGS if pattern.search(command)]
|
||||
|
||||
|
||||
@@ -147,10 +147,80 @@ def shaped_file(entry: object) -> bool:
|
||||
return isinstance(entry.get("settings"), dict) and isinstance(entry.get("sha256"), str) and (entry["sha256"] == "" or bool(HASH.fullmatch(entry["sha256"])))
|
||||
|
||||
|
||||
def tool_state(settings: dict, name: str, entry: str) -> bool | None:
|
||||
"""Args:
|
||||
settings: a file's settings as signing.settings_view() keeps them.
|
||||
name: a signing.CAPABILITIES key.
|
||||
entry: the server name, plugin id or switch.
|
||||
|
||||
Returns:
|
||||
What the file sets for entry: False for a server it blocks or a
|
||||
switch it turns off, the boolean of a plugin, None where it sets
|
||||
nothing that counts. Claude Code merges the deny lists of every
|
||||
file, a false switch anywhere wins, and a project's plugin switch
|
||||
overrides the user's.
|
||||
"""
|
||||
if name == "deniedMcpServers":
|
||||
return False if {"serverName": entry} in (settings.get(name) or []) else None
|
||||
if name == "enabledPlugins":
|
||||
on = (settings.get(name) or {}).get(entry)
|
||||
return on if isinstance(on, bool) else None
|
||||
return False if settings.get(entry) is False else None
|
||||
|
||||
|
||||
def tool_names(every: list[dict], known: dict) -> dict:
|
||||
"""Args:
|
||||
every: the shown settings files.
|
||||
known: the view's {"servers", "plugins"} names.
|
||||
|
||||
Returns:
|
||||
Per signing.CAPABILITIES key the names its rows show: the known
|
||||
servers and plugins plus every one a file blocks or switches, and the
|
||||
fixed switches.
|
||||
"""
|
||||
blocked = {rule["serverName"] for entry in every for rule in entry["settings"].get("deniedMcpServers") or []}
|
||||
enabled = [name for entry in every for name in entry["settings"].get("enabledPlugins") or {}]
|
||||
return {
|
||||
"deniedMcpServers": signing.names_of([*signing.names_of(known.get("servers"), signing.MCP_NAME), *blocked], signing.MCP_NAME),
|
||||
"enabledPlugins": signing.names_of([*signing.names_of(known.get("plugins"), signing.PLUGIN_ID), *enabled], signing.PLUGIN_ID),
|
||||
"switches": list(signing.SWITCHES),
|
||||
}
|
||||
|
||||
|
||||
def tools_of(files: list[dict], known: object) -> dict | None:
|
||||
"""Args:
|
||||
files: the shown settings files.
|
||||
known: the view's {"servers", "plugins"} names.
|
||||
|
||||
Returns:
|
||||
{"file", "error", "groups"} for the file the view marks as
|
||||
~/.claude/settings.json, each group {"list", "label", "off", "rows"}
|
||||
with off the op that turns a row off, each row {"name", "on",
|
||||
"overrides"}: on as that file sets it, overrides every other listed
|
||||
file that sets it differently as {"file", "on"}; None while no file
|
||||
is marked.
|
||||
"""
|
||||
own = next((entry for entry in files if entry.get("own") is True), None)
|
||||
if own is None:
|
||||
return None
|
||||
settings = own["settings"]
|
||||
others = [entry for entry in files if entry is not own]
|
||||
names = tool_names([own, *others], known if isinstance(known, dict) else {})
|
||||
|
||||
def row(name: str, entry: str) -> dict:
|
||||
state = tool_state(settings, name, entry)
|
||||
on = state is True if name == "enabledPlugins" else state is None
|
||||
overrides = [{"file": other["path"], "on": found} for other in others if (found := tool_state(other["settings"], name, entry)) is not None and found != on]
|
||||
return {"name": entry, "on": on, "overrides": overrides}
|
||||
|
||||
labels = (("deniedMcpServers", "MCP servers", "add"), ("enabledPlugins", "Plugins", "remove"), ("switches", "Features", "remove"))
|
||||
return {"file": own["path"], "error": own["error"], "groups": [{"list": name, "label": label, "off": off, "rows": [row(name, entry) for entry in names[name]]} for name, label, off in labels]}
|
||||
|
||||
|
||||
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.
|
||||
The unified diff of the part of the settings the view shows 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)
|
||||
@@ -183,16 +253,16 @@ 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.
|
||||
{"path", "exists", "sha256", "error", "settings", "own"} with
|
||||
settings only the part signing.settings_view() keeps, and the
|
||||
view's written time, error and tools_of().
|
||||
"""
|
||||
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": ""}
|
||||
return [], {"written": None, "error": "no settings view yet: the kvb-orchestrator-firewall unit writes it on the host", "tools": None}
|
||||
shown = [{**entry, "settings": signing.settings_view(entry["settings"]), "error": str(entry.get("error") or ""), "own": entry.get("own") is True} for entry in files if shaped_file(entry)]
|
||||
return shown, {"written": view.get("written"), "error": "", "tools": tools_of(shown, view.get("known"))}
|
||||
|
||||
def firewall(self) -> dict:
|
||||
files, meta = self.settings_files()
|
||||
@@ -216,19 +286,33 @@ class Firewall:
|
||||
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)
|
||||
order = self.settings_order(files, entry)
|
||||
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 settings_order(self, files: dict[str, dict], entry: object) -> dict:
|
||||
"""Args:
|
||||
files: the listed settings files by path.
|
||||
entry: one item of the page.
|
||||
|
||||
Returns:
|
||||
Its file, base and changes once they apply to the listed file;
|
||||
ToolError otherwise.
|
||||
"""
|
||||
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 not files[order["file"]]["own"] and any(change["list"] in signing.CAPABILITIES for change in order["changes"]):
|
||||
raise ToolError("MCP servers, plugins and switches change only in ~/.claude/settings.json")
|
||||
return order
|
||||
|
||||
def applicable(self, files: dict[str, dict], order: dict) -> dict:
|
||||
shown = files.get(order["file"])
|
||||
if shown is None:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const Nav = (() => {
|
||||
"use strict";
|
||||
const TABS = [["home", "Home"], ["stream", "Stream"], ["agents", "Agents"], ["artifacts", "Artifacts"], ["tasks", "Tasks"], ["resources", "Resources"]];
|
||||
const SUBS = {stream: [["rules", "Firewall"]]};
|
||||
const SUBS = {stream: [["rules", "Controls"]]};
|
||||
const PANES = {inbox: ["tasks", "operator"], match: ["tasks", "match"]};
|
||||
const VIEWS = [["orbit", "Orbit"], ["chord", "Chord"], ["swimlane", "Swimlane"], ["tree", "Tree"], ["3d", "3D"]];
|
||||
const TASK_VIEWS = [["list", "List"], ["board", "Board"], ["rasci", "RASCI"], ["gantt", "Gantt"], ["burn", "Burndown and burnup"], ["3d", "3D"]];
|
||||
|
||||
@@ -14,7 +14,16 @@
|
||||
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: {}, shown: new Set(ROW_FILTERS.map(([id]) => id)), open: new Set()};
|
||||
const CONTROL_TABS = [["tools", "Tools", "bi-plug"], ["rules", "Rules", "bi-shield-lock"], ["groups", "Groups", "bi-people"]];
|
||||
const CAPABILITY_WORDS = {deniedMcpServers: ["Unblock server", "Block server"], enabledPlugins: ["Enable plugin", "Disable plugin"], switches: ["Turn on", "Turn off"]};
|
||||
const TOOL_HINTS = {
|
||||
deniedMcpServers: "Off blocks the server before it loads, in every session and project.",
|
||||
enabledPlugins: "Off disables the plugin with its skills, hooks and servers.",
|
||||
switches: "Built-in features of Claude Code.",
|
||||
};
|
||||
const SWITCH_TITLES = {enableArtifact: "Artifacts"};
|
||||
const OTHER_OP = {add: "remove", remove: "add"};
|
||||
const firewall = {data: null, busy: false, staged: {}, dom: null, targets: new Set(), picks: {}, shown: new Set(ROW_FILTERS.map(([id]) => id)), open: new Set(), tab: CONTROL_TABS[0][0]};
|
||||
|
||||
const knownAgents = () => Object.keys(people()).filter((key) => key !== HUMAN && SESSION_KEY.test(key)).sort();
|
||||
const firewallGroups = () => (firewall.data ? firewall.data.groups : []);
|
||||
@@ -171,15 +180,41 @@
|
||||
dom.sets.replaceChildren(setsCard());
|
||||
dom.patterns.replaceChildren(patternsCard());
|
||||
dom.settings.replaceChildren(settingsCard());
|
||||
dom.tools.replaceChildren(toolsCard());
|
||||
const count = Object.values(firewall.staged).reduce((sum, changes) => sum + changes.length, 0);
|
||||
dom.bar.hidden = !count;
|
||||
dom.bar.replaceChildren(...(count ? applyBar(count) : []));
|
||||
}
|
||||
|
||||
function firewallSections() {
|
||||
firewall.dom = {groups: h("div", {}), sets: h("div", {}), patterns: h("div", {}), settings: h("div", {})};
|
||||
firewall.dom = {tools: h("div", {}), groups: h("div", {}), sets: h("div", {}), patterns: h("div", {}), settings: h("div", {}), bar: h("div", {class: "apply-bar", role: "region", "aria-label": "Apply changes", hidden: true})};
|
||||
window.setTimeout(() => {
|
||||
drawFirewall();
|
||||
fetchFirewall();
|
||||
}, 0);
|
||||
return [firewall.dom.settings, firewall.dom.groups, firewall.dom.sets, firewall.dom.patterns];
|
||||
return firewall.dom;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} panels per tab of CONTROL_TABS the nodes it shows.
|
||||
* @param {HTMLElement} bar the Apply bar every tab shares.
|
||||
* @returns {HTMLElement} the Controls screen: title, tab list, one panel per tab, only the chosen one shown, and the bar.
|
||||
*/
|
||||
function controlsPage(panels, bar) {
|
||||
const views = {};
|
||||
const tabs = {};
|
||||
const pick = (id) => {
|
||||
firewall.tab = id;
|
||||
for (const [key, tab] of Object.entries(tabs)) {
|
||||
tab.setAttribute("aria-selected", String(key === id));
|
||||
views[key].hidden = key !== id;
|
||||
}
|
||||
};
|
||||
for (const [id, label, glyph] of CONTROL_TABS) {
|
||||
tabs[id] = h("button", {type: "button", role: "tab", id: `controls-tab-${id}`, "data-tab": id, "aria-controls": `controls-${id}`, "aria-selected": String(firewall.tab === id), on: {click: () => pick(id)}}, icon(glyph), label);
|
||||
views[id] = h("div", {class: "stack", role: "tabpanel", id: `controls-${id}`, "aria-labelledby": `controls-tab-${id}`, hidden: firewall.tab !== id}, panels[id]);
|
||||
}
|
||||
return h("div", {class: "stack controls"}, h("h2", {class: "title"}, "Controls"), h("div", {class: "segmented", role: "tablist", "aria-label": "Controls"}, Object.values(tabs)), Object.values(views), bar);
|
||||
}
|
||||
|
||||
async function firewallPost(path, payload, label) {
|
||||
@@ -200,7 +235,7 @@
|
||||
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`)));
|
||||
iconBtn("bi-trash3", "Delete group", "btn small danger", () => firewallPost(`/api/firewall/groups/${encodeURIComponent(group.id)}/delete`, {}, "Group deleted"), revealed(`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);
|
||||
@@ -209,7 +244,7 @@
|
||||
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 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}, revealed(`${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) => {
|
||||
@@ -232,7 +267,7 @@
|
||||
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`));
|
||||
iconBtn("bi-trash3", "Delete set", "btn small danger", () => firewallPost(`/api/firewall/sets/${encodeURIComponent(set.id)}/delete`, {}, "Rule set deleted"), revealed(`Delete set ${set.name}: its signed rules stay`)));
|
||||
fillTargets(target);
|
||||
return row;
|
||||
}
|
||||
@@ -413,16 +448,87 @@
|
||||
|
||||
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 turnsOn = (change) => (change.list === "deniedMcpServers") !== (change.op === "add");
|
||||
const stagedOf = (path, list, entry) => (firewall.staged[path] || []).find((change) => change.list === list && change.entry === entry);
|
||||
|
||||
/**
|
||||
* @param {Object} change a staged change.
|
||||
* @returns {Array} its pill and text: on or off with Block server x, Enable plugin y or Turn off Artifacts for a tool, add or remove with list: entry otherwise.
|
||||
*/
|
||||
function stagedWords(change) {
|
||||
const words = CAPABILITY_WORDS[change.list];
|
||||
if (!words) {
|
||||
return [pill(change.op, change.op === "add" ? "ok" : "bad"), `${change.list}: ${change.entry}`];
|
||||
}
|
||||
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));
|
||||
const on = turnsOn(change);
|
||||
return [pill(on ? "on" : "off", on ? "ok" : "bad"), `${words[on ? 0 : 1]} ${SWITCH_TITLES[change.entry] || change.entry}`];
|
||||
}
|
||||
|
||||
function stagedList() {
|
||||
return h("ul", {class: "mini", "aria-label": "Staged changes"}, Object.entries(firewall.staged).flatMap(([path, changes]) => changes.map((change) => {
|
||||
const [state, words] = stagedWords(change);
|
||||
return h("li", {"data-staged": `${change.op} ${change.entry}`}, h("div", {class: "row"}, state, h("code", {}, revealed(words)), h("span", {class: "muted fw-path"}, revealed(path)), settingsFile(path) ? null : pill("file gone: not applied", "bad"), h("span", {class: "spacer"}),
|
||||
iconBtn("bi-x-circle", "Unstage", "btn small ghost", () => unstageChange(path, change), "Unstage: drop this change")));
|
||||
})));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} count how many changes are staged, at least one.
|
||||
* @returns {HTMLElement[]} the bar's content: the folded list of staged changes, Discard and Apply, which shows the diff of the changes to a listed file and signs it.
|
||||
*/
|
||||
function applyBar(count) {
|
||||
const ready = settingsItems().reduce((sum, item) => sum + item.changes.length, 0);
|
||||
const apply = h("button", {type: "button", class: "btn primary", "data-apply": "", disabled: !ready, title: "Apply: show the diff of every staged change to a listed file, then sign it with your passkey", on: {click: reviewSettings}}, icon("bi-send-check"), `Apply (${ready})`);
|
||||
const discard = iconBtn("bi-arrow-counterclockwise", "Discard", "btn ghost", () => {
|
||||
firewall.staged = {};
|
||||
drawFirewall();
|
||||
}, "Discard: drop every staged change");
|
||||
return [h("details", {class: "apply-list"}, h("summary", {}, `${count} staged ${count === 1 ? "change" : "changes"}`), stagedList()), h("span", {class: "spacer"}), discard, apply];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} path the settings file the tools live in.
|
||||
* @param {Object} group a tools group: list, label, off (the op that turns a row off) and rows.
|
||||
* @param {Object} row one server, plugin or switch: name, on as the host read it, and overrides, each other settings file that sets it differently as {file, on}.
|
||||
* @returns {HTMLElement} the row with a pill per override and a switch that stages the flip, or drops the staged flip to turn it back.
|
||||
*/
|
||||
function toolRow(path, group, row) {
|
||||
const staged = stagedOf(path, group.list, row.name);
|
||||
const on = staged ? turnsOn(staged) : row.on;
|
||||
const title = SWITCH_TITLES[row.name] || row.name;
|
||||
const flip = () => (staged ? unstageChange(path, staged) : stageChange(path, {list: group.list, op: row.on ? group.off : OTHER_OP[group.off], entry: row.name}));
|
||||
const overrides = row.overrides.map((other) => h("span", {class: "pill", "data-tone": "warn", "data-override": other.file, title: revealed(`${other.file} sets it ${other.on ? "on" : "off"}, which wins in that repository`)},
|
||||
`${other.on ? "on" : "off"} in ${revealed(other.file.split("/").slice(-3, -2)[0] || other.file)}`));
|
||||
return h("label", {class: "tool-row", "data-tool": row.name, "data-on": String(on), "data-staged": staged ? "" : null},
|
||||
h("span", {class: "tool-name"}, revealed(title)), overrides, staged ? pill("staged", "warn") : null, h("span", {class: "spacer"}),
|
||||
h("input", {type: "checkbox", role: "switch", class: "switch", checked: on, "aria-label": title, on: {change: flip}}));
|
||||
}
|
||||
|
||||
function blockForm(path) {
|
||||
const name = h("input", {class: "field", type: "text", placeholder: "plugin:name:server", "aria-label": "Server name"});
|
||||
const form = h("form", {class: "tool-add", "aria-label": "Block another MCP server"}, name,
|
||||
h("button", {type: "submit", class: "btn soft", ...named("Block", "Block: stage a deny rule for this server name; Apply signs it")}, icon("bi-slash-circle"), "Block"));
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
if (name.value.trim()) {
|
||||
stageChange(path, {list: "deniedMcpServers", op: "add", entry: name.value.trim()});
|
||||
}
|
||||
});
|
||||
return form;
|
||||
}
|
||||
|
||||
function toolsCard() {
|
||||
const data = firewall.data;
|
||||
const tools = data ? data.tools : null;
|
||||
if (!tools) {
|
||||
return h("section", {class: "card"}, h("p", {class: "muted"}, !data ? "Loading the tools …" : data.error ? data.error : "The host view marks no ~/.claude/settings.json yet: the kvb-orchestrator-firewall unit writes it with its next run."));
|
||||
}
|
||||
const groups = tools.groups.map((group) => h("div", {class: "tool-group", "data-list": group.list}, h("h4", {}, group.label), h("p", {class: "muted"}, TOOL_HINTS[group.list]),
|
||||
group.rows.length ? h("div", {class: "tool-rows"}, group.rows.map((row) => toolRow(tools.file, group, row))) : h("p", {class: "muted"}, "None known."),
|
||||
group.list === "deniedMcpServers" ? blockForm(tools.file) : null));
|
||||
return h("section", {class: "card stack-tight", "aria-label": "Tools"}, h("h3", {}, "Tools"),
|
||||
h("p", {class: "muted"}, "What every agent session may load, as ~/.claude/settings.json sets it. A pill names a repository whose settings set it differently, which wins there; a .claude/settings.local.json stays unseen. A switch only stages; Apply shows the diff, you sign it with your passkey and the host writes it. Each session picks it up at its next start."),
|
||||
tools.error ? pill(tools.error, "bad") : null, h("div", {class: "tool-groups"}, groups));
|
||||
}
|
||||
|
||||
function settingsCard() {
|
||||
@@ -434,7 +540,7 @@
|
||||
return h("section", {class: "card stack-tight fw-rules", "aria-label": "Firewall rules"}, h("h3", {}, "Firewall rules"),
|
||||
h("p", {class: "muted"}, `Every rule in one table: the hub rules and the permissions and sandbox entries of the listed settings files as the host read them, one folded group per source. Hits count the asks of the last ${data.days} days a rule matches, with the matcher of the rule request dry run; allow, deny and sandbox entries never reach the ask ledger and show not seen. A settings 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,
|
||||
filterChips(), ruleTable(), files.length ? addForm(files) : null, stagedList());
|
||||
filterChips(), ruleTable(), files.length ? addForm(files) : null);
|
||||
}
|
||||
|
||||
function diffLines(text) {
|
||||
@@ -459,7 +565,7 @@
|
||||
});
|
||||
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)))),
|
||||
h("div", {class: "stack-tight", "aria-label": "Diff"}, preview.data.diffs.map((entry) => h("div", {"data-diff": entry.file}, h("code", {class: "fw-path"}, revealed(entry.file)), diffLines(entry.diff)))),
|
||||
outcome,
|
||||
h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), confirm),
|
||||
], true);
|
||||
@@ -482,7 +588,9 @@
|
||||
const {good, lines} = showJob(data, outcome, "file", SETTINGS_RESULTS);
|
||||
toast(`Settings: ${good ? "written" : "not everything written"}`, lines, good);
|
||||
if (good) {
|
||||
firewall.staged = {};
|
||||
for (const item of items) {
|
||||
delete firewall.staged[item.file];
|
||||
}
|
||||
}
|
||||
fetchFirewall();
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
{label: "Radio …", hint: "Post, Call, Newsletter, Broadcast, Pan-Pan, Security, Mayday; the gear holds tones and read aloud", scope: "general", run: openRadio},
|
||||
...ACTIONS.map(([id, label]) => ({label, hint: id === "clear-mayday" ? "Mayday" : "Day/Night", scope: "general", run: () => confirmAct(id, [])})),
|
||||
{label: "Priority …", hint: "agent order in the hierarchy", scope: "agents", run: openAgentOrder},
|
||||
{label: "Firewall …", hint: "automatic grants", scope: "stream", run: () => go("rules", null)},
|
||||
{label: "Controls …", hint: "tools, rules and groups", scope: "stream", run: () => go("rules", null)},
|
||||
{label: "Settings …", hint: "Ambience, location, colors, music, notifications, internet radio", scope: "general", run: settingsSheet},
|
||||
{label: settings.music.on ? "Music off" : "Music on", hint: "Ambience", scope: "general", run: toggleMusic},
|
||||
{label: space.look ? "Leave the sky" : "Look at the sky", hint: "h", scope: "general", run: () => skyLook(!space.look)},
|
||||
|
||||
@@ -71,6 +71,7 @@
|
||||
toast(result.ok ? "Rule created" : "Rule not created", result.ok ? [] : fail(result), result.ok);
|
||||
await load();
|
||||
});
|
||||
const [table, ...rest] = firewallSections();
|
||||
return h("div", {class: "stack"}, h("h2", {class: "title"}, "Firewall"), table, h("div", {class: "card"}, h("h3", {}, "New hub rule for automatic grants"), hint, form), ...rest);
|
||||
const dom = firewallSections();
|
||||
const ruleCard = h("div", {class: "card"}, h("h3", {}, "New hub rule for automatic grants"), hint, form);
|
||||
return controlsPage({tools: [dom.tools], rules: [dom.settings, ruleCard, dom.patterns], groups: [dom.groups, dom.sets]}, dom.bar);
|
||||
}
|
||||
@@ -20,4 +20,29 @@
|
||||
.fw-diff .add { color: var(--ok); }
|
||||
.fw-diff .del { color: var(--bad); }
|
||||
.rule-row select.field { width: auto; max-width: 100%; min-width: 0; }
|
||||
.controls > .segmented { justify-self: start; max-width: 100%; }
|
||||
.controls > .segmented button { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.controls [role="tabpanel"][hidden], .apply-bar[hidden] { display: none; }
|
||||
.tool-groups { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr)); gap: 12px; align-items: start; }
|
||||
.tool-group { display: grid; gap: 6px; min-width: 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--sunken); }
|
||||
.tool-group h4 { margin: 0; }
|
||||
.tool-group > p { margin: 0; font-size: var(--fs-sm); }
|
||||
.tool-rows { display: grid; gap: 4px; }
|
||||
.tool-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; padding: 7px 10px; border-radius: 9px; background: var(--panel); cursor: pointer; transition: background .15s; }
|
||||
.tool-row:hover { background: var(--hover); }
|
||||
.tool-row[data-staged] { box-shadow: inset 3px 0 0 var(--warn); }
|
||||
.tool-row[data-on="false"] .tool-name { color: var(--muted); }
|
||||
.tool-name { min-width: 0; font-family: var(--mono); font-size: var(--fs-sm); overflow-wrap: anywhere; }
|
||||
.switch { appearance: none; position: relative; flex: none; width: 36px; height: 20px; margin: 0; border-radius: 999px; background: var(--line-strong); cursor: pointer; transition: background .15s; }
|
||||
.switch::after { content: ""; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgb(0 0 0 / 30%); transition: transform .15s; }
|
||||
.switch:checked { background: var(--ok); }
|
||||
.switch:checked::after { transform: translateX(16px); }
|
||||
.switch:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.tool-add { display: flex; gap: 6px; min-width: 0; }
|
||||
.tool-add .field { flex: 1; min-width: 0; }
|
||||
.apply-bar { position: sticky; bottom: var(--sp-3); z-index: 5; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px 12px; border: 1px solid var(--line-strong); border-radius: 14px; background: var(--glass-card); box-shadow: var(--shadow-lift); backdrop-filter: blur(10px); }
|
||||
.apply-list { flex: 1 1 260px; min-width: 0; }
|
||||
.apply-list > summary { font-weight: 600; cursor: pointer; }
|
||||
.apply-list ul { max-height: 40vh; margin: 8px 0 0; overflow: auto; }
|
||||
@media (prefers-reduced-motion: reduce) { .tool-row, .switch, .switch::after { transition: none; } }
|
||||
.passkey-prompt { position: fixed; top: 18px; left: 50%; z-index: 60; width: min(440px, calc(100vw - 36px)); transform: translateX(-50%); }
|
||||
@@ -26,7 +26,7 @@ WIDTHS = ((1920, 1080), (1366, 768), (390, 844))
|
||||
VIEWS = ("orbit", "chord", "swimlane", "tree", "3d")
|
||||
TASK_VIEWS = ("list", "board", "rasci", "gantt", "burn", "3d")
|
||||
SCREENS = ["home", "stream", "tasks/operator", "tasks/match", "stream/rules", *(f"{tab}/{view}" for tab in ("agents", "artifacts") for view in VIEWS), "agents/hierarchy", *(f"tasks/{view}" for view in TASK_VIEWS), "resources"]
|
||||
SUBS = ["Firewall"]
|
||||
SUBS = ["Controls"]
|
||||
TABS = ["Home", "Stream", "Agents", "Artifacts", "Tasks", "Resources"]
|
||||
HELPERS = """
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
@@ -23,6 +23,9 @@ SECRET = ORIGINAL["env"]["EXAMPLE_FLAG"]
|
||||
ASKED = ["Bash(make deploy:*)", "Bash(make clean:*)", "Bash(git push:*)"]
|
||||
SHOW = """(async () => {@HELPERS@
|
||||
await screenShown(8000);
|
||||
const tabs = () => all('#main [role="tab"]').map((node) => [node.dataset.tab, node.getAttribute("aria-selected"), document.getElementById(node.getAttribute("aria-controls")).hidden]);
|
||||
const first = tabs();
|
||||
document.querySelector('#main [role="tab"][data-tab="rules"]').click();
|
||||
const ready = await until(() => all("#main table.fw-table tbody[data-source]").length > 1, 10000);
|
||||
if (!ready) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
@@ -45,6 +48,7 @@ SHOW = """(async () => {@HELPERS@
|
||||
await sleep(100);
|
||||
return {
|
||||
title: text(document.querySelector("#main h2.title")),
|
||||
tabs: {first, picked: tabs()},
|
||||
subs: all("#tabs .subtabs button").map(name),
|
||||
sources,
|
||||
folded,
|
||||
@@ -75,7 +79,7 @@ SIGN = """(async () => {@HELPERS@
|
||||
form.requestSubmit();
|
||||
await sleep(100);
|
||||
const staged = all('#main [aria-label="Staged changes"] li').map((node) => node.dataset.staged);
|
||||
document.querySelector('#main button[aria-label="Review and sign"]').click();
|
||||
document.querySelector("#main .apply-bar button[data-apply]").click();
|
||||
const diff = await until(() => document.querySelector('.sheet-box [aria-label="Diff"] pre.fw-diff'), 8000);
|
||||
if (!diff) {
|
||||
return {error: "no diff", toasts: all("#toasts .toast").map(text)};
|
||||
@@ -90,6 +94,47 @@ SIGN = """(async () => {@HELPERS@
|
||||
shown.wide = document.documentElement.scrollWidth > innerWidth + 1;
|
||||
return shown;
|
||||
})()"""
|
||||
TOOLS = """(async () => {@HELPERS@
|
||||
await screenShown(8000);
|
||||
const rowOf = (name) => document.querySelector(`#main .tool-row[data-tool="${name}"]`);
|
||||
const flip = async (name, staged) => {
|
||||
rowOf(name).querySelector("input.switch").click();
|
||||
return until(() => rowOf(name).hasAttribute("data-staged") === staged, 4000);
|
||||
};
|
||||
if (!await until(() => rowOf("blender"), 10000)) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
const rows = () => all("#main .tool-row").map((node) => [node.closest("[data-list]").dataset.list, node.dataset.tool, node.dataset.on, node.hasAttribute("data-staged")]);
|
||||
const bar = () => document.querySelector("#main .apply-bar");
|
||||
const found = {before: rows(), hidden: bar().hidden};
|
||||
await flip("blender", true);
|
||||
await flip("caveman@caveman", true);
|
||||
await flip("caveman@caveman", false);
|
||||
await flip("enableArtifact", true);
|
||||
found.staged = {rows: rows(), apply: text(bar().querySelector("button[data-apply]")), hidden: bar().hidden, list: all("li code", bar()).map(text)};
|
||||
found.wide = document.documentElement.scrollWidth > innerWidth + 1;
|
||||
found.unlabelled = all("#main input.switch").filter((node) => !node.getAttribute("aria-label")).length;
|
||||
if (!@SIGN@) {
|
||||
bar().querySelector('button[aria-label="Discard"]').click();
|
||||
found.discarded = {hidden: bar().hidden, rows: rows()};
|
||||
return found;
|
||||
}
|
||||
bar().querySelector("button[data-apply]").click();
|
||||
const diff = await until(() => document.querySelector('.sheet-box [aria-label="Diff"] pre.fw-diff'), 8000);
|
||||
if (!diff) {
|
||||
return {...found, error: "no diff", toasts: all("#toasts .toast").map(text)};
|
||||
}
|
||||
const lines = (cls) => all(`span.${cls}`, diff).map((node) => node.textContent.trim());
|
||||
found.added = lines("add");
|
||||
found.removed = lines("del");
|
||||
document.querySelector('.sheet-box button[aria-label="Sign and apply"]').click();
|
||||
const done = await until(() => document.querySelector(".sheet-box [data-result]"), 30000);
|
||||
found.result = done ? done.dataset.result : null;
|
||||
found.after = await until(() => rowOf("blender") && rowOf("blender").dataset.on === "false" && !rowOf("blender").hasAttribute("data-staged") && rows(), 15000);
|
||||
found.barAfter = bar().hidden;
|
||||
found.secret = document.documentElement.innerHTML.includes("fixture-secret");
|
||||
return found;
|
||||
})()"""
|
||||
GROUP_RULE = """(async () => {@HELPERS@
|
||||
const prompts = [];
|
||||
new MutationObserver((records) => records.forEach((record) => record.addedNodes.forEach((node) => {
|
||||
@@ -244,7 +289,8 @@ class TestFirewallE2E(HubCase):
|
||||
shown, signed = data["results"][2 * index : 2 * index + 2]
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", shown, shown)
|
||||
self.assertEqual((shown["title"], shown["subs"]), ("Firewall", base.SUBS))
|
||||
self.assertEqual((shown["title"], shown["subs"]), ("Controls", base.SUBS))
|
||||
self.assertEqual(shown["tabs"], {"first": [["tools", "true", False], ["rules", "false", True], ["groups", "false", True]], "picked": [["tools", "false", True], ["rules", "true", False], ["groups", "false", True]]})
|
||||
self.assertEqual(shown["sources"], ["hub", str(self.settings), str(self.outside / "demo" / ".claude" / "settings.json")])
|
||||
self.assertEqual(shown["folded"], {"expanded": ["false"] * 3, "rows": 0})
|
||||
self.assertEqual(shown["opened"], ["true"] * 3)
|
||||
@@ -280,6 +326,36 @@ class TestFirewallE2E(HubCase):
|
||||
backups = sorted(self.settings.parent.glob("settings.json.before-firewall-*"))
|
||||
self.assertEqual((len(backups), self.settings.stat().st_mode & 0o777), (3, 0o640))
|
||||
|
||||
def test_chromium_switches_tools_stages_them_in_the_apply_bar_and_signs_them_at_three_widths(self):
|
||||
home = self.settings.parent.parent
|
||||
(home / ".claude.json").write_text(json.dumps({"mcpServers": {"blender": {"command": "fixture-secret-command"}}, "claudeAiMcpEverConnected": ["claude.ai Google Drive"]}), encoding="utf-8")
|
||||
(home / ".claude" / "plugins").mkdir()
|
||||
(home / ".claude" / "plugins" / "installed_plugins.json").write_text(json.dumps({"plugins": {"caveman@caveman": []}}), encoding="utf-8")
|
||||
self.settings.write_text(json.dumps({**ORIGINAL, "enabledPlugins": {"caveman@caveman": True}}, indent=2) + "\n", encoding="utf-8")
|
||||
verifier.write_private(self.spool / "view.json", self.writer.view())
|
||||
authenticator = self.authenticator()
|
||||
self.beside(self.host_unit)
|
||||
steps = [{"width": width, "height": height, "url": f"{self.page_url}?{width}#stream/rules", "wait": 1500, "probe": probe(TOOLS, {"SIGN": "true" if width == 390 else "false"}), "shot": str(OUT / f"chromium-{width}-controls-tools.png")} for width, height in base.WIDTHS]
|
||||
data = self.drive(steps, authenticator)
|
||||
(OUT / "chromium-controls-tools.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual(data["errors"], [])
|
||||
before = [["deniedMcpServers", "blender", "true", False], ["deniedMcpServers", "claude.ai Google Drive", "true", False], ["enabledPlugins", "caveman@caveman", "true", False], ["switches", "enableArtifact", "true", False]]
|
||||
staged = [["deniedMcpServers", "blender", "false", True], before[1], before[2], ["switches", "enableArtifact", "false", True]]
|
||||
for (width, _), found in zip(base.WIDTHS, data["results"], strict=True):
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual((found["before"], found["hidden"]), (before, True))
|
||||
self.assertEqual(found["staged"], {"rows": staged, "apply": "Apply (2)", "hidden": False, "list": ["Block server blender", "Turn off Artifacts"]})
|
||||
self.assertEqual((found["wide"], found["unlabelled"]), (False, 0))
|
||||
if width != 390:
|
||||
self.assertEqual(found["discarded"], {"hidden": True, "rows": before})
|
||||
signed = data["results"][-1]
|
||||
self.assertTrue(any('"serverName": "blender"' in line for line in signed["added"]), signed["added"])
|
||||
self.assertTrue(any('"enableArtifact": false' in line for line in signed["added"]), signed["added"])
|
||||
self.assertEqual((signed["result"], signed["after"], signed["barAfter"], signed["secret"]), ("done", [[*row[:3], False] for row in staged], True, False), signed)
|
||||
written = json.loads(self.settings.read_text(encoding="utf-8"))
|
||||
self.assertEqual(written, {**ORIGINAL, "enabledPlugins": {"caveman@caveman": True}, "deniedMcpServers": [{"serverName": "blender"}], "enableArtifact": False})
|
||||
|
||||
def test_chromium_names_a_group_and_signs_a_rule_for_it(self):
|
||||
authenticator = self.authenticator()
|
||||
steps = [{"width": 1366, "height": 768, "url": f"{self.page_url}#stream/rules", "wait": 1500, "probe": probe(GROUP_RULE, {}), "shot": str(OUT / "chromium-1366-firewall-group-rule.png")}]
|
||||
|
||||
@@ -206,7 +206,7 @@ class TestOrchestratorE2E(base.OrchestratorE2ECase):
|
||||
self.assertEqual(actions["ambience"], ["sky-look", "music-toggle", "leitstand", "notify"])
|
||||
self.assertEqual((actions["settingsUnlabelled"], actions["popupUnlabelled"]), (0, 0))
|
||||
self.assertEqual((actions["sections"], actions["radioFields"]), (["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"], 0))
|
||||
for tool in ("Radio …", "Cancel mayday", "Priority …", "Drain", "Suspend", "Resume", "Firewall …", "Settings …", "Look at the sky", "Toggle control room", "Enable notifications"):
|
||||
for tool in ("Radio …", "Cancel mayday", "Priority …", "Drain", "Suspend", "Resume", "Controls …", "Settings …", "Look at the sky", "Toggle control room", "Enable notifications"):
|
||||
with self.subTest(tool=tool):
|
||||
self.assertTrue(any(tool in entry for entry in actions["palette"]), actions["palette"])
|
||||
self.assertEqual(actions["popup"], [["post", True], ["call", False]])
|
||||
|
||||
@@ -189,7 +189,7 @@ class TestWorkbenchOperatorTasks(HubCase):
|
||||
self.assertEqual(feedback["labels"], {"float": [], "menu": [], "sheet": []})
|
||||
with self.subTest(browser=browser, width=width):
|
||||
self.assertNotIn("error", tasks, tasks)
|
||||
self.assertEqual((tasks["hash"], tasks["tabs"], tasks["subs"], tasks["streamInbox"], tasks["current"]), ("#tasks/operator", base.TABS, ["Firewall"], False, ["Tasks"]))
|
||||
self.assertEqual((tasks["hash"], tasks["tabs"], tasks["subs"], tasks["streamInbox"], tasks["current"]), ("#tasks/operator", base.TABS, ["Controls"], False, ["Tasks"]))
|
||||
self.assertRegex(tasks["badge"] or "", r"^[1-9][0-9]*$")
|
||||
self.assertEqual((tasks["kinds"], tasks["boxes"]), (["k-review", "k-operator", "k-ask"], [True, True, True]))
|
||||
operator = tasks["operator"]
|
||||
|
||||
@@ -132,7 +132,7 @@ class TestHubContextMenu(unittest.TestCase):
|
||||
self.assertEqual(self.data["operator"], "agents")
|
||||
|
||||
def test_a_sub_screen_takes_the_items_of_its_tab(self):
|
||||
self.assertEqual(self.data["rules"], [["stream", "Stream", ["View: Stream › Firewall", "Stream: For you", "Stream: Mine", "Firewall …"]], ["general", "General", GENERAL]])
|
||||
self.assertEqual(self.data["rules"], [["stream", "Stream", ["View: Stream › Controls", "Stream: For you", "Stream: Mine", "Controls …"]], ["general", "General", GENERAL]])
|
||||
|
||||
def test_every_palette_item_has_a_scope_and_the_palette_still_lists_them_all(self):
|
||||
palette = self.data["palette"]
|
||||
|
||||
@@ -240,6 +240,54 @@ class TestHubFirewall(HubCase):
|
||||
self.assertEqual(status, 400, body)
|
||||
self.assertIn(reason, body.decode("utf-8"))
|
||||
|
||||
def test_the_tools_tab_switches_servers_plugins_and_features_of_the_own_file_only(self):
|
||||
capabilities = {"deniedMcpServers": [{"serverName": "blender"}], "enabledPlugins": {"caveman@caveman": True, "ponytail@ponytail": False}}
|
||||
project_tools = {"deniedMcpServers": [{"serverName": "kvb-orchestrator"}], "enabledPlugins": {"ponytail@ponytail": True, "caveman@caveman": True}, "enableArtifact": False}
|
||||
files = [{**self.home_view(), "own": True, "settings": {**self.home_view()["settings"], **capabilities}}, {"path": PROJECT_FILE, "exists": False, "sha256": "", "error": "", "settings": project_tools, "own": False}]
|
||||
known = {"servers": ["blender", "kvb-orchestrator", "hid\u200bden", 5], "plugins": ["caveman@caveman", "tokeneconomizer@tokeneconomizer", "no id"]}
|
||||
(self.state / "firewall" / "view.json").write_text(json.dumps({"written": time.time(), "files": files, "known": known}), encoding="utf-8")
|
||||
tools = self.firewall()["tools"]
|
||||
overridden = {(group["list"], row["name"]): row["overrides"] for group in tools["groups"] for row in group["rows"] if row["overrides"]}
|
||||
self.assertEqual(overridden, {
|
||||
("deniedMcpServers", "kvb-orchestrator"): [{"file": PROJECT_FILE, "on": False}],
|
||||
("enabledPlugins", "ponytail@ponytail"): [{"file": PROJECT_FILE, "on": True}],
|
||||
("switches", "enableArtifact"): [{"file": PROJECT_FILE, "on": False}],
|
||||
})
|
||||
groups = {group["list"]: (group["off"], [(row["name"], row["on"]) for row in group["rows"]]) for group in tools["groups"]}
|
||||
self.assertEqual(groups, {
|
||||
"deniedMcpServers": ("add", [("blender", False), ("kvb-orchestrator", True)]),
|
||||
"enabledPlugins": ("remove", [("caveman@caveman", True), ("ponytail@ponytail", False), ("tokeneconomizer@tokeneconomizer", False)]),
|
||||
"switches": ("remove", [("enableArtifact", True)]),
|
||||
})
|
||||
changes = [{"list": "deniedMcpServers", "op": "remove", "entry": "blender"}, {"list": "enabledPlugins", "op": "add", "entry": "ponytail@ponytail"}, {"list": "switches", "op": "remove", "entry": "enableArtifact"}]
|
||||
item = {"kind": "settings", "file": HOME_FILE, "base": SHA, "changes": changes}
|
||||
status, body = self.post("/api/firewall/preview", {"items": [item]})
|
||||
self.assertEqual(status, 200, body)
|
||||
changed = {line[0] + line[1:].strip() for line in json.loads(body)["diffs"][0]["diff"].splitlines() if line[:1] in "+-" and line[:3] not in ("+++", "---")}
|
||||
self.assertLessEqual({'-"serverName": "blender"', '-"ponytail@ponytail": false', '+"ponytail@ponytail": true', '+"enableArtifact": false'}, changed)
|
||||
proof = self.pin().proof(self.prepare([item])["payload"], self.origin)
|
||||
self.assertEqual(self.post("/api/firewall/settings", {"items": [item], "proof": proof})[0], 202)
|
||||
project = {"kind": "settings", "file": PROJECT_FILE, "base": "", "changes": [{"list": "deniedMcpServers", "op": "add", "entry": "blender"}]}
|
||||
for name, items, reason in (
|
||||
("project file", [project], "only in ~/.claude/settings.json"),
|
||||
("chained name", [{**item, "changes": [{**changes[0], "op": "add", "entry": "x;rm"}]}], "no valid deniedMcpServers name"),
|
||||
("unknown switch", [{**item, "changes": [{**changes[2], "entry": "hooks"}]}], "no valid switches name"),
|
||||
("already on", [{**item, "changes": [{**changes[1], "entry": "caveman@caveman"}]}], "enabled already"),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
status, body = self.post("/api/firewall/preview", {"items": items})
|
||||
self.assertEqual(status, 400, body)
|
||||
self.assertIn(reason, body.decode("utf-8"))
|
||||
broken = {**files[0], "settings": {**files[0]["settings"], "enabledPlugins": None, "deniedMcpServers": None}}
|
||||
(self.state / "firewall" / "view.json").write_text(json.dumps({"written": time.time(), "files": [broken], "known": known}), encoding="utf-8")
|
||||
rows = {group["list"]: [row["name"] for row in group["rows"]] for group in self.firewall()["tools"]["groups"]}
|
||||
self.assertEqual(rows["enabledPlugins"], ["caveman@caveman", "tokeneconomizer@tokeneconomizer"])
|
||||
status, body = self.post("/api/firewall/preview", {"items": [{**item, "changes": changes[1:2]}]})
|
||||
self.assertEqual(status, 400, body)
|
||||
self.assertIn("holds the wrong type", body.decode("utf-8"))
|
||||
(self.state / "firewall" / "view.json").write_text(json.dumps({"written": time.time(), "files": [{**files[0], "own": "yes"}], "known": known}), encoding="utf-8")
|
||||
self.assertIsNone(self.firewall()["tools"])
|
||||
|
||||
def test_groups_and_rule_sets_hold_known_agents_and_stored_rules(self):
|
||||
for name, payload, expected in (
|
||||
("unknown session", {"name": "builders", "members": ["s1", "s9"]}, 400),
|
||||
|
||||
@@ -66,7 +66,7 @@ class TestNavModule(unittest.TestCase):
|
||||
cls.data = json.loads(done.stdout)
|
||||
|
||||
def test_the_navigation_has_six_entries_home_first_and_no_inbox_and_stream_keeps_only_the_firewall(self):
|
||||
stream = ["stream", "Stream", [["rules", "Firewall"]]]
|
||||
stream = ["stream", "Stream", [["rules", "Controls"]]]
|
||||
self.assertEqual(self.data["tabs"], [["home", "Home", []], stream, ["agents", "Agents", []], ["artifacts", "Artifacts", []], ["tasks", "Tasks", []], ["resources", "Resources", []]])
|
||||
self.assertNotIn("inbox", json.dumps(self.data["tabs"]))
|
||||
|
||||
|
||||
@@ -461,6 +461,77 @@ class TestSettingsWriter(unittest.TestCase):
|
||||
self.assertEqual((project["exists"], project["sha256"], project["settings"]), (False, "", {}))
|
||||
self.assertNotIn("fixture-value-not-a-secret", json.dumps(view))
|
||||
|
||||
def test_a_signed_tool_switch_changes_only_its_key_of_the_own_file_and_never_a_project_file(self):
|
||||
url = {"serverUrl": "https://mcp.example.org/fixture-token-not-a-secret"}
|
||||
self.settings.write_text(json.dumps({**ORIGINAL, "deniedMcpServers": [url], "enabledPlugins": {"a@m": True, "b@m": False}}), encoding="utf-8")
|
||||
off = [
|
||||
{"list": "deniedMcpServers", "op": "add", "entry": "claude.ai Google Drive"},
|
||||
{"list": "enabledPlugins", "op": "remove", "entry": "a@m"},
|
||||
{"list": "enabledPlugins", "op": "add", "entry": "b@m"},
|
||||
{"list": "switches", "op": "remove", "entry": "enableArtifact"},
|
||||
]
|
||||
self.assertEqual(self.signed(self.item(self.settings, off))["status"], "done")
|
||||
written = json.loads(self.settings.read_text(encoding="utf-8"))
|
||||
self.assertEqual(written, {**ORIGINAL, "deniedMcpServers": [url, {"serverName": "claude.ai Google Drive"}], "enabledPlugins": {"a@m": False, "b@m": True}, "enableArtifact": False})
|
||||
for name, changes in (("blocked twice", off[:1]), ("disabled twice", off[1:2]), ("off twice", off[3:])):
|
||||
with self.subTest(name=name):
|
||||
self.assertIn("already", self.signed(self.item(self.settings, changes))["reason"])
|
||||
back = [{**off[0], "op": "remove"}, {**off[3], "op": "add"}]
|
||||
self.assertEqual(self.signed(self.item(self.settings, back))["status"], "done")
|
||||
self.assertEqual(json.loads(self.settings.read_text(encoding="utf-8")), {key: value for key, value in written.items() if key != "enableArtifact"} | {"deniedMcpServers": [url]})
|
||||
result = self.signed({"file": str(self.project_settings), "base": "", "changes": off[3:]})
|
||||
self.assertEqual((result["status"], result["reason"], self.project_settings.exists()), ("refused", "MCP servers, plugins and switches change only in ~/.claude/settings.json", False))
|
||||
for name, change in (("chained name", {**off[0], "entry": "x;rm -rf /"}), ("hidden character", {**off[0], "entry": "blen\u200bder"}), ("unknown switch", {**off[3], "entry": "hooks"}), ("no plugin id", {**off[1], "entry": "a"})):
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(self.run_job([self.item(self.settings, [change])], None)["error"], "malformed job: refused, nothing changed")
|
||||
|
||||
def test_the_view_marks_the_own_file_and_names_known_servers_and_plugins_but_no_value(self):
|
||||
config = {
|
||||
"mcpServers": {"user-server": {"env": {"TOKEN": "fixture-secret-one"}}},
|
||||
"projects": {"/p": {"mcpServers": {"project-server": {"command": "run --token fixture-secret-two"}}}, "/q": "junk"},
|
||||
"claudeAiMcpEverConnected": ["claude.ai Google Drive", "hid\u200bden", 5],
|
||||
"oauthAccount": {"key": "fixture-secret-three"},
|
||||
}
|
||||
(self.home / ".claude.json").write_text(json.dumps(config), encoding="utf-8")
|
||||
(self.home / ".claude" / "plugins").mkdir()
|
||||
(self.home / ".claude" / "plugins" / "installed_plugins.json").write_text(json.dumps({"plugins": {"caveman@caveman": [{"installPath": "/x"}], "no id": []}}), encoding="utf-8")
|
||||
capabilities = {"deniedMcpServers": [{"serverName": "blender"}, {"serverUrl": "https://h/fixture-secret-four"}], "enabledPlugins": {"caveman@caveman": True, "x@y": "yes"}, "enableArtifact": False}
|
||||
self.settings.write_text(json.dumps({**ORIGINAL, **capabilities}), encoding="utf-8")
|
||||
view = self.writer.view()
|
||||
self.assertEqual(view["known"], {"servers": ["claude.ai Google Drive", "project-server", "user-server"], "plugins": ["caveman@caveman"]})
|
||||
self.assertEqual([entry["own"] for entry in view["files"]], [True, False])
|
||||
shown = view["files"][0]["settings"]
|
||||
self.assertEqual({name: shown[name] for name in capabilities}, {"deniedMcpServers": [{"serverName": "blender"}], "enabledPlugins": {"caveman@caveman": True, "x@y": None}, "enableArtifact": False})
|
||||
self.assertNotIn("fixture-secret", json.dumps(view))
|
||||
config_file = self.home / ".claude.json"
|
||||
for name, make in (("no json", lambda: config_file.write_text("{not json", encoding="utf-8")), ("fifo", lambda: os.mkfifo(config_file)), ("link to /dev/zero", lambda: config_file.symlink_to("/dev/zero"))):
|
||||
with self.subTest(name=name):
|
||||
config_file.unlink()
|
||||
make()
|
||||
self.assertEqual(self.writer.view()["known"]["servers"], [])
|
||||
|
||||
def test_a_tool_value_of_the_wrong_type_is_refused_in_the_view_as_in_the_file_and_an_unblock_drops_every_copy(self):
|
||||
for name, value, change in (
|
||||
("plugins null", {"enabledPlugins": None}, {"list": "enabledPlugins", "op": "add", "entry": "a@m"}),
|
||||
("plugins list", {"enabledPlugins": []}, {"list": "enabledPlugins", "op": "add", "entry": "a@m"}),
|
||||
("plugin value list", {"enabledPlugins": {"a@m": ["x"]}}, {"list": "enabledPlugins", "op": "add", "entry": "a@m"}),
|
||||
("servers null", {"deniedMcpServers": None}, {"list": "deniedMcpServers", "op": "add", "entry": "blender"}),
|
||||
("switch text", {"enableArtifact": "false"}, {"list": "switches", "op": "remove", "entry": "enableArtifact"}),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
self.settings.write_text(json.dumps({**ORIGINAL, **value}), encoding="utf-8")
|
||||
shown = self.writer.view()["files"][0]["settings"]
|
||||
for settings in (shown, json.loads(self.settings.read_text(encoding="utf-8"))):
|
||||
with self.assertRaisesRegex(signing.Refused, "holds the wrong type"):
|
||||
signing.apply_changes(settings, [change])
|
||||
self.assertEqual(self.signed(self.item(self.settings, [change]))["status"], "refused")
|
||||
self.settings.write_text(json.dumps({**ORIGINAL, "deniedMcpServers": [{"serverName": "dup"}, {"serverName": "dup"}]}), encoding="utf-8")
|
||||
self.assertEqual(self.signed(self.item(self.settings, [{"list": "deniedMcpServers", "op": "remove", "entry": "dup"}]))["status"], "done")
|
||||
self.assertEqual(json.loads(self.settings.read_text(encoding="utf-8"))["deniedMcpServers"], [])
|
||||
for entry in ("https://u:tok@h/p", "a b", "a ", "x" * 129):
|
||||
with self.subTest(entry=entry):
|
||||
self.assertIsNotNone(signing.change_problem({"list": "deniedMcpServers", "op": "add", "entry": entry}))
|
||||
|
||||
def test_a_missing_directory_shows_in_the_view_as_the_writer_handles_it(self):
|
||||
self.project_settings.parent.rmdir()
|
||||
shown = self.writer.view()["files"][1]
|
||||
|
||||
Reference in new issue
Block a user