Files
2026-06-25 14:58:52 +08:00

320 lines
8.7 KiB
Python

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from .fingerprint import generate_fingerprint
from .runtime import registry
from .schemas import FingerprintGenerateRequest, LaunchRequest, RunningResponse, RuntimeConfigUpdate
app = FastAPI(title="local-controller", version="0.2.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/health")
def health():
return {"ok": True}
@app.get("/diagnostics/fingerprint", response_class=HTMLResponse)
def fingerprint_diagnostics_page():
return HTMLResponse(
"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Fingerprint Diagnostics</title>
<style>
:root {
color-scheme: light;
--bg: #f3efe7;
--panel: #fffdf8;
--ink: #1f2937;
--muted: #6b7280;
--line: #d6d3d1;
--accent: #b45309;
--ok: #166534;
}
* { box-sizing: border-box; }
body {
margin: 0;
background:
radial-gradient(circle at top right, rgba(180, 83, 9, 0.08), transparent 28%),
linear-gradient(180deg, #f8f5ee 0%, var(--bg) 100%);
color: var(--ink);
font: 14px/1.5 "Segoe UI", "PingFang SC", sans-serif;
}
.wrap {
max-width: 1080px;
margin: 0 auto;
padding: 32px 20px 56px;
}
.hero {
margin-bottom: 20px;
padding: 24px;
border: 1px solid rgba(180, 83, 9, 0.18);
border-radius: 20px;
background: linear-gradient(135deg, rgba(255,255,255,0.95), rgba(250,245,235,0.92));
box-shadow: 0 18px 40px rgba(31, 41, 55, 0.06);
}
h1 {
margin: 0 0 8px;
font-size: 28px;
line-height: 1.15;
}
.sub {
color: var(--muted);
max-width: 760px;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 16px;
}
.card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 18px;
padding: 18px;
box-shadow: 0 10px 24px rgba(31, 41, 55, 0.04);
}
.card h2 {
margin: 0 0 12px;
font-size: 16px;
}
.kv {
display: grid;
grid-template-columns: 140px 1fr;
gap: 8px 12px;
}
.k {
color: var(--muted);
}
.v {
word-break: break-word;
font-family: Consolas, "Courier New", monospace;
}
pre {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-family: Consolas, "Courier New", monospace;
font-size: 12px;
color: #111827;
}
.hint {
margin-top: 12px;
color: var(--ok);
font-size: 13px;
}
.loading {
color: var(--accent);
font-weight: 600;
}
</style>
</head>
<body>
<div class="wrap">
<section class="hero">
<h1>Fingerprint Diagnostics</h1>
<div class="sub">
This page shows what the site can read on the first document load from JavaScript and request headers.
Use it to verify whether the browser environment is already masked before the target page opens.
</div>
</section>
<section class="grid">
<article class="card">
<h2>Navigator</h2>
<div id="navigator" class="kv"><div class="loading">Loading...</div></div>
</article>
<article class="card">
<h2>UA Client Hints</h2>
<div id="uaData" class="kv"><div class="loading">Loading...</div></div>
</article>
<article class="card">
<h2>Screen</h2>
<div id="screen" class="kv"><div class="loading">Loading...</div></div>
</article>
<article class="card">
<h2>Request Headers</h2>
<pre id="headers" class="loading">Loading...</pre>
</article>
</section>
</div>
<script>
function renderKv(id, entries) {
const target = document.getElementById(id)
target.innerHTML = entries.map(([k, v]) => (
`<div class="k">${k}</div><div class="v">${String(v)}</div>`
)).join('')
}
async function readUaData() {
const ua = navigator.userAgentData
if (!ua) {
return { available: false }
}
const high = await ua.getHighEntropyValues([
'architecture',
'bitness',
'fullVersionList',
'model',
'platformVersion',
'uaFullVersion',
'wow64'
])
return {
available: true,
brands: JSON.stringify(ua.brands),
mobile: ua.mobile,
platform: ua.platform,
architecture: high.architecture,
bitness: high.bitness,
fullVersionList: JSON.stringify(high.fullVersionList),
model: high.model,
platformVersion: high.platformVersion,
uaFullVersion: high.uaFullVersion,
wow64: high.wow64
}
}
async function loadHeaders() {
const res = await fetch('/diagnostics/fingerprint/echo', {
credentials: 'same-origin',
cache: 'no-store'
})
return await res.json()
}
async function main() {
renderKv('navigator', [
['userAgent', navigator.userAgent],
['language', navigator.language],
['languages', JSON.stringify(navigator.languages)],
['platform', navigator.platform],
['vendor', navigator.vendor],
['hardwareConcurrency', navigator.hardwareConcurrency],
['deviceMemory', navigator.deviceMemory],
['timezone', Intl.DateTimeFormat().resolvedOptions().timeZone]
])
const uaData = await readUaData()
renderKv('uaData', Object.entries(uaData))
renderKv('screen', [
['width', screen.width],
['height', screen.height],
['availWidth', screen.availWidth],
['availHeight', screen.availHeight],
['colorDepth', screen.colorDepth],
['pixelDepth', screen.pixelDepth]
])
const headers = await loadHeaders()
document.getElementById('headers').textContent = JSON.stringify(headers, null, 2)
}
main().catch((error) => {
document.getElementById('headers').textContent = String(error)
})
</script>
</body>
</html>
""".strip()
)
@app.get("/diagnostics/fingerprint/echo")
def fingerprint_diagnostics_echo(request: Request):
interesting_headers = [
"user-agent",
"accept-language",
"sec-ch-ua",
"sec-ch-ua-mobile",
"sec-ch-ua-platform",
"sec-ch-ua-full-version",
"sec-ch-ua-full-version-list",
"upgrade-insecure-requests",
]
data = {}
for key in interesting_headers:
value = request.headers.get(key)
if value is not None:
data[key] = value
return data
@app.get("/runtime/status")
def runtime_status():
return registry.runtime_status()
@app.get("/runtime/config")
def runtime_config():
return {"ok": True, "data": registry.runtime_config()}
@app.put("/runtime/config")
def save_runtime_config(req: RuntimeConfigUpdate):
return {"ok": True, "data": registry.save_runtime_config(req)}
@app.post("/profiles/{profile_id}/launch")
def launch_profile(profile_id: str, req: LaunchRequest):
if req.profile_id != profile_id:
raise HTTPException(status_code=400, detail="profile_id mismatch")
try:
instance = registry.launch(req)
return {"ok": True, "data": instance.model_dump()}
except FileNotFoundError as exc:
raise HTTPException(status_code=400, detail=f"runtime not found: {exc}") from exc
except RuntimeError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
@app.post("/profiles/{profile_id}/close")
def close_profile(profile_id: str):
closed = registry.close(profile_id)
return {"ok": closed}
@app.get("/profiles/running", response_model=RunningResponse)
def running_profiles():
return RunningResponse(items=registry.running())
@app.get("/profiles/{profile_id}/status")
def profile_status(profile_id: str):
instance = registry.status(profile_id)
if not instance:
raise HTTPException(status_code=404, detail="profile not running")
return {"ok": True, "data": instance.model_dump()}
@app.post("/fingerprints/generate")
def generate_fingerprint_config(req: FingerprintGenerateRequest):
return {
"ok": True,
"data": generate_fingerprint(
req.browser_family,
browser_version=req.browser_version,
full_version=req.full_version,
locale=req.locale,
timezone=req.timezone,
geo_country=req.geo_country,
geo_mode=req.geo_mode,
screen_width=req.screen_width,
screen_height=req.screen_height,
runtime_path=req.runtime_path,
),
}