gpt2agent 0.0.5__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.
gpt2agent/__init__.py ADDED
File without changes
@@ -0,0 +1,67 @@
1
+ """Shared helper for redacting session-scoped headers from log/error output.
2
+
3
+ Both ``sse`` and ``sentinel`` surface raw response text in error messages.
4
+ Bearer tokens, Sentinel session tokens, and the ``OAI-*`` device/session
5
+ identifiers leak account-tracking metadata. ``redact_error`` is the single
6
+ canonical place to scrub those before user-visible output.
7
+
8
+ Distinct from :mod:`gpt2agent.tools._redact`, which strips PII (emails,
9
+ phone numbers) from data returned by MCP tools — separate scopes, kept
10
+ separate so a future change to one doesn't accidentally weaken the other.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+
17
+ # 1. JSON-encoded session-scoped headers — redact the value, keep the key.
18
+ _SENSITIVE_KEY_RE = re.compile(
19
+ r'"(Openai-Sentinel-[A-Za-z-]+-Token|Authorization|OAI-[A-Za-z-]+)"\s*:\s*"[^"]*"',
20
+ re.IGNORECASE,
21
+ )
22
+
23
+ # 2. JSON token fields by name — `"access_token":"…"`, `"accessToken":"…"`,
24
+ # `"session_token":"…"`, `"id_token":"…"`, `"refresh_token":"…"`. Covers the
25
+ # nested `"tokens":{"access_token":"…"}` shape too (the pair is matched directly).
26
+ _TOKEN_FIELD_RE = re.compile(
27
+ r'"((?:access|session|id|refresh|bearer)[_-]?token|accessToken)"\s*:\s*"[^"]*"',
28
+ re.IGNORECASE,
29
+ )
30
+
31
+ # 3. Bare `Bearer <token>` not wrapped in a JSON key (e.g. echoed plain in a body).
32
+ _BEARER_RE = re.compile(r"Bearer\s+[A-Za-z0-9._\-]+", re.IGNORECASE)
33
+
34
+ # 4. Auth/session cookies, e.g. `__Secure-next-auth.session-token=…`.
35
+ _COOKIE_RE = re.compile(
36
+ r"((?:__Secure-|__Host-)?[A-Za-z0-9_.\-]*(?:session-token|auth-token|csrf)[A-Za-z0-9_.\-]*)=[^;\s\"]+",
37
+ re.IGNORECASE,
38
+ )
39
+
40
+ # 5. Token-bearing query params, e.g. `?access_token=…` / `&token=…`.
41
+ _QUERY_TOKEN_RE = re.compile(
42
+ r"([?&](?:access_token|id_token|refresh_token|token|sig|signature)=)[^&\s\"]+",
43
+ re.IGNORECASE,
44
+ )
45
+
46
+
47
+ def redact_error(text: str, max_len: int = 200) -> str:
48
+ """Truncate + redact session-scoped secrets before surfacing to the user.
49
+
50
+ Strips header values (``Authorization``/``OAI-*``/``Openai-Sentinel-*-Token``),
51
+ named JSON token fields (``access_token`` and friends), bare ``Bearer <token>``
52
+ strings, auth/session cookies, and token-bearing query params; then truncates
53
+ to ``max_len`` so a 1 MB error body doesn't blow up the user's terminal.
54
+
55
+ Redaction runs BEFORE truncation so a secret near the start can't survive by
56
+ being split across the cut.
57
+ """
58
+ if not isinstance(text, str):
59
+ text = str(text)
60
+ cleaned = _SENSITIVE_KEY_RE.sub(r'"\1":"<REDACTED>"', text)
61
+ cleaned = _TOKEN_FIELD_RE.sub(r'"\1":"<REDACTED>"', cleaned)
62
+ cleaned = _BEARER_RE.sub("Bearer <REDACTED>", cleaned)
63
+ cleaned = _COOKIE_RE.sub(r"\1=<REDACTED>", cleaned)
64
+ cleaned = _QUERY_TOKEN_RE.sub(r"\1<REDACTED>", cleaned)
65
+ if len(cleaned) > max_len:
66
+ cleaned = cleaned[:max_len] + "...[truncated]"
67
+ return cleaned
@@ -0,0 +1,2 @@
1
+ """Pure-Python ports of OpenAI Sentinel solvers from lanqian528/chat2api (MIT).
2
+ See NOTICES.md for attribution."""
@@ -0,0 +1,467 @@
1
+ # Ported from lanqian528/chat2api (MIT License)
2
+ # Copyright (c) 2024 aurora-develop
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ # The above copyright notice and this permission notice shall be included in all
10
+ # copies or substantial portions of the Software.
11
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17
+ # SOFTWARE.
18
+ # Source: https://github.com/lanqian528/chat2api See NOTICES.md for full attribution.
19
+
20
+ from __future__ import annotations
21
+
22
+ import base64
23
+ import hashlib
24
+ import json
25
+ import random
26
+ import time
27
+ import uuid
28
+ from datetime import datetime, timedelta, timezone
29
+
30
+ _cores = [8, 16, 24, 32]
31
+ _time_layout = "%a %b %d %Y %H:%M:%S"
32
+
33
+ navigator_key = [
34
+ "registerProtocolHandler−function registerProtocolHandler() { [native code] }",
35
+ "storage−[object StorageManager]",
36
+ "locks−[object LockManager]",
37
+ "appCodeName−Mozilla",
38
+ "permissions−[object Permissions]",
39
+ "share−function share() { [native code] }",
40
+ "webdriver−false",
41
+ "managed−[object NavigatorManagedData]",
42
+ "canShare−function canShare() { [native code] }",
43
+ "vendor−Google Inc.",
44
+ "vendor−Google Inc.",
45
+ "mediaDevices−[object MediaDevices]",
46
+ "vibrate−function vibrate() { [native code] }",
47
+ "storageBuckets−[object StorageBucketManager]",
48
+ "mediaCapabilities−[object MediaCapabilities]",
49
+ "getGamepads−function getGamepads() { [native code] }",
50
+ "bluetooth−[object Bluetooth]",
51
+ "share−function share() { [native code] }",
52
+ "cookieEnabled−true",
53
+ "virtualKeyboard−[object VirtualKeyboard]",
54
+ "product−Gecko",
55
+ "mediaDevices−[object MediaDevices]",
56
+ "canShare−function canShare() { [native code] }",
57
+ "getGamepads−function getGamepads() { [native code] }",
58
+ "product−Gecko",
59
+ "xr−[object XRSystem]",
60
+ "clipboard−[object Clipboard]",
61
+ "storageBuckets−[object StorageBucketManager]",
62
+ "unregisterProtocolHandler−function unregisterProtocolHandler() { [native code] }",
63
+ "productSub−20030107",
64
+ "login−[object NavigatorLogin]",
65
+ "vendorSub−",
66
+ "login−[object NavigatorLogin]",
67
+ "getInstalledRelatedApps−function getInstalledRelatedApps() { [native code] }",
68
+ "mediaDevices−[object MediaDevices]",
69
+ "locks−[object LockManager]",
70
+ "webkitGetUserMedia−function webkitGetUserMedia() { [native code] }",
71
+ "vendor−Google Inc.",
72
+ "xr−[object XRSystem]",
73
+ "mediaDevices−[object MediaDevices]",
74
+ "virtualKeyboard−[object VirtualKeyboard]",
75
+ "virtualKeyboard−[object VirtualKeyboard]",
76
+ "appName−Netscape",
77
+ "storageBuckets−[object StorageBucketManager]",
78
+ "presentation−[object Presentation]",
79
+ "onLine−true",
80
+ "mimeTypes−[object MimeTypeArray]",
81
+ "credentials−[object CredentialsContainer]",
82
+ "presentation−[object Presentation]",
83
+ "getGamepads−function getGamepads() { [native code] }",
84
+ "vendorSub−",
85
+ "virtualKeyboard−[object VirtualKeyboard]",
86
+ "serviceWorker−[object ServiceWorkerContainer]",
87
+ "xr−[object XRSystem]",
88
+ "product−Gecko",
89
+ "keyboard−[object Keyboard]",
90
+ "gpu−[object GPU]",
91
+ "getInstalledRelatedApps−function getInstalledRelatedApps() { [native code] }",
92
+ "webkitPersistentStorage−[object DeprecatedStorageQuota]",
93
+ "doNotTrack",
94
+ "clearAppBadge−function clearAppBadge() { [native code] }",
95
+ "presentation−[object Presentation]",
96
+ "serial−[object Serial]",
97
+ "locks−[object LockManager]",
98
+ "requestMIDIAccess−function requestMIDIAccess() { [native code] }",
99
+ "locks−[object LockManager]",
100
+ "requestMediaKeySystemAccess−function requestMediaKeySystemAccess() { [native code] }",
101
+ "vendor−Google Inc.",
102
+ "pdfViewerEnabled−true",
103
+ # Must match the OAI-Language header set by BackendClient — Cloudflare's
104
+ # bot manager cross-checks the navigator-fingerprint against the request
105
+ # header and 403s on mismatch. Was zh-CN inherited from upstream chat2api;
106
+ # we send en-US, so use en-US here too.
107
+ "language−en-US",
108
+ "setAppBadge−function setAppBadge() { [native code] }",
109
+ "geolocation−[object Geolocation]",
110
+ "userAgentData−[object NavigatorUAData]",
111
+ "mediaCapabilities−[object MediaCapabilities]",
112
+ "requestMIDIAccess−function requestMIDIAccess() { [native code] }",
113
+ "getUserMedia−function getUserMedia() { [native code] }",
114
+ "mediaDevices−[object MediaDevices]",
115
+ "webkitPersistentStorage−[object DeprecatedStorageQuota]",
116
+ "sendBeacon−function sendBeacon() { [native code] }",
117
+ "hardwareConcurrency−32",
118
+ "credentials−[object CredentialsContainer]",
119
+ "storage−[object StorageManager]",
120
+ "cookieEnabled−true",
121
+ "pdfViewerEnabled−true",
122
+ "windowControlsOverlay−[object WindowControlsOverlay]",
123
+ "scheduling−[object Scheduling]",
124
+ "pdfViewerEnabled−true",
125
+ "hardwareConcurrency−32",
126
+ "xr−[object XRSystem]",
127
+ "webdriver−false",
128
+ "getInstalledRelatedApps−function getInstalledRelatedApps() { [native code] }",
129
+ "getInstalledRelatedApps−function getInstalledRelatedApps() { [native code] }",
130
+ "bluetooth−[object Bluetooth]",
131
+ ]
132
+
133
+ document_key = ["_reactListeningo743lnnpvdg", "location"]
134
+
135
+ window_key = [
136
+ "0",
137
+ "window",
138
+ "self",
139
+ "document",
140
+ "name",
141
+ "location",
142
+ "customElements",
143
+ "history",
144
+ "navigation",
145
+ "locationbar",
146
+ "menubar",
147
+ "personalbar",
148
+ "scrollbars",
149
+ "statusbar",
150
+ "toolbar",
151
+ "status",
152
+ "closed",
153
+ "frames",
154
+ "length",
155
+ "top",
156
+ "opener",
157
+ "parent",
158
+ "frameElement",
159
+ "navigator",
160
+ "origin",
161
+ "external",
162
+ "screen",
163
+ "innerWidth",
164
+ "innerHeight",
165
+ "scrollX",
166
+ "pageXOffset",
167
+ "scrollY",
168
+ "pageYOffset",
169
+ "visualViewport",
170
+ "screenX",
171
+ "screenY",
172
+ "outerWidth",
173
+ "outerHeight",
174
+ "devicePixelRatio",
175
+ "clientInformation",
176
+ "screenLeft",
177
+ "screenTop",
178
+ "styleMedia",
179
+ "onsearch",
180
+ "isSecureContext",
181
+ "trustedTypes",
182
+ "performance",
183
+ "onappinstalled",
184
+ "onbeforeinstallprompt",
185
+ "crypto",
186
+ "indexedDB",
187
+ "sessionStorage",
188
+ "localStorage",
189
+ "onbeforexrselect",
190
+ "onabort",
191
+ "onbeforeinput",
192
+ "onbeforematch",
193
+ "onbeforetoggle",
194
+ "onblur",
195
+ "oncancel",
196
+ "oncanplay",
197
+ "oncanplaythrough",
198
+ "onchange",
199
+ "onclick",
200
+ "onclose",
201
+ "oncontentvisibilityautostatechange",
202
+ "oncontextlost",
203
+ "oncontextmenu",
204
+ "oncontextrestored",
205
+ "oncuechange",
206
+ "ondblclick",
207
+ "ondrag",
208
+ "ondragend",
209
+ "ondragenter",
210
+ "ondragleave",
211
+ "ondragover",
212
+ "ondragstart",
213
+ "ondrop",
214
+ "ondurationchange",
215
+ "onemptied",
216
+ "onended",
217
+ "onerror",
218
+ "onfocus",
219
+ "onformdata",
220
+ "oninput",
221
+ "oninvalid",
222
+ "onkeydown",
223
+ "onkeypress",
224
+ "onkeyup",
225
+ "onload",
226
+ "onloadeddata",
227
+ "onloadedmetadata",
228
+ "onloadstart",
229
+ "onmousedown",
230
+ "onmouseenter",
231
+ "onmouseleave",
232
+ "onmousemove",
233
+ "onmouseout",
234
+ "onmouseover",
235
+ "onmouseup",
236
+ "onmousewheel",
237
+ "onpause",
238
+ "onplay",
239
+ "onplaying",
240
+ "onprogress",
241
+ "onratechange",
242
+ "onreset",
243
+ "onresize",
244
+ "onscroll",
245
+ "onsecuritypolicyviolation",
246
+ "onseeked",
247
+ "onseeking",
248
+ "onselect",
249
+ "onslotchange",
250
+ "onstalled",
251
+ "onsubmit",
252
+ "onsuspend",
253
+ "ontimeupdate",
254
+ "ontoggle",
255
+ "onvolumechange",
256
+ "onwaiting",
257
+ "onwebkitanimationend",
258
+ "onwebkitanimationiteration",
259
+ "onwebkitanimationstart",
260
+ "onwebkittransitionend",
261
+ "onwheel",
262
+ "onauxclick",
263
+ "ongotpointercapture",
264
+ "onlostpointercapture",
265
+ "onpointerdown",
266
+ "onpointermove",
267
+ "onpointerrawupdate",
268
+ "onpointerup",
269
+ "onpointercancel",
270
+ "onpointerover",
271
+ "onpointerout",
272
+ "onpointerenter",
273
+ "onpointerleave",
274
+ "onselectstart",
275
+ "onselectionchange",
276
+ "onanimationend",
277
+ "onanimationiteration",
278
+ "onanimationstart",
279
+ "ontransitionrun",
280
+ "ontransitionstart",
281
+ "ontransitionend",
282
+ "ontransitioncancel",
283
+ "onafterprint",
284
+ "onbeforeprint",
285
+ "onbeforeunload",
286
+ "onhashchange",
287
+ "onlanguagechange",
288
+ "onmessage",
289
+ "onmessageerror",
290
+ "onoffline",
291
+ "ononline",
292
+ "onpagehide",
293
+ "onpageshow",
294
+ "onpopstate",
295
+ "onrejectionhandled",
296
+ "onstorage",
297
+ "onunhandledrejection",
298
+ "onunload",
299
+ "crossOriginIsolated",
300
+ "scheduler",
301
+ "alert",
302
+ "atob",
303
+ "blur",
304
+ "btoa",
305
+ "cancelAnimationFrame",
306
+ "cancelIdleCallback",
307
+ "captureEvents",
308
+ "clearInterval",
309
+ "clearTimeout",
310
+ "close",
311
+ "confirm",
312
+ "createImageBitmap",
313
+ "fetch",
314
+ "find",
315
+ "focus",
316
+ "getComputedStyle",
317
+ "getSelection",
318
+ "matchMedia",
319
+ "moveBy",
320
+ "moveTo",
321
+ "open",
322
+ "postMessage",
323
+ "print",
324
+ "prompt",
325
+ "queueMicrotask",
326
+ "releaseEvents",
327
+ "reportError",
328
+ "requestAnimationFrame",
329
+ "requestIdleCallback",
330
+ "resizeBy",
331
+ "resizeTo",
332
+ "scroll",
333
+ "scrollBy",
334
+ "scrollTo",
335
+ "setInterval",
336
+ "setTimeout",
337
+ "stop",
338
+ "structuredClone",
339
+ "webkitCancelAnimationFrame",
340
+ "webkitRequestAnimationFrame",
341
+ "chrome",
342
+ "caches",
343
+ "cookieStore",
344
+ "ondevicemotion",
345
+ "ondeviceorientation",
346
+ "ondeviceorientationabsolute",
347
+ "launchQueue",
348
+ "documentPictureInPicture",
349
+ "getScreenDetails",
350
+ "queryLocalFonts",
351
+ "showDirectoryPicker",
352
+ "showOpenFilePicker",
353
+ "showSaveFilePicker",
354
+ "originAgentCluster",
355
+ "onpageswap",
356
+ "onpagereveal",
357
+ "credentialless",
358
+ "speechSynthesis",
359
+ "onscrollend",
360
+ "webkitRequestFileSystem",
361
+ "webkitResolveLocalFileSystemURL",
362
+ "sendMsgToSolverCS",
363
+ "webpackChunk_N_E",
364
+ "__next_set_public_path__",
365
+ "next",
366
+ "__NEXT_DATA__",
367
+ "__SSG_MANIFEST_CB",
368
+ "__NEXT_P",
369
+ "_N_E",
370
+ "regeneratorRuntime",
371
+ "__REACT_INTL_CONTEXT__",
372
+ "DD_RUM",
373
+ "_",
374
+ "filterCSS",
375
+ "filterXSS",
376
+ "__SEGMENT_INSPECTOR__",
377
+ "__NEXT_PRELOADREADY",
378
+ "Intercom",
379
+ "__MIDDLEWARE_MATCHERS",
380
+ "__STATSIG_SDK__",
381
+ "__STATSIG_JS_SDK__",
382
+ "__STATSIG_RERENDER_OVERRIDE__",
383
+ "_oaiHandleSessionExpired",
384
+ "__BUILD_MANIFEST",
385
+ "__SSG_MANIFEST",
386
+ "__intercomAssignLocation",
387
+ "__intercomReloadLocation",
388
+ ]
389
+
390
+
391
+ def _parse_time() -> str:
392
+ now = datetime.now(timezone(timedelta(hours=-5)))
393
+ return now.strftime(_time_layout) + " GMT-0500 (Eastern Standard Time)"
394
+
395
+
396
+ def build_config(user_agent: str, dpl: str = "", script_src: str = "") -> list:
397
+ return [
398
+ random.choice([1920 + 1080, 2560 + 1440, 1920 + 1200, 2560 + 1600]),
399
+ _parse_time(),
400
+ 4294705152,
401
+ 0,
402
+ user_agent,
403
+ script_src,
404
+ dpl,
405
+ "en-US",
406
+ "en-US,es-US,en,es",
407
+ 0,
408
+ random.choice(navigator_key),
409
+ random.choice(document_key),
410
+ random.choice(window_key),
411
+ time.perf_counter() * 1000,
412
+ str(uuid.uuid4()),
413
+ "",
414
+ random.choice(_cores),
415
+ time.time() * 1000 - (time.perf_counter() * 1000),
416
+ ]
417
+
418
+
419
+ def _generate_answer(seed: str, diff: str, config: list) -> tuple[str, bool]:
420
+ diff_len = len(diff)
421
+ seed_encoded = seed.encode()
422
+ part1 = (
423
+ json.dumps(config[:3], separators=(",", ":"), ensure_ascii=False)[:-1] + ","
424
+ ).encode()
425
+ part2 = (
426
+ ","
427
+ + json.dumps(config[4:9], separators=(",", ":"), ensure_ascii=False)[1:-1]
428
+ + ","
429
+ ).encode()
430
+ part3 = (
431
+ "," + json.dumps(config[10:], separators=(",", ":"), ensure_ascii=False)[1:]
432
+ ).encode()
433
+ target = bytes.fromhex(diff)
434
+
435
+ for i in range(500000):
436
+ dyn_i = str(i).encode()
437
+ dyn_j = str(i >> 1).encode()
438
+ final_bytes = part1 + dyn_i + part2 + dyn_j + part3
439
+ base_encoded = base64.b64encode(final_bytes)
440
+ h = hashlib.sha3_512(seed_encoded + base_encoded).digest()
441
+ if h[:diff_len] <= target:
442
+ return base_encoded.decode(), True
443
+
444
+ return (
445
+ "wQ8Lk5FbGpA2NcR9dShT6gYjU7VxZ4D"
446
+ + base64.b64encode(f'"{seed}"'.encode()).decode(),
447
+ False,
448
+ )
449
+
450
+
451
+ def solve_pow(seed: str, difficulty: str, user_agent: str) -> str:
452
+ config = build_config(user_agent)
453
+ answer, _solved = _generate_answer(seed, difficulty, config)
454
+ if not _solved:
455
+ import logging
456
+
457
+ logging.getLogger(__name__).warning(
458
+ "POW solver did not find an answer within the iteration budget — "
459
+ "falling back to stub token; request may be challenged."
460
+ )
461
+ return "gAAAAAB" + answer
462
+
463
+
464
+ def get_requirements_token(user_agent: str) -> str:
465
+ config = build_config(user_agent)
466
+ require, _ = _generate_answer(format(random.random()), "0fffff", config)
467
+ return "gAAAAAC" + require