fix: 设置令牌后校验本机接口并限制访问主机

This commit is contained in:
2026-10-25 07:14:13 +08:00
parent 0d7bc8ed22
commit 5690b598b0
+35 -1
View File
@@ -1,16 +1,22 @@
"""本机接口。只监听 127.0.0.1。功能路由按目录挂上。"""
from __future__ import annotations
import asyncio
import ctypes
import logging
import msvcrt
import os
import secrets
import sys
from contextlib import asynccontextmanager, suppress
from ctypes import wintypes
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from starlette.datastructures import Headers
from starlette.responses import JSONResponse
from app.features.download.router import router as download_router
from app.platform.auth import router as auth_router
@@ -128,6 +134,33 @@ def _release_data_lock() -> None:
handle.close()
def _token_matches(provided: str, expected: str) -> bool:
if len(provided) != len(expected):
return False
return secrets.compare_digest(provided, expected)
class LocalTokenMiddleware:
"""仅当设置了 NQI_TOKEN 时校验 /api/*。健康检查除外。"""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope.get("type") != "http":
await self.app(scope, receive, send)
return
token = os.environ.get("NQI_TOKEN") or ""
path = scope.get("path") or ""
if token and path.startswith("/api/") and path.rstrip("/") != "/api/health":
provided = Headers(scope=scope).get("x-nqi-token") or ""
if not _token_matches(provided, token):
response = JSONResponse({"detail": "未授权"}, status_code=401)
await response(scope, receive, send)
return
await self.app(scope, receive, send)
@asynccontextmanager
async def lifespan(_app: FastAPI):
configure_logging()
@@ -154,6 +187,8 @@ async def lifespan(_app: FastAPI):
app = FastAPI(title="NqiTools", lifespan=lifespan)
app.add_middleware(LocalTokenMiddleware)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["127.0.0.1", "localhost"])
app.add_middleware(
CORSMiddleware,
allow_origins=ORIGINS,
@@ -171,7 +206,6 @@ async def health() -> dict:
if __name__ == "__main__":
import os
import socket
import uvicorn