scripts/git-credential-token.py
scripts/git-credential-token.pyBrowse 17 files
455 tokens
1,788 bytes
Token encoding: o200k_base
Snapshot 24fd22b
← Back to SKILL.md
1#!/usr/bin/env python32"""Print the first unambiguous GitHub token in a git credential-store file."""3 4from pathlib import Path5import re6import sys7from urllib.parse import unquote, urlsplit8 9 10_TOKEN_PREFIXES = ("ghp_", "github_pat_", "gho_", "ghu_", "ghs_", "ghr_")11_INVALID_ESCAPE = re.compile(r"%(?![0-9A-Fa-f]{2})")12 13 14def _decode(value: str | None) -> str:15 if value is None or _INVALID_ESCAPE.search(value):16 return ""17 decoded = unquote(value)18 if not decoded or any(ord(char) <= 0x1F or 0x7F <= ord(char) <= 0x9F for char in decoded):19 return ""20 return decoded21 22 23def _token_from_url(line: str) -> str:24 if "\r" in line or "\n" in line:25 return ""26 try:27 credential = urlsplit(line)28 port = credential.port29 except ValueError:30 return ""31 if credential.scheme != "https" or credential.hostname != "github.com" or port not in (None, 443):32 return ""33 34 username = _decode(credential.username)35 password = _decode(credential.password)36 if not username:37 return ""38 if password and password != "x-oauth-basic":39 return password40 if password == "x-oauth-basic":41 return username42 return username if username.startswith(_TOKEN_PREFIXES) else ""43 44 45def main() -> int:46 path = Path(sys.argv[1]).expanduser() if len(sys.argv) > 1 else Path.home() / ".git-credentials"47 try:48 lines = path.read_bytes().split(b"\n")49 except OSError:50 return 151 52 for raw_line in lines:53 try:54 line = raw_line.decode("utf-8")55 except UnicodeDecodeError:56 continue57 token = _token_from_url(line)58 if token:59 print(token)60 return 061 return 162 63 64if __name__ == "__main__":65 raise SystemExit(main())66