安全性更新
This commit is contained in:
1 parent
5bd77d2599
commit
e75f0c95e9
29 files changed
+726
-143
No files matched your search
@@ -5,7 +5,7 @@
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
from . import clock, config, db, notices
|
||||
from . import clock, config, db, limits, notices
|
||||
from .titles import fmt_uid
|
||||
|
||||
|
||||
@@ -42,3 +42,4 @@ async def loop() -> None:
|
||||
while True:
|
||||
await asyncio.sleep(config.CHECK_INTERVAL)
|
||||
await asyncio.to_thread(check_safe)
|
||||
limits.sweep_all() # 順便清掉過期的限流紀錄
|
||||
+59
-45
@@ -1,18 +1,18 @@
|
||||
"""信箱驗證碼登入(沒有密碼):第一次驗證成功就自動建立帳號。
|
||||
|
||||
管理員:信箱欄輸入 ADMIN_LOGIN,驗證碼是 Aegis 算的 TOTP(不寄信)。錯 3 次就全域鎖定,時間逐次加倍。
|
||||
對外的回應和一般信箱完全相同(包括鎖定時),別人沒辦法從回應試出哪個是管理員。
|
||||
"""
|
||||
import re
|
||||
import random
|
||||
import secrets
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
from collections import deque
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from . import clock, config, db, mailer, notices, totp
|
||||
from . import clock, config, db, limits, mailer, notices, totp
|
||||
from .db import get_db, get_meta, set_meta, transaction
|
||||
from .deps import client_ip, current_user, fail, session_token, sha256
|
||||
from .i18n import norm_lang
|
||||
@@ -20,36 +20,33 @@ from .users import create_user, profile
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
||||
|
||||
# 同一 IP 的寄信次數(單一 worker,放記憶體就夠)
|
||||
_ip_hits: dict[str, deque] = defaultdict(deque)
|
||||
_ip_lock = threading.Lock()
|
||||
_ip_mail = limits.Window("IP_LIMIT", "IP_WINDOW") # 同一 IP 的寄信次數
|
||||
_all_mail = limits.Window("MAIL_LIMIT", "MAIL_WINDOW") # 全站的寄信次數
|
||||
_day_mail = limits.Window("MAIL_DAY_LIMIT", "MAIL_DAY_WINDOW")
|
||||
_send_times: deque = deque(maxlen=20) # 最近實際寄信花的秒數;管理員不寄信,用它等差不多久
|
||||
|
||||
|
||||
def ip_allowed(ip: str) -> bool:
|
||||
now = time.monotonic()
|
||||
with _ip_lock:
|
||||
q = _ip_hits[ip]
|
||||
while q and q[0] < now - config.IP_WINDOW:
|
||||
q.popleft()
|
||||
if len(q) >= config.IP_LIMIT:
|
||||
return False
|
||||
q.append(now)
|
||||
return True
|
||||
|
||||
|
||||
def is_admin_login(raw: str) -> bool:
|
||||
return db.admin_ok and raw.strip().lower() == config.ADMIN_LOGIN.lower()
|
||||
def is_admin(conn: sqlite3.Connection, email: str) -> bool:
|
||||
"""管理員的信箱。就算管理員登入停用了也算:不能寄信給它,也不能用一般流程登入。"""
|
||||
row = conn.execute("SELECT uid FROM users WHERE email = ?", (email,)).fetchone()
|
||||
return row is not None and row["uid"] == config.ADMIN_UID
|
||||
|
||||
|
||||
def norm_email(email: str) -> str:
|
||||
email = email.strip().lower()
|
||||
if len(email) > 254 or not EMAIL_RE.match(email):
|
||||
if not limits.valid_email(email):
|
||||
fail(400, "invalid_email")
|
||||
return email
|
||||
|
||||
|
||||
def mail_allowed() -> bool:
|
||||
for window, name in ((_day_mail, "24 h"), (_all_mail, "10 min")):
|
||||
if not window.allow("all"):
|
||||
notices.add("mail_limit", None, name)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class CodeRequest(BaseModel):
|
||||
email: str
|
||||
lang: str = config.DEFAULT_LANG
|
||||
@@ -64,12 +61,6 @@ class VerifyRequest(BaseModel):
|
||||
@router.post("/api/auth/request-code")
|
||||
def request_code(body: CodeRequest, request: Request, conn: sqlite3.Connection = Depends(get_db)):
|
||||
sent = {"status": "sent", "expires_in": config.CODE_TTL, "resend_in": config.CODE_RESEND}
|
||||
if is_admin_login(body.email):
|
||||
# 管理員不寄信,驗證碼看 Aegis。回應和一般信箱完全相同
|
||||
if not ip_allowed(client_ip(request)):
|
||||
fail(429, "too_many_requests")
|
||||
return sent
|
||||
|
||||
email = norm_email(body.email)
|
||||
now = clock.ts()
|
||||
conn.execute("DELETE FROM login_codes WHERE expires_at < ?", (now,))
|
||||
@@ -77,7 +68,7 @@ def request_code(body: CodeRequest, request: Request, conn: sqlite3.Connection =
|
||||
old = conn.execute("SELECT last_sent_at FROM login_codes WHERE email = ?", (email,)).fetchone()
|
||||
if old and now - old["last_sent_at"] < config.CODE_RESEND:
|
||||
fail(429, "too_many_requests")
|
||||
if not ip_allowed(client_ip(request)):
|
||||
if not _ip_mail.allow(limits.ip_key(client_ip(request))) or not mail_allowed():
|
||||
fail(429, "too_many_requests")
|
||||
|
||||
# secrets 才是密碼學安全的亂數
|
||||
@@ -88,8 +79,15 @@ def request_code(body: CodeRequest, request: Request, conn: sqlite3.Connection =
|
||||
"expires_at = excluded.expires_at, last_sent_at = excluded.last_sent_at",
|
||||
(email, sha256(code), now + config.CODE_TTL, now),
|
||||
)
|
||||
if is_admin(conn, email):
|
||||
# 管理員不寄信,驗證碼看 Aegis。等一段和實際寄信差不多的時間,從快慢也看不出來
|
||||
if config.SMTP_USER and config.SMTP_PASSWORD:
|
||||
time.sleep((random.choice(_send_times) if _send_times else 1.5) * random.uniform(0.9, 1.1))
|
||||
return sent
|
||||
started = time.monotonic()
|
||||
try:
|
||||
mailer.send_code(email, code, norm_lang(body.lang))
|
||||
_send_times.append(time.monotonic() - started)
|
||||
except Exception as e:
|
||||
print("Error sending email:", e, flush=True)
|
||||
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
|
||||
@@ -151,13 +149,6 @@ def issue_session(conn: sqlite3.Connection, response: Response, user: sqlite3.Ro
|
||||
@router.post("/api/auth/verify")
|
||||
def verify(body: VerifyRequest, request: Request, response: Response,
|
||||
conn: sqlite3.Connection = Depends(get_db)):
|
||||
if is_admin_login(body.email):
|
||||
err = admin_check(conn, body.code.strip(), client_ip(request))
|
||||
if err:
|
||||
fail(429 if err == "too_many_requests" else 400, err)
|
||||
admin = conn.execute("SELECT * FROM users WHERE uid = ?", (config.ADMIN_UID,)).fetchone()
|
||||
return issue_session(conn, response, admin)
|
||||
|
||||
email = norm_email(body.email)
|
||||
code = body.code.strip()
|
||||
now = clock.ts()
|
||||
@@ -169,18 +160,41 @@ def verify(body: VerifyRequest, request: Request, response: Response,
|
||||
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
|
||||
fail(400, "expired")
|
||||
|
||||
# 先用掉一次機會再比對(一句 SQL,同時送很多個也不會多猜)。認 code_hash:不會扣到剛重寄的新碼
|
||||
this_code = (email, row["code_hash"])
|
||||
used = conn.execute("UPDATE login_codes SET attempts = attempts + 1 "
|
||||
"WHERE email = ? AND code_hash = ? AND attempts < ? RETURNING attempts",
|
||||
(*this_code, config.CODE_MAX_ATTEMPTS)).fetchall()
|
||||
if not used:
|
||||
fail(400, "expired")
|
||||
|
||||
admin = is_admin(conn, email)
|
||||
if admin:
|
||||
# 停用時一律不對;鎖定中也只當作碼錯了,不透露這是管理員
|
||||
err = admin_check(conn, code, client_ip(request)) if db.admin_ok else "wrong_code"
|
||||
if err == "code_used": # 碼是對的,只是用過了:不算猜錯
|
||||
conn.execute("UPDATE login_codes SET attempts = attempts - 1 WHERE email = ? AND code_hash = ?", this_code)
|
||||
fail(400, err)
|
||||
ok = err is None
|
||||
else:
|
||||
ok = code.isascii() and secrets.compare_digest(sha256(code), row["code_hash"])
|
||||
|
||||
# 錯太多次直接作廢,防止暴力猜碼
|
||||
if not secrets.compare_digest(sha256(code), row["code_hash"]):
|
||||
attempts = row["attempts"] + 1
|
||||
if attempts >= config.CODE_MAX_ATTEMPTS:
|
||||
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
|
||||
if not ok:
|
||||
if used[0]["attempts"] >= config.CODE_MAX_ATTEMPTS:
|
||||
conn.execute("DELETE FROM login_codes WHERE email = ? AND code_hash = ?", this_code)
|
||||
fail(400, "expired")
|
||||
conn.execute("UPDATE login_codes SET attempts = ? WHERE email = ?", (attempts, email))
|
||||
fail(400, "wrong_code")
|
||||
|
||||
# 驗證碼只能用一次
|
||||
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
|
||||
# 驗證碼只能用一次(同時送兩個對的,只有一個成功)
|
||||
if conn.execute("DELETE FROM login_codes WHERE email = ? AND code_hash = ?", this_code).rowcount == 0:
|
||||
fail(400, "not_requested")
|
||||
user = create_user(conn, email, body.lang)
|
||||
if admin:
|
||||
agent = "".join(ch for ch in request.headers.get("user-agent", "") if ch.isprintable())[:160]
|
||||
country = request.headers.get("cf-ipcountry", "")[:8]
|
||||
notices.add("admin_login", None, " · ".join(x for x in (client_ip(request)[:64], country, agent) if x),
|
||||
merge=False)
|
||||
return issue_session(conn, response, user)
|
||||
|
||||
|
||||
|
||||
+6
-19
@@ -10,8 +10,7 @@ import shutil
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict, defaultdict, deque
|
||||
from collections import OrderedDict
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
@@ -20,15 +19,14 @@ from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
||||
|
||||
from . import clock, config
|
||||
from . import clock, config, limits
|
||||
from .checkin import list_memes, stats
|
||||
from .db import get_db
|
||||
from .deps import client_ip, fail
|
||||
from .i18n import norm_lang, t
|
||||
from .images import FORMATS
|
||||
from .titles import badge_colors, fmt_uid
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000 # 擋解壓縮炸彈
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
W, H = 1080, 1350
|
||||
@@ -90,7 +88,7 @@ def rounded_mask(size, radius) -> Image.Image:
|
||||
|
||||
def load_image(path: Path) -> Image.Image | None:
|
||||
try:
|
||||
with Image.open(path) as im:
|
||||
with Image.open(path, formats=FORMATS) as im:
|
||||
im.seek(0) # gif 只取第一幀
|
||||
im = ImageOps.exif_transpose(im)
|
||||
return im.convert("RGB")
|
||||
@@ -238,21 +236,10 @@ def get_card(uid: int, day: str, conn: sqlite3.Connection = Depends(get_db)):
|
||||
|
||||
GUEST_CODE_RE = re.compile(r"^[A-Z0-9]{4}$")
|
||||
_guest_lock = threading.Lock()
|
||||
_guest_hits: dict[str, deque] = defaultdict(deque) # IP -> 最近畫圖的時間
|
||||
_guest_hits = limits.Window("GUEST_CARD_LIMIT", "GUEST_CARD_WINDOW")
|
||||
_guest_cache: "OrderedDict[tuple, bytes]" = OrderedDict() # 最近畫過的幾張(PNG)
|
||||
|
||||
|
||||
def _guest_allowed(ip: str) -> bool:
|
||||
now = time.monotonic()
|
||||
q = _guest_hits[ip]
|
||||
while q and q[0] < now - config.GUEST_CARD_WINDOW:
|
||||
q.popleft()
|
||||
if len(q) >= config.GUEST_CARD_LIMIT:
|
||||
return False
|
||||
q.append(now)
|
||||
return True
|
||||
|
||||
|
||||
def guest_meme(code: str, day: str) -> str | None:
|
||||
"""同一個訪客同一天固定抽到同一張(伺服器沒有地方記,所以用代號 + 日期當亂數種子)。"""
|
||||
memes = list_memes()
|
||||
@@ -269,7 +256,7 @@ def get_guest_card(request: Request, code: str = "", n: str = "0", lang: str = c
|
||||
with _guest_lock:
|
||||
png = _guest_cache.get(key)
|
||||
if png is None:
|
||||
if not _guest_allowed(client_ip(request)):
|
||||
if not _guest_hits.allow(limits.ip_key(client_ip(request))):
|
||||
fail(429, "too_many_requests")
|
||||
buf = io.BytesIO()
|
||||
render_guest(lang, code, day, meme, clicks).save(buf, "PNG")
|
||||
|
||||
+20
-1
@@ -51,7 +51,26 @@ IP_WINDOW = 10 * 60
|
||||
SESSION_TTL = 90 * 24 * 3600
|
||||
ADMIN_SESSION_TTL = 7 * 24 * 3600
|
||||
|
||||
# 管理員:信箱欄輸入 ADMIN_LOGIN,驗證碼是 ADMIN_TOTP(base32 密鑰)算出的 TOTP。兩個都設定才啟用
|
||||
# 全站寄信上限:擋轟炸別人信箱,也避免把寄信服務的額度用光
|
||||
MAIL_LIMIT = 40
|
||||
MAIL_WINDOW = 10 * 60
|
||||
MAIL_DAY_LIMIT = 400
|
||||
MAIL_DAY_WINDOW = 24 * 3600
|
||||
|
||||
# 請求大小上限
|
||||
BODY_MAX = 64 * 1024
|
||||
UPLOAD_BODY_MAX = 6 * 1024 * 1024 # 圖片上限 5MB,加上表單的部分
|
||||
UPLOAD_PATHS = ("/api/me/avatar", "/api/submissions")
|
||||
|
||||
# 上傳的圖:像素上限(2400 萬像素的手機照片可以過)、等前一張處理完最多幾秒
|
||||
IMAGE_MAX_PIXELS = 30_000_000
|
||||
IMAGE_WAIT = 10
|
||||
# 每個帳號每分鐘最多處理幾次(失敗也算)
|
||||
AVATAR_LIMIT = 3
|
||||
SUBMIT_LIMIT = 10
|
||||
UPLOAD_WINDOW = 60
|
||||
|
||||
# 管理員:ADMIN_LOGIN 要是信箱格式(不會寄信),驗證碼是 ADMIN_TOTP(base32 密鑰)算出的 TOTP。兩個都設定才啟用
|
||||
ADMIN_LOGIN = os.environ.get("ADMIN_LOGIN", "").strip()
|
||||
ADMIN_TOTP = os.environ.get("ADMIN_TOTP", "").strip()
|
||||
ADMIN_UID = 0
|
||||
|
||||
+4
-1
@@ -131,12 +131,15 @@ def _migrate(conn: sqlite3.Connection) -> None:
|
||||
def _init_admin(conn: sqlite3.Connection) -> None:
|
||||
"""建立或更新管理員帳號(uid 0)。改了 ADMIN_LOGIN 重啟就會生效。"""
|
||||
global admin_ok
|
||||
from . import totp
|
||||
from . import limits, totp
|
||||
|
||||
admin_ok = False
|
||||
login, secret = config.ADMIN_LOGIN, config.ADMIN_TOTP
|
||||
if not login or not secret:
|
||||
return
|
||||
if not limits.valid_email(login):
|
||||
print("[ERROR] ADMIN_LOGIN 要是信箱格式(例如 [email protected],不會真的寄信),管理員登入停用", flush=True)
|
||||
return
|
||||
try:
|
||||
if len(totp.decode_secret(secret)) < 10:
|
||||
raise ValueError("too short")
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""讀使用者上傳的圖:限制格式、限制像素、同時只處理一張。"""
|
||||
import io
|
||||
import threading
|
||||
import warnings
|
||||
from contextlib import contextmanager
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from . import config
|
||||
from .deps import fail
|
||||
|
||||
# 只開這幾種。Pillow 還能讀 PSD、FITS、TIFF 等幾十種,漏洞多半出在那些格式
|
||||
FORMATS = ("JPEG", "PNG", "WEBP", "GIF")
|
||||
|
||||
# 第二道保險:Pillow 自己在超過這個值的兩倍時會拒絕(例如檔頭和實際內容不一樣大)
|
||||
Image.MAX_IMAGE_PIXELS = config.IMAGE_MAX_PIXELS // 2
|
||||
warnings.simplefilter("ignore", Image.DecompressionBombWarning)
|
||||
|
||||
_slot = threading.Lock()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def slot():
|
||||
"""解碼很吃記憶體,全站同時只處理一張;等太久就請使用者稍後再試。"""
|
||||
if not _slot.acquire(timeout=config.IMAGE_WAIT):
|
||||
fail(429, "too_frequent")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_slot.release()
|
||||
|
||||
|
||||
def decode(data: bytes) -> tuple[Image.Image, bool]:
|
||||
"""回傳 (RGB 或 RGBA 的圖, 有沒有透明度)。GIF 只取第一格;方向依 EXIF 轉正。"""
|
||||
try:
|
||||
with Image.open(io.BytesIO(data), formats=FORMATS) as im:
|
||||
if im.width * im.height > config.IMAGE_MAX_PIXELS: # 只讀了檔頭,還沒解碼
|
||||
raise ValueError("too many pixels")
|
||||
im.seek(0)
|
||||
im.load()
|
||||
ImageOps.exif_transpose(im, in_place=True)
|
||||
alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info)
|
||||
return im.convert("RGBA" if alpha else "RGB"), alpha
|
||||
except Exception:
|
||||
fail(400, "invalid_image")
|
||||
@@ -0,0 +1,107 @@
|
||||
"""限流(放記憶體,只有一個 worker)、IP 分組、信箱格式、請求大小上限。"""
|
||||
import ipaddress
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
from fastapi import HTTPException
|
||||
from starlette.responses import JSONResponse
|
||||
|
||||
from . import config
|
||||
|
||||
# 只收一個單純的 ASCII 地址。<[email protected]>、x,[email protected] 這類寫法會寄到同一個人,卻被當成不同信箱
|
||||
EMAIL_RE = re.compile(
|
||||
r"[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}"
|
||||
r"@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])")
|
||||
|
||||
|
||||
def valid_email(email: str) -> bool:
|
||||
return len(email) <= 254 and EMAIL_RE.fullmatch(email) is not None
|
||||
|
||||
|
||||
def ip_key(ip: str) -> str:
|
||||
"""限流用的 IP。IPv6 的使用者手上通常有一整段 /64 可以換,所以算同一個。"""
|
||||
try:
|
||||
addr = ipaddress.ip_address(ip.strip())
|
||||
except ValueError:
|
||||
return ip[:64]
|
||||
if addr.version == 6:
|
||||
if addr.ipv4_mapped:
|
||||
return str(addr.ipv4_mapped)
|
||||
return str(ipaddress.ip_network((int(addr), 64), strict=False))
|
||||
return str(addr)
|
||||
|
||||
|
||||
class Window:
|
||||
"""同一個 key 在 window 秒內最多 limit 次。傳 config 的名稱,測試改值才會生效。"""
|
||||
_all: list["Window"] = []
|
||||
|
||||
def __init__(self, limit: str, window: str):
|
||||
self._limit, self._window = limit, window
|
||||
self._hits: dict = {}
|
||||
self._lock = threading.Lock()
|
||||
Window._all.append(self)
|
||||
|
||||
def allow(self, key) -> bool:
|
||||
now = time.monotonic()
|
||||
with self._lock:
|
||||
q = self._hits.setdefault(key, deque())
|
||||
while q and q[0] < now - getattr(config, self._window):
|
||||
q.popleft()
|
||||
if len(q) >= getattr(config, self._limit):
|
||||
return False
|
||||
q.append(now)
|
||||
return True
|
||||
|
||||
def clear(self) -> None:
|
||||
with self._lock:
|
||||
self._hits.clear()
|
||||
|
||||
def sweep(self) -> None:
|
||||
"""丟掉已經過期的 key,不然來過的 IP 會一直佔著記憶體。"""
|
||||
old = time.monotonic() - getattr(config, self._window)
|
||||
with self._lock:
|
||||
for key in [k for k, q in self._hits.items() if not q or q[-1] < old]:
|
||||
del self._hits[key]
|
||||
|
||||
|
||||
def sweep_all() -> None:
|
||||
for w in Window._all:
|
||||
w.sweep()
|
||||
|
||||
|
||||
class BodyLimit:
|
||||
"""擋太大的請求。沒有這個的話,還沒檢查登入就會先把整個請求收完。"""
|
||||
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
return await self.app(scope, receive, send)
|
||||
limit = config.UPLOAD_BODY_MAX if scope["path"] in config.UPLOAD_PATHS else config.BODY_MAX
|
||||
too_big = JSONResponse({"detail": "file_too_large"}, status_code=413)
|
||||
length = dict(scope["headers"]).get(b"content-length", b"")
|
||||
if length.isdigit() and int(length[:20]) > limit:
|
||||
return await too_big(scope, receive, send)
|
||||
got, replaced = 0, False
|
||||
|
||||
async def limited(): # chunked 沒有 Content-Length,邊收邊算
|
||||
nonlocal got
|
||||
message = await receive()
|
||||
if message["type"] == "http.request":
|
||||
got += len(message.get("body", b""))
|
||||
if got > limit:
|
||||
raise HTTPException(413, "file_too_large")
|
||||
return message
|
||||
|
||||
async def answer(message): # 裡面會把上面的例外變成 400,統一換成 413
|
||||
nonlocal replaced
|
||||
if got <= limit:
|
||||
await send(message)
|
||||
elif not replaced:
|
||||
replaced = True
|
||||
await too_big(scope, receive, send)
|
||||
|
||||
await self.app(scope, limited, answer)
|
||||
+23
-3
@@ -1,6 +1,7 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import mimetypes
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from functools import lru_cache
|
||||
|
||||
@@ -8,7 +9,7 @@ from fastapi import FastAPI, Request
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from . import __version__, anticheat, auth, card, checkin, config, db, notices, share, submissions, users
|
||||
from . import __version__, anticheat, auth, card, checkin, config, db, limits, notices, share, submissions, users
|
||||
|
||||
# python:3.12-slim 沒有 /etc/mime.types,這些副檔名會被當成 text/plain;加上 nosniff 後瀏覽器可能拒絕播放
|
||||
for _type, _ext in (("image/webp", ".webp"), ("video/mp4", ".mp4"), ("audio/mp4", ".m4a"), ("application/manifest+json", ".webmanifest"),
|
||||
@@ -19,8 +20,25 @@ CSP = ("default-src 'self'; img-src 'self' data: blob:; media-src 'self'; style-
|
||||
"script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
|
||||
|
||||
|
||||
def check_storage() -> None:
|
||||
"""容器不是用 root 跑:資料夾的擁有者不對時,啟動就講清楚。"""
|
||||
who = f"{os.geteuid()}:{os.getegid()}" if hasattr(os, "geteuid") else "?"
|
||||
|
||||
def bad(path):
|
||||
return path.exists() and not os.access(path, os.R_OK | os.W_OK | (os.X_OK if path.is_dir() else 0))
|
||||
|
||||
data = config.DATA_DIR
|
||||
paths = (data, *(data / n for n in ("zhiwu.db", "zhiwu.db-wal", "zhiwu.db-shm", "avatars", "cards", "submissions")))
|
||||
for p in paths:
|
||||
if bad(p):
|
||||
raise RuntimeError(f"{p} 不能讀寫。目前用 UID:GID {who} 執行,請先 chown -R {who} 掛到 /data 的資料夾")
|
||||
if bad(config.MEME_DIR):
|
||||
print(f"[WARN] {config.MEME_DIR} 不能讀寫,圖庫或投稿會失敗。請 chown -R {who} 掛到 /memes 的資料夾", flush=True)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
check_storage()
|
||||
db.init()
|
||||
if not config.SMTP_USER or not config.SMTP_PASSWORD:
|
||||
print("[WARN] SMTP_USER / SMTP_PASSWORD 沒有設定:不會寄信,驗證碼只印在 log([DEV] verify code ...)",
|
||||
@@ -41,7 +59,7 @@ async def guard(request: Request, call_next):
|
||||
# 防 CSRF:會改資料的 /api 請求要帶 X-ZHIWU: 1(跨站表單帶不了自訂 header)。
|
||||
# 用 Bearer token 的客戶端(Android)沒有 cookie,不受 CSRF 影響,所以不檢查。
|
||||
if (request.method in ("POST", "PUT", "PATCH", "DELETE")
|
||||
and request.url.path.startswith("/api/")
|
||||
and request.scope["path"].startswith("/api/")
|
||||
and request.headers.get("x-zhiwu") != "1"
|
||||
and not request.headers.get("authorization")):
|
||||
return JSONResponse({"detail": "csrf"}, status_code=403)
|
||||
@@ -55,13 +73,15 @@ async def guard(request: Request, call_next):
|
||||
response.headers.setdefault("X-Content-Type-Options", "nosniff")
|
||||
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
response.headers.setdefault("Content-Security-Policy", CSP)
|
||||
if request.url.path.startswith("/assets/"):
|
||||
if request.scope["path"].startswith("/assets/"):
|
||||
# 沒有這行時 Cloudflare 會自己快取 .js / .css,改版後使用者拿到舊檔。
|
||||
# no-cache = 每次向伺服器確認,沒變就回 304
|
||||
response.headers.setdefault("Cache-Control", "no-cache")
|
||||
return response
|
||||
|
||||
|
||||
app.add_middleware(limits.BodyLimit) # 最後加的在最外層
|
||||
|
||||
for module in (auth, users, checkin, card, share, submissions, notices):
|
||||
app.include_router(module.router)
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@ router = APIRouter()
|
||||
PAGE_SIZE = 50
|
||||
|
||||
|
||||
def add(kind: str, uid: int | None = None, detail: str = "") -> None:
|
||||
"""自己開一條連線;不要在交易裡呼叫(會等自己的寫入鎖)。"""
|
||||
def add(kind: str, uid: int | None = None, detail: str = "", merge: bool = True) -> None:
|
||||
"""自己開一條連線;不要在交易裡呼叫(會等自己的寫入鎖)。merge=False = 每次都是新的一則。"""
|
||||
try:
|
||||
conn = db.connect()
|
||||
try:
|
||||
@@ -28,8 +28,8 @@ def add(kind: str, uid: int | None = None, detail: str = "") -> None:
|
||||
cur = conn.execute(
|
||||
"UPDATE notices SET count = count + 1, updated_at = ?, read_at = NULL "
|
||||
"WHERE kind = ? AND uid IS ? AND detail = ? AND updated_at > ?",
|
||||
(now, kind, uid, detail, now - config.NOTICE_MERGE))
|
||||
if cur.rowcount == 0:
|
||||
(now, kind, uid, detail, now - config.NOTICE_MERGE)) if merge else None
|
||||
if cur is None or cur.rowcount == 0:
|
||||
conn.execute(
|
||||
"INSERT INTO notices(kind, uid, detail, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",
|
||||
(kind, uid, detail, now, now))
|
||||
|
||||
+10
-12
@@ -15,9 +15,9 @@ from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, File, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from PIL import Image, ImageOps
|
||||
from PIL import Image
|
||||
|
||||
from . import clock, config
|
||||
from . import clock, config, images, limits
|
||||
from .db import get_db, transaction
|
||||
from .deps import admin_user, current_user, fail
|
||||
from .titles import badge, fmt_uid
|
||||
@@ -39,15 +39,7 @@ def pending_path(row: sqlite3.Row) -> Path:
|
||||
|
||||
def process_meme(data: bytes) -> tuple[bytes, str]:
|
||||
"""重新編碼成 JPEG(有透明度就用 PNG):去掉 EXIF(含 GPS)和偽裝成圖片的內容,GIF 只取第一格。"""
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as im:
|
||||
im.seek(0)
|
||||
im.load()
|
||||
im = ImageOps.exif_transpose(im)
|
||||
has_alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info)
|
||||
im = im.convert("RGBA" if has_alpha else "RGB")
|
||||
except Exception:
|
||||
fail(400, "invalid_image")
|
||||
im, has_alpha = images.decode(data)
|
||||
if max(im.size) > config.SUBMIT_MAX_SIDE:
|
||||
im.thumbnail((config.SUBMIT_MAX_SIDE, config.SUBMIT_MAX_SIDE), Image.LANCZOS)
|
||||
out = io.BytesIO()
|
||||
@@ -104,12 +96,18 @@ def pending_count(conn: sqlite3.Connection) -> int:
|
||||
|
||||
# ---------- 使用者 ----------
|
||||
|
||||
_upload_hits = limits.Window("SUBMIT_LIMIT", "UPLOAD_WINDOW")
|
||||
|
||||
|
||||
@router.post("/api/submissions")
|
||||
def upload(file: UploadFile = File(...), user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
|
||||
if not _upload_hits.allow(user["uid"]):
|
||||
fail(429, "too_frequent")
|
||||
data = file.file.read(config.SUBMIT_MAX_BYTES + 1)
|
||||
if len(data) > config.SUBMIT_MAX_BYTES:
|
||||
fail(413, "file_too_large")
|
||||
body, ext = process_meme(data) # 先處理圖片,不佔用寫入鎖
|
||||
with images.slot():
|
||||
body, ext = process_meme(data) # 先處理圖片,不佔用寫入鎖
|
||||
day = clock.today()
|
||||
submission_dir().mkdir(parents=True, exist_ok=True)
|
||||
# BEGIN IMMEDIATE:同時上傳好幾張也不會超過額度;寫檔失敗會連同 INSERT 一起還原
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ def code_at(key: bytes, step: int) -> str:
|
||||
|
||||
def verify(secret: str, code: str, unix_time: int, window: int = 1) -> int | None:
|
||||
"""比對前後各 window 個時間窗(容忍手機時鐘誤差),成功回傳符合的時間步。"""
|
||||
if len(code) != DIGITS or not code.isdigit():
|
||||
if len(code) != DIGITS or not code.isascii() or not code.isdigit():
|
||||
return None
|
||||
key = decode_secret(secret)
|
||||
current = unix_time // PERIOD
|
||||
|
||||
+9
-11
@@ -11,7 +11,7 @@ from markdown_it import MarkdownIt
|
||||
from PIL import Image, ImageOps
|
||||
from pydantic import BaseModel
|
||||
|
||||
from . import card, clock, config, notices
|
||||
from . import card, clock, config, images, limits, notices
|
||||
from .checkin import stats
|
||||
from .db import get_db, transaction
|
||||
from .deps import admin_user, current_user, fail, optional_user
|
||||
@@ -139,15 +139,7 @@ def patch_me(body: ProfilePatch, user=Depends(current_user), conn: sqlite3.Conne
|
||||
|
||||
def process_avatar(data: bytes) -> bytes:
|
||||
"""置中裁成正方形、縮成 1024×1024、重新編成 WebP(順便去掉 EXIF 與偽裝成圖片的內容)。"""
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as im:
|
||||
im.seek(0)
|
||||
im.load()
|
||||
im = ImageOps.exif_transpose(im)
|
||||
has_alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info)
|
||||
im = im.convert("RGBA" if has_alpha else "RGB")
|
||||
except Exception:
|
||||
fail(400, "invalid_image")
|
||||
im, _ = images.decode(data)
|
||||
size = config.AVATAR_SIZE
|
||||
im = ImageOps.fit(im, (size, size), Image.LANCZOS)
|
||||
out = io.BytesIO()
|
||||
@@ -155,13 +147,19 @@ def process_avatar(data: bytes) -> bytes:
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
_avatar_hits = limits.Window("AVATAR_LIMIT", "UPLOAD_WINDOW")
|
||||
|
||||
|
||||
@router.put("/api/me/avatar")
|
||||
def put_avatar(file: UploadFile = File(...), user=Depends(current_user),
|
||||
conn: sqlite3.Connection = Depends(get_db)):
|
||||
if not _avatar_hits.allow(user["uid"]):
|
||||
fail(429, "too_frequent")
|
||||
data = file.file.read(config.AVATAR_MAX_BYTES + 1)
|
||||
if len(data) > config.AVATAR_MAX_BYTES:
|
||||
fail(413, "file_too_large")
|
||||
webp = process_avatar(data)
|
||||
with images.slot():
|
||||
webp = process_avatar(data)
|
||||
folder = config.DATA_DIR / "avatars"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
|
||||
|
||||
Reference in new issue
Block a user