git-credential-token.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env python3
  2. """Print the first unambiguous GitHub token in a git credential-store file."""
  3. from pathlib import Path
  4. import re
  5. import sys
  6. from urllib.parse import unquote, urlsplit
  7. _TOKEN_PREFIXES = ("ghp_", "github_pat_", "gho_", "ghu_", "ghs_", "ghr_")
  8. _INVALID_ESCAPE = re.compile(r"%(?![0-9A-Fa-f]{2})")
  9. def _decode(value: str | None) -> str:
  10. if value is None or _INVALID_ESCAPE.search(value):
  11. return ""
  12. decoded = unquote(value)
  13. if not decoded or any(ord(char) <= 0x1F or 0x7F <= ord(char) <= 0x9F for char in decoded):
  14. return ""
  15. return decoded
  16. def _token_from_url(line: str) -> str:
  17. if "\r" in line or "\n" in line:
  18. return ""
  19. try:
  20. credential = urlsplit(line)
  21. port = credential.port
  22. except ValueError:
  23. return ""
  24. if credential.scheme != "https" or credential.hostname != "github.com" or port not in (None, 443):
  25. return ""
  26. username = _decode(credential.username)
  27. password = _decode(credential.password)
  28. if not username:
  29. return ""
  30. if password and password != "x-oauth-basic":
  31. return password
  32. if password == "x-oauth-basic":
  33. return username
  34. return username if username.startswith(_TOKEN_PREFIXES) else ""
  35. def main() -> int:
  36. path = Path(sys.argv[1]).expanduser() if len(sys.argv) > 1 else Path.home() / ".git-credentials"
  37. try:
  38. lines = path.read_bytes().split(b"\n")
  39. except OSError:
  40. return 1
  41. for raw_line in lines:
  42. try:
  43. line = raw_line.decode("utf-8")
  44. except UnicodeDecodeError:
  45. continue
  46. token = _token_from_url(line)
  47. if token:
  48. print(token)
  49. return 0
  50. return 1
  51. if __name__ == "__main__":
  52. raise SystemExit(main())