secrets_cli.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. """CLI handlers for ``hermes secrets bitwarden ...``."""
  2. from __future__ import annotations
  3. import argparse
  4. import io
  5. import json
  6. import os
  7. import subprocess
  8. import sys
  9. from pathlib import Path
  10. from typing import List, Optional
  11. from rich.console import Console
  12. from rich.panel import Panel
  13. from rich.table import Table
  14. from hermes_cli._secrets_common import (
  15. arg, cfg_str, cli_version, disable_secret_source, flag, print_status_panel, print_table,
  16. prompt_index, register_subcommands, require_enabled, rotate_token, secret_cli_env, section_cfg,
  17. yn,
  18. )
  19. from hermes_cli.config import get_env_path, load_config, save_config, save_env_value
  20. from hermes_cli.secret_prompt import masked_secret_prompt
  21. # Old names kept bound: tests monkeypatch ``secrets_cli._bws_version``.
  22. _bws_version = cli_version
  23. _yn = yn
  24. _DEFAULT_TOKEN_ENV = "BWS_ACCESS_TOKEN"
  25. _NOT_BSM_TOKEN_WARNING = (
  26. "[yellow]Warning: token doesn't start with '0.' — usually that means "
  27. "you pasted something other than a BSM access token.[/yellow]"
  28. )
  29. _NOT_BSM_TOKEN_WARNING_CONTINUING = (
  30. " [yellow]Warning: token doesn't start with '0.' — usually that means "
  31. "you pasted something other than a BSM access token. Continuing anyway.[/yellow]"
  32. )
  33. def _load_bw():
  34. """Import ``agent.secret_sources.bitwarden`` on first use (crypto payload)."""
  35. from agent.secret_sources import bitwarden as _bw
  36. return _bw
  37. def __getattr__(name: str):
  38. """PEP 562 lazy ``bw`` attribute (tests monkeypatch ``secrets_cli.bw``); an eager binding
  39. would re-import ``cryptography`` at import time.
  40. Existing callers (and upstream tests) monkeypatch attributes on ``hermes_cli.secrets_cli.bw`` directly.
  41. Resolving that attribute at module-import time would re-import ``cryptography`` eagerly — the very
  42. self-lock we are preventing (#86781). Defer the backend import until the first actual attribute access,
  43. so ``import hermes_cli.secrets_cli`` stays crypto-free while ``secrets_cli.bw.find_bws`` still resolves.
  44. """
  45. if name == "bw":
  46. return _load_bw()
  47. raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
  48. # ── Argparse wiring — called from hermes_cli.main ──
  49. def register_cli(parent_parser: argparse.ArgumentParser) -> None:
  50. """Attach the ``bitwarden`` subcommand tree to a parent parser."""
  51. register_subcommands(parent_parser, "secrets_bw_command", (
  52. ("setup", "Interactive wizard: install bws, store access token, pick project", cmd_setup, (
  53. arg("--project-id", "Pre-select a project UUID instead of prompting"),
  54. arg("--access-token", "Provide the access token non-interactively (will be stored in .env)"),
  55. arg("--server-url", (
  56. "Bitwarden region / self-hosted endpoint. Examples: "
  57. "https://vault.bitwarden.com (US, default), "
  58. "https://vault.bitwarden.eu (EU), or your self-hosted URL. "
  59. "Skips the interactive region prompt."
  60. )),
  61. )),
  62. ("status", "Show config + binary + token validation status", cmd_status, ()),
  63. ("token", "Rotate the access token: validate a new one and store it in .env", cmd_token, (
  64. arg("--access-token", "Provide the new token non-interactively (default: masked prompt)"),
  65. flag("--no-verify", "Store without probing Bitwarden first (not recommended)"),
  66. )),
  67. ("sync", "Fetch secrets now and report what changed", cmd_sync, (
  68. flag("--apply", "Actually export the secrets into the current shell's env (default: dry-run)"),
  69. )),
  70. ("disable", "Turn off the Bitwarden integration", cmd_disable, ()),
  71. ("install", "Install the PM-pinned bws binary", cmd_install, (
  72. flag("--force", "Verify and repair the managed copy"),
  73. )),
  74. ))
  75. # ── Handlers ──
  76. def _step(console: Console, n: int, title: str) -> None:
  77. console.print()
  78. console.print(f"[bold]Step {n}[/bold] {title}")
  79. def _setup_binary(bw, console: Console) -> Optional[Path]:
  80. """Step 1: locate or download bws; None (after printing) on failure."""
  81. _step(console, 1, "Install the bws CLI")
  82. try:
  83. binary = bw.find_bws(install_if_missing=False)
  84. if binary is None:
  85. console.print(" No bws on PATH — downloading…")
  86. binary = bw.install_bws()
  87. console.print(f" [green]✓[/green] {binary} ({_bws_version(binary)})")
  88. return binary
  89. except Exception as exc:
  90. console.print(f" [red]✗ Could not install bws: {exc}[/red]")
  91. console.print(" Manual install: https://github.com/bitwarden/sdk-sm/releases")
  92. return None
  93. def _missing_noninteractive_flags(args: argparse.Namespace) -> list[str]:
  94. """Setup flags a no-TTY run must supply (BWS_SERVER_URL env substitutes for --server-url)."""
  95. provided = {
  96. "--access-token": args.access_token,
  97. "--server-url": (args.server_url or "").strip() or os.environ.get("BWS_SERVER_URL", ""),
  98. "--project-id": args.project_id}
  99. return [flag for flag, value in provided.items() if not (value and value.strip())]
  100. def _setup_token(args: argparse.Namespace, console: Console, token_env: str) -> Optional[str]:
  101. """Step 2: take the token from ``--access-token`` or a masked prompt and persist it."""
  102. _step(console, 2, "Provide your access token")
  103. token = (args.access_token or "").strip() or masked_secret_prompt(f" Paste access token ({token_env}): ").strip()
  104. if not token:
  105. console.print(" [red]Empty token, aborting.[/red]")
  106. return None
  107. if not token.startswith("0."):
  108. console.print(_NOT_BSM_TOKEN_WARNING_CONTINUING)
  109. save_env_value(token_env, token)
  110. os.environ[token_env] = token # so the test fetch below sees it
  111. console.print(f" [green]✓[/green] stored in {get_env_path()} as {token_env}")
  112. return token
  113. def _setup_project(binary: Path, token: str, console: Console, server_url: str) -> Optional[str]:
  114. """Step 4: list projects and let the user pick one; None (after printing) when none usable."""
  115. _step(console, 4, "Pick a project")
  116. projects = _list_projects(binary, token, console, server_url=server_url)
  117. if projects is None:
  118. return None
  119. if not projects:
  120. console.print(" [yellow]No projects visible to this machine account.[/yellow]")
  121. console.print(" In the Bitwarden web app, open the machine account → Projects tab "
  122. "and grant it access to at least one project.")
  123. return None
  124. print_table(console, (("#", {"style": "cyan", "width": 4}), "Name", ("ID", {"style": "dim"})),
  125. ((str(i), p.get("name", "?"), p.get("id", "?")) for i, p in enumerate(projects, 1)))
  126. idx = prompt_index(console, f" Select project [1-{len(projects)}]: ", len(projects))
  127. return projects[idx - 1]["id"]
  128. def cmd_setup(args: argparse.Namespace) -> int:
  129. bw = _load_bw()
  130. console = Console()
  131. console.print(Panel.fit(
  132. "[bold]Bitwarden Secrets Manager setup[/bold]\n\n"
  133. "Need an access token? In the Bitwarden web app:\n"
  134. " Secrets Manager → Machine accounts → [your account] →\n"
  135. " Access tokens → Create access token\n\n"
  136. "Copy the token (starts with [cyan]0.[/cyan]…) — it cannot be retrieved later.",
  137. border_style="cyan"))
  138. binary = _setup_binary(bw, console)
  139. if binary is None:
  140. return 1
  141. if not sys.stdin.isatty():
  142. missing = _missing_noninteractive_flags(args)
  143. if missing:
  144. console.print(
  145. f" [red]Non-interactive mode (no TTY) requires all setup flags.[/red]\n"
  146. f" Missing: {', '.join(missing)}\n\n"
  147. " Usage:\n"
  148. " hermes secrets bitwarden setup \\\n"
  149. " --access-token '0.xxx' \\\n"
  150. " --server-url 'https://vault.bitwarden.com' \\\n"
  151. " --project-id 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'")
  152. return 1
  153. cfg = load_config()
  154. secrets_cfg = cfg.setdefault("secrets", {}).setdefault("bitwarden", {})
  155. token_env = secrets_cfg.get("access_token_env", _DEFAULT_TOKEN_ENV)
  156. token = _setup_token(args, console, token_env)
  157. if token is None:
  158. return 1
  159. _step(console, 3, "Pick a Bitwarden region")
  160. server_url = _resolve_server_url(args, secrets_cfg, console)
  161. if server_url is None:
  162. return 1
  163. console.print(f" [green]✓[/green] using {server_url}" if server_url
  164. else " [green]✓[/green] using bws default (US Cloud, https://vault.bitwarden.com)")
  165. project_id = (args.project_id or "").strip()
  166. project_given = bool(project_id)
  167. if not project_given:
  168. project_id = _setup_project(binary, token, console, server_url)
  169. if project_id is None:
  170. return 1
  171. _step(console, 4 if project_given else 5, "Test fetch")
  172. try:
  173. secrets, warnings = bw.fetch_bitwarden_secrets(
  174. access_token=token, project_id=project_id, binary=binary, use_cache=False, server_url=server_url)
  175. except Exception as exc:
  176. console.print(f" [red]✗ Fetch failed: {exc}[/red]")
  177. return 1
  178. if not secrets:
  179. console.print(" [yellow]Fetch succeeded but the project has no secrets.[/yellow]")
  180. else:
  181. print_table(console, (("Name", {"style": "cyan"}), "Status"),
  182. ((key, _fetch_status(key, token_env)) for key in sorted(secrets)))
  183. for w in warnings:
  184. console.print(f" [yellow]warning:[/yellow] {w}")
  185. secrets_cfg.update(enabled=True, project_id=project_id, server_url=server_url)
  186. for key, default in (("access_token_env", token_env), ("cache_ttl_seconds", 300),
  187. ("override_existing", True), ("auto_install", True)):
  188. secrets_cfg.setdefault(key, default)
  189. save_config(cfg)
  190. console.print()
  191. console.print("[green]✓ Bitwarden Secrets Manager is enabled.[/green] "
  192. "Secrets will be pulled at the start of every Hermes process.")
  193. console.print(" Status: [cyan]hermes secrets bitwarden status[/cyan]\n"
  194. " Refresh: [cyan]hermes secrets bitwarden sync[/cyan]\n"
  195. " Disable: [cyan]hermes secrets bitwarden disable[/cyan]")
  196. return 0
  197. def _bw_cfg(cfg: dict) -> dict:
  198. return section_cfg(cfg, "bitwarden")
  199. def _fetch_status(key: str, token_env: str) -> str:
  200. if key == token_env:
  201. return "[dim]bootstrap token — never overrides itself[/dim]"
  202. if os.environ.get(key):
  203. return "[yellow]already set in env (will be overwritten)[/yellow]"
  204. return "[green]new[/green]"
  205. def cmd_status(args: argparse.Namespace) -> int:
  206. bw = _load_bw()
  207. console = Console()
  208. bw_cfg = _bw_cfg(load_config())
  209. enabled = bool(bw_cfg.get("enabled"))
  210. token_env = bw_cfg.get("access_token_env", _DEFAULT_TOKEN_ENV)
  211. project_id = bw_cfg.get("project_id", "")
  212. server_url = cfg_str(bw_cfg, "server_url")
  213. token = os.environ.get(token_env, "").strip()
  214. binary = bw.find_bws(install_if_missing=False)
  215. token_validation, validation_messages = _token_validation_status(
  216. enabled=enabled, binary=binary, token=token, server_url=server_url)
  217. print_status_panel(console, "Bitwarden Secrets Manager", (
  218. ("Enabled", _yn(enabled)),
  219. ("Token env var", token_env),
  220. ("Token in env", _yn(bool(token))),
  221. ("Token validation", token_validation),
  222. ("Project ID", project_id or "[dim](unset)[/dim]"),
  223. ("Server URL", server_url or "[dim]default (US Cloud, https://vault.bitwarden.com)[/dim]"),
  224. ("Override existing", _yn(bool(bw_cfg.get("override_existing", False)))),
  225. ("Cache TTL (s)", str(bw_cfg.get("cache_ttl_seconds", 300))),
  226. ("Auto-install", _yn(bool(bw_cfg.get("auto_install", True)))),
  227. ("bws binary", f"{binary} ({_bws_version(binary)})" if binary else "[yellow]not installed[/yellow]"),
  228. ))
  229. for message in validation_messages:
  230. console.print(message)
  231. if not enabled:
  232. console.print("\n Run [cyan]hermes secrets bitwarden setup[/cyan] to enable.")
  233. return 0
  234. if not token:
  235. console.print(f"\n [yellow]Enabled but {token_env} is not set — Hermes will skip BSM "
  236. "and warn on next startup.[/yellow]")
  237. if not project_id:
  238. console.print("\n [yellow]Enabled but no project_id — nothing to fetch.[/yellow]")
  239. return 0
  240. def cmd_token(args: argparse.Namespace) -> int:
  241. """Rotate the BSM access token without re-running the whole setup wizard: probe Bitwarden
  242. with the new token (unless ``--no-verify``) and only then persist it, so a bad paste never
  243. bricks the working token."""
  244. bw = _load_bw()
  245. console = Console()
  246. bw_cfg = _bw_cfg(load_config())
  247. token_env = bw_cfg.get("access_token_env", _DEFAULT_TOKEN_ENV)
  248. server_url = cfg_str(bw_cfg, "server_url")
  249. def verify(token: str) -> bool:
  250. if not token.startswith("0."):
  251. console.print(_NOT_BSM_TOKEN_WARNING)
  252. if args.no_verify:
  253. return True
  254. binary = bw.find_bws(install_if_missing=True)
  255. if binary is None:
  256. console.print("[red]bws binary not available — cannot verify. "
  257. "Re-run with --no-verify to store anyway.[/red]")
  258. return False
  259. console.print("Verifying against Bitwarden…")
  260. projects = _list_projects(binary, token, console, server_url=server_url)
  261. if projects is None:
  262. console.print("[red]✗ New token was rejected — nothing was changed.[/red]")
  263. return False
  264. console.print(f"[green]✓ Token accepted[/green] "
  265. f"({len(projects)} project{'s' if len(projects) != 1 else ''} visible).")
  266. project_id = str(bw_cfg.get("project_id", "") or "")
  267. if project_id and projects and project_id not in {p["id"] for p in projects}:
  268. console.print(
  269. f"[yellow]Warning: configured project {project_id} is not visible "
  270. "to this machine account. Grant it access in the Bitwarden web "
  271. "app or re-run `hermes secrets bitwarden setup` to pick a different project.[/yellow]")
  272. return True
  273. return rotate_token(
  274. console, args.access_token, token_env,
  275. flag="--access-token",
  276. intro=(
  277. "Create a new token in the Bitwarden web app:\n"
  278. " Secrets Manager → Machine accounts → [your account] → "
  279. "Access tokens → Create access token\n"
  280. ),
  281. prompt=f"Paste new access token ({token_env}): ",
  282. verify=verify,
  283. save=save_env_value, env_path=get_env_path, clear_caches=bw.clear_caches,
  284. disabled_note=None if bw_cfg.get("enabled") else (
  285. "[yellow]Note: the Bitwarden integration is currently disabled — "
  286. "run `hermes secrets bitwarden setup` (or set "
  287. "secrets.bitwarden.enabled: true) to turn it on.[/yellow]"
  288. ))
  289. def cmd_sync(args: argparse.Namespace) -> int:
  290. bw = _load_bw()
  291. console = Console()
  292. bw_cfg = _bw_cfg(load_config())
  293. if not require_enabled(console, bw_cfg, "Bitwarden", "bitwarden"):
  294. return 1
  295. token_env = bw_cfg.get("access_token_env", _DEFAULT_TOKEN_ENV)
  296. token = os.environ.get(token_env, "").strip()
  297. if not token:
  298. console.print(f"[red]{token_env} is not set.[/red]")
  299. return 1
  300. project_id = bw_cfg.get("project_id", "")
  301. if not project_id:
  302. console.print("[red]No project_id configured.[/red]")
  303. return 1
  304. try:
  305. secrets, warnings = bw.fetch_bitwarden_secrets(
  306. access_token=token, project_id=project_id, use_cache=False, server_url=cfg_str(bw_cfg, "server_url"),
  307. )
  308. except Exception as exc:
  309. console.print(f"[red]Fetch failed: {exc}[/red]")
  310. return 1
  311. if not secrets:
  312. console.print("[yellow]No secrets in project.[/yellow]")
  313. return 0
  314. override = bool(bw_cfg.get("override_existing", False)) or args.apply
  315. rows = []
  316. applied = 0
  317. for key in sorted(secrets):
  318. already = bool(os.environ.get(key))
  319. if key == token_env:
  320. action = "[dim]skip (bootstrap token)[/dim]"
  321. elif already and not override:
  322. action = "[dim]skip (already set)[/dim]"
  323. elif args.apply:
  324. os.environ[key] = secrets[key]
  325. applied += 1
  326. action = "[green]exported[/green]" + (" (overrode)" if already else "")
  327. else:
  328. action = "[green]would export[/green]" + (" (overrides)" if already else "")
  329. rows.append((key, action))
  330. print_table(console, (("Name", {"style": "cyan"}), "Action"), rows, warnings)
  331. if not args.apply:
  332. console.print("\n This was a dry-run — secrets are picked up automatically on the "
  333. "next [cyan]hermes[/cyan] invocation. Re-run with [cyan]--apply[/cyan] "
  334. "to export into the current shell instead.")
  335. else:
  336. console.print(f"\n [green]Exported {applied} secret(s) into current process.[/green]")
  337. return 0
  338. def cmd_disable(args: argparse.Namespace) -> int:
  339. return disable_secret_source(
  340. "bitwarden",
  341. "[green]Disabled.[/green] Bitwarden secrets will NOT be pulled on the next "
  342. "Hermes invocation.\n"
  343. " Your access token is left in .env — remove it manually if you also want "
  344. "to revoke the credential.")
  345. def cmd_install(args: argparse.Namespace) -> int:
  346. bw = _load_bw()
  347. console = Console()
  348. try:
  349. path = bw.install_bws(force=bool(args.force))
  350. console.print(f"[green]✓[/green] {path} ({_bws_version(path)})")
  351. return 0
  352. except Exception as exc:
  353. console.print(f"[red]Install failed: {exc}[/red]")
  354. return 1
  355. # ── Helpers ──
  356. def _token_validation_status(
  357. *, enabled: bool, binary: Optional[Path], token: str, server_url: str = "",
  358. ) -> tuple[str, list[str]]:
  359. for skipped, reason in ((not enabled, "integration disabled"), (not token, "token missing"),
  360. (binary is None, "bws not installed")):
  361. if skipped:
  362. return f"[dim]not checked[/dim] ({reason})", []
  363. messages: list[str] = []
  364. if not token.startswith("0."):
  365. messages.append(_NOT_BSM_TOKEN_WARNING_CONTINUING)
  366. probe_console = Console(file=io.StringIO(), record=True, width=200)
  367. if _list_projects(binary, token, probe_console, server_url=server_url) is None:
  368. details = probe_console.export_text(styles=False).strip()
  369. if details:
  370. messages.extend(line.rstrip() for line in details.splitlines())
  371. return "[red]failed[/red]", messages
  372. return "[green]passed[/green]", messages
  373. # (substring of the lowercased bws error, follow-up hint) — first match wins.
  374. _PROJECT_LIST_HINTS = (
  375. (("invalid_client", "400 bad request"),
  376. " [yellow]'invalid_client' from the US identity endpoint usually "
  377. "means the token is for a different Bitwarden region. Re-run "
  378. "[cyan]hermes secrets bitwarden setup[/cyan] and pick EU or "
  379. "self-hosted at the region prompt, or set [cyan]secrets.bitwarden."
  380. "server_url[/cyan] in config.yaml.[/yellow]"),
  381. (("authorization", "invalid"),
  382. " [yellow]This usually means the access token is wrong or revoked. "
  383. "Double-check it in the Bitwarden web app.[/yellow]"),
  384. )
  385. def _list_projects(
  386. binary: Path, token: str, console: Console, *, server_url: str = ""
  387. ) -> Optional[list[dict]]:
  388. """Call ``bws project list`` and return the parsed list, or None on failure."""
  389. env = secret_cli_env()
  390. env["BWS_ACCESS_TOKEN"] = token
  391. if server_url:
  392. env["BWS_SERVER_URL"] = server_url
  393. try:
  394. res = subprocess.run(
  395. [str(binary), "project", "list", "--output", "json"],
  396. env=env, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=15, check=False)
  397. except (OSError, subprocess.TimeoutExpired) as exc:
  398. console.print(f" [red]Couldn't list projects: {exc}[/red]")
  399. return None
  400. if res.returncode != 0:
  401. err = (res.stderr or res.stdout).strip()[:300]
  402. console.print(f" [red]bws project list failed: {err}[/red]")
  403. lowered = err.lower()
  404. for needles, hint in _PROJECT_LIST_HINTS:
  405. if any(n in lowered for n in needles):
  406. console.print(hint)
  407. break
  408. return None
  409. try:
  410. data = json.loads(res.stdout or "[]")
  411. except json.JSONDecodeError as exc:
  412. console.print(f" [red]bws returned non-JSON: {exc}[/red]")
  413. return None
  414. if not isinstance(data, list):
  415. return []
  416. return [p for p in data if isinstance(p, dict) and p.get("id")]
  417. # Canonical Bitwarden region endpoints; add a new region here and it appears in the prompt.
  418. _REGION_PRESETS = [
  419. ("US Cloud (https://vault.bitwarden.com — bws default)", ""),
  420. ("EU Cloud (https://vault.bitwarden.eu)", "https://vault.bitwarden.eu"),
  421. ]
  422. def _resolve_server_url(
  423. args: argparse.Namespace, secrets_cfg: dict, console: Console,
  424. ) -> Optional[str]:
  425. """Pick a Bitwarden server URL: ``--server-url``, then ``BWS_SERVER_URL``, then the existing
  426. ``secrets.bitwarden.server_url``, then the interactive US / EU / self-hosted menu. None (after
  427. printing) when a custom URL is left empty."""
  428. if args.server_url and args.server_url.strip():
  429. return args.server_url.strip()
  430. env_url = os.environ.get("BWS_SERVER_URL", "").strip()
  431. if env_url:
  432. console.print(f" Detected [cyan]BWS_SERVER_URL[/cyan]={env_url} in your shell — using it.")
  433. return env_url
  434. existing = cfg_str(secrets_cfg, "server_url")
  435. if existing:
  436. console.print(f" Existing config: [cyan]{existing}[/cyan]. "
  437. "Press Enter to keep, or pick a different option below.")
  438. table = Table(show_header=True, header_style="bold", box=None, padding=(0, 2))
  439. table.add_column("#", style="cyan", width=4)
  440. table.add_column("Region / endpoint")
  441. for i, (label, _url) in enumerate(_REGION_PRESETS, 1):
  442. table.add_row(str(i), label)
  443. custom_idx = len(_REGION_PRESETS) + 1
  444. table.add_row(str(custom_idx), "Self-hosted / custom URL")
  445. console.print(table)
  446. prompt = f" Select region [1-{custom_idx}]" + (" (Enter to keep current)" if existing else "")
  447. idx = prompt_index(console, prompt + ": ", custom_idx, allow_empty=bool(existing),
  448. empty_message=" [red]Enter a number.[/red]")
  449. if idx == 0:
  450. return existing
  451. if idx <= len(_REGION_PRESETS):
  452. return _REGION_PRESETS[idx - 1][1]
  453. custom = console.input(" Enter your Bitwarden server URL (e.g. https://vault.example.com): ").strip()
  454. if not custom:
  455. console.print(" [red]Empty URL, aborting.[/red]")
  456. return None
  457. if not custom.startswith(("http://", "https://")):
  458. console.print(" [yellow]Warning: URL doesn't start with http:// or https:// — bws may reject it.[/yellow]")
  459. return custom