chore(python): audit providers claudecode codex cursor gemini

Add _runtime (paths, config validation, status checks) and _shell_command
(quoting, parsers) and move the four providers onto them.

Claude-Session: https://claude.ai/code/session_01Agoc9bRVE9KL7mmWtey9Vq
This commit is contained in:
雷电芽衣 committed 2026-09-02 23:36:33 -04:00
1 parent ed34831c20
commit 6dd0197cab
15 files changed
+732 -1755

No files matched your search

+27 -177
View File
@@ -2,17 +2,23 @@
from __future__ import annotations
import base64
from dataclasses import dataclass
import json
import ntpath
import os
import re
import shlex
import subprocess # nosec B404 - used only for legacy argument rendering
import sys
import subprocess
from typing import Any, Dict, List, Optional, Tuple
from elydora._runtime_paths import runtime_root
from ._runtime import managed_script_reference, same_agent_id, same_path
from ._shell_command import (
encoded_windows_command,
is_python_executable,
parse_encoded_windows_command,
parse_posix_command,
posix_source,
)
from ._strict_json import JsonObject, parse_json_object
@@ -51,164 +57,16 @@ class RuntimeContract:
audit_path: str
@dataclass(frozen=True)
class _ParsedArgument:
value: str
next_index: int
def runtime_root() -> str:
return os.path.join(os.path.expanduser("~"), ".elydora")
def same_path(left: str, right: str) -> bool:
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
os.path.abspath(right)
)
def _same_agent_id(left: str, right: str) -> bool:
return os.path.normcase(left) == os.path.normcase(right)
def _quote_posix(value: str) -> str:
return "'" + value.replace("'", "'\"'\"'") + "'"
def _quote_powershell(value: str) -> str:
return "'" + value.replace("'", "''") + "'"
def _windows_powershell_path() -> str:
configured = os.environ.get("SystemRoot") if os.name == "nt" else None
system_root = (
configured
if configured
and ntpath.isabs(configured)
and re.search(r'["%\r\n]', configured) is None
else r"C:\Windows"
)
return ntpath.join(
system_root,
"System32",
"WindowsPowerShell",
"v1.0",
"powershell.exe",
)
def _windows_command(script_path: str) -> str:
source = (
f"& {_quote_powershell(sys.executable)} "
f"{_quote_powershell(script_path)}; exit $LASTEXITCODE"
)
encoded = base64.b64encode(source.encode("utf-16le")).decode("ascii")
return (
f'"{_windows_powershell_path()}" -NoLogo -NoProfile '
f"-NonInteractive -EncodedCommand {encoded}"
)
def build_handler(script_path: str, status_message: str) -> JsonObject:
return {
"type": "command",
"command": f"{_quote_posix(sys.executable)} {_quote_posix(script_path)}",
"commandWindows": _windows_command(script_path),
"command": posix_source(script_path),
"commandWindows": encoded_windows_command(script_path),
"timeout": HOOK_TIMEOUT_SECONDS,
"statusMessage": status_message,
}
def _read_posix_argument(command: str, start: int) -> Optional[_ParsedArgument]:
if start >= len(command) or command[start] != "'":
return None
apostrophe = "'\"'\"'"
value = ""
index = start + 1
while index < len(command):
if command.startswith(apostrophe, index):
value += "'"
index += len(apostrophe)
continue
if command[index] == "'":
return _ParsedArgument(value, index + 1)
value += command[index]
index += 1
return None
def _parse_posix_command(command: Any) -> Optional[Tuple[str, str]]:
if not isinstance(command, str):
return None
executable = _read_posix_argument(command, 0)
if (
executable is None
or command[executable.next_index : executable.next_index + 1] != " "
):
return None
script = _read_posix_argument(command, executable.next_index + 1)
if script is None or script.next_index != len(command):
return None
return executable.value, script.value
def _read_powershell_argument(command: str, start: int) -> Optional[_ParsedArgument]:
if start >= len(command) or command[start] != "'":
return None
value = ""
index = start + 1
while index < len(command):
if command[index] != "'":
value += command[index]
index += 1
continue
if index + 1 < len(command) and command[index + 1] == "'":
value += "'"
index += 2
continue
return _ParsedArgument(value, index + 1)
return None
def _parse_powershell_source(source: str) -> Optional[Tuple[str, str]]:
if not source.startswith("& "):
return None
executable = _read_powershell_argument(source, 2)
if (
executable is None
or source[executable.next_index : executable.next_index + 1] != " "
):
return None
script = _read_powershell_argument(source, executable.next_index + 1)
if script is None or source[script.next_index :] != "; exit $LASTEXITCODE":
return None
return executable.value, script.value
def _parse_windows_command(command: Any) -> Optional[Tuple[str, str]]:
if not isinstance(command, str):
return None
match = re.fullmatch(
r'"([^"\r\n]+)" -NoLogo -NoProfile -NonInteractive '
r"-EncodedCommand ([A-Za-z0-9+/]+={0,2})",
command,
)
if (
match is None
or not ntpath.isabs(match.group(1))
or ntpath.basename(match.group(1)).lower() != "powershell.exe"
):
return None
try:
raw = base64.b64decode(match.group(2), validate=True)
if base64.b64encode(raw).decode("ascii") != match.group(2):
return None
source = raw.decode("utf-16le")
except (UnicodeDecodeError, ValueError):
return None
return _parse_powershell_source(source)
def _parse_legacy_commands(handler: JsonObject) -> Optional[Tuple[str, str]]:
command = handler.get("command")
command_windows = handler.get("commandWindows")
@@ -228,17 +86,6 @@ def _parse_legacy_commands(handler: JsonObject) -> Optional[Tuple[str, str]]:
return arguments[0], arguments[1]
def _is_python_executable(file_path: str) -> bool:
return (
re.fullmatch(
r"python(?:[0-9]+(?:\.[0-9]+)*)?(?:\.exe)?",
os.path.basename(file_path),
re.I,
)
is not None
)
def _managed_script_path(
handler: JsonObject,
status_message: str,
@@ -252,8 +99,14 @@ def _managed_script_path(
or handler.get("statusMessage") != status_message
):
return None
posix = _parse_posix_command(handler.get("command"))
windows = _parse_windows_command(handler.get("commandWindows"))
command = handler.get("command")
command_windows = handler.get("commandWindows")
posix = parse_posix_command(command) if isinstance(command, str) else None
windows = (
parse_encoded_windows_command(command_windows)
if isinstance(command_windows, str)
else None
)
if posix is None or windows is None:
legacy = _parse_legacy_commands(handler)
posix = legacy
@@ -263,8 +116,8 @@ def _managed_script_path(
or windows is None
or not os.path.isabs(posix[0])
or not os.path.isabs(posix[1])
or not _is_python_executable(posix[0])
or not _is_python_executable(windows[0])
or not is_python_executable(posix[0])
or not is_python_executable(windows[0])
or not same_path(posix[0], windows[0])
or not same_path(posix[1], windows[1])
):
@@ -278,13 +131,10 @@ def _managed_agent_id(
status_message: str,
) -> Optional[str]:
script_path = _managed_script_path(handler, status_message)
if script_path is None or os.path.basename(script_path) != script_name:
if script_path is None:
return None
agent_directory = os.path.dirname(script_path)
if not same_path(os.path.dirname(agent_directory), runtime_root()):
return None
agent_id = os.path.basename(agent_directory)
return agent_id if agent_id not in {"", ".", ".."} else None
reference = managed_script_reference(script_path, script_name)
return None if reference is None else reference[0]
def _read_hooks(value: Any, label: str) -> CodexHooks:
@@ -339,7 +189,7 @@ def _remove_from_groups(
for handler in group["hooks"]:
managed_id = _managed_agent_id(handler, script_name, status_message)
remove = managed_id is not None and (
not agent_id or _same_agent_id(managed_id, agent_id)
not agent_id or same_agent_id(managed_id, agent_id)
)
if not remove:
handlers.append(handler)