vault.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. """``hermes vault`` — manage the local encrypted autofill vault.
  2. Subcommands:
  3. - ``hermes vault add`` interactive wizard; the password is read via
  4. getpass (never echoed, never accepted as argv). The login identifier is
  5. visible metadata and prompted normally.
  6. - ``hermes vault list`` metadata — labels, kinds, identifiers, origins,
  7. handles. Passwords are never shown.
  8. - ``hermes vault rm`` remove an item by handle/id.
  9. - ``hermes vault key`` where the vault key lives; ``key migrate --to keychain|file`` moves it.
  10. The vault backs the password-blind browser autofill tools
  11. (``browser_vault`` list / fill): the agent sees handles
  12. and login identifiers, types the identifier itself, and fills the password
  13. server-side without ever seeing it.
  14. """
  15. from __future__ import annotations
  16. import getpass
  17. def _console():
  18. from rich.console import Console
  19. return Console()
  20. def _cmd_add(args) -> None:
  21. from agent.vault_store import (
  22. LOGIN_IDENTIFIER_TYPES,
  23. VAULT_KINDS,
  24. VaultError,
  25. get_vault_store,
  26. )
  27. c = _console()
  28. c.print(
  29. "[bold]Add a vault item[/] (the password is encrypted at rest and the "
  30. "agent never sees it; the identifier is visible metadata the agent "
  31. "can type itself)"
  32. )
  33. kind = (args.kind or "").strip().lower()
  34. while kind not in VAULT_KINDS:
  35. kind = input(f"Kind ({'/'.join(VAULT_KINDS)}) [login]: ").strip().lower() or "login"
  36. if kind not in VAULT_KINDS:
  37. c.print(f"[red]Unknown kind {kind!r}[/]")
  38. kind = ""
  39. label = ""
  40. while not label:
  41. label = input("Label (e.g. 'GitHub work account'): ").strip()
  42. try:
  43. if kind == "login":
  44. origin = ""
  45. while not origin:
  46. origin = input("Site origin (e.g. https://github.com): ").strip()
  47. id_type = ""
  48. while id_type not in LOGIN_IDENTIFIER_TYPES:
  49. id_type = (
  50. input(f"Identifier type ({'/'.join(LOGIN_IDENTIFIER_TYPES)}) [email]: ")
  51. .strip()
  52. .lower()
  53. or "email"
  54. )
  55. identifier = ""
  56. while not identifier:
  57. identifier = input(f"{id_type.capitalize()}: ").strip()
  58. password = ""
  59. while not password:
  60. password = getpass.getpass("Password (hidden): ")
  61. otp_secret = getpass.getpass(
  62. "Authenticator key (optional, hidden; the 2FA \"setup key\" or otpauth:// link — Enter to skip): ")
  63. # identifier_type/identifier are stored as metadata (not secret);
  64. # add_item moves them out of the encrypted payload.
  65. secret = {
  66. "identifier_type": id_type,
  67. "identifier": identifier,
  68. "password": password,
  69. **({"otp_secret": otp_secret} if otp_secret.strip() else {}),
  70. }
  71. meta = get_vault_store().add_item(
  72. kind="login", label=label, secret=secret, origin=origin
  73. )
  74. else:
  75. from agent.vault_store import ADDRESS_FIELDS, PAYMENT_FIELDS, REQUIRED_FIELDS
  76. fields = PAYMENT_FIELDS if kind == "payment" else ADDRESS_FIELDS
  77. origin = ""
  78. while not origin:
  79. origin = input("Site origin the item may be filled on (e.g. https://shop.example.com): ").strip()
  80. c.print(f"[dim]{kind} fields are filled only on that origin; card values are read hidden.[/]")
  81. secret = {}
  82. for field in fields:
  83. required = field in REQUIRED_FIELDS[kind]
  84. prompt = f"{field.replace('_', ' ')}{'' if required else ' (optional)'}: "
  85. read = getpass.getpass if kind == "payment" else input
  86. value = read(prompt).strip()
  87. while required and not value:
  88. value = read(prompt).strip()
  89. if value:
  90. secret[field] = value
  91. meta = get_vault_store().add_item(kind=kind, label=label, secret=secret, origin=origin)
  92. except VaultError as exc:
  93. c.print(f"[red]Error:[/] {exc}")
  94. return
  95. c.print(f"[green]Stored.[/] handle=[bold]{meta.id}[/] kind={meta.kind} origin={meta.origin or '-'}")
  96. def _cmd_list(args) -> None:
  97. """Local items always; external managers only for the lifetime of this CLI process (a
  98. `hermes vault list` unlock does not carry into a chat session — unlock there when asked)."""
  99. from agent.vault_backends import enabled_backends
  100. c = _console()
  101. rows, locked = [], []
  102. for backend in enabled_backends():
  103. if backend.needs_unlock and not backend.is_unlocked():
  104. locked.append(backend.display_name)
  105. continue
  106. rows.extend((backend.display_name, meta) for meta in backend.list_items())
  107. if not rows and not locked:
  108. c.print("[dim]Vault is empty. Add an item with `hermes vault add`.[/]")
  109. return
  110. if rows:
  111. from rich.table import Table
  112. table = Table(title=f"Vault items ({len(rows)})")
  113. for col in ("Handle", "Source", "Kind", "Label", "Identifier", "Origin"):
  114. table.add_column(col, style="bold" if col == "Handle" else None)
  115. for source, meta in rows:
  116. table.add_row(meta.id, source, meta.kind, meta.label, meta.identifier or "-", meta.origin or "-")
  117. c.print(table)
  118. c.print("[dim]Passwords are never shown; the agent fills them server-side from the handle.[/]")
  119. for name in locked:
  120. c.print(f"[yellow]{name}[/] is enabled but locked — the agent will ask you to unlock it when it needs a login.")
  121. def _cmd_sources(args) -> None:
  122. """Show the detected password managers; `--disable`/`--enable` flip the opt-out (`vault.<name>.enabled`)."""
  123. from agent.vault_backends import enabled_backends
  124. from agent.vault_backends.base import external_backend_classes, is_installed
  125. from hermes_cli.config import _ensure_dict, load_config, save_config
  126. c = _console()
  127. classes = {cls.name: cls for cls in external_backend_classes()}
  128. if args.enable or args.disable:
  129. name = args.enable or args.disable
  130. if name not in classes:
  131. c.print(f"[red]Unknown password manager {name!r}[/] (expected one of {', '.join(classes)})")
  132. return
  133. cfg = load_config()
  134. section = _ensure_dict(_ensure_dict(cfg, "vault"), name)
  135. if args.enable:
  136. section.pop("enabled", None) # detected managers are on by default; drop the opt-out
  137. else:
  138. section["enabled"] = False
  139. save_config(cfg)
  140. c.print(f"[green]{classes[name].display_name} {'on' if args.enable else 'off'}[/] for browser logins.")
  141. return
  142. enabled = {b.name for b in enabled_backends()}
  143. for name, cls in classes.items():
  144. if name in enabled:
  145. status = "[green]detected[/] · the agent asks you to unlock it when it needs a login"
  146. elif is_installed(name):
  147. status = f"[dim]turned off[/] (`hermes vault sources --enable {name}` to use it)"
  148. else:
  149. status = "[dim]not installed[/]"
  150. c.print(f" {cls.display_name:<10} {status}")
  151. c.print("[dim]Managers are picked up automatically when their CLI is installed and signed in.[/]")
  152. def _cmd_rm(args) -> None:
  153. from agent.vault_store import get_vault_store
  154. c = _console()
  155. if get_vault_store().remove_item(args.handle):
  156. c.print(f"[green]Removed[/] {args.handle}")
  157. else:
  158. c.print(f"[red]No vault item with handle {args.handle!r}[/]")
  159. def _cmd_key(args) -> None:
  160. """Show where the local vault's key lives, or move it between vault.key and the OS keychain."""
  161. from agent import vault_keychain
  162. from agent.vault_store import configured_key_storage, get_vault_store
  163. c = _console()
  164. store = get_vault_store()
  165. target = getattr(args, "to", None)
  166. if target:
  167. if target == "keychain" and not _ensure_keychain_extra(c):
  168. return
  169. store.migrate_key(target)
  170. _set_key_storage(target)
  171. if store.key_location()["storage"] == "none": # nothing was moved or verified, only the setting
  172. c.print(f"No vault key exists yet. The first saved item creates one in "
  173. f"{'the OS keychain' if target == 'keychain' else 'vault.key'} (vault.key_storage = {target}).")
  174. elif target == "keychain":
  175. c.print(f"[green]Vault key moved to the OS keychain[/] ({vault_keychain.backend_label()}); "
  176. "vault.key was removed after the keychain copy decrypted the vault.")
  177. c.print("[dim]Backups of this profile now hold the encrypted vault without its key; "
  178. "`hermes vault key migrate --to file` before moving the profile to another machine.[/]")
  179. else:
  180. where = store.key_location()
  181. c.print(f"[green]Vault key moved to[/] {where.get('path')} (0600).")
  182. if where.get("keychain_entry_left"):
  183. c.print(f"[yellow]The keychain copy ({where['keychain_entry_left']}) could not be removed yet;[/] "
  184. "run this command again when the keychain is reachable.")
  185. else:
  186. c.print("Keychain entry removed.")
  187. return
  188. where = store.key_location()
  189. if where["storage"] == "file":
  190. c.print(f"Vault key: [bold]file[/] {where['path']} (0600, beside the encrypted vault)")
  191. elif where["storage"] == "keychain":
  192. c.print(f"Vault key: [bold]OS keychain[/] service {where.get('service')!r}, account {where['account']!r}")
  193. else:
  194. c.print("Vault key: [dim]none yet[/] (created with the first saved item)")
  195. c.print(f"New vaults use: vault.key_storage = {configured_key_storage()}")
  196. c.print(f"OS keychain here: {vault_keychain.backend_label()}")
  197. def _ensure_keychain_extra(c) -> bool:
  198. from pm.extras import available, ensure_import
  199. from pm.package import InstallError
  200. if available("keychain"):
  201. return True
  202. try:
  203. ensure_import("keychain")
  204. except InstallError as exc:
  205. c.print(f"[red]The keychain feature is not installed:[/] {exc}")
  206. return False
  207. return True
  208. def _set_key_storage(value: str) -> None:
  209. from hermes_cli.config import _ensure_dict, load_config, save_config
  210. cfg = load_config()
  211. _ensure_dict(cfg, "vault")["key_storage"] = value
  212. save_config(cfg)
  213. def register_cli(subparser) -> None:
  214. """Build the ``hermes vault`` argparse tree (called from main.py)."""
  215. subs = subparser.add_subparsers(dest="vault_action")
  216. p_add = subs.add_parser(
  217. "add",
  218. help="Save a login, card or address ahead of time (optional: the agent asks you on the page when it needs one)",
  219. )
  220. p_add.add_argument(
  221. "--kind", choices=["login", "payment", "address"], default=None,
  222. help="Item kind (interactive prompt when omitted)",
  223. )
  224. p_add.set_defaults(_vault_handler=_cmd_add)
  225. p_list = subs.add_parser("list", help="List vault items (metadata only, never values)")
  226. p_list.set_defaults(_vault_handler=_cmd_list)
  227. p_rm = subs.add_parser("rm", help="Remove a vault item by handle")
  228. p_rm.add_argument("handle", help="Item handle (see `hermes vault list`)")
  229. p_rm.set_defaults(_vault_handler=_cmd_rm)
  230. p_src = subs.add_parser("sources", help="Show detected password managers (1Password, Bitwarden); they are on automatically")
  231. group = p_src.add_mutually_exclusive_group()
  232. group.add_argument("--disable", metavar="NAME", help="Stop using a detected manager: onepassword | bitwarden")
  233. group.add_argument("--enable", metavar="NAME", help="Undo --disable")
  234. p_src.set_defaults(_vault_handler=_cmd_sources)
  235. p_key = subs.add_parser("key", help="Show where the local vault key is stored (vault.key file or OS keychain)")
  236. p_key.set_defaults(_vault_handler=_cmd_key, to=None)
  237. key_subs = p_key.add_subparsers(dest="vault_key_action")
  238. p_migrate = key_subs.add_parser(
  239. "migrate", help="Move the vault key to the OS keychain or back to vault.key (verified before the old copy is removed)")
  240. p_migrate.add_argument("--to", choices=["keychain", "file"], required=True, help="Destination for the key")
  241. p_migrate.set_defaults(_vault_handler=_cmd_key)
  242. def vault_command(args) -> None:
  243. from agent.vault_store import VaultError
  244. handler = getattr(args, "_vault_handler", None)
  245. try:
  246. if handler is None:
  247. _cmd_list(args)
  248. return
  249. handler(args)
  250. except VaultError as exc:
  251. _console().print(f"[red]Error:[/] {exc}")