fix(python): protect CLI install credentials
This commit is contained in:
1 parent
2e699c11e3
commit
4d97660cec
21 files changed
+784
-175
No files matched your search
@@ -0,0 +1,151 @@
|
||||
"""Secure credential input for the Elydora CLI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import getpass
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
import warnings
|
||||
from typing import NamedTuple, Optional, Protocol
|
||||
|
||||
|
||||
MAX_SECRET_FILE_BYTES = 64 * 1024
|
||||
|
||||
|
||||
class InstallSecrets(NamedTuple):
|
||||
private_key: str
|
||||
token: Optional[str]
|
||||
|
||||
|
||||
class SecretTerminal(Protocol):
|
||||
@property
|
||||
def interactive(self) -> bool:
|
||||
...
|
||||
|
||||
def read_hidden(self, prompt: str) -> str:
|
||||
...
|
||||
|
||||
|
||||
class _DefaultTerminal:
|
||||
@property
|
||||
def interactive(self) -> bool:
|
||||
return sys.stdin.isatty() and sys.stderr.isatty()
|
||||
|
||||
def read_hidden(self, prompt: str) -> str:
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", getpass.GetPassWarning)
|
||||
return getpass.getpass(prompt=prompt, stream=sys.stderr)
|
||||
except getpass.GetPassWarning as error:
|
||||
raise RuntimeError(
|
||||
"hidden input requires an interactive terminal"
|
||||
) from error
|
||||
except (EOFError, KeyboardInterrupt) as error:
|
||||
raise RuntimeError("secret input cancelled") from error
|
||||
|
||||
|
||||
def _parse_single_line_secret(raw: str, label: str, allow_empty: bool) -> str:
|
||||
if len(raw.encode("utf-8")) > MAX_SECRET_FILE_BYTES:
|
||||
raise ValueError(f"{label} exceeds {MAX_SECRET_FILE_BYTES} bytes")
|
||||
if raw.endswith("\r\n"):
|
||||
value = raw[:-2]
|
||||
elif raw.endswith("\n"):
|
||||
value = raw[:-1]
|
||||
else:
|
||||
value = raw
|
||||
if not allow_empty and not value:
|
||||
raise ValueError(f"{label} is empty")
|
||||
if "\r" in value or "\n" in value or "\0" in value:
|
||||
raise ValueError(f"{label} must contain exactly one line")
|
||||
return value
|
||||
|
||||
|
||||
def _validate_secret_file(
|
||||
metadata: os.stat_result,
|
||||
path: str,
|
||||
label: str,
|
||||
) -> None:
|
||||
if not stat.S_ISREG(metadata.st_mode):
|
||||
raise ValueError(f"{label} file is not a regular file: {path}")
|
||||
if metadata.st_size > MAX_SECRET_FILE_BYTES:
|
||||
raise ValueError(
|
||||
f"{label} file exceeds {MAX_SECRET_FILE_BYTES} bytes: {path}"
|
||||
)
|
||||
if os.name != "nt" and metadata.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
|
||||
raise ValueError(
|
||||
f"{label} file must be accessible only by its owner: {path}"
|
||||
)
|
||||
|
||||
|
||||
def _read_secret_file(path: str, label: str) -> str:
|
||||
before = os.lstat(path)
|
||||
_validate_secret_file(before, path, label)
|
||||
|
||||
flags = os.O_RDONLY
|
||||
flags |= getattr(os, "O_BINARY", 0)
|
||||
flags |= getattr(os, "O_CLOEXEC", 0)
|
||||
flags |= getattr(os, "O_NOFOLLOW", 0)
|
||||
descriptor = os.open(path, flags)
|
||||
try:
|
||||
file = os.fdopen(descriptor, "rb")
|
||||
descriptor = -1
|
||||
with file:
|
||||
after = os.fstat(file.fileno())
|
||||
_validate_secret_file(after, path, label)
|
||||
if (before.st_dev, before.st_ino) != (after.st_dev, after.st_ino):
|
||||
raise OSError(f"{label} file changed while opening: {path}")
|
||||
encoded = file.read(MAX_SECRET_FILE_BYTES + 1)
|
||||
finally:
|
||||
if descriptor >= 0:
|
||||
os.close(descriptor)
|
||||
|
||||
if len(encoded) > MAX_SECRET_FILE_BYTES:
|
||||
raise ValueError(
|
||||
f"{label} file exceeds {MAX_SECRET_FILE_BYTES} bytes: {path}"
|
||||
)
|
||||
try:
|
||||
raw = encoded.decode("utf-8")
|
||||
except UnicodeDecodeError as error:
|
||||
raise ValueError(f"{label} file must contain UTF-8 text: {path}") from error
|
||||
return _parse_single_line_secret(raw, label, False)
|
||||
|
||||
|
||||
def resolve_install_secrets(
|
||||
*,
|
||||
private_key_file: Optional[str],
|
||||
token_file: Optional[str],
|
||||
terminal: Optional[SecretTerminal] = None,
|
||||
) -> InstallSecrets:
|
||||
active_terminal = terminal if terminal is not None else _DefaultTerminal()
|
||||
|
||||
if private_key_file:
|
||||
private_key = _read_secret_file(private_key_file, "private key")
|
||||
elif active_terminal.interactive:
|
||||
private_key = _parse_single_line_secret(
|
||||
active_terminal.read_hidden("Private key: "),
|
||||
"private key",
|
||||
False,
|
||||
)
|
||||
else:
|
||||
raise RuntimeError(
|
||||
"private key input requires an interactive terminal or "
|
||||
"--private_key_file <path>"
|
||||
)
|
||||
|
||||
token: Optional[str]
|
||||
if token_file:
|
||||
token = _read_secret_file(token_file, "API token")
|
||||
elif active_terminal.interactive:
|
||||
token = (
|
||||
_parse_single_line_secret(
|
||||
active_terminal.read_hidden("API token (optional): "),
|
||||
"API token",
|
||||
True,
|
||||
)
|
||||
or None
|
||||
)
|
||||
else:
|
||||
token = None
|
||||
|
||||
return InstallSecrets(private_key=private_key, token=token)
|
||||
+48
-12
@@ -10,10 +10,10 @@ import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
from typing import Dict, NamedTuple, NoReturn, Optional, Type
|
||||
|
||||
from ._cli_secrets import resolve_install_secrets
|
||||
from ._version import __version__
|
||||
from ._runtime_paths import (
|
||||
ensure_private_directory,
|
||||
@@ -40,6 +40,7 @@ from .plugins.kimi import KimiPlugin
|
||||
from .plugins.letta import LettaPlugin
|
||||
from .plugins.opencode import OpenCodePlugin
|
||||
from .plugins.qwen import QwenPlugin
|
||||
from .plugins._file_io import write_text_atomic
|
||||
|
||||
|
||||
PLUGIN_MAP: Dict[str, Type[AgentPlugin]] = {
|
||||
@@ -60,6 +61,11 @@ PLUGIN_MAP: Dict[str, Type[AgentPlugin]] = {
|
||||
"qwen": QwenPlugin,
|
||||
}
|
||||
|
||||
LEGACY_SECRET_OPTIONS = {
|
||||
"--private_key": "--private_key_file",
|
||||
"--token": "--token_file",
|
||||
}
|
||||
|
||||
|
||||
def _runtime_root() -> str:
|
||||
return os.path.join(os.path.expanduser("~"), ".elydora")
|
||||
@@ -70,6 +76,17 @@ def _exit_with_error(message: str) -> NoReturn:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def _reject_legacy_secret_arguments(arguments: list[str]) -> None:
|
||||
for argument in arguments:
|
||||
option = argument.split("=", 1)[0]
|
||||
replacement = LEGACY_SECRET_OPTIONS.get(option)
|
||||
if replacement:
|
||||
_exit_with_error(
|
||||
f"{option} exposes credentials in process arguments; "
|
||||
f"use {replacement} or hidden terminal input"
|
||||
)
|
||||
|
||||
|
||||
def _resolve_agent_directory_or_exit(agent_id: str) -> str:
|
||||
try:
|
||||
return resolve_agent_directory(_runtime_root(), agent_id)
|
||||
@@ -168,10 +185,19 @@ def cmd_install(args: argparse.Namespace) -> None:
|
||||
"""Handle the 'install' subcommand."""
|
||||
agent_name: str = args.agent
|
||||
agent_dir = _resolve_agent_directory_or_exit(args.agent_id)
|
||||
plugin = _get_plugin(agent_name)
|
||||
|
||||
try:
|
||||
secrets = resolve_install_secrets(
|
||||
private_key_file=args.private_key_file,
|
||||
token_file=args.token_file,
|
||||
)
|
||||
except (OSError, RuntimeError, ValueError) as error:
|
||||
_exit_with_error(str(error))
|
||||
|
||||
# Derive public key to verify the private key is valid
|
||||
try:
|
||||
pub = get_public_key_base64url(args.private_key)
|
||||
pub = get_public_key_base64url(secrets.private_key)
|
||||
except Exception as exc:
|
||||
print(f"Error: Invalid private key — {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -185,25 +211,26 @@ def cmd_install(args: argparse.Namespace) -> None:
|
||||
# Generate and write the guard script
|
||||
guard_script_path = os.path.join(agent_dir, "guard.py")
|
||||
guard_script = generate_guard_script(agent_name, args.agent_id)
|
||||
with open(guard_script_path, "w", encoding="utf-8") as f:
|
||||
f.write(guard_script)
|
||||
if os.name != "nt":
|
||||
os.chmod(guard_script_path, os.stat(guard_script_path).st_mode | stat.S_IEXEC)
|
||||
write_text_atomic(
|
||||
guard_script_path,
|
||||
guard_script,
|
||||
0o700,
|
||||
"Elydora guard runtime",
|
||||
)
|
||||
print(f" Guard script: {guard_script_path}")
|
||||
|
||||
config: InstallConfig = {
|
||||
"org_id": args.org_id,
|
||||
"agent_id": args.agent_id,
|
||||
"agent_name": agent_name,
|
||||
"private_key": args.private_key,
|
||||
"private_key": secrets.private_key,
|
||||
"kid": args.kid,
|
||||
"base_url": args.base_url,
|
||||
"guard_script_path": guard_script_path,
|
||||
}
|
||||
if args.token:
|
||||
config["token"] = args.token
|
||||
if secrets.token:
|
||||
config["token"] = secrets.token
|
||||
|
||||
plugin = _get_plugin(agent_name)
|
||||
plugin.install(config)
|
||||
|
||||
|
||||
@@ -291,9 +318,17 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
install_parser.add_argument("--agent", required=True, help="Agent name (e.g. claudecode, cursor)")
|
||||
install_parser.add_argument("--org_id", required=True, help="Organization ID")
|
||||
install_parser.add_argument("--agent_id", required=True, help="Agent ID")
|
||||
install_parser.add_argument("--private_key", required=True, help="Base64url-encoded Ed25519 private key seed")
|
||||
install_parser.add_argument(
|
||||
"--private_key_file",
|
||||
default=None,
|
||||
help="Owner-only file containing the Ed25519 private key seed",
|
||||
)
|
||||
install_parser.add_argument("--kid", required=True, help="Key ID")
|
||||
install_parser.add_argument("--token", default="", help="API token (from Console)")
|
||||
install_parser.add_argument(
|
||||
"--token_file",
|
||||
default=None,
|
||||
help="Owner-only file containing the optional API token",
|
||||
)
|
||||
install_parser.add_argument("--base_url", default="https://api.elydora.com", help="API base URL")
|
||||
|
||||
# uninstall
|
||||
@@ -312,6 +347,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
|
||||
def main() -> None:
|
||||
"""CLI entry point."""
|
||||
_reject_legacy_secret_arguments(sys.argv[1:])
|
||||
parser = build_parser()
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
@@ -211,7 +211,6 @@ class AugmentPlugin(AgentPlugin):
|
||||
audit_script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
|
||||
@@ -4,9 +4,9 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
|
||||
from ._file_io import write_json_atomic, write_text_atomic
|
||||
from .base import AgentPlugin, InstallConfig, PluginStatus
|
||||
from .hook_template import generate_hook_script
|
||||
|
||||
@@ -40,34 +40,36 @@ class ClaudeCodePlugin(AgentPlugin):
|
||||
"agent_name": agent_name,
|
||||
}
|
||||
config_path = os.path.join(agent_dir, "config.json")
|
||||
with open(config_path, "w", encoding="utf-8") as f:
|
||||
json.dump(config_data, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(
|
||||
config_path,
|
||||
config_data,
|
||||
0o600,
|
||||
"Elydora runtime config",
|
||||
)
|
||||
|
||||
# Write private key
|
||||
private_key_path = os.path.join(agent_dir, "private.key")
|
||||
with open(private_key_path, "w", encoding="utf-8") as f:
|
||||
f.write(config.get("private_key", ""))
|
||||
try:
|
||||
os.chmod(private_key_path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
private_key_path,
|
||||
config.get("private_key", ""),
|
||||
0o600,
|
||||
"Elydora private key",
|
||||
)
|
||||
|
||||
# Write the hook script
|
||||
script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
hook_path = self._hook_path_for(agent_id)
|
||||
with open(hook_path, "w", encoding="utf-8") as f:
|
||||
f.write(script)
|
||||
try:
|
||||
os.chmod(hook_path, stat.S_IRWXU)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
hook_path,
|
||||
script,
|
||||
0o700,
|
||||
"Elydora audit runtime",
|
||||
)
|
||||
|
||||
guard_script_path = config.get("guard_script_path", "")
|
||||
python_exe = sys.executable
|
||||
@@ -105,7 +107,7 @@ class ClaudeCodePlugin(AgentPlugin):
|
||||
})
|
||||
|
||||
_save_json(SETTINGS_PATH, settings)
|
||||
print(f"Elydora hook installed for Claude Code.")
|
||||
print("Elydora hook installed for Claude Code.")
|
||||
print(f" Hook script: {hook_path}")
|
||||
print(f" Settings: {SETTINGS_PATH}")
|
||||
|
||||
@@ -205,7 +207,4 @@ def _load_json(path: str) -> dict:
|
||||
|
||||
|
||||
def _save_json(path: str, data: dict) -> None:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(path, data, 0o600, "Claude Code settings")
|
||||
@@ -65,7 +65,6 @@ class ClinePlugin(AgentPlugin):
|
||||
audit_script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
|
||||
@@ -338,7 +338,6 @@ class CodexPlugin(AgentPlugin):
|
||||
hook_script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
|
||||
@@ -4,9 +4,9 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
|
||||
from ._file_io import write_json_atomic, write_text_atomic
|
||||
from .base import AgentPlugin, InstallConfig, PluginStatus
|
||||
from .hook_template import generate_hook_script
|
||||
|
||||
@@ -43,33 +43,35 @@ class CopilotPlugin(AgentPlugin):
|
||||
"agent_name": agent_name,
|
||||
}
|
||||
config_path = os.path.join(agent_dir, "config.json")
|
||||
with open(config_path, "w", encoding="utf-8") as f:
|
||||
json.dump(config_data, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(
|
||||
config_path,
|
||||
config_data,
|
||||
0o600,
|
||||
"Elydora runtime config",
|
||||
)
|
||||
|
||||
# Write private key
|
||||
private_key_path = os.path.join(agent_dir, "private.key")
|
||||
with open(private_key_path, "w", encoding="utf-8") as f:
|
||||
f.write(config.get("private_key", ""))
|
||||
try:
|
||||
os.chmod(private_key_path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
private_key_path,
|
||||
config.get("private_key", ""),
|
||||
0o600,
|
||||
"Elydora private key",
|
||||
)
|
||||
|
||||
script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
hook_path = self._hook_path_for(agent_id)
|
||||
with open(hook_path, "w", encoding="utf-8") as f:
|
||||
f.write(script)
|
||||
try:
|
||||
os.chmod(hook_path, stat.S_IRWXU)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
hook_path,
|
||||
script,
|
||||
0o700,
|
||||
"Elydora audit runtime",
|
||||
)
|
||||
|
||||
guard_script_path = config.get("guard_script_path", "")
|
||||
python_exe = sys.executable
|
||||
@@ -103,7 +105,7 @@ class CopilotPlugin(AgentPlugin):
|
||||
})
|
||||
|
||||
_save_json(settings_path, settings)
|
||||
print(f"Elydora hook installed for Copilot CLI.")
|
||||
print("Elydora hook installed for Copilot CLI.")
|
||||
print(f" Hook script: {hook_path}")
|
||||
print(f" Settings: {settings_path}")
|
||||
|
||||
@@ -194,7 +196,4 @@ def _load_json(path: str) -> dict:
|
||||
|
||||
|
||||
def _save_json(path: str, data: dict) -> None:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(path, data, 0o600, "GitHub Copilot hooks config")
|
||||
@@ -4,9 +4,9 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
|
||||
from ._file_io import write_json_atomic, write_text_atomic
|
||||
from .base import AgentPlugin, InstallConfig, PluginStatus
|
||||
from .hook_template import generate_hook_script
|
||||
|
||||
@@ -40,33 +40,35 @@ class CursorPlugin(AgentPlugin):
|
||||
"agent_name": agent_name,
|
||||
}
|
||||
config_path = os.path.join(agent_dir, "config.json")
|
||||
with open(config_path, "w", encoding="utf-8") as f:
|
||||
json.dump(config_data, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(
|
||||
config_path,
|
||||
config_data,
|
||||
0o600,
|
||||
"Elydora runtime config",
|
||||
)
|
||||
|
||||
# Write private key
|
||||
private_key_path = os.path.join(agent_dir, "private.key")
|
||||
with open(private_key_path, "w", encoding="utf-8") as f:
|
||||
f.write(config.get("private_key", ""))
|
||||
try:
|
||||
os.chmod(private_key_path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
private_key_path,
|
||||
config.get("private_key", ""),
|
||||
0o600,
|
||||
"Elydora private key",
|
||||
)
|
||||
|
||||
script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
hook_path = self._hook_path_for(agent_id)
|
||||
with open(hook_path, "w", encoding="utf-8") as f:
|
||||
f.write(script)
|
||||
try:
|
||||
os.chmod(hook_path, stat.S_IRWXU)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
hook_path,
|
||||
script,
|
||||
0o700,
|
||||
"Elydora audit runtime",
|
||||
)
|
||||
|
||||
guard_script_path = config.get("guard_script_path", "")
|
||||
python_exe = sys.executable
|
||||
@@ -92,7 +94,7 @@ class CursorPlugin(AgentPlugin):
|
||||
})
|
||||
|
||||
_save_json(SETTINGS_PATH, settings)
|
||||
print(f"Elydora hook installed for Cursor.")
|
||||
print("Elydora hook installed for Cursor.")
|
||||
print(f" Hook script: {hook_path}")
|
||||
print(f" Settings: {SETTINGS_PATH}")
|
||||
|
||||
@@ -176,7 +178,4 @@ def _load_json(path: str) -> dict:
|
||||
|
||||
|
||||
def _save_json(path: str, data: dict) -> None:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(path, data, 0o600, "Cursor hooks config")
|
||||
@@ -108,7 +108,6 @@ class DroidPlugin(AgentPlugin):
|
||||
audit_script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
|
||||
@@ -4,9 +4,9 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
|
||||
from ._file_io import write_json_atomic, write_text_atomic
|
||||
from .base import AgentPlugin, InstallConfig, PluginStatus
|
||||
from .hook_template import generate_hook_script
|
||||
|
||||
@@ -40,33 +40,35 @@ class GeminiPlugin(AgentPlugin):
|
||||
"agent_name": agent_name,
|
||||
}
|
||||
config_path = os.path.join(agent_dir, "config.json")
|
||||
with open(config_path, "w", encoding="utf-8") as f:
|
||||
json.dump(config_data, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(
|
||||
config_path,
|
||||
config_data,
|
||||
0o600,
|
||||
"Elydora runtime config",
|
||||
)
|
||||
|
||||
# Write private key
|
||||
private_key_path = os.path.join(agent_dir, "private.key")
|
||||
with open(private_key_path, "w", encoding="utf-8") as f:
|
||||
f.write(config.get("private_key", ""))
|
||||
try:
|
||||
os.chmod(private_key_path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
private_key_path,
|
||||
config.get("private_key", ""),
|
||||
0o600,
|
||||
"Elydora private key",
|
||||
)
|
||||
|
||||
script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
hook_path = self._hook_path_for(agent_id)
|
||||
with open(hook_path, "w", encoding="utf-8") as f:
|
||||
f.write(script)
|
||||
try:
|
||||
os.chmod(hook_path, stat.S_IRWXU)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
hook_path,
|
||||
script,
|
||||
0o700,
|
||||
"Elydora audit runtime",
|
||||
)
|
||||
|
||||
guard_script_path = config.get("guard_script_path", "")
|
||||
python_exe = sys.executable
|
||||
@@ -102,7 +104,7 @@ class GeminiPlugin(AgentPlugin):
|
||||
})
|
||||
|
||||
_save_json(SETTINGS_PATH, settings)
|
||||
print(f"Elydora hook installed for Gemini CLI.")
|
||||
print("Elydora hook installed for Gemini CLI.")
|
||||
print(f" Hook script: {hook_path}")
|
||||
print(f" Settings: {SETTINGS_PATH}")
|
||||
|
||||
@@ -201,7 +203,4 @@ def _load_json(path: str) -> dict:
|
||||
|
||||
|
||||
def _save_json(path: str, data: dict) -> None:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(path, data, 0o600, "Gemini settings")
|
||||
@@ -9,7 +9,7 @@ import shlex
|
||||
# subprocess provides argument quoting only; this module starts no process.
|
||||
import subprocess # nosec B404
|
||||
import sys
|
||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from ._file_io import (
|
||||
read_json as _read_json,
|
||||
@@ -362,7 +362,6 @@ class GrokPlugin(AgentPlugin):
|
||||
audit_script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
|
||||
@@ -14,7 +14,6 @@ def generate_hook_script(
|
||||
*,
|
||||
org_id: str,
|
||||
agent_id: str,
|
||||
private_key: str,
|
||||
kid: str,
|
||||
base_url: str,
|
||||
) -> str:
|
||||
@@ -38,6 +37,7 @@ import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import stat
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
@@ -47,14 +47,15 @@ import time
|
||||
# ---------------------------------------------------------------------------
|
||||
ORG_ID = {org_id!r}
|
||||
AGENT_ID = {agent_id!r}
|
||||
PRIVATE_KEY = {private_key!r}
|
||||
KID = {kid!r}
|
||||
BASE_URL = {base_url!r}
|
||||
|
||||
ELYDORA_DIR = os.path.join(os.path.expanduser("~"), ".elydora")
|
||||
PRIVATE_KEY_PATH = os.path.join(ELYDORA_DIR, AGENT_ID, "private.key")
|
||||
CHAIN_STATE_PATH = os.path.join(ELYDORA_DIR, AGENT_ID, "chain-state.json")
|
||||
ERROR_LOG_PATH = os.path.join(ELYDORA_DIR, AGENT_ID, "error.log")
|
||||
ZERO_CHAIN_HASH = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
MAX_PRIVATE_KEY_BYTES = 64 * 1024
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Base64url helpers
|
||||
@@ -134,6 +135,45 @@ def sign_ed25519(private_key_b64url, data):
|
||||
key = Ed25519PrivateKey.from_private_bytes(seed)
|
||||
return base64url_encode(key.sign(data))
|
||||
|
||||
def read_private_key():
|
||||
before = os.lstat(PRIVATE_KEY_PATH)
|
||||
if not stat.S_ISREG(before.st_mode):
|
||||
raise ValueError("Private key path is not a regular file: " + PRIVATE_KEY_PATH)
|
||||
if before.st_size > MAX_PRIVATE_KEY_BYTES:
|
||||
raise ValueError("Private key file exceeds the size limit: " + PRIVATE_KEY_PATH)
|
||||
if os.name != "nt" and before.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
|
||||
raise PermissionError("Private key file permissions are too broad: " + PRIVATE_KEY_PATH)
|
||||
|
||||
flags = os.O_RDONLY
|
||||
flags |= getattr(os, "O_BINARY", 0)
|
||||
flags |= getattr(os, "O_CLOEXEC", 0)
|
||||
flags |= getattr(os, "O_NOFOLLOW", 0)
|
||||
descriptor = os.open(PRIVATE_KEY_PATH, flags)
|
||||
try:
|
||||
file = os.fdopen(descriptor, "rb")
|
||||
descriptor = -1
|
||||
with file:
|
||||
after = os.fstat(file.fileno())
|
||||
if not stat.S_ISREG(after.st_mode):
|
||||
raise ValueError("Private key path is not a regular file: " + PRIVATE_KEY_PATH)
|
||||
if after.st_size > MAX_PRIVATE_KEY_BYTES:
|
||||
raise ValueError("Private key file exceeds the size limit: " + PRIVATE_KEY_PATH)
|
||||
if os.name != "nt" and after.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
|
||||
raise PermissionError("Private key file permissions are too broad: " + PRIVATE_KEY_PATH)
|
||||
if (before.st_dev, before.st_ino) != (after.st_dev, after.st_ino):
|
||||
raise OSError("Private key file changed while opening: " + PRIVATE_KEY_PATH)
|
||||
encoded = file.read(MAX_PRIVATE_KEY_BYTES + 1)
|
||||
finally:
|
||||
if descriptor >= 0:
|
||||
os.close(descriptor)
|
||||
|
||||
if len(encoded) > MAX_PRIVATE_KEY_BYTES:
|
||||
raise ValueError("Private key file exceeds the size limit: " + PRIVATE_KEY_PATH)
|
||||
value = encoded.decode("utf-8")
|
||||
if not value or "\\r" in value or "\\n" in value or "\\0" in value:
|
||||
raise ValueError("Private key file must contain exactly one line")
|
||||
return value
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# UUIDv7
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -259,7 +299,7 @@ def main():
|
||||
}}
|
||||
|
||||
canonical = jcs_canonicalize(eor_without_sig)
|
||||
signature = sign_ed25519(PRIVATE_KEY, canonical.encode("utf-8"))
|
||||
signature = sign_ed25519(read_private_key(), canonical.encode("utf-8"))
|
||||
|
||||
eor = dict(eor_without_sig)
|
||||
eor["chain_hash"] = chain_hash
|
||||
|
||||
@@ -413,7 +413,6 @@ class KimiPlugin(AgentPlugin):
|
||||
audit_script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
|
||||
@@ -105,7 +105,6 @@ class KiroCliPlugin(AgentPlugin):
|
||||
hook_script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
|
||||
@@ -4,9 +4,9 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
|
||||
from ._file_io import write_json_atomic, write_text_atomic
|
||||
from .base import AgentPlugin, InstallConfig, PluginStatus
|
||||
from .hook_template import generate_hook_script
|
||||
|
||||
@@ -44,34 +44,36 @@ class KiroIdePlugin(AgentPlugin):
|
||||
"agent_name": agent_name,
|
||||
}
|
||||
config_path = os.path.join(agent_dir, "config.json")
|
||||
with open(config_path, "w", encoding="utf-8") as f:
|
||||
json.dump(config_data, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(
|
||||
config_path,
|
||||
config_data,
|
||||
0o600,
|
||||
"Elydora runtime config",
|
||||
)
|
||||
|
||||
# Write private key
|
||||
private_key_path = os.path.join(agent_dir, "private.key")
|
||||
with open(private_key_path, "w", encoding="utf-8") as f:
|
||||
f.write(config.get("private_key", ""))
|
||||
try:
|
||||
os.chmod(private_key_path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
private_key_path,
|
||||
config.get("private_key", ""),
|
||||
0o600,
|
||||
"Elydora private key",
|
||||
)
|
||||
|
||||
# Write the Python hook script
|
||||
script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
script_path = self._hook_path_for(agent_id)
|
||||
with open(script_path, "w", encoding="utf-8") as f:
|
||||
f.write(script)
|
||||
try:
|
||||
os.chmod(script_path, stat.S_IRWXU)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
script_path,
|
||||
script,
|
||||
0o700,
|
||||
"Elydora audit runtime",
|
||||
)
|
||||
|
||||
guard_script_path = config.get("guard_script_path", "")
|
||||
python_exe = sys.executable
|
||||
@@ -93,13 +95,15 @@ class KiroIdePlugin(AgentPlugin):
|
||||
},
|
||||
}
|
||||
|
||||
os.makedirs(KIRO_HOOK_DIR, exist_ok=True)
|
||||
hook_path = self._kiro_hook_path()
|
||||
with open(hook_path, "w", encoding="utf-8") as f:
|
||||
json.dump(hook_config, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(
|
||||
hook_path,
|
||||
hook_config,
|
||||
0o600,
|
||||
"Kiro IDE hook definition",
|
||||
)
|
||||
|
||||
print(f"Elydora hook installed for Kiro IDE.")
|
||||
print("Elydora hook installed for Kiro IDE.")
|
||||
print(f" Hook script: {script_path}")
|
||||
print(f" Hook definition: {hook_path}")
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
|
||||
from ._file_io import write_json_atomic, write_text_atomic
|
||||
from .base import AgentPlugin, InstallConfig, PluginStatus
|
||||
from .hook_template import generate_hook_script
|
||||
|
||||
@@ -40,33 +40,35 @@ class LettaPlugin(AgentPlugin):
|
||||
"agent_name": agent_name,
|
||||
}
|
||||
config_path = os.path.join(agent_dir, "config.json")
|
||||
with open(config_path, "w", encoding="utf-8") as f:
|
||||
json.dump(config_data, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(
|
||||
config_path,
|
||||
config_data,
|
||||
0o600,
|
||||
"Elydora runtime config",
|
||||
)
|
||||
|
||||
# Write private key
|
||||
private_key_path = os.path.join(agent_dir, "private.key")
|
||||
with open(private_key_path, "w", encoding="utf-8") as f:
|
||||
f.write(config.get("private_key", ""))
|
||||
try:
|
||||
os.chmod(private_key_path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
private_key_path,
|
||||
config.get("private_key", ""),
|
||||
0o600,
|
||||
"Elydora private key",
|
||||
)
|
||||
|
||||
script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
hook_path = self._hook_path_for(agent_id)
|
||||
with open(hook_path, "w", encoding="utf-8") as f:
|
||||
f.write(script)
|
||||
try:
|
||||
os.chmod(hook_path, stat.S_IRWXU)
|
||||
except Exception:
|
||||
pass # chmod may fail on Windows
|
||||
write_text_atomic(
|
||||
hook_path,
|
||||
script,
|
||||
0o700,
|
||||
"Elydora audit runtime",
|
||||
)
|
||||
|
||||
guard_script_path = config.get("guard_script_path", "")
|
||||
python_exe = sys.executable
|
||||
@@ -104,7 +106,7 @@ class LettaPlugin(AgentPlugin):
|
||||
})
|
||||
|
||||
_save_json(SETTINGS_PATH, settings)
|
||||
print(f"Elydora hook installed for Letta Code.")
|
||||
print("Elydora hook installed for Letta Code.")
|
||||
print(f" Hook script: {hook_path}")
|
||||
print(f" Settings: {SETTINGS_PATH}")
|
||||
|
||||
@@ -203,7 +205,4 @@ def _load_json(path: str) -> dict:
|
||||
|
||||
|
||||
def _save_json(path: str, data: dict) -> None:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
f.write("\n")
|
||||
write_json_atomic(path, data, 0o600, "Letta settings")
|
||||
@@ -7,6 +7,7 @@ import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from ._file_io import write_json_atomic, write_text_atomic
|
||||
from .base import AgentPlugin, InstallConfig, PluginStatus
|
||||
from .hook_template import generate_hook_script
|
||||
|
||||
@@ -44,35 +45,41 @@ class OpenCodePlugin(AgentPlugin):
|
||||
"token": config.get("token", ""),
|
||||
"agent_name": config.get("agent_name", "opencode"),
|
||||
}
|
||||
_write_text(
|
||||
write_json_atomic(
|
||||
os.path.join(agent_dir, "config.json"),
|
||||
json.dumps(config_data, indent=2) + "\n",
|
||||
config_data,
|
||||
0o600,
|
||||
"Elydora runtime config",
|
||||
)
|
||||
_write_text(
|
||||
write_text_atomic(
|
||||
os.path.join(agent_dir, "private.key"),
|
||||
config.get("private_key", ""),
|
||||
0o600,
|
||||
"Elydora private key",
|
||||
)
|
||||
|
||||
hook_path = self._hook_path(agent_id)
|
||||
hook_script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
_write_text(hook_path, hook_script, 0o700)
|
||||
write_text_atomic(
|
||||
hook_path,
|
||||
hook_script,
|
||||
0o700,
|
||||
"Elydora audit runtime",
|
||||
)
|
||||
|
||||
os.makedirs(PLUGIN_DIR, exist_ok=True)
|
||||
_write_text(
|
||||
write_text_atomic(
|
||||
self._plugin_path(),
|
||||
_generate_js_plugin(
|
||||
hook_script_path=hook_path,
|
||||
guard_script_path=guard_script_path,
|
||||
),
|
||||
0o700,
|
||||
"OpenCode Elydora plugin",
|
||||
)
|
||||
print("Elydora hook installed for OpenCode.")
|
||||
print(f" Plugin: {self._plugin_path()}")
|
||||
@@ -105,16 +112,6 @@ class OpenCodePlugin(AgentPlugin):
|
||||
details = f"Plugin: {plugin_path}" if installed else "Not installed"
|
||||
return PluginStatus(installed=installed, agent="opencode", details=details)
|
||||
|
||||
|
||||
def _write_text(path: str, content: str, mode: int) -> None:
|
||||
with open(path, "w", encoding="utf-8") as file:
|
||||
file.write(content)
|
||||
try:
|
||||
os.chmod(path, mode)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _generate_js_plugin(*, hook_script_path: str, guard_script_path: str) -> str:
|
||||
return f'''// Elydora Audit Plugin for OpenCode
|
||||
// Generated by elydora-sdk — DO NOT EDIT
|
||||
|
||||
@@ -87,7 +87,6 @@ class QwenPlugin(AgentPlugin):
|
||||
audit_script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
private_key=config.get("private_key", ""),
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user