feat(hub): the permission hook asks for every tool and signs its whole input
The PermissionRequest hook now registers for every tool (matcher *); make orchestrator-check reports an entry that matches less. What the hub shows and the passkey signs is a Bash call's command when it sets nothing beyond command, description, timeout and run_in_background, else the whole tool input as sorted JSON, so an allow never covers a value the operator did not see (before, an Edit was signed by its file_path alone). The inbox, the stream and Match show an ask like Claude Code's dialog: 1 Yes, 2 No and 'Tell Claude what to do instead', whose text denies with it as the reason. README describes it.
Stacked on dialog (88e53ac); applied cleanly. ruff, node --check and bash -n pass.
Break: an auto-approval rule that matched a non-Bash tool by its path alone no longer matches the JSON summary, so that call asks instead of passing (fails closed). The matcher change takes effect with make orchestrator-hook.
Tests: test_hub_asks, test_hub_decision_rows, test_hub_grant_mode, test_hub_inbox_gone, test_hub_operator_tasks and the Match waiting e2e updated. Written, not run: the full suite runs once on master after all bundles (operator order).
Security: MEDUSA over the staged tree on master: 100, no findings, all 12 files covered.
🎯 Fix: 90 %
💥 Break: 5 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 86
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
88e53ac51f
commit
aa4a337c9a
12 files changed
+119
-38
No files matched your search
@@ -480,7 +480,7 @@ The Tasks tab (key 4, `#tasks/list`, `#tasks/board`, `#tasks/rasci`) shows the `
|
|||||||
|
|
||||||
Without reinstalling the skills, `make orchestrator-install` installs, builds and starts only the hub, `make orchestrator-check` checks the installed hub (image, container, logs, HTTP, pinned keys, hook, runner, tree timer, disk; exit 1 on a failure), `make orchestrator-pin CREDENTIAL=<blob>` pins the passkey that "Register passkey" shows, `make orchestrator-runner` enables the runner service, and `make orchestrator-hook` registers the PermissionRequest hook in `~/.claude/settings.json`, replacing an earlier Agent Orchestrator entry and keeping the file mode, after a copy to `settings.json.before-kvb-orchestrator-hook` (Claude Code reads `~/.claude/settings.local.json` only in sessions started in the home directory). Agents that reach the Docker socket are root-equivalent: until the agent VMs of core requirement 093 isolate them, the signatures do not hold against such an agent. `make watch-check` shows whether the resource watch hook is stuck (running hooks, holders of the kept queue history, age of the stored stage).
|
Without reinstalling the skills, `make orchestrator-install` installs, builds and starts only the hub, `make orchestrator-check` checks the installed hub (image, container, logs, HTTP, pinned keys, hook, runner, tree timer, disk; exit 1 on a failure), `make orchestrator-pin CREDENTIAL=<blob>` pins the passkey that "Register passkey" shows, `make orchestrator-runner` enables the runner service, and `make orchestrator-hook` registers the PermissionRequest hook in `~/.claude/settings.json`, replacing an earlier Agent Orchestrator entry and keeping the file mode, after a copy to `settings.json.before-kvb-orchestrator-hook` (Claude Code reads `~/.claude/settings.local.json` only in sessions started in the home directory). Agents that reach the Docker socket are root-equivalent: until the agent VMs of core requirement 093 isolate them, the signatures do not hold against such an agent. `make watch-check` shows whether the resource watch hook is stuck (running hooks, holders of the kept queue history, age of the stored stage).
|
||||||
|
|
||||||
For approvals the hub is only a relay: every approval of an ask, a staged commit or an operator command is signed end to end with a WebAuthn passkey held in KeePassXC (through KeePassXC-Browser, relying party `localhost`, origin `http://localhost:<port>`; ES256, EdDSA and RS256, so a hardware key can be pinned beside it). To register, open the hub at `http://localhost:<port>/` (WebAuthn needs the domain; on `127.0.0.1` the page links there), choose "Register passkey" in the settings and run the host command the page shows, `python3 ~/.local/share/kvb-orchestrator/client/approval.py pin --port <port> --approvers ~/.config/kvb-orchestrator/approvers.json --credential '<blob>'`, in a terminal outside every sandbox: it pins the key in `~/.config/kvb-orchestrator/approvers.json` with mode 0600, a file no sandboxed agent can write and the hub mounts read-only; the hub never pins. Each approval, or one bulk selection, is one signature over the hashes of every item, a nonce and an expiry; each auto-approval rule is signed once. In the inbox, an operator command run with "Run" shows the runner's output in a console under its row until "Close". "Deny" on an ask, an operator row or a rule request signs the denial with its channel and optional reason (a hash no approval shares) and, after the 3 s undo, tells the requesting agent by post or by the radio class picked, never mayday; the hub verifies that signature against the pinned keys before it stores or sends anything, the hook passes the reason on only when it verifies the signature too, and a denied operator row ends as `stopped`. Agents ask for an auto-approval rule with the MCP tool `rule_request` (the rules form's limits; a request stays open for the ask lifetime of one hour, at most 20 in all, and 3 per agent name, which only spreads the queue since MCP names no caller); its row shows a dry run over the last 7 days, and only "Accept" with the passkey stores it. The hub stores no rule, of any kind, whose passkey assertion it cannot verify. The executors verify it themselves against the pinned keys and fail closed: the runner (`client/runner.py`, the `kvb-orchestrator-runner` user service) runs only signed commands, each signature once, recorded in `~/.local/state/kvb-orchestrator-approvals/runner.json`; the PermissionRequest hook (`client/permission_hook.py --port <port> --timeout <seconds> --approvers ~/.config/kvb-orchestrator/approvers.json --replay ~/.local/state/kvb-orchestrator-approvals/hook.json`) allows only a signed item that matches its own tool, command, cwd and session, else it leaves the decision to Claude Code's own prompt, and turns each question of an AskUserQuestion call into a decision card that expires with its timeout, answering the call only once a pinned key signed the pick of every question (a multi-select card toggles options and sends them with one signature, and every such card also takes one signed line of "Other" text); the commit skills run `approval.py verify` on the staged tree before committing, else they ask in the terminal. With no key pinned, every executor refuses; review rejections and a decision a rule takes stay unsigned. A signed rule never covers a command holding `;`, `&`, `|`, a backtick, `$`, `<`, `>`, parentheses or a line break: such a command always asks. The hub page is trusted while it asks for a signature or shows the blob to pin: whoever controls the hub container can show one item and have another signed, or hand over a key of its own. Any local process, sandboxed agents included, can also send the unsigned operator actions (the bare decision choice `/api/decisions/<id>/choose`, which sends no answer, the priority order, settings that add no stream origin, review rejections, the bare ask denial `/api/asks/<id>/deny`, console dismissals) with the hub's guard headers, and the container reads the review pages from `pages/` of the council root, which every sandboxed agent can write; it mounts the council root at its host path and no longer reads the host `/tmp`. All three close with the agent VMs of core requirement 093, like the Docker-socket gap.
|
For approvals the hub is only a relay: every approval of an ask, a staged commit or an operator command is signed end to end with a WebAuthn passkey held in KeePassXC (through KeePassXC-Browser, relying party `localhost`, origin `http://localhost:<port>`; ES256, EdDSA and RS256, so a hardware key can be pinned beside it). To register, open the hub at `http://localhost:<port>/` (WebAuthn needs the domain; on `127.0.0.1` the page links there), choose "Register passkey" in the settings and run the host command the page shows, `python3 ~/.local/share/kvb-orchestrator/client/approval.py pin --port <port> --approvers ~/.config/kvb-orchestrator/approvers.json --credential '<blob>'`, in a terminal outside every sandbox: it pins the key in `~/.config/kvb-orchestrator/approvers.json` with mode 0600, a file no sandboxed agent can write and the hub mounts read-only; the hub never pins. Each approval, or one bulk selection, is one signature over the hashes of every item, a nonce and an expiry; each auto-approval rule is signed once. In the inbox, an operator command run with "Run" shows the runner's output in a console under its row until "Close". "Deny" on an ask, an operator row or a rule request signs the denial with its channel and optional reason (a hash no approval shares) and, after the 3 s undo, tells the requesting agent by post or by the radio class picked, never mayday; the hub verifies that signature against the pinned keys before it stores or sends anything, the hook passes the reason on only when it verifies the signature too, and a denied operator row ends as `stopped`. Agents ask for an auto-approval rule with the MCP tool `rule_request` (the rules form's limits; a request stays open for the ask lifetime of one hour, at most 20 in all, and 3 per agent name, which only spreads the queue since MCP names no caller); its row shows a dry run over the last 7 days, and only "Accept" with the passkey stores it. The hub stores no rule, of any kind, whose passkey assertion it cannot verify. The executors verify it themselves against the pinned keys and fail closed: the runner (`client/runner.py`, the `kvb-orchestrator-runner` user service) runs only signed commands, each signature once, recorded in `~/.local/state/kvb-orchestrator-approvals/runner.json`; the PermissionRequest hook (`client/permission_hook.py --port <port> --timeout <seconds> --approvers ~/.config/kvb-orchestrator/approvers.json --replay ~/.local/state/kvb-orchestrator-approvals/hook.json`) allows only a signed item that matches its own tool, command, cwd and session, else it leaves the decision to Claude Code's own prompt; it runs for every tool, and its command is a Bash call's command line, or for any other call, and for a Bash call that sets more than its command, description, timeout and background flag, the whole tool input as sorted JSON, so a signature never covers a value the hub did not show (over 4000 characters Claude Code asks itself); the inbox, the stream and Match show an ask like Claude Code's dialog, 1 Yes, 2 No and "Tell Claude what to do instead", whose text denies with it as the reason; it also turns each question of an AskUserQuestion call into a decision card that expires with its timeout, answering the call only once a pinned key signed the pick of every question (a multi-select card toggles options and sends them with one signature, and every such card also takes one signed line of "Other" text); the commit skills run `approval.py verify` on the staged tree before committing, else they ask in the terminal. With no key pinned, every executor refuses; review rejections and a decision a rule takes stay unsigned. A signed rule never covers a command holding `;`, `&`, `|`, a backtick, `$`, `<`, `>`, parentheses or a line break: such a command always asks. The hub page is trusted while it asks for a signature or shows the blob to pin: whoever controls the hub container can show one item and have another signed, or hand over a key of its own. Any local process, sandboxed agents included, can also send the unsigned operator actions (the bare decision choice `/api/decisions/<id>/choose`, which sends no answer, the priority order, settings that add no stream origin, review rejections, the bare ask denial `/api/asks/<id>/deny`, console dismissals) with the hub's guard headers, and the container reads the review pages from `pages/` of the council root, which every sandboxed agent can write; it mounts the council root at its host path and no longer reads the host `/tmp`. All three close with the agent VMs of core requirement 093, like the Docker-socket gap.
|
||||||
|
|
||||||
Restart your agent afterwards so it loads the new skills.
|
Restart your agent afterwards so it loads the new skills.
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,8 @@
|
|||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
stdout: the PermissionRequest decision JSON: allow only when a pinned
|
stdout: the PermissionRequest decision JSON: allow only when a pinned
|
||||||
passkey signed exactly this tool, command, cwd, session and ask id;
|
passkey signed exactly this tool, command (summary()), cwd, session
|
||||||
|
and ask id;
|
||||||
deny when the operator denied in the Agent Orchestrator, with the
|
deny when the operator denied in the Agent Orchestrator, with the
|
||||||
reason only when a pinned passkey signed it. Nothing on timeout,
|
reason only when a pinned passkey signed it. Nothing on timeout,
|
||||||
error, a missing or invalid signature, a value longer than the hub
|
error, a missing or invalid signature, a value longer than the hub
|
||||||
@@ -66,21 +67,27 @@ ALLOW = {"behavior": "allow"}
|
|||||||
REASON_LIMIT = 2000
|
REASON_LIMIT = 2000
|
||||||
FAILURES = (OSError, ValueError, staged_diff.DiffError)
|
FAILURES = (OSError, ValueError, staged_diff.DiffError)
|
||||||
QUESTION_TOOL = "AskUserQuestion"
|
QUESTION_TOOL = "AskUserQuestion"
|
||||||
|
SHELL = "Bash"
|
||||||
|
SHELL_KEYS = frozenset({"command", "description", "timeout", "run_in_background"})
|
||||||
OPTION_KEYS = ("label", "description", "preview")
|
OPTION_KEYS = ("label", "description", "preview")
|
||||||
|
|
||||||
|
|
||||||
def summary(tool_input: object) -> str:
|
def summary(tool: str, tool_input: object) -> str:
|
||||||
if isinstance(tool_input, dict):
|
"""Returns:
|
||||||
for key in ("command", "file_path", "url", "pattern", "path"):
|
What the hub shows and the passkey signs: a Bash call's command when
|
||||||
if isinstance(tool_input.get(key), str):
|
it sets nothing beyond SHELL_KEYS, else the whole input as sorted
|
||||||
return tool_input[key]
|
JSON, so an allow never covers a value the operator did not see.
|
||||||
return json.dumps(tool_input, ensure_ascii=False)
|
"""
|
||||||
|
if tool == SHELL and isinstance(tool_input, dict) and isinstance(tool_input.get("command"), str) and set(tool_input) <= SHELL_KEYS:
|
||||||
|
return tool_input["command"]
|
||||||
|
return json.dumps(tool_input, ensure_ascii=False, indent=1, sort_keys=True)
|
||||||
|
|
||||||
|
|
||||||
def facts(hook: dict) -> dict:
|
def facts(hook: dict) -> dict:
|
||||||
|
tool = str(hook.get("tool_name") or "?")
|
||||||
return {
|
return {
|
||||||
"tool": str(hook.get("tool_name") or "?"),
|
"tool": tool,
|
||||||
"command": summary(hook.get("tool_input")),
|
"command": summary(tool, hook.get("tool_input")),
|
||||||
"cwd": str(hook.get("cwd") or ""),
|
"cwd": str(hook.get("cwd") or ""),
|
||||||
"session": str(hook.get("session_id") or ""),
|
"session": str(hook.get("session_id") or ""),
|
||||||
"agent": str(hook.get("agent_type") or ""),
|
"agent": str(hook.get("agent_type") or ""),
|
||||||
@@ -88,15 +95,15 @@ def facts(hook: dict) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def commit_target(ask: dict) -> Path | None:
|
def commit_target(ask: dict) -> Path | None:
|
||||||
return staged_diff.commit_of(ask["command"], ask["cwd"]) if ask["tool"] == "Bash" and ask["cwd"] else None
|
return staged_diff.commit_of(ask["command"], ask["cwd"]) if ask["tool"] == SHELL and ask["cwd"] else None
|
||||||
|
|
||||||
|
|
||||||
def tree_target(ask: dict) -> tuple[Path, str, list[str]] | None:
|
def tree_target(ask: dict) -> tuple[Path, str, list[str]] | None:
|
||||||
return staged_diff.tree_of(ask["command"], ask["cwd"]) if ask["tool"] == "Bash" and ask["cwd"] else None
|
return staged_diff.tree_of(ask["command"], ask["cwd"]) if ask["tool"] == SHELL and ask["cwd"] else None
|
||||||
|
|
||||||
|
|
||||||
def unapprovable(ask: dict) -> bool:
|
def unapprovable(ask: dict) -> bool:
|
||||||
return ask["tool"] == "Bash" and staged_diff.names_commit(ask["command"]) and commit_target(ask) is None and tree_target(ask) is None
|
return ask["tool"] == SHELL and staged_diff.names_commit(ask["command"]) and commit_target(ask) is None and tree_target(ask) is None
|
||||||
|
|
||||||
|
|
||||||
def tree_preview(ask: dict, rules: Path | None) -> dict:
|
def tree_preview(ask: dict, rules: Path | None) -> dict:
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
|
const OTHER_PROMPT = "Other: type your own answer …";
|
||||||
|
const ALLOW = "Yes";
|
||||||
|
const TELL = "Tell Claude what to do instead";
|
||||||
|
const askDialog = (id) => ({id, options: [{label: ALLOW, description: "allow this one call"}, {label: "No", description: "deny it"}], recommended: "", multi: false});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {Object} item a decision, a decision row or a decision card: id, options [{label, description, preview}], recommended (labels joined by PICKED), multi.
|
* @param {Object} item a decision, a decision row, a decision card or a permission ask: id, options [{label, description, preview}], recommended (labels joined by PICKED), multi.
|
||||||
* @param {Object} how pick: called with the answer, one label, the toggled labels in option order joined by PICKED, or the trimmed Other text; toggled: the Set of toggled labels of a multi decision, kept by the caller across redraws; chosen: the answer given so far, "" for none; locked: whether the dialog takes no answer; hint: what an answer does, shown in the titles; group: an extra class of the option list.
|
* @param {Object} how pick: called with the answer, one label, the toggled labels in option order joined by PICKED, or the trimmed Other text, and true for the Other text only; other: the Other field's placeholder; toggled: the Set of toggled labels of a multi decision, kept by the caller across redraws; chosen: the answer given so far, "" for none; locked: whether the dialog takes no answer; hint: what an answer does, shown in the titles; group: an extra class of the option list.
|
||||||
* @returns {HTMLElement} the dialog an AskUserQuestion shows: numbered options with their description, the recommended ones tagged, a free-text Other row, Send for a multi decision, and a preview pane beside them once an option has one. The keys 1 to n pick or toggle an option, n + 1 focuses Other.
|
* @returns {HTMLElement} the dialog an AskUserQuestion shows: numbered options with their description, the recommended ones tagged, a free-text Other row, Send for a multi decision, and a preview pane beside them once an option has one. The keys 1 to n pick or toggle an option, n + 1 focuses Other.
|
||||||
*/
|
*/
|
||||||
function choiceDialog(item, how) {
|
function choiceDialog(item, how) {
|
||||||
@@ -20,7 +25,7 @@
|
|||||||
title: revealed(`${option.label}: ${how.hint}`),
|
title: revealed(`${option.label}: ${how.hint}`),
|
||||||
on: {click: () => {
|
on: {click: () => {
|
||||||
if (!item.multi) {
|
if (!item.multi) {
|
||||||
how.pick(option.label);
|
how.pick(option.label, false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
how.toggled.has(option.label) ? how.toggled.delete(option.label) : how.toggled.add(option.label);
|
how.toggled.has(option.label) ? how.toggled.delete(option.label) : how.toggled.add(option.label);
|
||||||
@@ -32,16 +37,16 @@
|
|||||||
return button;
|
return button;
|
||||||
});
|
});
|
||||||
if (send) {
|
if (send) {
|
||||||
send.addEventListener("click", () => how.pick(item.options.filter((option) => how.toggled.has(option.label)).map((option) => option.label).join(PICKED)));
|
send.addEventListener("click", () => how.pick(item.options.filter((option) => how.toggled.has(option.label)).map((option) => option.label).join(PICKED), false));
|
||||||
}
|
}
|
||||||
const typed = chosen.length === 1 && !item.options.some((option) => option.label === chosen[0]) ? chosen[0] : null;
|
const typed = chosen.length === 1 && !item.options.some((option) => option.label === chosen[0]) ? chosen[0] : null;
|
||||||
const input = h("input", {class: "field", type: "text", maxlength: OTHER_LIMIT, placeholder: "Other: type your own answer …", "aria-label": `Other answer to ${item.id}`, value: typed, disabled: how.locked});
|
const input = h("input", {class: "field", type: "text", maxlength: OTHER_LIMIT, placeholder: how.other, "aria-label": `Other answer to ${item.id}`, value: typed, disabled: how.locked});
|
||||||
const other = h("form", {class: "option other"}, input,
|
const other = h("form", {class: "option other"}, input,
|
||||||
h("button", {type: "submit", class: "btn small", disabled: how.locked, ...named("Send", revealed(`Send this text: ${how.hint}`))}, icon("bi-send"), "Send"));
|
h("button", {type: "submit", class: "btn small", disabled: how.locked, ...named("Send", revealed(`Send this text: ${how.hint}`))}, icon("bi-send"), "Send"));
|
||||||
other.addEventListener("submit", (event) => {
|
other.addEventListener("submit", (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (input.value.trim()) {
|
if (input.value.trim()) {
|
||||||
how.pick(input.value.trim());
|
how.pick(input.value.trim(), true);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const list = h("div", {class: `options dialog${how.group ? ` ${how.group}` : ""}`, role: "group", "aria-label": "Options", "data-multi": item.multi ? "" : null}, buttons, other, send);
|
const list = h("div", {class: `options dialog${how.group ? ` ${how.group}` : ""}`, role: "group", "aria-label": "Options", "data-multi": item.multi ? "" : null}, buttons, other, send);
|
||||||
|
|||||||
@@ -122,17 +122,27 @@
|
|||||||
|
|
||||||
const signsFor = (item) => `your passkey signs this answer, a post to ${item.agent}`;
|
const signsFor = (item) => `your passkey signs this answer, a post to ${item.agent}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Object} item a permission ask.
|
||||||
|
* @param {string} answer the picked label, or the typed text.
|
||||||
|
* @param {boolean} typed whether answer is typed text, which always denies with it as the reason.
|
||||||
|
*/
|
||||||
|
const answerAsk = (item, answer, typed) => (!typed && answer === ALLOW ? approveOne(item) : denyNow(item, "post", typed ? answer : ""));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {Object} item an inbox item.
|
* @param {Object} item an inbox item.
|
||||||
* @param {Function} after called before a picked answer is sent.
|
* @param {Function} after called before a picked answer is sent.
|
||||||
* @returns {HTMLElement|Array|null} the choiceDialog() of a decision or a decision row, with its recipient line for a row; null for every other item.
|
* @returns {HTMLElement|Array|null} the choiceDialog() of a decision, a decision row or a permission ask, with its recipient line for a row; null for every other item.
|
||||||
*/
|
*/
|
||||||
const choiceOf = (item, after) => {
|
const choiceOf = (item, after) => {
|
||||||
if (item.kind === "decision") {
|
if (item.kind === "decision") {
|
||||||
return choiceDialog(item, {pick: (label) => { after(); chooseOne(item, label); }, toggled: new Set(), chosen: "", locked: item.held, hint: signsFor(item), group: ""});
|
return choiceDialog(item, {pick: (label) => { after(); chooseOne(item, label); }, toggled: new Set(), chosen: "", locked: item.held, hint: signsFor(item), group: "", other: OTHER_PROMPT});
|
||||||
|
}
|
||||||
|
if (item.kind === "ask") {
|
||||||
|
return choiceDialog(askDialog(item.id), {pick: (answer, typed) => { after(); answerAsk(item, answer, typed); }, toggled: new Set(), chosen: ui.selected.has(keyOf(item)) ? ALLOW : "", locked: item.held, hint: `your passkey signs it, the answer goes to ${item.to || "its session"}`, group: "", other: TELL});
|
||||||
}
|
}
|
||||||
const told = answerOf(item);
|
const told = answerOf(item);
|
||||||
return asked(item) ? [answerTo(item), choiceDialog(item, {pick: (label) => { after(); answerRow(item, label); }, toggled: new Set(), chosen: told, locked: item.held || Boolean(told), hint: signsFor(item), group: ""})] : null;
|
return asked(item) ? [answerTo(item), choiceDialog(item, {pick: (label) => { after(); answerRow(item, label); }, toggled: new Set(), chosen: told, locked: item.held || Boolean(told), hint: signsFor(item), group: "", other: OTHER_PROMPT})] : null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -230,8 +240,6 @@
|
|||||||
if (item.kind === "review") {
|
if (item.kind === "review") {
|
||||||
grant(iconBtn("bi-check-lg", "Grant", "btn small primary", () => approveOne(item)));
|
grant(iconBtn("bi-check-lg", "Grant", "btn small primary", () => approveOne(item)));
|
||||||
buttons.push(denySplit(item));
|
buttons.push(denySplit(item));
|
||||||
} else if (item.kind === "ask") {
|
|
||||||
grant(iconBtn("bi-check-lg", "Grant", "btn small primary", () => approveOne(item)));
|
|
||||||
} else if (item.kind === "decision" && item.recommended) {
|
} else if (item.kind === "decision" && item.recommended) {
|
||||||
grant(h("button", {type: "button", class: "btn small primary", ...named(revealed(`Recommendation: ${shownPick(item.recommended)}`)), on: {click: () => approveOne(item)}}, icon("bi-check-lg"), revealed(shownPick(item.recommended))));
|
grant(h("button", {type: "button", class: "btn small primary", ...named(revealed(`Recommendation: ${shownPick(item.recommended)}`)), on: {click: () => approveOne(item)}}, icon("bi-check-lg"), revealed(shownPick(item.recommended))));
|
||||||
} else if (item.kind === "operator" && item.runnable) {
|
} else if (item.kind === "operator" && item.runnable) {
|
||||||
|
|||||||
@@ -287,7 +287,18 @@
|
|||||||
matchView.toggles.delete(key);
|
matchView.toggles.delete(key);
|
||||||
decide(card, "accept", "", label);
|
decide(card, "accept", "", label);
|
||||||
};
|
};
|
||||||
return choiceDialog({...card, id: card.ref}, {pick, toggled, chosen: kept ? kept.label : "", locked: false, hint: `picked now, sent to ${card.agent || "its agent"} at the release`, group: "match-options"});
|
return choiceDialog({...card, id: card.ref}, {pick, toggled, chosen: kept ? kept.label : "", locked: false, hint: `picked now, sent to ${card.agent || "its agent"} at the release`, group: "match-options", other: OTHER_PROMPT});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Object} card a permission ask card.
|
||||||
|
* @returns {HTMLElement} its choiceDialog(): Yes accepts, No rejects, typed text rejects with it as the feedback; all sent at the release.
|
||||||
|
*/
|
||||||
|
function matchAsk(card) {
|
||||||
|
const kept = matchView.decisions.get(cardKey(card));
|
||||||
|
const chosen = !kept ? "" : kept.verdict === "accept" ? ALLOW : kept.feedback || "No";
|
||||||
|
const pick = (answer, typed) => (!typed && answer === ALLOW ? acceptCard(card) : decide(card, "reject", typed ? answer : "", ""));
|
||||||
|
return choiceDialog(askDialog(card.ref), {pick, toggled: new Set(), chosen, locked: false, hint: `picked now, sent to ${card.agent || "its session"} at the release`, group: "match-options", other: TELL});
|
||||||
}
|
}
|
||||||
|
|
||||||
function matchPayload(card) {
|
function matchPayload(card) {
|
||||||
@@ -299,7 +310,7 @@
|
|||||||
}
|
}
|
||||||
if (card.kind === "ask") {
|
if (card.kind === "ask") {
|
||||||
return h("section", {class: "match-payload"}, h("pre", {class: "match-command"}, h("code", {}, revealed(card.command))), h("p", {class: "match-directory"}, revealed(card.directory)),
|
return h("section", {class: "match-payload"}, h("pre", {class: "match-command"}, h("code", {}, revealed(card.command))), h("p", {class: "match-directory"}, revealed(card.directory)),
|
||||||
card.warnings.length ? h("p", {class: "match-warnings"}, card.warnings.map((warning) => pill(warning, "bad"))) : null);
|
card.warnings.length ? h("p", {class: "match-warnings"}, card.warnings.map((warning) => pill(warning, "bad"))) : null, matchAsk(card));
|
||||||
}
|
}
|
||||||
if (card.kind !== "command") {
|
if (card.kind !== "command") {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
+23
-6
@@ -88,7 +88,7 @@ mode = path.stat().st_mode & 0o777 if path.exists() else 0o600
|
|||||||
entries = settings.setdefault("hooks", {}).setdefault("PermissionRequest", [])
|
entries = settings.setdefault("hooks", {}).setdefault("PermissionRequest", [])
|
||||||
entries[:] = [entry for entry in entries if not any(marker in hook.get("command", "") for hook in entry.get("hooks", []))]
|
entries[:] = [entry for entry in entries if not any(marker in hook.get("command", "") for hook in entry.get("hooks", []))]
|
||||||
if added:
|
if added:
|
||||||
entries.append({"matcher": "Bash|AskUserQuestion", "hooks":[{"type": "command", "command": added[0], "timeout": int(added[1])}]})
|
entries.append({"matcher": "*", "hooks":[{"type": "command", "command": added[0], "timeout": int(added[1])}]})
|
||||||
temporary = path.with_name(f"{path.name}.{os.getpid()}")
|
temporary = path.with_name(f"{path.name}.{os.getpid()}")
|
||||||
temporary.write_text(json.dumps(settings, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
temporary.write_text(json.dumps(settings, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||||
temporary.chmod(mode)
|
temporary.chmod(mode)
|
||||||
@@ -96,6 +96,22 @@ temporary.replace(path)
|
|||||||
PY
|
PY
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Args: settings files. Prints the matcher of every PermissionRequest entry
|
||||||
|
# whose hook runs this hub's client, one per line.
|
||||||
|
hook_matchers() {
|
||||||
|
python3 - "${NAME}/client/permission_hook.py" "$@" <<'PY'
|
||||||
|
import json, sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
marker, *paths = sys.argv[1:]
|
||||||
|
for path in (Path(name) for name in paths):
|
||||||
|
if path.is_file():
|
||||||
|
for entry in json.loads(path.read_text(encoding="utf-8")).get("hooks", {}).get("PermissionRequest", []):
|
||||||
|
if any(marker in hook.get("command", "") for hook in entry.get("hooks", [])):
|
||||||
|
print(entry.get("matcher", ""))
|
||||||
|
PY
|
||||||
|
}
|
||||||
|
|
||||||
move_once() {
|
move_once() {
|
||||||
local from="$1" to="$2"
|
local from="$1" to="$2"
|
||||||
[[ -e "${from}" ]] || return 0
|
[[ -e "${from}" ]] || return 0
|
||||||
@@ -389,12 +405,13 @@ check() {
|
|||||||
code="$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:${port}/" || true)"
|
code="$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:${port}/" || true)"
|
||||||
if [[ "${code}" == "200" ]]; then ok "http://localhost:${port}/ answers 200"; else fail "http://localhost:${port}/ answers ${code}"; fi
|
if [[ "${code}" == "200" ]]; then ok "http://localhost:${port}/ answers 200"; else fail "http://localhost:${port}/ answers ${code}"; fi
|
||||||
check_keys
|
check_keys
|
||||||
if grep -qs "${NAME}/client/permission_hook.py" "${SETTINGS}" "${LOCAL_SETTINGS}" && ! grep -qs '"Bash|AskUserQuestion"' "${SETTINGS}" "${LOCAL_SETTINGS}"; then
|
matchers="$(hook_matchers "${SETTINGS}" "${LOCAL_SETTINGS}")"
|
||||||
todo "PermissionRequest hook misses AskUserQuestion: make orchestrator-hook"
|
if [[ -z "${matchers}" ]]; then
|
||||||
elif grep -qs "${NAME}/client/permission_hook.py" "${SETTINGS}" "${LOCAL_SETTINGS}"; then
|
|
||||||
ok "PermissionRequest hook registered"
|
|
||||||
else
|
|
||||||
todo "PermissionRequest hook missing: make orchestrator-hook"
|
todo "PermissionRequest hook missing: make orchestrator-hook"
|
||||||
|
elif grep -qvx '\*' <<<"${matchers}"; then
|
||||||
|
todo "PermissionRequest hook matches only ${matchers//$'\n'/, }, not every tool: make orchestrator-hook"
|
||||||
|
else
|
||||||
|
ok "PermissionRequest hook registered for every tool"
|
||||||
fi
|
fi
|
||||||
if [[ "$(systemctl --user is-active "${RUNNER}" 2>/dev/null || true)" == "active" ]]; then
|
if [[ "$(systemctl --user is-active "${RUNNER}" 2>/dev/null || true)" == "active" ]]; then
|
||||||
ok "runner active; last lines:"
|
ok "runner active; last lines:"
|
||||||
|
|||||||
@@ -158,7 +158,7 @@ class TestMatchWaiting(HubCase):
|
|||||||
self.assertEqual(sorted(seen), sorted([PICK, ask, choice, rule]), found)
|
self.assertEqual(sorted(seen), sorted([PICK, ask, choice, rule]), found)
|
||||||
self.assertEqual({card_id: entry["kind"] for card_id, entry in seen.items()}, {PICK: "decision", ask: "ask", choice: "decision", rule: "rule"})
|
self.assertEqual({card_id: entry["kind"] for card_id, entry in seen.items()}, {PICK: "decision", ask: "ask", choice: "decision", rule: "rule"})
|
||||||
self.assertEqual(seen[ask]["chips"], ["fix=95 %", "break=2 %", "score=93", "value=1:4"], found)
|
self.assertEqual(seen[ask]["chips"], ["fix=95 %", "break=2 %", "score=93", "value=1:4"], found)
|
||||||
self.assertEqual(seen[ask]["command"], SCORED)
|
self.assertEqual((seen[ask]["command"], seen[ask]["options"]), (SCORED, ["Yes", "No"]), found)
|
||||||
self.assertEqual((seen[PICK]["options"], seen[PICK]["acts"]["Accept"], seen[PICK]["acts"]["Reject"]), (["Merge now", "Wait"], False, False), found)
|
self.assertEqual((seen[PICK]["options"], seen[PICK]["acts"]["Accept"], seen[PICK]["acts"]["Reject"]), (["Merge now", "Wait"], False, False), found)
|
||||||
self.assertEqual((seen[choice]["acts"]["Accept"], seen[choice]["acts"]["Reject"], seen[choice]["refused"]), (True, True, True), found)
|
self.assertEqual((seen[choice]["acts"]["Accept"], seen[choice]["acts"]["Reject"], seen[choice]["refused"]), (True, True, True), found)
|
||||||
self.assertEqual((seen[rule]["rule"], seen[rule]["sheet"], seen[rule]["stayed"]), (True, True, True), found)
|
self.assertEqual((seen[rule]["rule"], seen[rule]["sheet"], seen[rule]["stayed"]), (True, True, True), found)
|
||||||
|
|||||||
@@ -148,6 +148,21 @@ class TestHubAsks(HubCase):
|
|||||||
self.assertEqual(self.call("POST", f"/api/asks/{ask['id']}/deny", b"", self.guard(self.host))[0], 200)
|
self.assertEqual(self.call("POST", f"/api/asks/{ask['id']}/deny", b"", self.guard(self.host))[0], 200)
|
||||||
self.assertEqual(json.loads(self.finish(process)[1])["hookSpecificOutput"]["decision"]["behavior"], "deny")
|
self.assertEqual(json.loads(self.finish(process)[1])["hookSpecificOutput"]["decision"]["behavior"], "deny")
|
||||||
|
|
||||||
|
def test_every_tool_but_a_plain_bash_call_shows_and_signs_its_whole_input(self):
|
||||||
|
edit = {"file_path": "/repo/a.py", "old_string": "x = 1", "new_string": "x = 2\n"}
|
||||||
|
unsandboxed = {"command": "ls", "dangerouslyDisableSandbox": True}
|
||||||
|
for tool, tool_input, shown in (
|
||||||
|
("Edit", edit, '{\n "file_path": "/repo/a.py",\n "new_string": "x = 2\\n",\n "old_string": "x = 1"\n}'),
|
||||||
|
("Bash", unsandboxed, '{\n "command": "ls",\n "dangerouslyDisableSandbox": true\n}'),
|
||||||
|
("Bash", {"command": "ls", "description": "list", "timeout": 5, "run_in_background": False}, "ls"),
|
||||||
|
):
|
||||||
|
with self.subTest(tool=tool, keys=sorted(tool_input)):
|
||||||
|
process = self.hook(self.port, "20", {**HOOK, "tool_name": tool, "tool_input": tool_input})
|
||||||
|
ask = self.first_ask()
|
||||||
|
self.assertEqual((ask["tool"], ask["command"]), (tool, shown))
|
||||||
|
self.assertEqual(self.call("POST", f"/api/asks/{ask['id']}/deny", b"", self.guard(self.host))[0], 200)
|
||||||
|
self.finish(process)
|
||||||
|
|
||||||
def test_a_bad_timeout_names_the_field_the_caller_sent(self):
|
def test_a_bad_timeout_names_the_field_the_caller_sent(self):
|
||||||
status, _, body = self.post_json("/api/asks", {**ASK, "timeout": -1}, self.local())
|
status, _, body = self.post_json("/api/asks", {**ASK, "timeout": -1}, self.local())
|
||||||
self.assertEqual((status, body), (400, b"timeout must be a finite number of seconds, 0 or more\n"))
|
self.assertEqual((status, body), (400, b"timeout must be a finite number of seconds, 0 or more\n"))
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ const items = {
|
|||||||
bare: {...base, kind: "operator", id: "operator/bare", title: "decide: rename it", command: "decide: rename it", check: "decision"},
|
bare: {...base, kind: "operator", id: "operator/bare", title: "decide: rename it", command: "decide: rename it", check: "decision"},
|
||||||
orphan: {...base, kind: "operator", id: "operator/orphan", title: question, command: question, check: "decision", options, agent: ""},
|
orphan: {...base, kind: "operator", id: "operator/orphan", title: question, command: question, check: "decision", options, agent: ""},
|
||||||
run: {...base, kind: "operator", id: "operator/run", title: "make install", command: "make install", check: "manual", runnable: true},
|
run: {...base, kind: "operator", id: "operator/run", title: "make install", command: "make install", check: "manual", runnable: true},
|
||||||
|
ask: {...base, kind: "ask", id: "a-1", title: "Bash: rm -rf build", command: "rm -rf build"},
|
||||||
pick: {...base, kind: "decision", id: "d-1", title: "Layout?", deniable: false, recommended: "B", options: [{label: "A", description: "tabs", preview: "[A]\nline"}, {label: "B", description: "card", preview: "[B]"}, {label: "C", description: "none"}]},
|
pick: {...base, kind: "decision", id: "d-1", title: "Layout?", deniable: false, recommended: "B", options: [{label: "A", description: "tabs", preview: "[A]\nline"}, {label: "B", description: "card", preview: "[B]"}, {label: "C", description: "none"}]},
|
||||||
};
|
};
|
||||||
const context = {
|
const context = {
|
||||||
@@ -109,6 +110,17 @@ const results = {};
|
|||||||
results.keys = {submits: submits.splice(0), stopped, focused: document.activeElement === null ? "" : document.activeElement.tag};
|
results.keys = {submits: submits.splice(0), stopped, focused: document.activeElement === null ? "" : document.activeElement.tag};
|
||||||
press("4");
|
press("4");
|
||||||
results.keys.other = document.activeElement.tag;
|
results.keys.other = document.activeElement.tag;
|
||||||
|
const denials = [];
|
||||||
|
denyNow = (item, channel, reason) => { denials.push([item.id, channel, reason]); };
|
||||||
|
const asking = inboxItem(items.ask, 6);
|
||||||
|
results.ask = {options: shape(asking).options, other: shape(asking).other};
|
||||||
|
await optionNamed(asking, "No").fire("click");
|
||||||
|
const tell = classed(asking, "other")[0];
|
||||||
|
all(tell).find((el) => el.tag === "input").value = " Yes ";
|
||||||
|
await tell.fire("submit");
|
||||||
|
await optionNamed(asking, "Yes").fire("click");
|
||||||
|
results.ask.denials = denials.splice(0);
|
||||||
|
results.ask.grants = submits.splice(0).map((label) => label.split(":")[0]);
|
||||||
console.log(JSON.stringify(results));
|
console.log(JSON.stringify(results));
|
||||||
})().catch((error) => { console.error(error && error.stack || error); process.exit(1); });
|
})().catch((error) => { console.error(error && error.stack || error); process.exit(1); });
|
||||||
`;
|
`;
|
||||||
@@ -173,6 +185,12 @@ class TestDecisionRows(unittest.TestCase):
|
|||||||
self.assertEqual((keys["submits"], keys["stopped"], keys["focused"]), (["Choice: B"], 1, ""))
|
self.assertEqual((keys["submits"], keys["stopped"], keys["focused"]), (["Choice: B"], 1, ""))
|
||||||
self.assertEqual(keys["other"], "input")
|
self.assertEqual(keys["other"], "input")
|
||||||
|
|
||||||
|
def test_a_permission_ask_offers_yes_and_no_and_typed_text_always_denies_with_it_as_the_reason(self):
|
||||||
|
ask = self.data["ask"]
|
||||||
|
self.assertEqual((ask["options"], ask["other"]), ([["Yes", False], ["No", False]], 1))
|
||||||
|
self.assertEqual(ask["denials"], [["a-1", "post", ""], ["a-1", "post", "Yes"]])
|
||||||
|
self.assertEqual(ask["grants"], ["Grant"])
|
||||||
|
|
||||||
|
|
||||||
class TestDecisionFeed(HubCase):
|
class TestDecisionFeed(HubCase):
|
||||||
def test_the_inbox_carries_a_decision_rows_options_and_drops_malformed_ones(self):
|
def test_the_inbox_carries_a_decision_rows_options_and_drops_malformed_ones(self):
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import unittest
|
|||||||
from hub_support import HUB
|
from hub_support import HUB
|
||||||
|
|
||||||
TEMPLATES = HUB / "templates"
|
TEMPLATES = HUB / "templates"
|
||||||
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-inbox.js", "page-grant.js"]
|
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-inbox.js", "page-grant.js"]
|
||||||
PROBE = r"""
|
PROBE = r"""
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const vm = require("vm");
|
const vm = require("vm");
|
||||||
@@ -110,8 +110,8 @@ const byName = (node, label) => buttons(node).find((button) => button.getAttribu
|
|||||||
results.direct_press = press(of("green"));
|
results.direct_press = press(of("green"));
|
||||||
await approveOne(of("green"));
|
await approveOne(of("green"));
|
||||||
results.direct = take();
|
results.direct = take();
|
||||||
ui.selected.add(keyOf(of("ask")));
|
ui.selected.add(keyOf(of("run")));
|
||||||
results.direct_picked = press(of("ask"));
|
results.direct_picked = press(of("run"));
|
||||||
drawGrant();
|
drawGrant();
|
||||||
results.direct_selection = {main: buttons(bar)[0].getAttribute("aria-label"), labels: labels(bar)};
|
results.direct_selection = {main: buttons(bar)[0].getAttribute("aria-label"), labels: labels(bar)};
|
||||||
ui.selected.clear();
|
ui.selected.clear();
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import unittest
|
|||||||
from hub_support import HUB
|
from hub_support import HUB
|
||||||
|
|
||||||
TEMPLATES = HUB / "templates"
|
TEMPLATES = HUB / "templates"
|
||||||
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-api.js", "page-passkey.js", "page-inbox.js", "page-grant.js", "page-console.js", "page-rule-request.js", "page-load.js"]
|
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-api.js", "page-passkey.js", "page-inbox.js", "page-grant.js", "page-console.js", "page-rule-request.js", "page-load.js"]
|
||||||
GONE = "operator/gui-agentbox-merge-push"
|
GONE = "operator/gui-agentbox-merge-push"
|
||||||
NOTICE = "already done or removed elsewhere"
|
NOTICE = "already done or removed elsewhere"
|
||||||
PROBE = r"""
|
PROBE = r"""
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ hub_limits = importlib.import_module("hub_limits")
|
|||||||
approval = importlib.import_module("approval")
|
approval = importlib.import_module("approval")
|
||||||
TEMPLATES = HUB / "templates"
|
TEMPLATES = HUB / "templates"
|
||||||
DIFFS = TEMPLATES / "diffs.js"
|
DIFFS = TEMPLATES / "diffs.js"
|
||||||
PAGE_MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-diff.js", "page-inbox.js", "page-grant.js", "page-stream.js", "page-screens.js", "page-keyboard.js"]
|
PAGE_MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-inbox.js", "page-grant.js", "page-stream.js", "page-screens.js", "page-keyboard.js"]
|
||||||
SECRET = 'api_key = "plain-example-words"'
|
SECRET = 'api_key = "plain-example-words"'
|
||||||
ARMOURED = "before\n-----BEGIN EXAMPLE-----\nplain words only\n-----END EXAMPLE-----\nafter\n"
|
ARMOURED = "before\n-----BEGIN EXAMPLE-----\nplain words only\n-----END EXAMPLE-----\nafter\n"
|
||||||
WITHHELD = "content withheld"
|
WITHHELD = "content withheld"
|
||||||
|
|||||||
Reference in new issue
Block a user