File size: 1,870 Bytes
d87880a
4c34c0c
a32f715
d87880a
 
 
4c34c0c
d87880a
 
 
 
4c34c0c
 
1c9d1a9
4c34c0c
 
d87880a
1c9d1a9
4c34c0c
 
 
 
 
 
 
 
 
 
 
 
d87880a
871b55b
 
d87880a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9fe695
871b55b
a9fe695
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
from fastapi import FastAPI, Request, Response, status, WebSocket, WebSocketDisconnect
import httpx
import uvicorn
import asyncio
import websockets

app = FastAPI()

TARGET_BASE = "http://127.0.0.1:9222"  # 目标服务器(Chrome DevTools)
TARGET_WS_BASE = "ws://127.0.0.1:9222"  # WebSocket 目标

@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"])
async def proxy(request: Request, path: str):

    url = f"{TARGET_BASE}/{path}"
    headers = dict(request.headers)
    # 强制 Host 头为 127.0.0.1,避免 Chrome 拒绝
    headers["host"] = "127.0.0.1"
    body = await request.body()
    async with httpx.AsyncClient(follow_redirects=True) as client:
        resp = await client.request(
            request.method,
            url,
            headers=headers,
            content=body,
            params=request.query_params
        )
    return Response(
        content=resp.content,
        status_code=resp.status_code,
        headers=dict(resp.headers)
    )

@app.websocket("/{path:path}")
async def websocket_proxy(websocket: WebSocket, path: str):
    await websocket.accept()
    target_url = f"{TARGET_WS_BASE}/{path}"
    try:
        async with websockets.connect(target_url) as target_ws:
            async def client_to_server():
                while True:
                    data = await websocket.receive_text()
                    await target_ws.send(data)

            async def server_to_client():
                while True:
                    data = await target_ws.recv()
                    await websocket.send_text(data)

            await asyncio.gather(client_to_server(), server_to_client())
    except WebSocketDisconnect:
        pass
    except Exception:
        await websocket.close()

if __name__ == "__main__":
    uvicorn.run("fun:app", host="0.0.0.0", port=8000)