-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
303 lines (256 loc) · 10.2 KB
/
main.py
File metadata and controls
303 lines (256 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import asyncio
import json
import logging
import os
from contextlib import asynccontextmanager
from time import perf_counter
from fastapi import FastAPI, Query
from fastapi.responses import JSONResponse
from camoufox import AsyncCamoufox
from playwright.async_api import Browser, BrowserContext
logger = logging.getLogger("sentinel-web")
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
HOST = os.getenv("HOST", "0.0.0.0")
PORT = int(os.getenv("PORT", "8000"))
POOL_SIZE = int(os.getenv("POOL_SIZE", "1"))
HEADLESS = os.getenv("HEADLESS", "true").lower() in ("true", "1", "yes")
MAX_CONCURRENCY = int(os.getenv("MAX_CONCURRENCY", "5"))
NAVIGATION_TIMEOUT = int(os.getenv("NAVIGATION_TIMEOUT", "30000"))
TOKEN_TIMEOUT = int(os.getenv("TOKEN_TIMEOUT", "30000"))
PAGE_WAIT = int(os.getenv("PAGE_WAIT", "2000"))
TARGET_URL = "https://auth.openai.com/create-account"
# Resource types to block — saves memory and bandwidth per page
_BLOCKED_RESOURCE_TYPES = frozenset(
["image", "media", "font", "texttrack", "eventsource", "websocket", "manifest"]
)
# URL patterns for analytics/tracking — block to save CPU + memory
_BLOCKED_URL_PATTERNS = (
"google-analytics.com",
"googletagmanager.com",
"facebook.net",
"doubleclick.net",
"analytics.",
"/beacon",
"sentry.io",
"hotjar.com",
)
# ---------------------------------------------------------------------------
# Route handlers
# ---------------------------------------------------------------------------
def _should_block(route) -> bool:
"""Check if a request should be aborted to save resources."""
if route.request.resource_type in _BLOCKED_RESOURCE_TYPES:
return True
url = route.request.url
for pat in _BLOCKED_URL_PATTERNS:
if pat in url:
return True
return False
async def _fix_headers(route):
"""Strip CSP / fix MIME so Sentinel SDK can execute. Also blocks
unnecessary resource types (images, fonts, etc.) to save memory."""
if _should_block(route):
await route.abort()
return
response = await route.fetch()
headers = dict(response.headers)
headers.pop("content-security-policy", None)
headers.pop("content-security-policy-report-only", None)
headers.pop("x-content-type-options", None)
url = route.request.url
if "sentinel" in url and "sdk.js" in url:
if "text/html" in headers.get("content-type", ""):
headers["content-type"] = "application/javascript; charset=UTF-8"
await route.fulfill(
status=response.status, headers=headers, body=await response.body()
)
# ---------------------------------------------------------------------------
# JS: injected via script-tag to run in the page compartment (Firefox Xray).
# ---------------------------------------------------------------------------
_TOKEN_JS = """
(function(timeout) {
var el = document.createElement('div');
el.id = '__sr';
el.style.display = 'none';
document.body.appendChild(el);
function run() {
Promise.race([
SentinelSDK.token(),
new Promise(function(_, r) { setTimeout(function() { r(new Error('timeout')); }, timeout); })
]).then(function(t) {
el.setAttribute('data-v', typeof t === 'string' ? t : JSON.stringify(t));
el.className = 'ok';
}).catch(function(e) {
el.setAttribute('data-v', e.message || String(e));
el.className = 'e';
});
}
if (typeof SentinelSDK !== 'undefined') { run(); return; }
/* SDK not yet loaded — poll briefly (50ms intervals, up to 10s) */
var waited = 0;
var iv = setInterval(function() {
waited += 50;
if (typeof SentinelSDK !== 'undefined') { clearInterval(iv); run(); }
else if (waited >= 10000) {
clearInterval(iv);
el.className = 'e';
el.setAttribute('data-v', 'SentinelSDK undefined after wait');
}
}, 50);
})(%%TIMEOUT%%);
"""
# ---------------------------------------------------------------------------
# Context Pool — pre-warmed pages + resource blocking for low memory
# ---------------------------------------------------------------------------
class ContextPool:
"""Pre-warms pages with resource blocking for both fast response and low memory.
Pages are navigated to the target URL ahead of time so requests only inject
a script and wait for the result. Resource blocking (images, fonts, media,
analytics) keeps per-page memory low — combining the latency benefit of
pre-warming with the memory benefit of resource blocking.
"""
def __init__(self, size: int, headless: bool, max_concurrency: int):
self._size = size
self._headless = headless
self._cms: list[AsyncCamoufox] = []
self._browsers: list[Browser] = []
self._idx = 0
self._ready: asyncio.Queue[tuple[BrowserContext, object]] = asyncio.Queue()
self._bg: list[asyncio.Task] = []
self._sem = asyncio.Semaphore(max_concurrency)
self._running = False
# -- lifecycle -----------------------------------------------------------
async def startup(self):
for _ in range(self._size):
cm = AsyncCamoufox(headless=self._headless, os=["windows", "macos", "linux"])
browser = await cm.__aenter__()
self._cms.append(cm)
self._browsers.append(browser)
self._running = True
for _ in range(self._size):
await self._warm_one()
logger.info(
"Pool ready — %d browser(s), %d warm page(s)",
self._size, self._ready.qsize(),
)
async def shutdown(self):
self._running = False
for t in self._bg:
t.cancel()
while not self._ready.empty():
ctx, _ = self._ready.get_nowait()
await ctx.close()
for cm in self._cms:
try:
await cm.__aexit__(None, None, None)
except Exception:
pass
self._browsers.clear()
self._cms.clear()
# -- warm-up -------------------------------------------------------------
def _pick(self) -> Browser:
b = self._browsers[self._idx % self._size]
self._idx += 1
return b
async def _warm_one(self):
for attempt in range(3):
try:
browser = self._pick()
ctx = await browser.new_context(bypass_csp=True)
await ctx.route("https://auth.openai.com/**", _fix_headers)
await ctx.route("**/sentinel/**", _fix_headers)
page = await ctx.new_page()
await page.goto(
TARGET_URL,
timeout=NAVIGATION_TIMEOUT,
wait_until="domcontentloaded",
)
await page.wait_for_timeout(PAGE_WAIT)
await self._ready.put((ctx, page))
return
except Exception:
logger.warning("warm-up attempt %d failed", attempt + 1)
try:
await ctx.close()
except Exception:
pass
if attempt < 2:
await asyncio.sleep(2)
logger.error("warm-up failed after 3 attempts")
def _refill(self):
if self._running:
t = asyncio.create_task(self._warm_one())
self._bg.append(t)
t.add_done_callback(self._bg.remove)
# -- public --------------------------------------------------------------
async def acquire(self) -> tuple[BrowserContext, object]:
await self._sem.acquire()
self._refill()
try:
return await asyncio.wait_for(self._ready.get(), timeout=120)
except asyncio.TimeoutError:
self._sem.release()
raise TimeoutError("no warm page available")
def release(self):
self._sem.release()
pool = ContextPool(POOL_SIZE, HEADLESS, MAX_CONCURRENCY)
# ---------------------------------------------------------------------------
# Token extraction — event-driven, no polling
# ---------------------------------------------------------------------------
async def extract_token(*, timeout: int = TOKEN_TIMEOUT) -> dict:
ctx, page = await pool.acquire()
t0 = perf_counter()
try:
js = _TOKEN_JS.replace("%%TIMEOUT%%", str(timeout))
await page.evaluate(
"(c)=>{var s=document.createElement('script');s.textContent=c;document.head.appendChild(s)}",
js,
)
el = await page.wait_for_selector(
"#__sr.ok, #__sr.e", state="attached", timeout=timeout + 5000
)
cls = await el.get_attribute("class")
raw = await el.get_attribute("data-v")
if cls == "e":
raise RuntimeError(f"SentinelSDK error: {raw}")
try:
return json.loads(raw)
except (json.JSONDecodeError, TypeError):
return {"token": raw}
finally:
elapsed = (perf_counter() - t0) * 1000
logger.info("token extracted in %.0f ms", elapsed)
pool.release()
asyncio.create_task(_close(ctx))
async def _close(ctx: BrowserContext):
try:
for page in ctx.pages:
await page.unroute_all(behavior="ignoreErrors")
await ctx.close()
except Exception:
pass
# ---------------------------------------------------------------------------
# FastAPI
# ---------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(_app: FastAPI):
await pool.startup()
yield
await pool.shutdown()
app = FastAPI(title="Sentinel Web", lifespan=lifespan)
@app.get("/token")
async def get_token(
timeout: int = Query(default=TOKEN_TIMEOUT, ge=1000, le=120000),
):
try:
return await extract_token(timeout=timeout)
except TimeoutError as e:
return JSONResponse(status_code=504, content={"error": str(e)})
except Exception as e:
logger.exception("token error")
return JSONResponse(status_code=502, content={"error": f"{e}"})
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host=HOST, port=PORT)