diff --git a/.dockerignore b/.dockerignore index b0b0939..5189c64 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,3 +6,8 @@ web/node_modules web/dist **/__pycache__ .env +.env.* +.cursor +docs +backend/tests +scripts diff --git a/.env.example b/.env.example index 1c0801c..68624fb 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,8 @@ EUNIV_SECRET_KEY= # 生成密钥:python -c "import secrets;print(secrets.token_urlsafe(48))" +# 更换密钥时把旧密钥放到这里,用来解开已经保存的密文。容器环境变量是白名单,只改 .env 不会进容器。 +EUNIV_SECRET_KEY_OLD= +# 下面这行只对直接启动的进程生效。docker compose 里数据库路径写死为 /data/euniv.db。 EUNIV_DB_PATH=data/euniv.db # 不设置时,首次启动会在日志里打印一次随机管理员口令 EUNIV_ADMIN_PASSWORD= @@ -7,3 +10,9 @@ EUNIV_ADMIN_PASSWORD= EUNIV_ADMIN_RESET= # 本地 http 开发设为 0;对外只走 https 时设为 1 EUNIV_COOKIE_SECURE=0 +# INFO 或 WARNING。httpx 的请求日志固定在 WARNING,避免把带授权码的地址写进日志 +EUNIV_LOG_LEVEL=INFO +# 设为 1 才打开 /docs、/redoc、/openapi.json +EUNIV_OPENAPI= +# 设为 1 时不启动凭据刷新、自动学习、代理池和课程同步 +EUNIV_DISABLE_REFRESH= diff --git a/Dockerfile b/Dockerfile index 210aad9..b1ec660 100644 --- a/Dockerfile +++ b/Dockerfile @@ -16,5 +16,10 @@ COPY backend/alembic.ini . COPY --from=web /src/web/dist /web/dist ENV EUNIV_DB_PATH=/data/euniv.db ENV EUNIV_COOKIE_SECURE=1 +ENV PYTHONUNBUFFERED=1 EXPOSE 8000 -CMD ["uvicorn", "euniv.api:app", "--host", "0.0.0.0", "--port", "8000"] +RUN useradd --system --uid 10001 --home /app euniv \ + && mkdir -p /data \ + && chown -R euniv:euniv /app /data +USER euniv +CMD ["uvicorn", "euniv.api:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--ws", "wsproto", "--forwarded-allow-ips", "*"] diff --git a/backend/alembic.ini b/backend/alembic.ini index 3767dda..ffd6974 100644 --- a/backend/alembic.ini +++ b/backend/alembic.ini @@ -1,5 +1,7 @@ [alembic] script_location = alembic +prepend_sys_path = . +path_separator = os sqlalchemy.url = sqlite:///data/euniv.db [loggers] diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 40d7e8b..e7ee149 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -3,10 +3,18 @@ from __future__ import annotations import asyncio +import logging import os from contextlib import asynccontextmanager from pathlib import Path +logging.basicConfig( + level=os.getenv("EUNIV_LOG_LEVEL", "INFO"), + format="%(asctime)s %(levelname)s %(name)s %(message)s", +) +logging.getLogger("httpx").setLevel(logging.WARNING) +logging.getLogger("httpcore").setLevel(logging.WARNING) + from fastapi import Depends, FastAPI, HTTPException, Request, Response, WebSocket, WebSocketDisconnect from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, Field @@ -71,6 +79,11 @@ class StudyControlBody(_BaseModel): @asynccontextmanager async def lifespan(_app: FastAPI): + from euniv.instance_lock import acquire_instance_lock + + acquire_instance_lock() + if os.environ.get("EUNIV_DISABLE_REFRESH") == "1": + logging.getLogger("euniv.api").warning("EUNIV_DISABLE_REFRESH=1,后台刷新、自动学习和代理池都不会启动") init_db() ensure_admin_seed() from admin.settings import ensure_key_check @@ -129,7 +142,22 @@ class QrPollBody(BaseModel): @app.get("/api/health") def health() -> dict: - return {"ok": True} + from sqlalchemy import text + + from euniv.db import SessionLocal + + with SessionLocal() as db: + db.execute(text("SELECT 1")) + study_alive = False + try: + from euniv import autostudy + + worker = autostudy._worker + thread = getattr(worker, "_thread", None) if worker is not None else None + study_alive = bool(thread is not None and thread.is_alive()) + except Exception: + study_alive = False + return {"ok": True, "database": True, "study": study_alive} def _open_session(response: Response, payload: dict) -> dict: diff --git a/backend/euniv/crypto.py b/backend/euniv/crypto.py index 2723e8d..d6762c6 100644 --- a/backend/euniv/crypto.py +++ b/backend/euniv/crypto.py @@ -6,7 +6,7 @@ import base64 import hashlib import os -from cryptography.fernet import Fernet +from cryptography.fernet import Fernet, MultiFernet _PLACEHOLDER_SECRETS = {"请换成一串只放在服务器上的密钥"} @@ -19,8 +19,16 @@ def require_secret() -> str: return secret -def _fernet() -> Fernet: - digest = hashlib.sha256(require_secret().encode("utf-8")).digest() +def _fernet() -> MultiFernet: + fernets = [_one_fernet(require_secret())] + previous = os.environ.get("EUNIV_SECRET_KEY_OLD", "").strip() + if previous and previous != require_secret(): + fernets.append(_one_fernet(previous)) + return MultiFernet(fernets) + + +def _one_fernet(secret: str) -> Fernet: + digest = hashlib.sha256(secret.encode("utf-8")).digest() return Fernet(base64.urlsafe_b64encode(digest)) diff --git a/backend/euniv/instance_lock.py b/backend/euniv/instance_lock.py new file mode 100644 index 0000000..b6cfaf5 --- /dev/null +++ b/backend/euniv/instance_lock.py @@ -0,0 +1,35 @@ +"""保证同一份数据库只被一个进程使用。""" + +from __future__ import annotations + +import os +from pathlib import Path + +_handle = None + + +def acquire_instance_lock() -> None: + global _handle + if _handle is not None: + return + database = os.environ.get("EUNIV_DB_PATH", "data/euniv.db") + path = Path(database).resolve().with_name("euniv.lock") + path.parent.mkdir(parents=True, exist_ok=True) + handle = path.open("a+b") + try: + if handle.seek(0, os.SEEK_END) == 0: + handle.write(b"\0") + handle.flush() + handle.seek(0) + if os.name == "nt": + import msvcrt + + msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + + fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError as exc: + handle.close() + raise SystemExit("已经有一个实例在使用这份数据库") from exc + _handle = handle diff --git a/backend/requirements-dev.txt b/backend/requirements-dev.txt new file mode 100644 index 0000000..7345f25 --- /dev/null +++ b/backend/requirements-dev.txt @@ -0,0 +1 @@ +pytest==9.1.1 diff --git a/backend/requirements.txt b/backend/requirements.txt index 2d89732..b85c727 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,5 +1,4 @@ httpx==0.28.1 -socksio==1.0.0 httpx-socks==0.10.1 python-socks==3.2.1 sniffio==1.3.1 @@ -7,6 +6,7 @@ cryptography==50.0.2 pillow==13.0.0 qrcode==8.2 fastapi==0.162.0 +starlette==1.10.0 uvicorn==0.54.0 wsproto==1.2.0 sqlalchemy==2.1.6 diff --git a/docker-compose.yml b/docker-compose.yml index 6a95fb1..cbc7116 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -6,10 +6,26 @@ services: - "127.0.0.1:8000:8000" environment: EUNIV_SECRET_KEY: ${EUNIV_SECRET_KEY:?请在环境变量或 .env 中设置 EUNIV_SECRET_KEY} + EUNIV_SECRET_KEY_OLD: ${EUNIV_SECRET_KEY_OLD:-} EUNIV_DB_PATH: /data/euniv.db EUNIV_ADMIN_PASSWORD: ${EUNIV_ADMIN_PASSWORD:-} EUNIV_ADMIN_RESET: ${EUNIV_ADMIN_RESET:-} EUNIV_COOKIE_SECURE: ${EUNIV_COOKIE_SECURE:-1} + EUNIV_LOG_LEVEL: ${EUNIV_LOG_LEVEL:-INFO} + EUNIV_OPENAPI: ${EUNIV_OPENAPI:-} + EUNIV_DISABLE_REFRESH: ${EUNIV_DISABLE_REFRESH:-} + restart: unless-stopped + stop_grace_period: 20s + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/health')"] + interval: 30s + timeout: 5s + retries: 3 + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" volumes: - euniv-data:/data