169 lines
5.9 KiB
Python
169 lines
5.9 KiB
Python
"""Independent BrowserSkill pairing, status, and extension transport APIs."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, HTTPException, Request, WebSocket
|
|
from pydantic import BaseModel, Field
|
|
|
|
from app.gateway.deps import get_current_user
|
|
from deerflow.integrations.browser_skill.runtime import get_browser_skill_manager
|
|
from deerflow.persistence.engine import get_session_factory
|
|
|
|
router = APIRouter(tags=["browser-skill"])
|
|
|
|
|
|
class PairBrowserRequest(BaseModel):
|
|
action: str = "pair"
|
|
origin: str = Field(description="Public frontend origin, including any deployment base path")
|
|
|
|
|
|
class AuthorizeBrowserRequest(BaseModel):
|
|
action: str
|
|
next_token: str
|
|
label: str = "BrowserSkill Extension"
|
|
|
|
|
|
class BrowserTaskActionRequest(BaseModel):
|
|
action: str
|
|
|
|
|
|
def _bearer(value: str | None) -> str:
|
|
if not value:
|
|
raise HTTPException(status_code=401, detail="missing device credential")
|
|
scheme, _, credential = value.partition(" ")
|
|
if scheme.lower() != "bearer" or not credential:
|
|
raise HTTPException(status_code=401, detail="invalid device credential")
|
|
return credential.strip()
|
|
|
|
|
|
async def _user_id(request: Request) -> str:
|
|
user_id = await get_current_user(request)
|
|
if not user_id:
|
|
raise HTTPException(status_code=401, detail="authentication required")
|
|
return user_id
|
|
|
|
|
|
@router.get("/api/v1/me/browser")
|
|
async def browser_status(request: Request) -> dict[str, Any]:
|
|
manager = get_browser_skill_manager()
|
|
async with get_session_factory()() as session:
|
|
return {"success": True, "data": await manager.status(session, await _user_id(request))}
|
|
|
|
|
|
@router.post("/api/v1/me/browser")
|
|
async def pair_browser(request: Request, body: PairBrowserRequest) -> dict[str, Any]:
|
|
if body.action != "pair":
|
|
raise HTTPException(status_code=400, detail="unsupported browser action")
|
|
manager = get_browser_skill_manager()
|
|
try:
|
|
async with get_session_factory()() as session:
|
|
link = await manager.create_pairing(session, await _user_id(request), body.origin)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
except RuntimeError as exc:
|
|
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
|
return {"success": True, "data": {"pairing_link": link}}
|
|
|
|
|
|
@router.delete("/api/v1/me/browser")
|
|
async def revoke_browser(request: Request) -> dict[str, bool]:
|
|
manager = get_browser_skill_manager()
|
|
async with get_session_factory()() as session:
|
|
await manager.revoke(session, await _user_id(request))
|
|
return {"success": True}
|
|
|
|
|
|
@router.get("/api/threads/{thread_id}/local-browser")
|
|
async def browser_task_status(request: Request, thread_id: str) -> dict[str, Any]:
|
|
manager = get_browser_skill_manager()
|
|
return {
|
|
"success": True,
|
|
"data": manager.task_status(
|
|
user_id=await _user_id(request), thread_id=thread_id
|
|
),
|
|
}
|
|
|
|
|
|
@router.post("/api/threads/{thread_id}/local-browser")
|
|
async def browser_task_action(
|
|
request: Request, thread_id: str, body: BrowserTaskActionRequest
|
|
) -> dict[str, Any]:
|
|
manager = get_browser_skill_manager()
|
|
try:
|
|
data = await manager.task_action(
|
|
user_id=await _user_id(request),
|
|
thread_id=thread_id,
|
|
action=body.action,
|
|
)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
except RuntimeError as exc:
|
|
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
|
return {"success": True, "data": data}
|
|
|
|
|
|
@router.post("/api/v1/local-browser/extension/authorize")
|
|
async def authorize_browser(request: Request, body: AuthorizeBrowserRequest) -> dict[str, Any]:
|
|
manager = get_browser_skill_manager()
|
|
credential = _bearer(request.headers.get("authorization"))
|
|
try:
|
|
async with get_session_factory()() as session:
|
|
return await manager.authorize(
|
|
session,
|
|
credential=credential,
|
|
action=body.action,
|
|
next_token=body.next_token,
|
|
label=body.label,
|
|
)
|
|
except PermissionError as exc:
|
|
raise HTTPException(status_code=401, detail=str(exc)) from exc
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
except RuntimeError as exc:
|
|
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
|
|
|
|
|
def _browser_device_credential(subprotocol: str) -> str:
|
|
"""Extract the stored device credential from a WebSocket subprotocol."""
|
|
if subprotocol.startswith("bsk-auth."):
|
|
return subprotocol.removeprefix("bsk-auth.")
|
|
|
|
scheme, separator, credential = subprotocol.partition(" ")
|
|
if separator and scheme.lower() == "bearer":
|
|
return credential.strip()
|
|
|
|
return subprotocol
|
|
|
|
|
|
@router.websocket("/api/v1/local-browser/extension")
|
|
async def browser_extension_socket(websocket: WebSocket) -> None:
|
|
manager = get_browser_skill_manager()
|
|
requested = [
|
|
item.strip()
|
|
for item in websocket.headers.get("sec-websocket-protocol", "").split(",")
|
|
if item.strip()
|
|
]
|
|
authenticated = None
|
|
accepted_protocol = None
|
|
async with get_session_factory()() as session:
|
|
for candidate in reversed(requested):
|
|
authenticated = await manager.authenticate_device(
|
|
session,
|
|
_browser_device_credential(candidate),
|
|
)
|
|
if authenticated is not None:
|
|
accepted_protocol = candidate
|
|
break
|
|
if authenticated is None or accepted_protocol is None:
|
|
await websocket.close(code=1008, reason="invalid device authorization")
|
|
return
|
|
await manager.proxy_extension(
|
|
websocket,
|
|
user_id=authenticated.user_id,
|
|
device_id=authenticated.device_id,
|
|
subprotocol=accepted_protocol,
|
|
origin=websocket.headers.get("origin", "chrome-extension://browser-skill"),
|
|
)
|