create_session_browser.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. #!/usr/bin/env python3
  2. """
  3. Requirements:
  4. pip install -r tools/requirements.txt
  5. Usage:
  6. python3 tools/create_session_browser.py <username> <password> [totp_seed] [--append sessions.jsonl] [--headless]
  7. Examples:
  8. # Output to terminal
  9. python3 tools/create_session_browser.py myusername mypassword TOTP_SECRET
  10. # Append to sessions.jsonl
  11. python3 tools/create_session_browser.py myusername mypassword TOTP_SECRET --append sessions.jsonl
  12. # Headless mode (may increase detection risk)
  13. python3 tools/create_session_browser.py myusername mypassword TOTP_SECRET --headless
  14. Output:
  15. {"kind": "cookie", "username": "...", "id": "...", "auth_token": "...", "ct0": "..."}
  16. """
  17. import sys
  18. import json
  19. import asyncio
  20. import pyotp
  21. import nodriver as uc
  22. import os
  23. async def login_and_get_cookies(username, password, totp_seed=None, headless=False):
  24. """Authenticate with X.com and extract session cookies"""
  25. # Note: headless mode may increase detection risk from bot-detection systems
  26. browser = await uc.start(headless=headless)
  27. tab = await browser.get('https://x.com/i/flow/login')
  28. try:
  29. # Enter username
  30. print('[*] Entering username...', file=sys.stderr)
  31. username_input = await tab.find('input[autocomplete="username"]', timeout=10)
  32. await username_input.send_keys(username + '\n')
  33. await asyncio.sleep(1)
  34. # Enter password
  35. print('[*] Entering password...', file=sys.stderr)
  36. password_input = await tab.find('input[autocomplete="current-password"]', timeout=15)
  37. await password_input.send_keys(password + '\n')
  38. await asyncio.sleep(2)
  39. # Handle 2FA if needed
  40. page_content = await tab.get_content()
  41. if 'verification code' in page_content or 'Enter code' in page_content:
  42. if not totp_seed:
  43. raise Exception('2FA required but no TOTP seed provided')
  44. print('[*] 2FA detected, entering code...', file=sys.stderr)
  45. totp_code = pyotp.TOTP(totp_seed).now()
  46. code_input = await tab.select('input[type="text"]')
  47. await code_input.send_keys(totp_code + '\n')
  48. await asyncio.sleep(3)
  49. # Get cookies
  50. print('[*] Retrieving cookies...', file=sys.stderr)
  51. for _ in range(20): # 20 second timeout
  52. cookies = await browser.cookies.get_all()
  53. cookies_dict = {cookie.name: cookie.value for cookie in cookies}
  54. if 'auth_token' in cookies_dict and 'ct0' in cookies_dict:
  55. print('[*] Found both cookies', file=sys.stderr)
  56. # Extract ID from twid cookie (may be URL-encoded)
  57. user_id = None
  58. if 'twid' in cookies_dict:
  59. twid = cookies_dict['twid']
  60. # Try to extract the ID from twid (format: u%3D<id> or u=<id>)
  61. if 'u%3D' in twid:
  62. user_id = twid.split('u%3D')[1].split('&')[0].strip('"')
  63. elif 'u=' in twid:
  64. user_id = twid.split('u=')[1].split('&')[0].strip('"')
  65. cookies_dict['username'] = username
  66. if user_id:
  67. cookies_dict['id'] = user_id
  68. return cookies_dict
  69. await asyncio.sleep(1)
  70. raise Exception('Timeout waiting for cookies')
  71. finally:
  72. browser.stop()
  73. async def main():
  74. if len(sys.argv) < 3:
  75. print('Usage: python3 twitter-auth.py username password [totp_seed] [--append sessions.jsonl] [--headless]')
  76. sys.exit(1)
  77. username = sys.argv[1]
  78. password = sys.argv[2]
  79. totp_seed = None
  80. append_file = None
  81. headless = False
  82. # Parse optional arguments
  83. i = 3
  84. while i < len(sys.argv):
  85. arg = sys.argv[i]
  86. if arg == '--append':
  87. if i + 1 < len(sys.argv):
  88. append_file = sys.argv[i + 1]
  89. i += 2 # Skip '--append' and filename
  90. else:
  91. print('[!] Error: --append requires a filename', file=sys.stderr)
  92. sys.exit(1)
  93. elif arg == '--headless':
  94. headless = True
  95. i += 1
  96. elif not arg.startswith('--'):
  97. if totp_seed is None:
  98. totp_seed = arg
  99. i += 1
  100. else:
  101. # Unkown args
  102. print(f'[!] Warning: Unknown argument: {arg}', file=sys.stderr)
  103. i += 1
  104. try:
  105. cookies = await login_and_get_cookies(username, password, totp_seed, headless)
  106. session = {
  107. 'kind': 'cookie',
  108. 'username': cookies['username'],
  109. 'id': cookies.get('id'),
  110. 'auth_token': cookies['auth_token'],
  111. 'ct0': cookies['ct0']
  112. }
  113. output = json.dumps(session)
  114. if append_file:
  115. with open(append_file, 'a') as f:
  116. f.write(output + '\n')
  117. print(f'✓ Session appended to {append_file}', file=sys.stderr)
  118. else:
  119. print(output)
  120. os._exit(0)
  121. except Exception as error:
  122. print(f'[!] Error: {error}', file=sys.stderr)
  123. sys.exit(1)
  124. if __name__ == '__main__':
  125. asyncio.run(main())