twitter-generator 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ """Twitter/X Headers Generator - Python implementation for authentication token generation."""
2
+
3
+ from .client_transaction import ClientTransactionGenerator
4
+ from .xp_forwarded_for import XPForwardedForGenerator
5
+ from .exceptions import InvalidGuestIdError, InvalidHomePageError, InvalidOndemandFileError
6
+ from .version import __version__
7
+
8
+ __all__ = [
9
+ "ClientTransactionGenerator",
10
+ "XPForwardedForGenerator",
11
+ "InvalidGuestIdError",
12
+ "InvalidHomePageError",
13
+ "InvalidOndemandFileError",
14
+ "__version__",
15
+ ]
@@ -0,0 +1,3 @@
1
+ from .main import ClientTransactionGenerator
2
+
3
+ __all__ = ["ClientTransactionGenerator"]
@@ -0,0 +1,146 @@
1
+ from time import time
2
+ from math import floor
3
+ from random import randint
4
+ from hashlib import sha256
5
+ from base64 import b64encode, b64decode
6
+ from functools import reduce
7
+ from typing import List
8
+ from re import sub, compile, VERBOSE, MULTILINE
9
+ from bs4 import BeautifulSoup
10
+
11
+ from ..helpers import Cubic, MathUtils
12
+ from ..exceptions import InvalidHomePageError, InvalidOndemandFileError
13
+
14
+
15
+ class ClientTransactionGenerator:
16
+ def __init__(self, ondemand_file: str, home_page: str):
17
+ """
18
+ Initialize the client transaction generator.
19
+
20
+ Args:
21
+ ondemand_file: Content of the ondemand JavaScript file
22
+ home_page: HTML content of the Twitter home page
23
+ """
24
+ try:
25
+ # Extract indices from ondemand file
26
+ if not (indices := [
27
+ int(m.group(2)) for m in compile(
28
+ r"""(\(\w{1}\[(\d{1,2})\],\s*16\))+""",
29
+ flags=(VERBOSE | MULTILINE)
30
+ ).finditer(ondemand_file)
31
+ ]):
32
+ raise InvalidOndemandFileError("Couldn't get KEY_BYTE indices")
33
+ self.row_index, self.key_bytes_indices = indices[0], indices[1:]
34
+ except Exception as e:
35
+ raise InvalidOndemandFileError(f"Couldn't get KEY_BYTE indices: {e}")
36
+
37
+ try:
38
+ soup = BeautifulSoup(home_page, 'html.parser')
39
+ element = soup.select_one("meta[name='twitter-site-verification']")
40
+ if not element:
41
+ raise InvalidHomePageError("Couldn't get [twitter-site-verification] key")
42
+ key = element.get("content")
43
+ self.key_bytes = list(b64decode(key.encode()))
44
+ self.animation_key = self._get_animation_key(soup)
45
+ except Exception as e:
46
+ raise InvalidHomePageError(f"Couldn't get [twitter-site-verification] key: {e}")
47
+
48
+ def generate(self, method: str, path: str) -> str:
49
+ """
50
+ Generate client transaction ID for API request.
51
+
52
+ Args:
53
+ method: HTTP method (e.g., "GET", "POST")
54
+ path: API endpoint path
55
+
56
+ Returns:
57
+ Base64-encoded client transaction ID
58
+ """
59
+ # Calculate current time offset
60
+ time_now = floor((time() * 1000 - 1682924400000) / 1000)
61
+ time_now_bytes = [(time_now >> (i * 8)) & 0xFF for i in range(4)]
62
+
63
+ # Generate hash
64
+ hash_val = sha256(
65
+ f"{method}!{path}!{time_now}obfiowerehiring{self.animation_key}".encode()
66
+ ).digest()
67
+
68
+ # Build final byte array with XOR encoding
69
+ random_num = randint(0, 255)
70
+ bytes_arr = [*self.key_bytes, *time_now_bytes, *list(hash_val)[:16], 3]
71
+ out = bytearray([random_num, *[b ^ random_num for b in bytes_arr]])
72
+
73
+ return b64encode(out).decode().rstrip("=")
74
+
75
+
76
+ def _get_animation_key(self, home_page_response: BeautifulSoup) -> str:
77
+ """
78
+ Calculate animation key from key bytes.
79
+
80
+ Args:
81
+ home_page_response: Parsed HTML soup object from home page
82
+
83
+ Returns:
84
+ Animation key string
85
+ """
86
+ # Calculate row index and frame time
87
+ row_index = self.key_bytes[self.row_index] % 16
88
+ frame_time = reduce(lambda x, y: x * y,
89
+ [self.key_bytes[i] % 16 for i in self.key_bytes_indices])
90
+ frame_time = MathUtils.round(frame_time / 10) * 10
91
+
92
+
93
+ # Extract path data from animation frames
94
+ frames = home_page_response.select("[id^='loading-x-anim']")
95
+ path_data = list(list(frames[self.key_bytes[5] % 4].children)[0].children)[1].get("d")[9:]
96
+ arr = [
97
+ [int(x) for x in sub(r"[^\d]+", " ", item).strip().split()]
98
+ for item in path_data.split("C")
99
+ ]
100
+
101
+ # Animate the frame
102
+ frame_row = arr[row_index]
103
+ target_time = float(frame_time) / 4096
104
+ return self._animate(frame_row, target_time)
105
+
106
+ def _animate(self, frames: List[int], target_time: float) -> str:
107
+ """
108
+ Generate animation key from frame data and target time.
109
+
110
+ Args:
111
+ frames: List of frame data values
112
+ target_time: Target time for animation interpolation
113
+
114
+ Returns:
115
+ Animation key string
116
+ """
117
+ # Scale value from 0-255 range to min-max range
118
+ def solve(value, min_val, max_val, rounding):
119
+ result = value * (max_val - min_val) / 255 + min_val
120
+ return floor(result) if rounding else round(result, 2)
121
+
122
+ # Extract color and rotation data
123
+ from_color = [float(x) for x in [*frames[:3], 1]]
124
+ to_color = [float(x) for x in [*frames[3:6], 1]]
125
+ to_rotation = [solve(float(frames[6]), 60.0, 360.0, True)]
126
+
127
+ # Generate cubic bezier curves and interpolate
128
+ curves = [
129
+ solve(float(item), MathUtils.is_odd(i), 1.0, False)
130
+ for i, item in enumerate(frames[7:])
131
+ ]
132
+
133
+ val = Cubic(curves).get_value(target_time)
134
+ color = [max(0, min(255, v)) for v in MathUtils.interpolate(from_color, to_color, val)]
135
+ rotation = MathUtils.interpolate([0.0], to_rotation, val)
136
+ matrix = MathUtils.convert_rotation_to_matrix(rotation[0])
137
+
138
+ # Build animation key string
139
+ str_arr = [format(round(value), 'x') for value in color[:-1]]
140
+ for value in matrix:
141
+ rounded = abs(round(value, 2))
142
+ hex_value = MathUtils.float_to_hex(rounded)
143
+ str_arr.append(f"0{hex_value}".lower() if hex_value.startswith(".") else hex_value or '0')
144
+ str_arr.extend(["0", "0"])
145
+
146
+ return sub(r"[.-]", "", "".join(str_arr))
@@ -0,0 +1,11 @@
1
+ class TwitterGeneratorException(Exception):
2
+ pass
3
+
4
+ class InvalidHomePageError(TwitterGeneratorException):
5
+ pass
6
+
7
+ class InvalidOndemandFileError(TwitterGeneratorException):
8
+ pass
9
+
10
+ class InvalidGuestIdError(TwitterGeneratorException):
11
+ pass
@@ -0,0 +1,4 @@
1
+ from .cubic import Cubic
2
+ from .math_utils import MathUtils
3
+
4
+ __all__ = ['Cubic', 'MathUtils']
@@ -0,0 +1,72 @@
1
+ from typing import Union, List
2
+
3
+ class Cubic:
4
+ """
5
+ Cubic bezier curve calculator.
6
+ """
7
+
8
+ def __init__(self, curves: List[Union[float, int]]):
9
+ """
10
+ Initialize cubic bezier curve calculator.
11
+
12
+ Args:
13
+ curves: List of curve control points
14
+ """
15
+ self.curves = curves
16
+
17
+ def get_value(self, time: Union[float, int]) -> Union[float, int]:
18
+ """
19
+ Calculate the bezier curve value at a given time.
20
+
21
+ Args:
22
+ time: Time value (0.0 to 1.0 for normal range)
23
+
24
+ Returns:
25
+ Interpolated value from the bezier curve
26
+ """
27
+ start_gradient: float = 0.0
28
+ end_gradient: float = 0.0
29
+ start: float = 0.0
30
+ mid: float = 0.0
31
+ end: float = 1.0
32
+
33
+ if time <= 0.0:
34
+ if self.curves[0] > 0.0:
35
+ start_gradient = self.curves[1] / self.curves[0]
36
+ elif self.curves[1] == 0.0 and self.curves[2] > 0.0:
37
+ start_gradient = self.curves[3] / self.curves[2]
38
+ return start_gradient * time
39
+
40
+ if time >= 1.0:
41
+ if self.curves[2] < 1.0:
42
+ end_gradient = (self.curves[3] - 1.0) / (self.curves[2] - 1.0)
43
+ elif self.curves[2] == 1.0 and self.curves[0] < 1.0:
44
+ end_gradient = (self.curves[1] - 1.0) / (self.curves[0] - 1.0)
45
+ return 1.0 + end_gradient * (time - 1.0)
46
+
47
+ while start < end:
48
+ mid = (start + end) / 2
49
+ x_est = self.calculate(self.curves[0], self.curves[2], mid)
50
+ if abs(time - x_est) < 0.00001:
51
+ return self.calculate(self.curves[1], self.curves[3], mid)
52
+ if x_est < time:
53
+ start = mid
54
+ else:
55
+ end = mid
56
+ return self.calculate(self.curves[1], self.curves[3], mid)
57
+
58
+ @staticmethod
59
+ def calculate(a: Union[float, int], b: Union[float, int], m: Union[float, int]) -> Union[float, int]:
60
+ """
61
+ Calculate bezier point.
62
+
63
+ Args:
64
+ a: First control point
65
+ b: Second control point
66
+ m: Interpolation parameter (0.0 to 1.0)
67
+
68
+ Returns:
69
+ Calculated bezier point value
70
+ """
71
+ return 3.0 * a * (1 - m) * (1 - m) * m + 3.0 * b * (1 - m) * m * m + m * m * m
72
+
@@ -0,0 +1,138 @@
1
+ import math
2
+ from typing import Union, List
3
+
4
+ class MathUtils:
5
+ """
6
+ Custom math utilities.
7
+ """
8
+
9
+ @staticmethod
10
+ def round(num: Union[float, int]) -> Union[float, int]:
11
+ """
12
+ JavaScript-compatible rounding.
13
+
14
+ Args:
15
+ num: Number to round
16
+
17
+ Returns:
18
+ Rounded number with same sign as input
19
+ """
20
+ x = math.floor(num)
21
+ if (num - x) >= 0.5:
22
+ x = math.ceil(num)
23
+ return math.copysign(x, num)
24
+
25
+ @staticmethod
26
+ def interpolate_num(from_val: Union[float, int, bool], to_val: Union[float, int, bool], f: Union[float, int]) -> Union[float, int, bool]:
27
+ """
28
+ Interpolate between two numbers or booleans.
29
+
30
+ Args:
31
+ from_val: Starting value
32
+ to_val: Ending value
33
+ f: Interpolation factor (0.0 to 1.0)
34
+
35
+ Returns:
36
+ Interpolated value
37
+ """
38
+ if all([isinstance(number, (int, float)) for number in [from_val, to_val]]):
39
+ return from_val * (1 - f) + to_val * f
40
+ if all([isinstance(number, bool) for number in [from_val, to_val]]):
41
+ return from_val if f < 0.5 else to_val
42
+ return from_val
43
+
44
+ @staticmethod
45
+ def interpolate(from_list: List[Union[float, int]], to_list: List[Union[float, int]], f: Union[float, int]) -> List[Union[float, int]]:
46
+ """
47
+ Interpolate between two lists of values.
48
+
49
+ Args:
50
+ from_list: Starting list of values
51
+ to_list: Ending list of values
52
+ f: Interpolation factor (0.0 to 1.0)
53
+
54
+ Returns:
55
+ List of interpolated values
56
+
57
+ Raises:
58
+ ValueError: If input lists have different lengths
59
+ """
60
+ if len(from_list) != len(to_list):
61
+ raise ValueError(f"Mismatched interpolation arguments {from_list}: {to_list}")
62
+ return [MathUtils.interpolate_num(from_list[i], to_list[i], f) for i in range(len(from_list))]
63
+
64
+
65
+ @staticmethod
66
+ def convert_rotation_to_matrix(rotation: Union[float, int]) -> List[Union[float, int]]:
67
+ """
68
+ Convert rotation angle to transformation matrix.
69
+
70
+ Args:
71
+ rotation: Rotation angle in degrees
72
+
73
+ Returns:
74
+ List of 4 matrix values [cos, -sin, sin, cos]
75
+ """
76
+ rad = math.radians(rotation)
77
+ return [math.cos(rad), -math.sin(rad), math.sin(rad), math.cos(rad)]
78
+
79
+
80
+ @staticmethod
81
+ def float_to_hex(x: Union[float, int]) -> str:
82
+ """
83
+ Convert float to hexadecimal string.
84
+
85
+ Args:
86
+ x: Float or integer value to convert
87
+
88
+ Returns:
89
+ Hexadecimal string representation
90
+ """
91
+ result = []
92
+ quotient = int(x)
93
+ fraction = x - quotient
94
+
95
+ while quotient > 0:
96
+ quotient = int(x / 16)
97
+ remainder = int(x - (float(quotient) * 16))
98
+
99
+ if remainder > 9:
100
+ result.insert(0, chr(remainder + 55))
101
+ else:
102
+ result.insert(0, str(remainder))
103
+
104
+ x = float(quotient)
105
+
106
+ if fraction == 0:
107
+ return ''.join(result)
108
+
109
+ result.append('.')
110
+
111
+ while fraction > 0:
112
+ fraction *= 16
113
+ integer = int(fraction)
114
+ fraction -= float(integer)
115
+
116
+ if integer > 9:
117
+ result.append(chr(integer + 55))
118
+ else:
119
+ result.append(str(integer))
120
+
121
+ return ''.join(result)
122
+
123
+
124
+ @staticmethod
125
+ def is_odd(num: Union[int, float]) -> float:
126
+ """
127
+ Check if number is odd and return corresponding value.
128
+
129
+ Args:
130
+ num: Number to check
131
+
132
+ Returns:
133
+ -1.0 if odd, 0.0 if even
134
+ """
135
+ if num % 2:
136
+ return -1.0
137
+ return 0.0
138
+
@@ -0,0 +1,3 @@
1
+ """Version information for twitter_generator package."""
2
+
3
+ __version__ = "1.0.0"
@@ -0,0 +1,3 @@
1
+ from .main import XPForwardedForGenerator
2
+
3
+ __all__ = ["XPForwardedForGenerator"]
@@ -0,0 +1,235 @@
1
+ import base64
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import re
6
+ import time
7
+ from typing import Dict, Optional, Union
8
+
9
+ from cryptography.exceptions import InvalidTag
10
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
11
+
12
+ from ..exceptions import InvalidGuestIdError
13
+
14
+ class XPForwardedForGenerator:
15
+ """
16
+ Generator and decoder for X-XP-Forwarded-For authentication tokens.
17
+
18
+ This class provides methods to generate and decode Twitter/X's
19
+ x-xp-forwarded-for tokens using AES-256-GCM encryption.
20
+ """
21
+
22
+ # AES-256-GCM base encryption key (extracted from WASM binary)
23
+ AES_KEY_HEX = '0e6be1f1e21ffc33590b888fd4dc81b19713e570e805d4e5df80a493c9571a05'
24
+
25
+ # GCM parameters
26
+ IV_LENGTH = 12 # 12 bytes (96 bits) - standard for GCM
27
+ AUTH_TAG_LENGTH = 16 # 16 bytes (128 bits)
28
+
29
+ # Token validity duration
30
+ TOKEN_VALIDITY_MS = 60 * 60 * 1000 # 1 hour
31
+
32
+ def __init__(self, guest_id: Optional[str] = None):
33
+ """
34
+ Initialize the generator.
35
+
36
+ Args:
37
+ guest_id: Optional guest ID from cookie for key derivation
38
+ """
39
+ self.guest_id = guest_id
40
+ self._base_key = bytes.fromhex(self.AES_KEY_HEX)
41
+
42
+ def generate(self, env: Dict) -> Dict:
43
+ """
44
+ Generate x-xp-forwarded-for token.
45
+
46
+ Args:
47
+ env: Dictionary with keys:
48
+ - userAgent: Browser user agent
49
+ - hasBeenActive: User activation state
50
+ - webdriver: Webdriver detection flag
51
+ - guestId: Twitter guest_id cookie value (optional, for key derivation)
52
+
53
+ Returns:
54
+ Dictionary with 'str' (base64 token) and 'expiryTimeMillis'
55
+ """
56
+ # Build client signals
57
+ signals = self._build_client_signals(env)
58
+
59
+ # Serialize to JSON
60
+ json_data = json.dumps(signals, separators=(',', ':'))
61
+
62
+ # Use derived key if guestId is provided, otherwise use default key
63
+ key = None
64
+ guest_id = env.get('guestId') or self.guest_id
65
+ if guest_id:
66
+ key = self._derive_key_from_guest_id(guest_id)
67
+
68
+ # Encrypt
69
+ encrypted = self._encrypt(json_data, key)
70
+
71
+ # Encode as base64
72
+ return base64.b64encode(encrypted).decode('utf-8')
73
+
74
+ def decode(self, token: str, key: Optional[bytes] = None) -> Dict:
75
+ """
76
+ Decode and decrypt a token.
77
+
78
+ Args:
79
+ token: Base64-encoded or hex-encoded token
80
+ key: 32-byte encryption key (defaults to base key)
81
+
82
+ Returns:
83
+ Decoded client signals dictionary
84
+ """
85
+ # Check if hex or base64
86
+ if re.match(r'^[0-9a-fA-F]+$', token) and len(token) % 2 == 0:
87
+ # Hex encoded
88
+ ciphertext = bytes.fromhex(token)
89
+ else:
90
+ # Base64 encoded
91
+ ciphertext = base64.b64decode(token)
92
+
93
+ # Decrypt
94
+ json_data = self._decrypt(ciphertext, key)
95
+
96
+ # Parse JSON
97
+ return json.loads(json_data)
98
+
99
+ def decode_with_key(self, token: str, key_hex: str) -> Dict:
100
+ """
101
+ Decrypt with a custom key.
102
+
103
+ Args:
104
+ token: Base64 or hex encoded token
105
+ key_hex: 64-character hex key
106
+
107
+ Returns:
108
+ Decoded client signals dictionary
109
+ """
110
+ key = bytes.fromhex(key_hex)
111
+ return self.decode(token, key)
112
+
113
+ def decode_with_guest_id(self, token: str, guest_id: str) -> Dict:
114
+ """
115
+ Decrypt token using guest_id for key derivation.
116
+ This is the actual method used by Twitter/X.
117
+
118
+ Args:
119
+ token: Base64 or hex encoded token
120
+ guest_id: Guest ID from cookie
121
+
122
+ Returns:
123
+ Decoded client signals dictionary
124
+ """
125
+ derived_key = self._derive_key_hex_from_guest_id(guest_id)
126
+ return self.decode_with_key(token, derived_key)
127
+
128
+ def _derive_key_from_guest_id(self, guest_id: str) -> bytes:
129
+ """
130
+ Derive encryption key from guest_id.
131
+ Formula: SHA256(baseKey + guestId)
132
+
133
+ Args:
134
+ guest_id: Guest ID from cookie (e.g., "v1%3A176824413470818950")
135
+
136
+ Returns:
137
+ 32-byte derived key
138
+ """
139
+ combined = self.AES_KEY_HEX + guest_id
140
+ return hashlib.sha256(combined.encode('utf-8')).digest()
141
+
142
+ def _derive_key_hex_from_guest_id(self, guest_id: str) -> str:
143
+ """
144
+ Derive encryption key from guest_id and return as hex string.
145
+
146
+ Args:
147
+ guest_id: Guest ID from cookie
148
+
149
+ Returns:
150
+ 64-character hex key
151
+ """
152
+ return self._derive_key_from_guest_id(guest_id).hex()
153
+
154
+ def _encrypt(self, plaintext: Union[str, bytes], key: Optional[bytes] = None) -> bytes:
155
+ """
156
+ Encrypt data using AES-256-GCM.
157
+
158
+ Args:
159
+ plaintext: Data to encrypt (string or bytes)
160
+ key: 32-byte encryption key (defaults to base key)
161
+
162
+ Returns:
163
+ IV + ciphertext + auth tag
164
+ """
165
+ if key is None:
166
+ key = self._base_key
167
+
168
+ # Convert string to bytes if needed
169
+ if isinstance(plaintext, str):
170
+ plaintext = plaintext.encode('utf-8')
171
+
172
+ # Generate random 12-byte IV
173
+ iv = os.urandom(self.IV_LENGTH)
174
+
175
+ # Create AES-GCM cipher
176
+ aesgcm = AESGCM(key)
177
+
178
+ # Encrypt (GCM automatically appends auth tag)
179
+ ciphertext = aesgcm.encrypt(iv, plaintext, None)
180
+
181
+ # Combine: IV + ciphertext (ciphertext includes auth tag)
182
+ return iv + ciphertext
183
+
184
+ def _decrypt(self, ciphertext: bytes, key: Optional[bytes] = None) -> str:
185
+ """
186
+ Decrypt data using AES-256-GCM.
187
+
188
+ Args:
189
+ ciphertext: IV + encrypted data + auth tag
190
+ key: 32-byte encryption key (defaults to base key)
191
+
192
+ Returns:
193
+ Decrypted plaintext as string
194
+ """
195
+ if key is None:
196
+ key = self._base_key
197
+
198
+ # Extract components
199
+ iv = ciphertext[:self.IV_LENGTH]
200
+ encrypted = ciphertext[self.IV_LENGTH:]
201
+
202
+ # Create AES-GCM cipher
203
+ aesgcm = AESGCM(key)
204
+
205
+ # Decrypt (GCM automatically verifies auth tag)
206
+ try:
207
+ plaintext = aesgcm.decrypt(iv, encrypted, None)
208
+ except InvalidTag:
209
+ raise InvalidGuestIdError("Wrong guest ID provided")
210
+
211
+ return plaintext.decode('utf-8')
212
+
213
+ def _build_client_signals(self, env: Dict) -> Dict:
214
+ """
215
+ Build client signals from browser environment.
216
+
217
+ Args:
218
+ env: Dictionary with keys:
219
+ - userAgent: Browser user agent
220
+ - hasBeenActive: User activation state
221
+ - webdriver: Webdriver detection flag
222
+ - guestId: Twitter guest_id cookie value (optional, for key derivation)
223
+
224
+ Returns:
225
+ ClientSignals dictionary
226
+ """
227
+ return {
228
+ 'navigator_properties': {
229
+ 'user_agent': env.get('userAgent', 'Mozilla/5.0'),
230
+ 'has_been_active': env.get('hasBeenActive', False),
231
+ 'webdriver': env.get('webdriver', False),
232
+ 'guest_id': env.get('guestId', '')
233
+ },
234
+ 'created_at': int(time.time() * 1000)
235
+ }
@@ -0,0 +1,201 @@
1
+ Metadata-Version: 2.4
2
+ Name: twitter-generator
3
+ Version: 1.0.0
4
+ Summary: Python implementation for generating Twitter/X authentication headers (twitter-generator and X-XP-Forwarded-For)
5
+ Author-email: GlizzyKingDreko <glizzykingdreko@protonmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/GlizzyKingDreko/twitter-generator
8
+ Project-URL: Documentation, https://github.com/GlizzyKingDreko/twitter-generator/blob/main/LEARN.md
9
+ Project-URL: Repository, https://github.com/GlizzyKingDreko/twitter-generator
10
+ Project-URL: Issues, https://github.com/GlizzyKingDreko/twitter-generator/issues
11
+ Keywords: twitter,x,authentication,headers,client-transaction-id,xp-forwarded-for,reverse-engineering
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Internet :: WWW/HTTP
22
+ Classifier: Topic :: Security
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Requires-Python: >=3.8
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: cryptography>=41.0.0
28
+ Requires-Dist: beautifulsoup4>=4.12.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
31
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
32
+ Requires-Dist: black>=23.0.0; extra == "dev"
33
+ Requires-Dist: flake8>=6.0.0; extra == "dev"
34
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ # Twitter / X Headers Generator
38
+
39
+ ![Twitter headers](./images/headers.png)
40
+ <div align="center">
41
+ <img src="https://img.shields.io/badge/Status-Complete-brightgreen" alt="Status: Complete">
42
+ <img src="https://img.shields.io/badge/Type-Research-blue" alt="Type: Research">
43
+ <img src="https://img.shields.io/badge/License-MIT-yellow" alt="License: MIT">
44
+ <a href="https://www.npmjs.com/package/twitter_headers_generator"><img src="https://img.shields.io/npm/v/twitter_headers_generator.svg?style=flat-square&color=cb3837&logo=npm" alt="npm version"></a>
45
+ <a href="https://github.com/GlizzyKingDreko/twitter_headers_generator"><img src="https://img.shields.io/github/stars/GlizzyKingDreko/twitter_headers_generator?style=flat-square&logo=github" alt="GitHub stars"></a>
46
+ <a href="https://github.com/GlizzyKingDreko/twitter_headers_generator"><img src="https://img.shields.io/badge/GitHub-Repo-black?logo=github&style=flat-square" alt="GitHub repo"></a>
47
+ </div>
48
+
49
+ <br>
50
+
51
+ <div align="center">
52
+ <a href="https://github.com/GlizzyKingDreko/twitter_headers_generator-python"><img src="https://img.shields.io/badge/Check%20the%20Python%20version-purple?logo=python&style=flat-square" alt="Check the Python version"></a>
53
+ <a href="https://medium.com/@glizzykingdreko/breaking-down-datadome-captcha-waf-d7b68cef3e21"><img src="https://img.shields.io/badge/Read%20the%20full%20article%20on%20Medium-12100E?logo=medium&logoColor=white&style=flat-square" alt="Read the full article on Medium"></a>
54
+ <a href="https://buymeacoffee.com/glizzykingdreko"><img src="https://img.shields.io/badge/Support%20my%20research%20by%20buying%20me%20a%20coffee-242424?style=flat-square&logo=buy-me-a-coffee&logoColor=yellow" alt="Buy me a coffee"></a>
55
+ </div>
56
+
57
+
58
+ Python module with an attached reverse-engineering study of the X (former Twitter) `x-client-transaction-id` and `x-xp-forwarded-for` request headers.
59
+
60
+ ## Series Context
61
+
62
+ This repository represents **Episode 1** of a multi-part analysis of Twitter/X login-flow protections.
63
+
64
+ Be sure to follow me on [Medium](https://medium.com/@glizzykingdreko) and [Github](https://github.com/GlizzyKingDreko) in order to prevent loosing next episodes.
65
+
66
+ Next one is going to be about the first antibot challenge.
67
+
68
+ ## Learning
69
+ Be sure to check out [LEARN.md](./LEARN.md) in order to understand how this has been made as well as the [full article on Medium](https://www.com)
70
+
71
+ ## Table of Contents
72
+
73
+ - [Installation](#installation)
74
+ - [Quick Start](#quick-start)
75
+ - [X-Client-Transaction-Id](#x-client-transaction-id)
76
+ - [X-XP-Forwarded-For](#x-xp-forwarded-for)
77
+ - [Learning](#learning)
78
+ - [Multi-Language Implementations](#step-10-multi-language-implementations)
79
+ - [Author](#author)
80
+
81
+
82
+ ---
83
+
84
+ ## Installation
85
+
86
+ ```bash
87
+ pip install twitter-generator
88
+ ```
89
+
90
+ Or from source:
91
+
92
+ ```bash
93
+ git clone https://github.com/GlizzyKingDreko/twitter-generator.git
94
+ cd twitter-generator
95
+ pip install -e .
96
+ ```
97
+
98
+
99
+ ## Quick Start
100
+
101
+ ### X-Client-Transaction-Id
102
+
103
+ ```python
104
+ from twitter_generator import ClientTransactionGenerator
105
+
106
+ generator = ClientTransactionGenerator(
107
+ ondemand_file=ondemand_js_content, # Dynamic js file content
108
+ home_page=home_page_html # Loaded homepage content
109
+ )
110
+
111
+ transaction_id = generator.generate(
112
+ "GET", # Method you are going to use
113
+ "/api/1.1/statuses/user_timeline.json" # Route of the request
114
+ )
115
+
116
+ print(transaction_id)
117
+ ```
118
+
119
+
120
+ ### X-XP-Forwarded-For
121
+
122
+ ```python
123
+ from twitter_generator import XPForwardedForGenerator
124
+
125
+ generator = XPForwardedForGenerator(
126
+ guest_id="v1%3A176824413470818950" # Your guest_id cookie
127
+ )
128
+
129
+ env = {
130
+ 'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36',
131
+ 'hasBeenActive': False,
132
+ 'webdriver': False
133
+ }
134
+
135
+ token = generator.generate(env)
136
+ print(token)
137
+
138
+
139
+ # Or decrypting it via
140
+ generator.decode(
141
+ token,
142
+ generator._derive_key_from_guest_id(guest_id)
143
+ )
144
+ ```
145
+
146
+
147
+ ## API Reference
148
+
149
+ ### ClientTransactionGenerator
150
+
151
+ ```python
152
+ class ClientTransactionGenerator:
153
+ def __init__(self, ondemand_file: str, home_page: str)
154
+ def generate(self, method: str, path: str) -> str
155
+ ```
156
+
157
+
158
+ ### XPForwardedForGenerator
159
+
160
+ ```python
161
+ class XPForwardedForGenerator:
162
+ def __init__(self, guest_id: Optional[str] = None)
163
+ def generate(self, env: Dict) -> str
164
+ def decode(self, token: str, key: Optional[bytes] = None) -> Dict
165
+ def decode_with_key(self, token: str, key_hex: str) -> Dict
166
+ def decode_with_guest_id(self, token: str, guest_id: str) -> Dict
167
+
168
+ @staticmethod
169
+ def extract_guest_id_from_cookie(
170
+ cookie_string: str
171
+ ) -> Optional[str]
172
+ ```
173
+
174
+
175
+ ## Implementations in Other Languages
176
+
177
+ Be sure to check the
178
+ - [GO Version](./xp_forwarded_for/go/main.go)
179
+ - [NodeJS Version](./xp_forwarded_for/nodejs/index.js)
180
+
181
+ ## License
182
+
183
+ MIT License.
184
+ See [LICENSE](LICENSE) for details.
185
+
186
+ ---
187
+
188
+
189
+ ## Author
190
+
191
+ If you found this project helpful or interesting, consider starring the repo and following me for more security research and tools, or buy me a coffee to keep me up.
192
+
193
+ <p align="center">
194
+ <a href="https://github.com/GlizzyKingDreko"><img src="https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white" alt="GitHub"></a>
195
+ <a href="https://twitter.com/GlizzyKingDreko"><img src="https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white" alt="Twitter"></a>
196
+ <a href="https://medium.com/@GlizzyKingDreko"><img src="https://img.shields.io/badge/Medium-12100E?style=for-the-badge&logo=medium&logoColor=white" alt="Medium"></a>
197
+ <a href="https://discord.com/users/GlizzyKingDreko"><img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white" alt="Discord"></a>
198
+ <a href="mailto:glizzykingdreko@protonmail.com"><img src="https://img.shields.io/badge/ProtonMail-8B89CC?style=for-the-badge&logo=protonmail&logoColor=white" alt="Email"></a>
199
+ <a href="https://buymeacoffee.com/glizzykingdreko"><img src="https://img.shields.io/badge/Buy%20Me%20a%20Coffee-yellow?style=for-the-badge&logo=buy-me-a-coffee&logoColor=white" alt="Buy Me a Coffee"></a>
200
+ </p>
201
+
@@ -0,0 +1,15 @@
1
+ twitter_generator/__init__.py,sha256=0eZYbparMaR1ElVh4yf80p-AnxN3iyDmNC53GINQShM,519
2
+ twitter_generator/exceptions.py,sha256=Jx8mQr2iKxVdUKBW2rhPLEmrmXwFCJE4gEN5klVhfsA,251
3
+ twitter_generator/version.py,sha256=YZlh8cbZNWa17zscguWJfxUF4okspowcxoRrOqQeoZ0,80
4
+ twitter_generator/client_transaction/__init__.py,sha256=xdxvJDBITB_xOXj19DZhOexMTsj61Y6fXyWJTsrPQHw,86
5
+ twitter_generator/client_transaction/main.py,sha256=JAbm5e6eeiO1gnz1-3yfskj-EntYpha5huqMlw-d5fk,5743
6
+ twitter_generator/helpers/__init__.py,sha256=R0FY7iB4SnELcpIujstjdi6fPRYyUiR8D7iObINF9Jw,92
7
+ twitter_generator/helpers/cubic.py,sha256=FOGkbZFcYhI78ztiGDkpBTPjKipGyYi2b1n89eqBkts,2337
8
+ twitter_generator/helpers/math_utils.py,sha256=VZRPTfYcyQRKg51n92rUKswQlSpfIJZk0qGJQx7bufY,3879
9
+ twitter_generator/xp_forwarded_for/__init__.py,sha256=VuJzwFGNTTcA_LruRRj_kT74ElLxjywK8wsmS-PBBT0,80
10
+ twitter_generator/xp_forwarded_for/main.py,sha256=Z9U6IdQ_fZHGjrXHsL-ZsKyB7doKGl8SVgqgzMW050A,7516
11
+ twitter_generator-1.0.0.dist-info/licenses/LICENSE,sha256=0t76uIGTc_IkKFGVHLvZb-E9D9KOncYS09l2J-PN-Bs,1072
12
+ twitter_generator-1.0.0.dist-info/METADATA,sha256=a832zuux30HePAc9m5h8Ix8bEgVVL94VEN3mNmLNr0U,7807
13
+ twitter_generator-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
14
+ twitter_generator-1.0.0.dist-info/top_level.txt,sha256=E5GC32c-NhTNBHlo6l9Y8VvUT5wWd8dD7zBL73kKbKI,18
15
+ twitter_generator-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GlizzyKingDreko
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ twitter_generator