Files
ChaosCrypt/chaoscrypt/cli.py
T
dvs 24a36d6fb4 cli: accept --json and --quiet in either position
The global output flags were only registered on the top-level parser, so
`chaoscrypt info -k my.key -P keypwd --json` failed with "unrecognized
arguments: --json". That is the form most people type first, since the flag
reads naturally at the end of a command.

Both flags are now also registered on every subcommand. They write to
separate destinations (json_local / quiet_local) because argparse would
otherwise let an unset subcommand flag overwrite an explicitly set global
one; the two are merged in main().

Three regression tests cover the flag in both positions plus the bare
ciphertext output when neither flag is given.
2026-09-27 17:07:13 +08:00

639 lines
21 KiB
Python

"""
ChaosCrypt command line interface.
Invocation contract:
* ``chaoscrypt`` with no arguments launches the interactive TUI;
* ``chaoscrypt <command> ...`` runs a scriptable CLI command.
Every command supports ``--json`` for machine-readable output.
Exit codes:
0 success
1 runtime error (a ChaosCrypt error was raised)
2 usage error (argument parsing failed)
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import List, Optional
from . import DEFAULT_KEY_FILE, __version__
from .errors import ChaosCryptError, ChaosCrypt_ERR_InvalidArgument_E013
__all__ = ["build_parser", "main", "cli_main"]
PROG = "chaoscrypt"
EXIT_OK = 0
EXIT_ERROR = 1
EXIT_USAGE = 2
# ---------------------------------------------------------------------------
# Password resolution
# ---------------------------------------------------------------------------
def _resolve_password(
inline: Optional[str],
env: Optional[str],
file_path: Optional[str],
what: str = "password",
) -> Optional[str]:
"""Resolve a password from the command line.
Precedence is inline value, then environment variable, then file. Files
are read from their last non-empty line, so ``echo secret > .pwd`` works.
Raises:
ChaosCrypt_ERR_InvalidArgument_E013: the source was unreadable.
"""
if inline is not None:
return inline
if env:
val = os.environ.get(env)
if val is None:
raise ChaosCrypt_ERR_InvalidArgument_E013(
detail=f"EnvVarNotSet:{env}", code="E013"
)
return val
if file_path:
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
except OSError as exc:
raise ChaosCrypt_ERR_InvalidArgument_E013(
detail=f"PasswordFileUnreadable:{exc}", code="E013"
)
lines = [ln.strip() for ln in content.splitlines() if ln.strip()]
if not lines:
raise ChaosCrypt_ERR_InvalidArgument_E013(
detail=f"PasswordFileEmpty:{file_path}", code="E013"
)
return lines[-1]
return None
def _add_global_flags(parser: argparse.ArgumentParser) -> None:
"""Re-register the global output flags on a subcommand.
``--json`` and ``--quiet`` are also accepted before the subcommand. Adding
them here as well lets users write either form, which is what most people
reach for first::
chaoscrypt --json info -k my.key -P keypwd
chaoscrypt info -k my.key -P keypwd --json
The values are merged in :func:`main` by taking whichever was set.
"""
parser.add_argument(
"-j", "--json", action="store_true", default=False,
dest="json_local",
help="emit machine-readable JSON on stdout",
)
parser.add_argument(
"-q", "--quiet", action="store_true", default=False,
dest="quiet_local",
help="suppress non-essential human-readable output",
)
def _add_password_opts(
parser: argparse.ArgumentParser,
prefix: str,
label: str,
*,
dest_prefix: str = "",
long_prefix: str = "pwd",
) -> None:
"""Attach a standard password option group to a subcommand.
Args:
parser: Subcommand parser to extend.
prefix: Short option such as ``-p`` or ``-P``.
label: Human-readable label, e.g. ``"encryption password"``.
dest_prefix: Attribute prefix so two password groups can coexist.
long_prefix: Long option stem, e.g. ``pwd`` or ``key-pwd``.
"""
group = parser.add_argument_group(f"{label} options")
group.add_argument(
prefix,
f"--{long_prefix}",
dest=f"{dest_prefix}password",
metavar="PWD",
help=f"{label} on the command line "
f"(not recommended: visible in shell history)",
)
group.add_argument(
f"--{long_prefix}-env",
dest=f"{dest_prefix}password_env",
metavar="VAR",
help=f"read {label} from environment variable VAR",
)
group.add_argument(
f"--{long_prefix}-file",
dest=f"{dest_prefix}password_file",
metavar="PATH",
help=f"read {label} from the last non-empty line of PATH",
)
# ---------------------------------------------------------------------------
# Parser
# ---------------------------------------------------------------------------
def build_parser() -> argparse.ArgumentParser:
"""Build the top-level argument parser."""
parser = argparse.ArgumentParser(
prog=PROG,
description=(
"ChaosCrypt - a chaos-based obfuscation cipher.\n"
"Unaudited and non-standardised: intended for obfuscation, "
"personal use and study, not for production systems."
),
epilog=(
"examples:\n"
" chaoscrypt launch the interactive TUI\n"
" chaoscrypt keygen -k my.key --key-pwd-env KP\n"
" chaoscrypt encrypt \"hello\" -p secret -k my.key -P keypass\n"
" chaoscrypt decrypt \"1a2b...\" -p secret -k my.key -P keypass\n"
" chaoscrypt file encrypt photo.png -p secret -k my.key -P keypass\n"
" chaoscrypt info -k my.key -P keypass --json\n"
),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"-V", "--version", action="version",
version=f"{PROG} {__version__} (MIT licence, unaudited, as-is)",
)
parser.add_argument(
"-j", "--json", action="store_true",
help="emit machine-readable JSON on stdout",
)
parser.add_argument(
"-q", "--quiet", action="store_true",
help="suppress non-essential human-readable output",
)
sub = parser.add_subparsers(dest="command", metavar="<command>")
# ------------------------------------------------------------------ keygen
p_keygen = sub.add_parser(
"keygen", help="generate a new key file",
description="Generate a new ChaosCrypt key file.",
)
_add_global_flags(p_keygen)
p_keygen.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
help=f"output key file (default: {DEFAULT_KEY_FILE})",
)
p_keygen.add_argument(
"-f", "--force", action="store_true",
help="overwrite if the target already exists",
)
_add_password_opts(p_keygen, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
# ----------------------------------------------------------------- encrypt
p_enc = sub.add_parser(
"encrypt", help="encrypt text",
description="Encrypt a string into a hexadecimal ciphertext.",
)
_add_global_flags(p_enc)
p_enc.add_argument("text", nargs="?", help="plaintext (use - for stdin)")
p_enc.add_argument(
"-i", "--in", dest="in_file", metavar="PATH",
help="read plaintext from a file instead of argv",
)
p_enc.add_argument(
"-o", "--out", dest="out_file", metavar="PATH",
help="write ciphertext to a file instead of stdout",
)
p_enc.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
help=f"key file (default: {DEFAULT_KEY_FILE})",
)
_add_password_opts(p_enc, "-p", "encryption password",
dest_prefix="", long_prefix="pwd")
_add_password_opts(p_enc, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
# ----------------------------------------------------------------- decrypt
p_dec = sub.add_parser(
"decrypt", help="decrypt text",
description="Decrypt a hexadecimal ciphertext back into text.",
)
_add_global_flags(p_dec)
p_dec.add_argument("text", nargs="?", help="ciphertext (use - for stdin)")
p_dec.add_argument(
"-i", "--in", dest="in_file", metavar="PATH",
help="read ciphertext from a file instead of argv",
)
p_dec.add_argument(
"-o", "--out", dest="out_file", metavar="PATH",
help="write plaintext to a file instead of stdout",
)
p_dec.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
help=f"key file (default: {DEFAULT_KEY_FILE})",
)
_add_password_opts(p_dec, "-p", "encryption password",
dest_prefix="", long_prefix="pwd")
_add_password_opts(p_dec, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
# -------------------------------------------------------------------- file
p_file = sub.add_parser(
"file", help="encrypt or decrypt whole files (binary-safe)",
description="Binary-safe file encryption and decryption.",
)
file_sub = p_file.add_subparsers(dest="file_command", metavar="<action>")
p_fe = file_sub.add_parser("encrypt", help="encrypt a file to .cc")
_add_global_flags(p_fe)
p_fe.add_argument("src", help="source file")
p_fe.add_argument(
"-o", "--out", dest="out_file", metavar="PATH",
help="output path (default: <src>.cc)",
)
p_fe.add_argument("-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH")
_add_password_opts(p_fe, "-p", "encryption password",
dest_prefix="", long_prefix="pwd")
_add_password_opts(p_fe, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
p_fd = file_sub.add_parser("decrypt", help="decrypt a .cc file")
_add_global_flags(p_fd)
p_fd.add_argument("src", help="source .cc file")
p_fd.add_argument(
"-o", "--out", dest="out_file", metavar="PATH",
help="output path (default: strip the .cc suffix)",
)
p_fd.add_argument("-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH")
_add_password_opts(p_fd, "-p", "encryption password",
dest_prefix="", long_prefix="pwd")
_add_password_opts(p_fd, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
# -------------------------------------------------------------------- info
p_info = sub.add_parser(
"info", help="show key file metadata",
description="Show metadata for a key file. Secret material is "
"redacted unless --show-maps is given.",
)
_add_global_flags(p_info)
p_info.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
help=f"key file (default: {DEFAULT_KEY_FILE})",
)
_add_password_opts(p_info, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
p_info.add_argument(
"--show-maps", action="store_true",
help="also print the substitution tables (sensitive)",
)
# ------------------------------------------------------------------- chpwd
p_chpwd = sub.add_parser(
"chpwd", help="change a key file password",
description="Re-wrap an existing key file under a new password. "
"The key material itself is unchanged.",
)
_add_global_flags(p_chpwd)
p_chpwd.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
)
_add_password_opts(p_chpwd, "-P", "current key file password",
dest_prefix="key_", long_prefix="key-pwd")
p_chpwd.add_argument(
"--new-pwd", metavar="PWD", help="new key file password",
)
p_chpwd.add_argument(
"--new-pwd-env", metavar="VAR",
help="read the new key file password from environment variable VAR",
)
p_chpwd.add_argument(
"--new-pwd-file", metavar="PATH",
help="read the new key file password from PATH",
)
# --------------------------------------------------------------------- tui
sub.add_parser(
"tui", help="launch the interactive TUI",
description="Launch the interactive terminal UI, identical to "
"running chaoscrypt with no arguments.",
)
return parser
# ---------------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------------
def _emit(payload: dict, args: argparse.Namespace,
human_lines: Optional[List[str]] = None) -> None:
"""Print either JSON or human-readable lines."""
if getattr(args, "json", False):
print(json.dumps(payload, ensure_ascii=False, indent=2))
return
if not getattr(args, "quiet", False) and human_lines:
for line in human_lines:
print(line)
def _err_exit(exc: ChaosCryptError, args: argparse.Namespace) -> int:
"""Report a unified error and return the runtime-error exit code."""
if getattr(args, "json", False):
print(json.dumps(
{"ok": False, "error": str(exc), "code": exc.code},
ensure_ascii=False, indent=2,
))
else:
print(f"error: {exc}", file=sys.stderr)
return EXIT_ERROR
def _read_input(inline: Optional[str], in_file: Optional[str],
what: str = "input") -> str:
"""Read payload from argv, a file, or stdin."""
if in_file:
try:
with open(in_file, "r", encoding="utf-8") as f:
return f.read().strip()
except OSError as exc:
raise ChaosCrypt_ERR_InvalidArgument_E013(
detail=f"InputFileUnreadable:{exc}", code="E013"
)
if inline is not None and inline != "-":
return inline
# '-' or nothing at all: read stdin.
data = sys.stdin.read()
if not data:
raise ChaosCrypt_ERR_InvalidArgument_E013(
detail=f"MissingInput:{what}", code="E013"
)
return data.strip()
# ---------------------------------------------------------------------------
# Command implementations
# ---------------------------------------------------------------------------
def _cmd_keygen(args: argparse.Namespace) -> int:
from . import ChaosCrypt
from .errors import ChaosCrypt_ERR_EmptyPassword_E006
pwd = _resolve_password(
args.key_password, args.key_password_env, args.key_password_file,
"key file password",
)
if pwd is None:
return _err_exit(
ChaosCrypt_ERR_EmptyPassword_E006(
detail="NoKeyFilePassword", code="E006"
),
args,
)
cc = ChaosCrypt()
path = cc.create_key(pwd, args.key_file, overwrite=args.force)
_emit(
{"ok": True, "key_file": os.path.abspath(path)},
args,
[f"Key file created: {os.path.abspath(path)}"],
)
return EXIT_OK
def _cmd_text(args: argparse.Namespace, mode: str) -> int:
from . import ChaosCrypt
from .errors import ChaosCrypt_ERR_EmptyPassword_E006, \
ChaosCrypt_ERR_FileWriteFailed_E015
pwd = _resolve_password(
args.password, args.password_env, args.password_file, "encryption password"
)
key_pwd = _resolve_password(
args.key_password, args.key_password_env, args.key_password_file,
"key file password",
)
if pwd is None or key_pwd is None:
return _err_exit(
ChaosCrypt_ERR_EmptyPassword_E006(
detail="MissingPassword", code="E006"
),
args,
)
text = _read_input(
args.text, args.in_file, "plaintext" if mode == "encrypt" else "ciphertext"
)
cc = ChaosCrypt()
cc.load(args.key_file, key_pwd)
if mode == "encrypt":
result = cc.encrypt(text, pwd)
payload = {"ok": True, "mode": "encrypt", "ciphertext": result}
else:
result = cc.decrypt(text, pwd)
payload = {"ok": True, "mode": "decrypt", "plaintext": result}
if args.out_file:
try:
with open(args.out_file, "w", encoding="utf-8") as f:
f.write(result)
except OSError as exc:
return _err_exit(
ChaosCrypt_ERR_FileWriteFailed_E015(
detail=f"OutputWriteFailed:{exc}", code="E015"
),
args,
)
payload["out_file"] = os.path.abspath(args.out_file)
if not args.json and not args.quiet:
print(f"Written to: {os.path.abspath(args.out_file)}")
return EXIT_OK
_emit(payload, args, [result])
return EXIT_OK
def _cmd_file(args: argparse.Namespace, mode: str) -> int:
from . import ChaosCrypt
from .errors import ChaosCrypt_ERR_EmptyPassword_E006
pwd = _resolve_password(
args.password, args.password_env, args.password_file, "encryption password"
)
key_pwd = _resolve_password(
args.key_password, args.key_password_env, args.key_password_file,
"key file password",
)
if pwd is None or key_pwd is None:
return _err_exit(
ChaosCrypt_ERR_EmptyPassword_E006(
detail="MissingPassword", code="E006"
),
args,
)
cc = ChaosCrypt()
cc.load(args.key_file, key_pwd)
if mode == "encrypt":
out = cc.encrypt_file(args.src, pwd, args.out_file)
else:
out = cc.decrypt_file(args.src, pwd, args.out_file)
_emit(
{
"ok": True,
"mode": f"file_{mode}",
"src": os.path.abspath(args.src),
"out_file": os.path.abspath(out),
},
args,
[f"{os.path.abspath(args.src)} -> {os.path.abspath(out)}"],
)
return EXIT_OK
def _cmd_info(args: argparse.Namespace) -> int:
from . import ChaosCrypt
from .errors import ChaosCrypt_ERR_EmptyPassword_E006
key_pwd = _resolve_password(
args.key_password, args.key_password_env, args.key_password_file,
"key file password",
)
if key_pwd is None:
return _err_exit(
ChaosCrypt_ERR_EmptyPassword_E006(
detail="NoKeyFilePassword", code="E006"
),
args,
)
cc = ChaosCrypt()
cc.load(args.key_file, key_pwd)
info = cc.info()
if not args.show_maps:
for k in ("upper_mapping", "lower_mapping", "digit_mapping", "equal_mapping"):
info[k] = f"<hidden, {len(info[k])} chars>"
if args.json:
print(json.dumps({"ok": True, **info}, ensure_ascii=False, indent=2))
return EXIT_OK
print("=" * 62)
print("ChaosCrypt key information")
print("=" * 62)
for key, val in info.items():
print(f"{key:<20}: {val}")
print("=" * 62)
return EXIT_OK
def _cmd_chpwd(args: argparse.Namespace) -> int:
from . import ChaosCrypt
from .errors import ChaosCrypt_ERR_EmptyPassword_E006
old = _resolve_password(
args.key_password, args.key_password_env, args.key_password_file,
"current key file password",
)
new = _resolve_password(
args.new_pwd, args.new_pwd_env, args.new_pwd_file, "new key file password"
)
if old is None or new is None:
return _err_exit(
ChaosCrypt_ERR_EmptyPassword_E006(
detail="MissingPassword", code="E006"
),
args,
)
cc = ChaosCrypt()
path = cc.change_key_password(old, new, args.key_file)
_emit(
{"ok": True, "key_file": os.path.abspath(path)},
args,
[f"Key file password updated: {os.path.abspath(path)}"],
)
return EXIT_OK
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def main(argv: Optional[List[str]] = None) -> int:
"""Run the CLI.
With no arguments this delegates to the interactive TUI; otherwise the
requested subcommand runs.
"""
raw = list(sys.argv[1:] if argv is None else argv)
if not raw:
from .tui import run_tui
return run_tui()
parser = build_parser()
args = parser.parse_args(raw)
# `--json` / `--quiet` are accepted both before and after the subcommand.
# The subparser writes to separate destinations so that an unset
# subcommand flag cannot clobber an explicitly set global one; the two are
# merged here.
args.json = bool(getattr(args, "json", False)
or getattr(args, "json_local", False))
args.quiet = bool(getattr(args, "quiet", False)
or getattr(args, "quiet_local", False))
if args.command is None or args.command == "tui":
from .tui import run_tui
return run_tui()
try:
if args.command == "keygen":
return _cmd_keygen(args)
if args.command == "encrypt":
return _cmd_text(args, "encrypt")
if args.command == "decrypt":
return _cmd_text(args, "decrypt")
if args.command == "info":
return _cmd_info(args)
if args.command == "chpwd":
return _cmd_chpwd(args)
if args.command == "file":
if args.file_command == "encrypt":
return _cmd_file(args, "encrypt")
if args.file_command == "decrypt":
return _cmd_file(args, "decrypt")
parser.parse_args(["file", "--help"])
return EXIT_USAGE
except ChaosCryptError as exc:
return _err_exit(exc, args)
except KeyboardInterrupt:
print("\nInterrupted.", file=sys.stderr)
return EXIT_ERROR
parser.print_help()
return EXIT_USAGE
def cli_main() -> None:
"""``console_scripts`` entry point."""
sys.exit(main())
if __name__ == "__main__": # pragma: no cover
cli_main()