keyexec 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
keyexec/__init__.py ADDED
File without changes
keyexec/cli.py ADDED
@@ -0,0 +1,241 @@
1
+ import argparse
2
+ import getpass
3
+ import json
4
+ import shutil
5
+ import sys
6
+ from collections.abc import Callable
7
+ from importlib import metadata
8
+ from pathlib import Path
9
+ from typing import Any, NoReturn
10
+
11
+ from keyexec import doctor, inject, migrate, store
12
+ from keyexec.config import JSONObject, Scope, default_config_path
13
+ from keyexec.errors import ErrorCode, KeyexecError, MissingSecretError, UsageError
14
+
15
+ EXIT_CODES = [
16
+ (0, "success"),
17
+ *sorted((error.exit_code, error.meaning) for error in KeyexecError.__subclasses__()),
18
+ (inject.INTERRUPTED, "run: interrupted"),
19
+ ]
20
+ EPILOG = "\n".join(
21
+ [
22
+ "exit codes:",
23
+ *(f" {code:<4} {meaning}" for code, meaning in EXIT_CODES),
24
+ " run otherwise returns the child's own exit code (128+N when signal N ended it).",
25
+ ]
26
+ )
27
+
28
+ Result = tuple[JSONObject, str]
29
+
30
+
31
+ class Parser(argparse.ArgumentParser):
32
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
33
+ # No abbreviations: doctor reads `--env` as written in the config, so `--en`, which argparse would accept, would launch a server doctor cannot check.
34
+ super().__init__(*args, **kwargs, allow_abbrev=False)
35
+
36
+ def error(self, message: str) -> NoReturn:
37
+ raise UsageError(message)
38
+
39
+
40
+ def stdin_is_tty() -> bool:
41
+ return sys.stdin.isatty()
42
+
43
+
44
+ def stdout_is_tty() -> bool:
45
+ return sys.stdout.isatty()
46
+
47
+
48
+ def find_keyexec() -> str | None:
49
+ # absolute(), not resolve(): the PATH shim survives a `uv tool upgrade`, the symlink target inside the tool venv may not. On Windows argv[0] can lack `.exe`.
50
+ for candidate in (shutil.which("keyexec"), sys.argv[0], f"{sys.argv[0]}.exe"):
51
+ if candidate and Path(candidate).is_file() and Path(candidate).stem.lower() == "keyexec":
52
+ return str(Path(candidate).absolute())
53
+ return None
54
+
55
+
56
+ def build_parser() -> Parser:
57
+ common = Parser(add_help=False)
58
+ common.add_argument("--json", action="store_true", help="force JSON output (the default when stdout is not a TTY)")
59
+ config = Parser(add_help=False)
60
+ config.add_argument("--config", type=Path, default=None, help="Claude Code config file (default: ~/.claude.json)")
61
+
62
+ parser = Parser(
63
+ prog="keyexec",
64
+ description="Keep MCP server tokens in the OS credential store and inject them only into the server process.",
65
+ epilog=EPILOG,
66
+ formatter_class=argparse.RawDescriptionHelpFormatter,
67
+ )
68
+ parser.add_argument("--version", action="version", version=f"keyexec {metadata.version('keyexec')}")
69
+ sub = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
70
+
71
+ p = sub.add_parser("set", parents=[common], help="store a secret, typed at a TTY prompt")
72
+ p.add_argument("name", metavar="entry")
73
+ p.add_argument("--force", action="store_true", help="overwrite an existing entry")
74
+
75
+ sub.add_parser("list", parents=[common], help="list entry names; never values")
76
+
77
+ p = sub.add_parser("delete", parents=[common], help="delete an entry")
78
+ p.add_argument("name", metavar="entry")
79
+ p.add_argument("--yes", action="store_true", help="skip the confirmation (required when stdin is not a TTY)")
80
+
81
+ p = sub.add_parser(
82
+ "run",
83
+ help="run a command with secrets injected as environment variables",
84
+ usage="keyexec run --env VAR=entry [--env ...] -- COMMAND [ARGS...]",
85
+ )
86
+ p.add_argument("--env", action="append", default=[], metavar="VAR=entry", help="inject entry as VAR; repeatable")
87
+
88
+ p = sub.add_parser("headers", help="print HTTP headers as JSON for Claude Code's headersHelper")
89
+ p.add_argument("--header", action="append", required=True, metavar="Name=template", help="{entry} is replaced; {{ and }} are literal braces; repeatable")
90
+
91
+ sub.add_parser("doctor", parents=[common, config], help="check every keyexec reference in the Claude Code config")
92
+
93
+ p = sub.add_parser("migrate", parents=[common, config], help="move plaintext MCP tokens into the credential store (plan only unless --apply)")
94
+ p.add_argument("--apply", action="store_true", help="store the secrets and rewrite the config")
95
+ p.add_argument("--yes", action="store_true", help="skip the confirmation (required with --apply when stdin is not a TTY)")
96
+ p.add_argument("--force", action="store_true", help="overwrite entries that already hold a different value")
97
+ return parser
98
+
99
+
100
+ def _confirm(question: str, yes: bool) -> None:
101
+ if yes:
102
+ return
103
+ if not stdin_is_tty():
104
+ raise UsageError("confirmation needed: pass --yes when stdin is not a TTY", ErrorCode.CONFIRMATION_REQUIRED)
105
+ print(f"{question} [y/N] ", end="", file=sys.stderr, flush=True)
106
+ if _ask(input).strip().lower() not in ("y", "yes"):
107
+ raise UsageError("aborted", ErrorCode.ABORTED)
108
+
109
+
110
+ def _ask(prompt: Callable[[str], str], text: str = "") -> str:
111
+ try:
112
+ return prompt(text)
113
+ except (EOFError, KeyboardInterrupt):
114
+ # Ctrl+C or Ctrl+D at a prompt is a refusal, not a crash; nothing has been written at that point.
115
+ print(file=sys.stderr)
116
+ raise UsageError("aborted", ErrorCode.ABORTED) from None
117
+
118
+
119
+ def _where(server: str, scope: Scope, project: str | None) -> str:
120
+ return server if scope is Scope.USER else f"{server} (local to {project})"
121
+
122
+
123
+ def cmd_set(args: argparse.Namespace) -> Result:
124
+ store.validate_name(args.name)
125
+ if not stdin_is_tty():
126
+ raise UsageError("set reads the value from a TTY prompt only; it never reads from a pipe or the command line", ErrorCode.NOT_A_TTY)
127
+ if store.get_secret(args.name) is not None and not args.force:
128
+ raise UsageError(f"entry {args.name!r} exists; pass --force to overwrite it", ErrorCode.ENTRY_EXISTS)
129
+ value = store.validate_value(_ask(getpass.getpass, f"Value for {args.name}: "))
130
+ if _ask(getpass.getpass, "Repeat to confirm: ") != value:
131
+ raise UsageError("the two values did not match", ErrorCode.MISMATCH)
132
+ store.set_secret(args.name, value)
133
+ return {"ok": True, "name": args.name}, f"Stored {args.name}."
134
+
135
+
136
+ def cmd_list(args: argparse.Namespace) -> Result:
137
+ names = store.list_names()
138
+ return {"ok": True, "entries": names}, "\n".join(names) or "No entries."
139
+
140
+
141
+ def cmd_delete(args: argparse.Namespace) -> Result:
142
+ store.validate_name(args.name)
143
+ _confirm(f"Delete {args.name}?", args.yes)
144
+ store.delete_secret(args.name)
145
+ return {"ok": True, "name": args.name}, f"Deleted {args.name}."
146
+
147
+
148
+ def _doctor_text(report: doctor.Report) -> str:
149
+ lines = [f"Config: {report.config}"]
150
+ for s in report.servers:
151
+ lines.append(f"{_where(s.server, s.scope, s.project)} [{s.transport}]")
152
+ lines.extend(f" {'ok ' if e.resolves else 'MISSING'} {e.name}" for e in s.entries)
153
+ if not report.servers:
154
+ lines.append("No server uses keyexec.")
155
+ if report.missing:
156
+ lines.append(f"Missing entries: {store.missing_hint(report.missing)}")
157
+ return "\n".join(lines)
158
+
159
+
160
+ def cmd_doctor(args: argparse.Namespace) -> Result:
161
+ report = doctor.diagnose(args.config or default_config_path())
162
+ return report.to_dict(), _doctor_text(report)
163
+
164
+
165
+ def _plan_text(plan: migrate.Plan) -> list[str]:
166
+ lines = [f"Config: {plan.config}", f"keyexec: {plan.keyexec or '(not found)'}", ""]
167
+ for i in plan.items:
168
+ target = f"-> {i.entry}" if i.status is migrate.Status.MIGRATE else f"({i.reason})"
169
+ lines.append(f" {i.status:<8} {_where(i.server, i.scope, i.project):<20} {i.kind:<6} {i.key} {target} [{i.value_length} chars]")
170
+ if not plan.items:
171
+ lines.append(" No plaintext secrets found.")
172
+ if plan.servers:
173
+ lines.append("\nNew server shape:")
174
+ for s in plan.servers:
175
+ launch = f"{s.launch} {migrate.ORIGINAL_ARGS}" if s.kind is migrate.Kind.ENV else f"headersHelper={s.launch}"
176
+ lines.append(f" {_where(s.server, s.scope, s.project)}: {launch} kept keys={list(s.kept_keys)}")
177
+ return lines
178
+
179
+
180
+ def _applied_text(applied: migrate.Applied, plan_shown: bool) -> str:
181
+ lines = [] if plan_shown else [*_plan_text(applied.plan), ""]
182
+ lines += [f"Stored: {', '.join(applied.stored)}", f"Backup: {applied.backup}", "Next steps:"]
183
+ lines.extend(f" - {step}" for step in applied.next_steps)
184
+ return "\n".join(lines)
185
+
186
+
187
+ def cmd_migrate(args: argparse.Namespace) -> Result:
188
+ plan = migrate.build_plan(args.config or default_config_path(), find_keyexec())
189
+ if not (args.apply and plan.migrating()):
190
+ lines = _plan_text(plan)
191
+ if plan.servers:
192
+ lines.append("\nNothing changed. Re-run with --apply to store the secrets and rewrite the config.")
193
+ return plan.to_dict(), "\n".join(lines)
194
+ if not args.yes:
195
+ print("\n".join(_plan_text(plan)), file=sys.stderr)
196
+ _confirm("Store these secrets and rewrite the config?", args.yes)
197
+ applied = migrate.apply_plan(plan, force=args.force)
198
+ # The confirmation already showed the plan; repeat it only when --yes skipped that.
199
+ return applied.to_dict(), _applied_text(applied, plan_shown=not args.yes)
200
+
201
+
202
+ COMMANDS: dict[str, Callable[[argparse.Namespace], Result]] = {
203
+ "set": cmd_set,
204
+ "list": cmd_list,
205
+ "delete": cmd_delete,
206
+ "doctor": cmd_doctor,
207
+ "migrate": cmd_migrate,
208
+ }
209
+
210
+
211
+ def main(argv: list[str] | None = None) -> int:
212
+ argv = list(sys.argv[1:] if argv is None else argv)
213
+ # Split by hand so the child's own flags never reach argparse, and decide JSON before parsing so a parse error is JSON too.
214
+ head, tail = argv, None
215
+ if "--" in argv:
216
+ split = argv.index("--")
217
+ head, tail = argv[:split], argv[split + 1 :]
218
+ as_json = "--json" in head or not stdout_is_tty()
219
+ try:
220
+ args = build_parser().parse_args(head)
221
+ if args.command == "run":
222
+ return inject.run(args.env, tail or [])
223
+ if tail is not None:
224
+ raise UsageError("`--` is only meaningful for run")
225
+ if args.command == "headers":
226
+ # Always JSON: Claude Code parses this output, and a TTY check would only matter to a human debugging it.
227
+ print(json.dumps(inject.render_headers(args.header)))
228
+ return 0
229
+ payload, text = COMMANDS[args.command](args)
230
+ if not as_json:
231
+ for warning in payload.get("warnings", []):
232
+ print(f"warning: {warning}", file=sys.stderr)
233
+ print(json.dumps(payload, indent=2) if as_json else text)
234
+ # doctor is the only command that reports ok: false, and only for a missing entry.
235
+ return 0 if payload.get("ok", True) else MissingSecretError.exit_code
236
+ except KeyexecError as exc:
237
+ if as_json:
238
+ print(json.dumps({"ok": False, "error": {"code": exc.code, "message": exc.message}}), file=sys.stderr)
239
+ else:
240
+ print(f"keyexec: {exc.message}", file=sys.stderr)
241
+ return exc.exit_code
keyexec/config.py ADDED
@@ -0,0 +1,88 @@
1
+ import hashlib
2
+ import json
3
+ from collections.abc import Iterator
4
+ from dataclasses import dataclass
5
+ from enum import StrEnum
6
+ from pathlib import Path, PureWindowsPath
7
+ from typing import Any
8
+
9
+ from keyexec.errors import ConfigError
10
+
11
+ # Any, because the shape is Claude Code's and changes without notice: a reader checks the type of each field it relies on instead of trusting a schema.
12
+ JSONObject = dict[str, Any]
13
+
14
+
15
+ class Scope(StrEnum):
16
+ USER = "user"
17
+ # Claude Code's name for servers kept per project directory inside ~/.claude.json; its "project" scope is a repo's .mcp.json, which keyexec does not read.
18
+ LOCAL = "local"
19
+
20
+
21
+ class Transport(StrEnum):
22
+ STDIO = "stdio"
23
+ HTTP = "http"
24
+ SSE = "sse"
25
+
26
+
27
+ @dataclass(frozen=True, slots=True, kw_only=True)
28
+ class ServerRef:
29
+ scope: Scope
30
+ project: str | None
31
+ name: str
32
+ server: JSONObject
33
+
34
+
35
+ def default_config_path() -> Path:
36
+ return Path.home() / ".claude.json"
37
+
38
+
39
+ def read_config(path: Path) -> tuple[bytes, JSONObject]:
40
+ try:
41
+ raw = path.read_bytes()
42
+ except OSError as exc:
43
+ raise ConfigError(f"cannot read {path}: {exc.strerror or exc}") from exc
44
+ try:
45
+ data = json.loads(raw)
46
+ except ValueError as exc:
47
+ raise ConfigError(f"{path} is not valid JSON: {exc}") from exc
48
+ if not isinstance(data, dict):
49
+ raise ConfigError(f"{path} does not hold a JSON object")
50
+ return raw, data
51
+
52
+
53
+ def digest(raw: bytes) -> str:
54
+ return hashlib.sha256(raw).hexdigest()
55
+
56
+
57
+ def iter_servers(data: JSONObject) -> Iterator[ServerRef]:
58
+ for name, server in _servers(data.get("mcpServers")):
59
+ yield ServerRef(scope=Scope.USER, project=None, name=name, server=server)
60
+ projects = data.get("projects")
61
+ if isinstance(projects, dict):
62
+ for project, settings in projects.items():
63
+ if isinstance(settings, dict):
64
+ for name, server in _servers(settings.get("mcpServers")):
65
+ yield ServerRef(scope=Scope.LOCAL, project=project, name=name, server=server)
66
+
67
+
68
+ def _servers(block: object) -> Iterator[tuple[str, JSONObject]]:
69
+ if isinstance(block, dict):
70
+ yield from ((name, server) for name, server in block.items() if isinstance(server, dict))
71
+
72
+
73
+ def is_keyexec(command: object) -> bool:
74
+ # PureWindowsPath splits on both separators, so a config written on Windows is recognised on any OS; case is ignored as Windows and macOS ignore it.
75
+ if not isinstance(command, str):
76
+ return False
77
+ path = PureWindowsPath(command)
78
+ return path.stem.lower() == "keyexec" and path.suffix.lower() in {"", ".exe", ".cmd", ".bat"}
79
+
80
+
81
+ def transport_of(server: JSONObject) -> Transport:
82
+ if not is_http(server):
83
+ return Transport.STDIO
84
+ return Transport.SSE if server.get("type") == "sse" else Transport.HTTP
85
+
86
+
87
+ def is_http(server: JSONObject) -> bool:
88
+ return server.get("type") in ("http", "sse") or ("url" in server and "command" not in server)
keyexec/doctor.py ADDED
@@ -0,0 +1,117 @@
1
+ import shlex
2
+ from dataclasses import asdict, dataclass
3
+ from itertools import pairwise
4
+ from pathlib import Path
5
+
6
+ from keyexec import migrate, store
7
+ from keyexec.config import JSONObject, Scope, Transport, is_keyexec, iter_servers, read_config, transport_of
8
+ from keyexec.errors import ConfigError, UsageError
9
+ from keyexec.inject import parse_env_mapping, parse_header_spec, template_entries
10
+
11
+
12
+ @dataclass(frozen=True, slots=True, kw_only=True)
13
+ class EntryCheck:
14
+ name: str
15
+ resolves: bool
16
+
17
+
18
+ @dataclass(frozen=True, slots=True, kw_only=True)
19
+ class ServerCheck:
20
+ scope: Scope
21
+ project: str | None
22
+ server: str
23
+ transport: Transport
24
+ entries: tuple[EntryCheck, ...]
25
+
26
+
27
+ @dataclass(frozen=True, slots=True, kw_only=True)
28
+ class Plaintext:
29
+ scope: Scope
30
+ project: str | None
31
+ server: str
32
+ key: str
33
+
34
+
35
+ @dataclass(frozen=True, slots=True, kw_only=True)
36
+ class Report:
37
+ config: Path
38
+ servers: tuple[ServerCheck, ...]
39
+ plaintext: tuple[Plaintext, ...]
40
+ backups: tuple[str, ...]
41
+
42
+ @property
43
+ def missing(self) -> list[str]:
44
+ return sorted({e.name for s in self.servers for e in s.entries if not e.resolves})
45
+
46
+ @property
47
+ def warnings(self) -> list[str]:
48
+ found = [f"server {p.server!r} still holds {p.key!r} in plaintext; run `keyexec migrate`" for p in self.plaintext]
49
+ return found + [migrate.backup_warning(backup) for backup in self.backups]
50
+
51
+ def to_dict(self) -> JSONObject:
52
+ return {"ok": not self.missing, **asdict(self), "config": str(self.config), "missing": self.missing, "warnings": self.warnings}
53
+
54
+
55
+ def _values(tokens: list[str], flag: str) -> list[str]:
56
+ # argparse takes both `--env X=y` and `--env=X=y` (and no abbreviation), so both must be read here or doctor passes a server that fails at launch.
57
+ values = []
58
+ for token, following in pairwise([*tokens, ""]):
59
+ if token == flag:
60
+ values.append(following)
61
+ elif token.startswith(f"{flag}="):
62
+ values.append(token[len(flag) + 1 :])
63
+ return values
64
+
65
+
66
+ def run_entries(args: list[object]) -> list[str]:
67
+ head = [arg for arg in (args[: args.index("--")] if "--" in args else args) if isinstance(arg, str)]
68
+ if not head or head[0] != "run":
69
+ return []
70
+ return [parse_env_mapping(spec)[1] for spec in _values(head, "--env")]
71
+
72
+
73
+ def helper_entries(helper: str) -> list[str] | None:
74
+ """None, not [], when the helper is not a keyexec invocation or cannot be split, so the caller can tell "not ours" from "ours with no entries"."""
75
+ try:
76
+ tokens = shlex.split(helper)
77
+ except ValueError:
78
+ return None
79
+ if len(tokens) < 2 or not is_keyexec(tokens[0]) or tokens[1] != "headers":
80
+ return None
81
+ return [entry for spec in _values(tokens, "--header") for entry in template_entries(parse_header_spec(spec)[1])]
82
+
83
+
84
+ def _keyexec_use(server: JSONObject) -> tuple[Transport, list[str]] | None:
85
+ args, helper = server.get("args"), server.get("headersHelper")
86
+ if is_keyexec(server.get("command")) and isinstance(args, list):
87
+ return Transport.STDIO, run_entries(args)
88
+ if isinstance(helper, str) and (entries := helper_entries(helper)) is not None:
89
+ return transport_of(server), entries
90
+ return None
91
+
92
+
93
+ def diagnose(path: Path) -> Report:
94
+ _, data = read_config(path)
95
+ # Names, not values: existence is all doctor needs, and on macOS each value read can raise a Keychain prompt.
96
+ stored = set(store.list_names())
97
+ checks = []
98
+ for ref in iter_servers(data):
99
+ try:
100
+ use = _keyexec_use(ref.server)
101
+ except UsageError as exc:
102
+ raise ConfigError(f"server {ref.name!r} has a malformed keyexec invocation: {exc.message}") from exc
103
+ if use is None:
104
+ continue
105
+ transport, entries = use
106
+ checks.append(
107
+ ServerCheck(
108
+ scope=ref.scope,
109
+ project=ref.project,
110
+ server=ref.name,
111
+ transport=transport,
112
+ entries=tuple(EntryCheck(name=e, resolves=e in stored) for e in entries),
113
+ )
114
+ )
115
+ plaintext = tuple(Plaintext(scope=ref.scope, project=ref.project, server=ref.name, key=key) for ref, key in migrate.plaintext_keys(data))
116
+ backups = tuple(sorted(str(p) for p in path.parent.glob(f"{path.name}.keyexec-backup-*")))
117
+ return Report(config=path, servers=tuple(checks), plaintext=plaintext, backups=backups)
keyexec/errors.py ADDED
@@ -0,0 +1,71 @@
1
+ from enum import StrEnum
2
+ from typing import ClassVar
3
+
4
+
5
+ class ErrorCode(StrEnum):
6
+ USAGE = "usage"
7
+ INVALID_NAME = "invalid_name"
8
+ EMPTY_VALUE = "empty_value"
9
+ VALUE_TOO_LONG = "value_too_long"
10
+ NOT_A_TTY = "not_a_tty"
11
+ MISMATCH = "mismatch"
12
+ ENTRY_EXISTS = "entry_exists"
13
+ CONFIRMATION_REQUIRED = "confirmation_required"
14
+ ABORTED = "aborted"
15
+ NOTHING_TO_MIGRATE = "nothing_to_migrate"
16
+ MISSING_SECRET = "missing_secret"
17
+ STORE_ERROR = "store_error"
18
+ CONFIG_ERROR = "config_error"
19
+ CONFIG_CHANGED = "config_changed"
20
+ KEYEXEC_NOT_FOUND = "keyexec_not_found"
21
+ JOB_OBJECT = "job_object"
22
+ COMMAND_NOT_FOUND = "command_not_found"
23
+
24
+
25
+ class KeyexecError(Exception):
26
+ # Raised only through a direct subclass, which sets all three: `--help` lists the direct subclasses, and `meaning` is the line it prints for `exit_code`, which docs/cli.md repeats and a test keeps equal.
27
+ exit_code: ClassVar[int]
28
+ code: ErrorCode
29
+ meaning: ClassVar[str]
30
+
31
+ def __init__(self, message: str, code: ErrorCode | None = None) -> None:
32
+ super().__init__(message)
33
+ self.message = message
34
+ if code:
35
+ self.code = code
36
+
37
+
38
+ class JobObjectError(KeyexecError):
39
+ exit_code = 1
40
+ code = ErrorCode.JOB_OBJECT
41
+ meaning = "run on Windows: the child could not be bound to keyexec's lifetime (job object), so nothing was launched"
42
+
43
+
44
+ class UsageError(KeyexecError):
45
+ exit_code = 2
46
+ code = ErrorCode.USAGE
47
+ meaning = "usage error, or a needed confirmation, --yes or --force was missing"
48
+
49
+
50
+ class MissingSecretError(KeyexecError):
51
+ exit_code = 3
52
+ code = ErrorCode.MISSING_SECRET
53
+ meaning = "a referenced entry is missing from the credential store (doctor still prints its report)"
54
+
55
+
56
+ class StoreError(KeyexecError):
57
+ exit_code = 4
58
+ code = ErrorCode.STORE_ERROR
59
+ meaning = "the credential store failed (locked, unavailable, or not Windows or macOS)"
60
+
61
+
62
+ class ConfigError(KeyexecError):
63
+ exit_code = 5
64
+ code = ErrorCode.CONFIG_ERROR
65
+ meaning = "the Claude Code config could not be read, parsed or safely written, or changed during migrate"
66
+
67
+
68
+ class CommandNotFoundError(KeyexecError):
69
+ exit_code = 127
70
+ code = ErrorCode.COMMAND_NOT_FOUND
71
+ meaning = "run: command not found"
keyexec/inject.py ADDED
@@ -0,0 +1,118 @@
1
+ import os
2
+ import re
3
+ import shutil
4
+ import signal
5
+ import string
6
+ import subprocess
7
+ import sys
8
+
9
+ from keyexec import store, winjob
10
+ from keyexec.errors import CommandNotFoundError, MissingSecretError, UsageError
11
+
12
+ ENV_VAR_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
13
+ HEADER_NAME_RE = re.compile(r"^[A-Za-z0-9!#$%&'*+.^_`|~-]+$")
14
+
15
+
16
+ def parse_env_mapping(spec: str) -> tuple[str, str]:
17
+ var, sep, name = spec.partition("=")
18
+ if not sep or not ENV_VAR_RE.fullmatch(var):
19
+ raise UsageError(f"--env expects VAR=entry, an entry name rather than the secret itself; got {len(spec)} characters that do not match")
20
+ return var, store.validate_name(name)
21
+
22
+
23
+ def parse_header_spec(spec: str) -> tuple[str, str]:
24
+ name, sep, template = spec.partition("=")
25
+ if not sep or not HEADER_NAME_RE.fullmatch(name):
26
+ raise UsageError(f"--header expects Name=template; got {len(spec)} characters that do not match")
27
+ template_entries(template)
28
+ return name, template
29
+
30
+
31
+ def _template_parts(template: str) -> list[tuple[str, str | None]]:
32
+ try:
33
+ parsed = list(string.Formatter().parse(template))
34
+ except ValueError as exc:
35
+ raise UsageError(f"malformed header template: {exc}") from exc
36
+ parts = []
37
+ for literal, field, spec, conversion in parsed:
38
+ if field is not None and (spec or conversion):
39
+ raise UsageError("malformed header template: placeholders take an entry name only")
40
+ parts.append((literal, None if field is None else store.validate_name(field)))
41
+ return parts
42
+
43
+
44
+ def template_entries(template: str) -> list[str]:
45
+ return [field for _, field in _template_parts(template) if field is not None]
46
+
47
+
48
+ def render_template(template: str, values: dict[str, str]) -> str:
49
+ return "".join(literal + (values[field] if field is not None else "") for literal, field in _template_parts(template))
50
+
51
+
52
+ def _resolve_or_fail(names: list[str]) -> dict[str, str]:
53
+ found, missing = store.resolve(names)
54
+ if missing:
55
+ raise MissingSecretError(f"missing entries: {store.missing_hint(missing)}")
56
+ return found
57
+
58
+
59
+ def render_headers(specs: list[str]) -> dict[str, str]:
60
+ parsed = [parse_header_spec(spec) for spec in specs]
61
+ values = _resolve_or_fail([name for _, template in parsed for name in template_entries(template)])
62
+ return {name: render_template(template, values) for name, template in parsed}
63
+
64
+
65
+ def build_env(mappings: list[str]) -> dict[str, str]:
66
+ parsed = [parse_env_mapping(spec) for spec in mappings]
67
+ values = _resolve_or_fail([name for _, name in parsed])
68
+ return {**os.environ, **{var: values[name] for var, name in parsed}}
69
+
70
+
71
+ # 128 + SIGINT, what a POSIX shell reports for Ctrl+C, so both platforms return the same code.
72
+ INTERRUPTED = 130
73
+
74
+
75
+ def run(mappings: list[str], command: list[str]) -> int:
76
+ if not command:
77
+ raise UsageError("run needs `-- COMMAND [ARGS...]` after the --env mappings")
78
+ env = build_env(mappings)
79
+ # A bare name like `npx` is a .cmd shim on Windows, which CreateProcess will not find without the extension.
80
+ executable = shutil.which(command[0], path=env.get("PATH"))
81
+ if executable is None:
82
+ raise CommandNotFoundError(f"command not found: {command[0]}")
83
+ argv = [executable, *command[1:]]
84
+ if sys.platform == "win32":
85
+ winjob.bind_descendants_to_this_process()
86
+ child = subprocess.Popen(argv, env=env)
87
+ try:
88
+ return child.wait()
89
+ except KeyboardInterrupt:
90
+ child.terminate()
91
+ child.wait()
92
+ return INTERRUPTED
93
+ return _run_forwarding_signals(argv, env)
94
+
95
+
96
+ def _run_forwarding_signals(argv: list[str], env: dict[str, str]) -> int:
97
+ # The parent of an MCP server stops it with SIGTERM, and POSIX has no parent-death signal: forwarding is what lets the server shut down instead of being orphaned.
98
+ # The handlers go in before the spawn, so a signal arriving during it is held and delivered rather than killing keyexec with the child already running.
99
+ assert sys.platform != "win32"
100
+ child: subprocess.Popen[bytes] | None = None
101
+ held: list[int] = []
102
+
103
+ def forward(signum: int, _frame: object) -> None:
104
+ if child is None:
105
+ held.append(signum)
106
+ else:
107
+ child.send_signal(signum)
108
+
109
+ previous = {sig: signal.signal(sig, forward) for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)}
110
+ try:
111
+ child = subprocess.Popen(argv, env=env)
112
+ for signum in held:
113
+ child.send_signal(signum)
114
+ code = child.wait()
115
+ finally:
116
+ for sig, handler in previous.items():
117
+ signal.signal(sig, handler)
118
+ return 128 - code if code < 0 else code