secret_prompt.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. """Secret input prompts with masked typing feedback."""
  2. from __future__ import annotations
  3. import getpass
  4. import os
  5. import sys
  6. from collections.abc import Callable
  7. _BACKSPACE_CHARS = {"\b", "\x7f"}
  8. _ENTER_CHARS = {"\r", "\n"}
  9. _EOF_CHARS = {"\x04", "\x1a", ""} # "" == stream closed
  10. def _collect_masked_input(
  11. read_char: Callable[[], str], write: Callable[[str], object], prompt: str, *, mask: str = "*",
  12. ) -> str:
  13. """Read one secret line while writing a mask character per typed char."""
  14. value: list[str] = []
  15. write(prompt)
  16. while True:
  17. ch = read_char()
  18. if ch in _ENTER_CHARS:
  19. write("\r\n")
  20. return "".join(value)
  21. if ch == "\x03":
  22. write("\r\n")
  23. raise KeyboardInterrupt
  24. if ch in _EOF_CHARS:
  25. write("\r\n")
  26. raise EOFError
  27. if ch in _BACKSPACE_CHARS:
  28. if value:
  29. value.pop()
  30. write("\b \b")
  31. continue
  32. if ch == "\x1b":
  33. # Terminals send escape-prefixed navigation/delete sequences; they must not become
  34. # secret text.
  35. continue
  36. value.append(ch)
  37. if mask:
  38. write(mask)
  39. def masked_secret_prompt(prompt: str, *, mask: str = "*") -> str:
  40. """Prompt for a secret while showing masked typing feedback.
  41. Falls back to ``getpass.getpass`` when stdin/stdout are not interactive or when raw terminal
  42. handling is unavailable.
  43. """
  44. if not _stream_is_tty(sys.stdin) or not _stream_is_tty(sys.stdout):
  45. return getpass.getpass(prompt)
  46. masked = _masked_secret_prompt_windows if os.name == "nt" else _masked_secret_prompt_posix
  47. try:
  48. return masked(prompt, mask=mask)
  49. except (KeyboardInterrupt, EOFError):
  50. raise
  51. except Exception:
  52. return getpass.getpass(prompt)
  53. def _stream_is_tty(stream) -> bool:
  54. try:
  55. return bool(stream.isatty())
  56. except Exception:
  57. return False
  58. def _write(text: str) -> None:
  59. sys.stdout.write(text)
  60. sys.stdout.flush()
  61. def _masked_secret_prompt_windows(prompt: str, *, mask: str) -> str:
  62. import msvcrt
  63. def read_char() -> str:
  64. ch = msvcrt.getwch()
  65. if ch in {"\x00", "\xe0"}:
  66. msvcrt.getwch()
  67. return "\x1b"
  68. return ch
  69. return _collect_masked_input(read_char, _write, prompt, mask=mask)
  70. def _masked_secret_prompt_posix(prompt: str, *, mask: str) -> str:
  71. import termios
  72. import tty
  73. fd = sys.stdin.fileno()
  74. old_attrs = termios.tcgetattr(fd)
  75. try:
  76. tty.setraw(fd)
  77. return _collect_masked_input(lambda: sys.stdin.read(1), _write, prompt, mask=mask)
  78. finally:
  79. termios.tcsetattr(fd, termios.TCSADRAIN, old_attrs)