fix: 堵住 /api/dev/* 公网入口,修会话过期时间与上传孤儿文件

安全(P0)
- app.py: QINGLING_ENV=prod 时不注册 /api/dev/*(6 条)与短信登录(2 条),
  请求落到 404;路由数 dev 57 / prod 49
- deploy: compose 默认 QINGLING_ENV=prod;Caddyfile 对 /api/dev/* 与
  /api/auth/sms-* 再兜一层 404(就算环境变量被改回 dev,公网也打不到)
- app.py: 生产环境不再把异常原文回给前端;CORS 生产默认不发
  Access-Control-Allow-Origin(需要跨域用 QINGLING_CORS 配置)

正确性
- services: sessions.expires_at 从「创建时刻」改成「创建 + 7 天」(4 处:
  login / login_ticket / login_phone / _session_payload),并新增
  purge_expired_sessions(),挂在 health 上顺手清理(这张表从没清过)
- services: create_paper_from_image 在 OCR 抛异常、或退回演示题库时删掉
  未入库的原图与擦除页,不再留孤儿文件;papers 表新增 image_path 并在
  建卷时写入
- services: 新增 cleanup_uploads()/sweep_uploads(),按「文件名主干 =
  papers.id」清掉 90 天前没人引用的上传文件(每天最多扫一次)
- app.py: 请求体按 Content-Length 限 16MB(直连 8000 时没有 Caddy 兜底),
  坏 Content-Length 回 400 而不是 500
- app.py: paper_clean 按真实后缀回 Content-Type(TextIn 擦除结果是 .jpg,
  以前一律当 png 发)

部署
- Dockerfile 安装 Pillow:没有它 img_w=img_h=0,「小图先拦一道」和
  「图太小就不做 TextIn 擦除」在容器里会静默失效
- README/上线清单:补 prod 路由数与 /api/dev 验收项

验证
- python -m unittest(5 个模块)91 passed
- 冒烟:prod 下 4 个 dev/sms 接口 404、routes=49、20MB 请求 413、
  坏 Content-Length 400、expires_at=created+7d、health 清理过期会话、
  清完旧令牌仍有效、papers.image_path 存在
- uploads 清理:孤儿文件删掉、被引用的原图与擦除页保留、新文件不动
This commit is contained in:
errortopic
2026-11-18 20:19:22 +08:00
parent f7b28e1740
commit cf6c2ca263
9 changed files with 176 additions and 30 deletions
+90 -11
View File
@@ -28,6 +28,15 @@ ADMIN_TOKEN_TTL = 7 * 24 * 3600 # 家长登录态 7 天
CHILD_TOKEN_TTL = 15 * 60 # 孩子口答会话 15 分钟
def _session_expires_at() -> str:
"""sessions 行上的到期时间。
令牌本身带 HMAC 里的 exp(7 天),这一列是让人能直接在库里看懂会话什么时候失效。
以前这里写的是 datetime.now()——等于「创建即过期」,账本一直是假的。
"""
return (datetime.now(TZ) + timedelta(seconds=ADMIN_TOKEN_TTL)).isoformat(timespec="seconds")
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str):
super().__init__(message)
@@ -137,7 +146,7 @@ def login(conn, code: str) -> dict:
log_event(conn, "login", None, guardian_id=row["id"], wx_mode=wechat.mode())
token = make_token(row["id"])
conn.execute("INSERT OR REPLACE INTO sessions (token, guardian_id, created_at, expires_at) VALUES (?,?,?,?)",
(token, row["id"], now(), datetime.now().isoformat(timespec="seconds")))
(token, row["id"], now(), _session_expires_at()))
ensure_trial(conn, row["id"])
return {
"token": token,
@@ -190,7 +199,7 @@ def login_ticket(conn, ticket: str) -> dict:
gid = row["guardian_id"]
token = make_token(gid)
conn.execute("INSERT OR REPLACE INTO sessions (token, guardian_id, created_at, expires_at) VALUES (?,?,?,?)",
(token, gid, now(), datetime.now().isoformat(timespec="seconds")))
(token, gid, now(), _session_expires_at()))
ensure_trial(conn, gid)
return {
"token": token, "guardian_id": gid, "is_new": False,
@@ -276,7 +285,7 @@ def login_phone(conn, phone: str, code: str) -> dict:
token = make_token(grow["id"])
conn.execute("INSERT OR REPLACE INTO sessions (token, guardian_id, created_at, expires_at) VALUES (?,?,?,?)",
(token, grow["id"], now(), datetime.now().isoformat(timespec="seconds")))
(token, grow["id"], now(), _session_expires_at()))
ensure_trial(conn, grow["id"])
return {
"token": token, "guardian_id": grow["id"], "is_new": is_new,
@@ -689,6 +698,16 @@ def deletion_status(conn, gid: str) -> dict | None:
return dict(row) if row else None
def purge_expired_sessions(conn) -> int:
"""删掉已经过期的会话行。
令牌过期后这些行没有任何用处;不删的话 sessions 会随登录次数一直长,
而且这张表从来没被清理过(旧数据里 expires_at 还都是错的)。
"""
cur = conn.execute("DELETE FROM sessions WHERE expires_at < ?", (now(),))
return cur.rowcount or 0
def purge_due(conn) -> dict:
"""把过了冷静期的账号真删掉。每次登录与 health 都会顺手跑一次。"""
rows = conn.execute("SELECT guardian_id FROM account_deletions WHERE purge_after <= ?",
@@ -1307,6 +1326,55 @@ def demo_data(conn, gid: str, nickname: str = "皮皮", grade: int = 2) -> dict:
# ---------------------------------------------------------------- 拍照识题
UPLOAD_DIR = Path(__file__).resolve().parent.parent / "data" / "uploads"
def _drop_upload(path: Path) -> None:
"""删掉一个没能入库的上传文件——失败路径不留孤儿。"""
try:
if path and path.exists():
path.unlink()
except OSError:
pass
def cleanup_uploads(conn, days: int = 90) -> int:
"""删掉没人引用、且超过 days 天的上传文件。
正常路径下 papers.image_path / clean_path 都有值;但 OCR 直接抛异常、
或者旧版本留下的文件可能只存在于磁盘。文件名主干就是 papers.id
(擦除页是 <pid>_clean),所以这里按「pid 还在不在 papers 里」兜底清一遍。
"""
if not UPLOAD_DIR.exists():
return 0
alive = {r["id"] for r in conn.execute("SELECT id FROM papers")}
cutoff = time.time() - days * 86400
n = 0
for f in UPLOAD_DIR.rglob("*"):
try:
if not f.is_file() or f.stat().st_mtime >= cutoff:
continue
except OSError:
continue
pid = f.stem[:-6] if f.stem.endswith("_clean") else f.stem
if pid in alive:
continue
_drop_upload(f)
n += 1
return n
_UPLOAD_SWEEP_AT = 0.0
def sweep_uploads(conn, days: int = 90) -> int:
"""每天最多扫一次上传目录——health 会被健康检查频繁打,不能每次都遍历磁盘。"""
global _UPLOAD_SWEEP_AT
if time.time() - _UPLOAD_SWEEP_AT < 86400:
return 0
_UPLOAD_SWEEP_AT = time.time()
return cleanup_uploads(conn, days=days)
ERASE_MIN_SIDE = 1200 # 短边不到这个尺寸就不擦:擦除会把印刷字也糊掉
@@ -1354,6 +1422,7 @@ def create_paper_from_image(conn, gid: str, cid: str, subject: str, image_bytes:
ext = ".jpg"
img_path = folder / f"{pid}{ext}"
img_path.write_bytes(image_bytes)
clean_path_obj = folder / f"{pid}_clean.jpg"
# 手写擦除(TextIn):干净页既能重印,也能让切题少被笔迹干扰。
# 图太小就别擦——这个接口在小图上会连印刷字一起抹掉,宁可不动。
@@ -1365,7 +1434,7 @@ def create_paper_from_image(conn, gid: str, cid: str, subject: str, image_bytes:
erase = {"used": True, "ok": bool(r.get("ok")), "ms": r.get("ms")}
if r.get("ok"):
clean_rel = f"data/uploads/{cid}/{pid}_clean.jpg"
(folder / f"{pid}_clean.jpg").write_bytes(r["image"])
clean_path_obj.write_bytes(r["image"])
erase["bytes"] = len(r["image"])
else:
erase["reason"] = r.get("message") or r.get("code")
@@ -1374,9 +1443,15 @@ def create_paper_from_image(conn, gid: str, cid: str, subject: str, image_bytes:
else:
erase["reason"] = "没配 TextIn 凭据"
res = ocr.recognize(img_path)
qual = ocr.quality(res)
questions = cut.segment(res["lines"], subject) if qual["ok"] else []
try:
res = ocr.recognize(img_path)
qual = ocr.quality(res)
questions = cut.segment(res["lines"], subject) if qual["ok"] else []
except Exception:
# OCR 自己崩了(没装语言包、子进程超时、图读不了):原图和擦除页都还没入库,删掉再抛
_drop_upload(img_path)
_drop_upload(clean_path_obj)
raise
if not qual["ok"] or not questions:
if not qual["ok"]:
@@ -1391,6 +1466,9 @@ def create_paper_from_image(conn, gid: str, cid: str, subject: str, image_bytes:
f"把卷子拍全、让题号露出来;也可以先用演示题库走一遍。(认到:{preview}…)")
if not fallback_demo:
raise ApiError(422, code, (size_warn + " " + reason).strip() if size_warn else reason)
# 退回演示题库:这张图不会有任何 papers 行指向它,留在磁盘上就是孤儿
_drop_upload(img_path)
_drop_upload(clean_path_obj)
paper = create_paper(conn, gid, cid, subject, image_count=1)
paper["source"] = "demo"
paper["too_small"] = bool(size_warn)
@@ -1401,9 +1479,10 @@ def create_paper_from_image(conn, gid: str, cid: str, subject: str, image_bytes:
return paper
with tx(conn):
conn.execute("INSERT INTO papers (id, child_id, subject, image_count, clean_path, created_at)"
" VALUES (?,?,?,?,?,?)",
(pid, cid, subject, 1, clean_rel, now()))
image_rel = f"data/uploads/{cid}/{img_path.name}"
conn.execute("INSERT INTO papers (id, child_id, subject, image_count, clean_path, image_path,"
" created_at) VALUES (?,?,?,?,?,?,?)",
(pid, cid, subject, 1, clean_rel, image_rel, now()))
for i, q in enumerate(questions, start=1):
conn.execute(
"INSERT INTO questions (id, paper_id, child_id, subject, seq, stem, answer, options,"
@@ -1488,7 +1567,7 @@ def _epoch() -> int:
def _session_payload(conn, gid: str, via: str = "scan") -> dict:
token = make_token(gid)
conn.execute("INSERT OR REPLACE INTO sessions (token, guardian_id, created_at, expires_at) VALUES (?,?,?,?)",
(token, gid, now(), datetime.now().isoformat(timespec="seconds")))
(token, gid, now(), _session_expires_at()))
ensure_trial(conn, gid)
log_event(conn, "login_" + via, None, guardian_id=gid)
return {