Files
ecs-relay-service/container-code/enrollment-signer/relay/web_session.py
T

184 lines
8.5 KiB
Python

"""Pilot H5 pairing and conversation. Credentials never appear in URLs."""
import hashlib
import json
import secrets
import time
from urllib.parse import urlsplit
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from .common import no_cache, peer, rate_limit
from .crypto import sign, verified, verify_device
from .platform import PlatformError
COOKIE = "hn_web_session"
def digest(value):
return hashlib.sha256(value.encode()).hexdigest()
def origin_tuple(value):
try:
parts = urlsplit(value)
if parts.scheme not in {"https", "http"} or not parts.hostname or parts.username or parts.password:
return None
return parts.scheme, parts.hostname.lower(), parts.port or (443 if parts.scheme == "https" else 80)
except ValueError:
return None
class PairProof(BaseModel):
host_id: str = Field(pattern=r"^[a-f0-9]{32}$")
proof: dict
class Claim(BaseModel):
code: str = Field(min_length=12, max_length=128)
class Chat(BaseModel):
text: str = Field(min_length=1, max_length=8000)
request_id: str = Field(pattern=r"^[a-f0-9]{32}$")
class WebSessions:
def __init__(self, settings, redis, store, broker, platform):
self.s, self.r, self.store, self.broker, self.platform = settings, redis, store, broker, platform
self.router = APIRouter()
for path, method, handler in [
("/device/web-pair", "POST", self.device_pair),
("/web/claim", "POST", self.claim),
("/web/session", "GET", self.session),
("/web/platform-session", "POST", self.platform_login),
("/web/chat", "POST", self.chat),
("/web/logout", "POST", self.logout),
]:
self.router.add_api_route(path, handler, methods=[method])
def check_origin(self, request):
actual = origin_tuple(request.headers.get("Origin", ""))
if not actual or actual != origin_tuple(self.s.public_url):
raise HTTPException(403, "same-origin browser request required")
async def valid_device(self, record):
device = self.store.device(record["host_id"])
if (not device or device["revoked"] or device["owner"] != record["owner"]
or device["fingerprint"] != record["fingerprint"]):
raise HTTPException(401, "device binding changed; pair again")
generation = await self.r.get("hn:web-generation:" + record["host_id"]) or "0"
if record.get("generation") != generation:
raise HTTPException(401, "device binding changed; pair again")
return device
async def device_pair(self, body: PairProof, request: Request):
await rate_limit(self.r, "web-pair-ip:" + peer(request), 20)
device = self.store.device(body.host_id)
if not device or device["revoked"] or not device["owner"]:
raise HTTPException(403, "active bound device required")
try:
key = verify_device(device["cert"], self.s.ca_cert.read_bytes(), body.host_id)
proof = verified(body.proof, key)
if (proof["host_id"] != body.host_id or proof["owner"] != device["owner"]
or proof["purpose"] != "h5-pair-v1" or abs(time.time() - proof["ts"]) > 90
or not isinstance(proof["nonce"], str) or len(proof["nonce"]) != 32):
raise ValueError("invalid proof")
except Exception:
raise HTTPException(403, "invalid device proof") from None
replay = "hn:web-pair-proof:" + digest(body.host_id + proof["nonce"])
if not await self.r.set(replay, "used", nx=True, ex=180):
raise HTTPException(409, "pairing request already used")
await rate_limit(self.r, "web-pair-device:" + body.host_id, 5)
code = secrets.token_urlsafe(18)
record = {"host_id": body.host_id, "owner": device["owner"], "fingerprint": device["fingerprint"],
"generation": await self.r.get("hn:web-generation:" + body.host_id) or "0"}
await self.r.set("hn:web-code:" + digest(code), json.dumps(record), ex=120)
self.store.audit(device["owner"], "web_pair_issued", body.host_id, "success")
return no_cache(JSONResponse(sign({"host_id": body.host_id, "code": code, "expires_in": 120,
"url": self.s.public_url.rstrip("/") + "/h5"}, self.broker.signer)))
async def new_session(self, record):
token = secrets.token_urlsafe(32)
record = {k: record[k] for k in ("host_id", "owner", "fingerprint", "generation")}
await self.r.set("hn:web-session:" + digest(token), json.dumps(record), ex=1800)
response = no_cache(JSONResponse({"status": "paired", "host_id": record["host_id"], "expires_in": 1800}))
response.set_cookie(COOKIE, token, max_age=1800, secure=True, httponly=True, samesite="strict", path="/")
return response
async def claim(self, body: Claim, request: Request):
self.check_origin(request)
await rate_limit(self.r, "web-claim:" + peer(request), 20)
key = "hn:web-code:" + digest(body.code.strip())
encoded = await self.r.get(key)
if not encoded:
raise HTTPException(404, "code expired or consumed")
await self.valid_device(json.loads(encoded))
encoded = await self.r.getdel(key)
if not encoded:
raise HTTPException(404, "code already consumed")
record = json.loads(encoded)
await self.valid_device(record)
self.store.audit(record["owner"], "web_pair_claimed", record["host_id"], "success")
return await self.new_session(record)
async def authenticated(self, request):
token = request.cookies.get(COOKIE, "")
if not token or len(token) > 128:
raise HTTPException(401, "pair this browser first")
encoded = await self.r.get("hn:web-session:" + digest(token))
if not encoded:
raise HTTPException(401, "browser session expired")
record = json.loads(encoded)
await self.valid_device(record)
return record
async def session(self, request: Request):
record = await self.authenticated(request)
return no_cache(JSONResponse({"authenticated": True, "host_id": record["host_id"],
"online": bool(await self.r.exists("hn:online:" + record["host_id"])),
"mode": "pilot-text-only", "relay_sees_content": True}))
async def platform_login(self, request: Request):
self.check_origin(request)
if not self.s.feishu_enabled:
raise HTTPException(503, "platform disabled")
await rate_limit(self.r, "web-platform:" + peer(request), 20)
auth = request.headers.get("Authorization", "")
if not auth.startswith("Bearer ") or len(auth) > 8192:
raise HTTPException(401, "user token required")
try:
info = await self.platform.user_info(auth[7:])
except PlatformError:
raise HTTPException(401, "invalid user token") from None
device = self.store.by_owner(info["open_id"])
if not device:
raise HTTPException(404, "bind your device first")
return await self.new_session({**device, "generation": await self.r.get("hn:web-generation:" + device["host_id"]) or "0"})
async def chat(self, body: Chat, request: Request):
self.check_origin(request)
record = await self.authenticated(request)
await rate_limit(self.r, "web-chat:" + record["owner"], 20)
text = body.text.strip()
if not text:
raise HTTPException(422, "empty message")
# PC accepts only its bound owner and the existing IM read-only channel.
if not (text == "/主机名" or text.startswith(("/回显 ", "/读取 ", "/助手 "))):
text = "/助手 " + text
turn = "web_" + digest(record["owner"] + "\0" + body.request_id)
result = await self.broker.dispatch(record["owner"], text, turn)
# Revoke/unbind during a long model call invalidates the browser immediately.
await self.authenticated(request)
return no_cache(JSONResponse(result))
async def logout(self, request: Request):
self.check_origin(request)
token = request.cookies.get(COOKIE, "")
if token and len(token) <= 128:
await self.r.delete("hn:web-session:" + digest(token))
response = no_cache(JSONResponse({"status": "logged_out"}))
response.delete_cookie(COOKIE, secure=True, httponly=True, samesite="strict", path="/")
return response