Repository navigation
Expand file tree
/
Copy pathcodec_consent.py
More file actions
274 lines (238 loc) · 12.1 KB
/
Copy pathcodec_consent.py
File metadata and controls
274 lines (238 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"""codec_consent — strict-consent gate for the chat + MCP skill paths.
Re-audit (red-team CHAIN-001/002/006): the Step-3 consent gate
(docs/PHASE1-STEP3-DESIGN.md §1.7) was wired ONLY into codec_agent_runner. The
chat ([SKILL:] tag + pre-LLM hijack → codec_dispatch.run_skill) and MCP
(codec_mcp.tool_fn) paths could reach high-power skills with only the
`is_dangerous` heuristic / path blocklists. This module is the shared
classifier + per-transport policy:
- MCP → hard-refuse destructive skills (claude.ai can't consent at the
operator tier; consistent with the _HTTP_BLOCKED principle).
Over HTTP only, the side-effect skills in
codec_config._HTTP_CONSENT_REQUIRED additionally wait for the owner
to approve each call in the PWA (mcp_http_consent_ok).
- chat → require explicit confirmation (the handler returns consent_required;
the user confirms; re-dispatch carries a token).
- voice/agent → existing ask_user announce-and-listen (unchanged).
A skill is "destructive" if it declares `SKILL_DESTRUCTIVE = True`
(registry-AST-extracted — the extensible per-skill path, Decision C), OR is in
`codec_config._HTTP_BLOCKED`, OR is one of the known high-power built-ins below
(so coverage doesn't depend on regenerating the hash-pinned skill manifest).
Kill switch: `CONSENT_GATE_ENABLED=false`.
"""
import os
__all__ = ["gate_enabled", "is_destructive_skill", "chat_consent_ok",
"mcp_refuse_message", "mcp_allowed", "mcp_http_consent_required",
"mcp_http_consent_ok", "mcp_http_consent_refuse_message",
"local_consent_needed", "local_consent_ok", "LOCAL_CANCELLED"]
# How long a remote MCP call waits for the owner's PWA approval before it is
# refused. Short on purpose: the claude.ai request is held open while we wait.
MCP_HTTP_CONSENT_TIMEOUT_SEC = int(os.environ.get("CODEC_MCP_CONSENT_TIMEOUT", "120"))
# Known high-power built-ins that are destructive but NOT in _HTTP_BLOCKED.
# (terminal / python_exec / process_manager / pm2_control / ax_control are
# already covered by the _HTTP_BLOCKED backstop.)
_DESTRUCTIVE_BUILTINS = frozenset({
"file_ops", # write/append/delete to the filesystem
"file_write", # writes files
"imessage_send", # sends messages as the user
"pilot", # drives a real browser session
"skill_forge", # writes a skill to disk (no review gate)
})
# Destructive skills that are nonetheless SAFE to expose over MCP because they
# self-guard. `file_write` is write-only (no read/delete/list), blocks the
# system tree + credential files + all of ~/.codec, restricts writes to $HOME
# or /tmp, caps size at 500 KB, and audits every write to ~/.codec/file_write.log.
# It was purpose-built for remote (claude.ai) callers — the blanket MCP refusal
# contradicted its own design and broke the Claude→CODEC→save-a-file flow.
# Allowing it here is the "scoped-safe write" the operator wants, WITHOUT opening
# delete/move (file_ops), shells (terminal/python_exec), messaging
# (imessage_send) or browser control (pilot), which all remain refused over MCP.
_MCP_SELF_GUARDED = frozenset({"file_write"})
# P-030 / P-080 (owner decision D-17, Oct 2026): skills that act on the owner's
# browser or screen. They ask once per call on the local paths (chat, voice
# call, wake word) but are NOT destructive in the MCP sense: adding them to
# _DESTRUCTIVE_BUILTINS would make mcp_allowed refuse them, while over HTTP MCP
# they already ask per call through codec_config._HTTP_CONSENT_REQUIRED.
#
# P-030 part 2 (same decision): "shell_execute" is the crew / custom-agent
# built-in tool, not a skill. codec_agents._shell_execute calls
# local_consent_ok(asked_from="crew") only for the commands
# codec_config.is_dangerous flags; every other command runs in the sandbox
# without asking. No skill has that name, so chat, voice and MCP are unchanged.
_LOCAL_CONSENT_REQUIRED = frozenset({"chrome_fill", "chrome_click_cdp", "mouse_control",
"shell_execute"})
# The wake word and the voice call wait this long for the owner's OK (PWA card
# or phone push), then cancel: a wake command must not hold the listener for
# ask()'s 600 s default.
LOCAL_CONSENT_TIMEOUT_SEC = 60
LOCAL_CANCELLED = "Cancelled: that needs your OK on the CODEC screen or your phone."
def gate_enabled() -> bool:
"""Consent gate on by default; CONSENT_GATE_ENABLED=false disables it."""
return os.environ.get("CONSENT_GATE_ENABLED", "true").lower() != "false"
def is_destructive_skill(tool_name, registry=None) -> bool:
"""True if `tool_name` is a high-power/destructive skill needing consent
(chat) or refusal (MCP). Never raises."""
if not tool_name:
return False
# 1) per-skill SKILL_DESTRUCTIVE flag (extensible — user skills opt in)
try:
reg = registry
if reg is None:
from codec_dispatch import registry as reg # the singleton
if reg is not None and reg.get_destructive(tool_name):
return True
except Exception:
pass
# 2) _HTTP_BLOCKED backstop (terminal, python_exec, process_manager, …)
try:
from codec_config import _HTTP_BLOCKED
if tool_name in _HTTP_BLOCKED:
return True
except Exception:
pass
# 3) known high-power built-ins
return tool_name in _DESTRUCTIVE_BUILTINS
def chat_consent_ok(tool_name, query, *, registry=None) -> bool:
"""Chat path (A2): a destructive skill requires explicit consent via the
existing AskUserQuestion PWA panel (Phase 1 Step 3 §1.7 — literal verb-match;
generic yes/ok rejected). Returns True if the skill may run (non-destructive,
gate disabled, or consent granted); False if blocked (declined / timeout /
ask_user unavailable). BLOCKS the worker thread on ask_user until answered —
the chat handler invokes this via asyncio.to_thread, so the event loop isn't
blocked. Fail-closed: any error → False (a destructive skill never
auto-runs)."""
if not gate_enabled() or not (is_destructive_skill(tool_name, registry=registry)
or tool_name in _LOCAL_CONSENT_REQUIRED):
return True
try:
import codec_ask_user
answer = codec_ask_user.ask(
f"CODEC wants to run the '{tool_name}' skill — a destructive / "
f"high-power operation — for: {(query or '')[:200]}",
destructive=True,
asked_from="chat",
tool_name=tool_name,
)
return answer not in (
codec_ask_user.TIMEOUT_SENTINEL,
codec_ask_user.DISABLED_SENTINEL,
)
except Exception:
return False
def _file_ops_reads_only(task, registry=None) -> bool:
"""file_ops list and read do not ask; write and append do. Uses the
skill's own parser; any error counts as a write (fail closed)."""
try:
reg = registry
if reg is None:
from codec_dispatch import registry as reg
mod = reg.load("file_ops")
if mod is None and not reg.names(): # a process that never scanned
reg.scan()
mod = reg.load("file_ops")
return mod._parse_action(task or "")[0] in ("list", "read")
except Exception:
return False
def local_consent_needed(tool_name, task="", registry=None) -> bool:
"""Does a wake-word or voice-call run of this skill need the owner's OK?"""
if tool_name in _LOCAL_CONSENT_REQUIRED:
return True
if not is_destructive_skill(tool_name, registry=registry):
return False
if tool_name == "file_ops":
return not _file_ops_reads_only(task, registry=registry)
return True
def _audit_local(tool_name, asked_from, decision, task):
try:
from codec_audit import log_event
log_event("local_consent_decision", "codec-consent",
f"{asked_from} consent for {tool_name}: {decision}",
tool=tool_name, level="info" if decision == "allowed" else "warning",
extra={"asked_from": asked_from, "decision": decision,
"task_chars": len(task or "")})
except Exception:
pass
def local_consent_ok(tool_name, task, asked_from, *, registry=None,
timeout=LOCAL_CONSENT_TIMEOUT_SEC) -> bool:
"""Wake word and voice call (P-080) and the browser/screen skills (P-030):
ask the owner through the PWA card (and a phone push) before a high-power
skill runs. True when it may run (no consent needed, gate disabled, or the
owner answered with the verb); False on decline, timeout or any error.
Blocks the calling thread for at most `timeout` seconds."""
if not gate_enabled() or not local_consent_needed(tool_name, task, registry=registry):
return True
try:
import codec_ask_user
answer = codec_ask_user.ask(
f"CODEC heard a request to run '{tool_name}' ({asked_from}): "
f"{(task or '')[:200]}",
destructive=True,
asked_from=asked_from,
tool_name=tool_name,
timeout=timeout,
)
ok = answer not in (codec_ask_user.TIMEOUT_SENTINEL,
codec_ask_user.DISABLED_SENTINEL)
except Exception:
ok = False
_audit_local(tool_name, asked_from, "allowed" if ok else "refused", task)
return ok
def mcp_allowed(tool_name, registry=None) -> bool:
"""May this skill run over MCP (remote claude.ai caller)?
Non-destructive skills always may. A destructive skill may ONLY if it
self-guards (see _MCP_SELF_GUARDED) — currently just file_write, which
enforces its own path safety + audit. Everything else destructive is refused.
Never raises; fail-closed (any error → not allowed)."""
try:
if not is_destructive_skill(tool_name, registry=registry):
return True
return tool_name in _MCP_SELF_GUARDED
except Exception:
return False
def mcp_refuse_message(tool_name) -> str:
return (
f"Skill '{tool_name}' is a destructive/high-power operation and is not "
"permitted over MCP. Run it locally (chat or voice), where the operator "
"can confirm it."
)
def mcp_http_consent_required(tool_name) -> bool:
"""Does this skill need the owner's per-call approval over HTTP MCP?
Fail-closed: if the list can't be read, every call needs approval."""
try:
from codec_config import _HTTP_CONSENT_REQUIRED
except Exception:
return True
return tool_name in _HTTP_CONSENT_REQUIRED
def mcp_http_consent_ok(tool_name, task="") -> bool:
"""HTTP MCP (remote claude.ai caller): ask the owner to approve this call.
Uses the Step 3 AskUserQuestion strict-consent path: the question shows in
the PWA (notifications.json, type="question") with an "Allow <tool>" button
and a "Decline" button. ask() polls pending_questions.json, so an answer the
dashboard writes reaches this (codec-mcp-http) process. Only the Allow
button (or a reply that is exactly "allow") approves; decline, timeout
(MCP_HTTP_CONSENT_TIMEOUT_SEC), ask_user disabled, or any error → False.
Blocks the calling worker thread (FastMCP runs sync tools in a threadpool).
"""
allow = f"Allow {tool_name}"
try:
import codec_ask_user
answer = codec_ask_user.ask(
f"claude.ai (remote MCP) wants to run the '{tool_name}' skill on "
f"this Mac for: {(task or '')[:200]}",
options=[allow, "Decline"],
timeout=MCP_HTTP_CONSENT_TIMEOUT_SEC,
destructive=True,
destructive_verb="allow",
asked_from="mcp",
tool_name=tool_name,
)
except Exception:
return False
# ask()'s strict mode accepts any reply containing the verb ("don't allow"
# included), so approve only on the exact button label or the bare verb.
return isinstance(answer, str) and answer.strip().lower() in (allow.lower(), "allow")
def mcp_http_consent_refuse_message(tool_name) -> str:
return (
f"Skill '{tool_name}' was not run: over remote MCP it needs the owner's "
"approval in the CODEC dashboard for each call, and none was given "
f"(declined or no answer within {MCP_HTTP_CONSENT_TIMEOUT_SEC}s)."
)