This commit is contained in:
Sahik committed 2026-11-22 18:38:53 +08:00
commit 21851bf8c5
61 files changed
+5260

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
# Pillow 畫小卡需要中日韓字型(NotoSansCJK-Regular/Bold.ttc)
RUN apt-get update \
&& apt-get install -y --no-install-recommends fonts-noto-cjk \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY server/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY server/app ./app
COPY web ./web
ENV DATA_DIR=/data MEME_DIR=/memes WEB_DIR=/app/web
EXPOSE 2040
# SQLite 與記憶體裡的限流都假設只有一個 worker
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "2040", "--workers", "1"]
View File
Whitespace-only changes.
+159
View File
@@ -0,0 +1,159 @@
"""管理指令(在容器裡執行):
docker compose exec zhiwuproject python -m app.admin info <email>
docker compose exec zhiwuproject python -m app.admin grant-uid <email> 777
docker compose exec zhiwuproject python -m app.admin set-title <uid> --title 稱號 --color '#ff8a1f' # --clear 清除
docker compose exec zhiwuproject python -m app.admin test-mail <email>
docker compose exec zhiwuproject python -m app.admin unlock # 解除管理員登入鎖定
docker compose exec zhiwuproject python -m app.admin totp-uri # 印出 Aegis 用的 otpauth:// 連結
docker compose exec zhiwuproject python -m app.admin reset-progress --yes # 清空簽到進度與吱吱次數
"""
import argparse
import os
import shutil
import sqlite3
import sys
from datetime import datetime
from . import card, config, db, totp
from .titles import fmt_uid
def cmd_info(args):
conn = db.connect()
row = conn.execute("SELECT * FROM users WHERE email = ?", (args.email.strip().lower(),)).fetchone()
if row is None:
sys.exit("找不到這個信箱")
days = conn.execute("SELECT COUNT(*) FROM checkins WHERE uid = ?", (row["uid"],)).fetchone()[0]
print(f"uid={fmt_uid(row['uid'])} name={row['display_name']} lang={row['lang']} checkins={days}")
next_uid = conn.execute("SELECT value FROM meta WHERE key = 'next_uid'").fetchone()[0]
print(f"next_uid={next_uid}")
def cmd_set_title(args):
"""指定某個 UID 的顏色與稱號;--clear 清除。網頁上管理員也可以在個人頁設定。"""
from .titles import DEFAULT_TITLE_COLOR, valid_color
from . import card
title, color = ("", "") if args.clear else (args.title.strip(), args.color.strip().lower())
if len(title) > config.TITLE_MAX:
sys.exit(f"稱號最多 {config.TITLE_MAX} 個字")
if color and not valid_color(color):
sys.exit("顏色要寫成 #rrggbb,例如 #ff8a1f")
if title and not color:
color = DEFAULT_TITLE_COLOR
conn = db.connect()
cur = conn.execute("UPDATE users SET title = ?, title_color = ? WHERE uid = ?", (title, color, args.uid))
if cur.rowcount == 0:
sys.exit("找不到這個 UID")
card.invalidate(args.uid)
print(f"uid={fmt_uid(args.uid)} title={title!r} color={color or '-'}")
def cmd_grant_uid(args):
"""把某個帳號的 UID 換成指定號碼(1–99999999,例如 777)。不會影響之後的依序給號。"""
conn = db.connect()
email = args.email.strip().lower()
new_uid = args.uid
if not 1 <= new_uid <= config.UID_MAX:
sys.exit(f"UID 要在 1–{config.UID_MAX} 之間(0 是管理員)")
with db.transaction(conn):
row = conn.execute("SELECT uid FROM users WHERE email = ?", (email,)).fetchone()
if row is None:
sys.exit("找不到這個信箱")
if conn.execute("SELECT 1 FROM users WHERE uid = ?", (new_uid,)).fetchone():
sys.exit(f"UID {new_uid} 已經有人使用")
old_uid = row["uid"]
if old_uid == config.ADMIN_UID:
sys.exit("不能改管理員的 UID")
# sessions、checkins 是 ON UPDATE CASCADE,會一起改
conn.execute("UPDATE users SET uid = ? WHERE uid = ?", (new_uid, old_uid))
old_av = config.DATA_DIR / "avatars" / f"{old_uid}.webp"
if old_av.exists():
os.replace(old_av, config.DATA_DIR / "avatars" / f"{new_uid}.webp")
card.invalidate(old_uid)
print(f"{email}: UID {fmt_uid(old_uid)} -> {fmt_uid(new_uid)}")
def cmd_test_mail(args):
"""實際寄一封測試信,失敗時印出 SMTP 的錯誤訊息。"""
from . import mailer
print(f"SMTP {config.SMTP_HOST}:{config.SMTP_PORT} user={config.SMTP_USER or '(empty)'} "
f"password={'(set)' if config.SMTP_PASSWORD else '(empty)'} from={config.MAIL_FROM}")
if not config.SMTP_USER or not config.SMTP_PASSWORD:
sys.exit("SMTP_USER / SMTP_PASSWORD 沒有設定,不會寄信。改好 .env 後執行 docker compose up -d")
try:
mailer.send_code(args.email, "123456", args.lang)
except Exception as e:
sys.exit(f"寄送失敗:{type(e).__name__}: {e}")
print(f"SMTP 伺服器已收下,寄到 {args.email}(驗證碼 123456 只是測試用)")
def cmd_unlock(args):
conn = db.connect()
for key in ("admin_fails", "admin_lock_level", "admin_lock_until"):
db.set_meta(conn, key, 0)
print("管理員登入已解除鎖定")
def cmd_totp_uri(args):
if not config.ADMIN_LOGIN or not config.ADMIN_TOTP:
sys.exit("ADMIN_LOGIN / ADMIN_TOTP 沒有設定")
print(totp.uri(config.ADMIN_TOTP, config.ADMIN_LOGIN))
def cmd_reset_progress(args):
"""清空所有簽到紀錄與小卡(Beta 結束、正式上線時用)。帳號、UID、名稱、大頭貼、自介都保留。"""
conn = db.connect()
checkins = conn.execute("SELECT COUNT(*) FROM checkins").fetchone()[0]
users = conn.execute("SELECT COUNT(DISTINCT uid) FROM checkins").fetchone()[0]
print(f"會刪除 {checkins} 筆簽到紀錄({users} 個帳號)、所有吱吱次數與小卡;帳號、UID、名稱、大頭貼、自介保留")
if not args.yes:
print("沒有做任何變更。確定要執行請加上 --yes")
return
backup = config.DATA_DIR / f"zhiwu.db.bak-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
dst = sqlite3.connect(backup)
conn.backup(dst)
dst.close()
conn.execute("DELETE FROM checkins")
conn.execute("UPDATE users SET clicks = 0")
shutil.rmtree(config.DATA_DIR / "cards", ignore_errors=True)
(config.DATA_DIR / "cards").mkdir(exist_ok=True)
print(f"完成。備份在 {backup}")
def main(argv=None):
p = argparse.ArgumentParser(prog="python -m app.admin")
sub = p.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("info", help="查看帳號")
s.add_argument("email")
s.set_defaults(func=cmd_info)
s = sub.add_parser("grant-uid", help="指定 UID")
s.add_argument("email")
s.add_argument("uid", type=int)
s.set_defaults(func=cmd_grant_uid)
s = sub.add_parser("set-title", help="指定 UID 的顏色與稱號")
s.add_argument("uid", type=int)
s.add_argument("--title", default="")
s.add_argument("--color", default="", help="#rrggbb")
s.add_argument("--clear", action="store_true", help="清除稱號與顏色")
s.set_defaults(func=cmd_set_title)
s = sub.add_parser("test-mail", help="寄一封測試信")
s.add_argument("email")
s.add_argument("--lang", default=config.DEFAULT_LANG)
s.set_defaults(func=cmd_test_mail)
s = sub.add_parser("unlock", help="解除管理員登入鎖定")
s.set_defaults(func=cmd_unlock)
s = sub.add_parser("totp-uri", help="印出 Aegis 用的 otpauth:// 連結")
s.set_defaults(func=cmd_totp_uri)
s = sub.add_parser("reset-progress", help="清空所有簽到進度(保留帳號)")
s.add_argument("--yes", action="store_true", help="確定執行")
s.set_defaults(func=cmd_reset_progress)
args = p.parse_args(argv)
db.init()
args.func(args)
if __name__ == "__main__":
main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

+192
View File
@@ -0,0 +1,192 @@
"""信箱驗證碼登入(沒有密碼):第一次驗證成功就自動建立帳號。
管理員:信箱欄輸入 ADMIN_LOGIN,驗證碼是 Aegis 算的 TOTP(不寄信)。錯 3 次就全域鎖定,時間逐次加倍。
"""
import re
import secrets
import sqlite3
import threading
import time
from collections import defaultdict, deque
from fastapi import APIRouter, Depends, Request, Response
from pydantic import BaseModel
from . import clock, config, db, mailer, 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
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()
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 norm_email(email: str) -> str:
email = email.strip().lower()
if len(email) > 254 or not EMAIL_RE.match(email):
fail(400, "invalid_email")
return email
class CodeRequest(BaseModel):
email: str
lang: str = config.DEFAULT_LANG
class VerifyRequest(BaseModel):
email: str
code: str
lang: str = config.DEFAULT_LANG
@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,))
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)):
fail(429, "too_many_requests")
# secrets 才是密碼學安全的亂數
code = f"{secrets.randbelow(10**6):06d}"
conn.execute(
"INSERT INTO login_codes(email, code_hash, attempts, expires_at, last_sent_at) VALUES (?, ?, 0, ?, ?) "
"ON CONFLICT(email) DO UPDATE SET code_hash = excluded.code_hash, attempts = 0, "
"expires_at = excluded.expires_at, last_sent_at = excluded.last_sent_at",
(email, sha256(code), now + config.CODE_TTL, now),
)
try:
mailer.send_code(email, code, norm_lang(body.lang))
except Exception as e:
print("Error sending email:", e, flush=True)
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
fail(502, "send_failed")
return sent
def admin_check(conn: sqlite3.Connection, code: str, ip: str) -> str | None:
"""比對管理員 TOTP。成功回傳 None,失敗回傳錯誤代碼。
計數寫在交易裡,同時送出多個請求也不會多猜幾次。"""
now = clock.ts()
with transaction(conn):
if now < get_meta(conn, "admin_lock_until"):
return "too_many_requests"
step = totp.verify(config.ADMIN_TOTP, code, now)
if step is not None and step <= get_meta(conn, "admin_last_step"):
# 碼是對的但用過了(例如登出後馬上用同一組再登入):拒絕,但不算猜錯、不計入鎖定。
# 拿得到正確的碼才會發生,不是暴力猜碼
return "code_used"
if step is not None:
set_meta(conn, "admin_fails", 0)
set_meta(conn, "admin_lock_level", 0)
set_meta(conn, "admin_last_step", step)
print(f"[ADMIN] login from {ip}", flush=True)
return None
fails = get_meta(conn, "admin_fails") + 1
print(f"[ADMIN] login failed from {ip} ({fails}/{config.ADMIN_MAX_FAILS})", flush=True)
if fails < config.ADMIN_MAX_FAILS:
set_meta(conn, "admin_fails", fails)
return "wrong_code"
level = get_meta(conn, "admin_lock_level")
lock = min(config.ADMIN_LOCK_BASE * 2 ** level, config.ADMIN_LOCK_MAX)
set_meta(conn, "admin_fails", 0)
set_meta(conn, "admin_lock_level", level + 1)
set_meta(conn, "admin_lock_until", now + lock)
print(f"[ADMIN] locked for {lock // 60} min", flush=True)
return "too_many_requests"
def issue_session(conn: sqlite3.Connection, response: Response, user: sqlite3.Row) -> dict:
now = clock.ts()
ttl = config.ADMIN_SESSION_TTL if user["uid"] == config.ADMIN_UID else config.SESSION_TTL
token = secrets.token_urlsafe(32)
conn.execute("DELETE FROM sessions WHERE expires_at < ?", (now,))
conn.execute(
"INSERT INTO sessions(token_hash, uid, created_at, expires_at) VALUES (?, ?, ?, ?)",
(sha256(token), user["uid"], now, now + ttl),
)
response.set_cookie(
config.COOKIE_NAME, token, max_age=ttl,
httponly=True, secure=config.COOKIE_SECURE, samesite="lax", path="/",
)
# token 也放在 JSON,之後 Android 用 Authorization: Bearer <token>
return {"token": token, "user": profile(conn, user, user["lang"], private=True)}
@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()
row = conn.execute("SELECT * FROM login_codes WHERE email = ?", (email,)).fetchone()
if row is None:
fail(400, "not_requested")
if row["expires_at"] < now:
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
fail(400, "expired")
# 錯太多次直接作廢,防止暴力猜碼
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,))
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,))
user = create_user(conn, email, body.lang)
return issue_session(conn, response, user)
@router.post("/api/auth/logout")
def logout(request: Request, response: Response, user=Depends(current_user),
conn: sqlite3.Connection = Depends(get_db)):
token = session_token(request)
if token:
conn.execute("DELETE FROM sessions WHERE token_hash = ?", (sha256(token),))
response.delete_cookie(config.COOKIE_NAME, path="/")
return {"status": "ok"}
+225
View File
@@ -0,0 +1,225 @@
"""用 Pillow 畫吱吱小卡(1080×1350 PNG),第一次被請求時才畫,之後快取在 /data/cards/<uid>/。
小卡上有吱吱(點擊)次數,所以快取檔名帶次數:<day>.v<版本>.c<次數>.png,次數變了就重畫。
"""
import os
import re
import shutil
import sqlite3
import tempfile
from functools import lru_cache
from pathlib import Path
from urllib.parse import urlparse
from fastapi import APIRouter, Depends
from fastapi.responses import FileResponse
from PIL import Image, ImageDraw, ImageFont, ImageOps
from . import config
from .checkin import stats
from .db import get_db
from .deps import fail
from .i18n import norm_lang, t
from .titles import badge_colors, fmt_uid
Image.MAX_IMAGE_PIXELS = 40_000_000 # 擋解壓縮炸彈
router = APIRouter()
W, H = 1080, 1350
PAD = 48
ACCENT = (255, 138, 31)
TEXT = (255, 246, 234)
MUTED = (217, 185, 147)
INK = (42, 20, 0)
DEFAULT_MEME = Path(__file__).resolve().parent / "assets" / "default-meme.jpg"
CARD_VERSION = 1 # 版面改了就加 1,舊的快取自動作廢
DAY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
# Debian 套件 fonts-noto-cjk;同一個 .ttc 裡依序是 JP、KR、SC、TC、HK
NOTO_DIR = Path("/usr/share/fonts/opentype/noto")
NOTO_INDEX = {"ja": 0, "ko": 1, "zh-CN": 2, "zh-TW": 3, "en": 0}
# 本機(Windows)開發用的備援字型
WIN_FONTS = {
"zh-TW": ["msjh.ttc", "NotoSansTC-VF.ttf"],
"zh-CN": ["msyh.ttc", "NotoSansSC-VF.ttf", "msjh.ttc"],
"ja": ["YuGothB.ttc", "YuGothR.ttc", "meiryo.ttc"],
"ko": ["malgunbd.ttf", "malgun.ttf"],
"en": ["YuGothB.ttc", "msjh.ttc", "NotoSansTC-VF.ttf"],
}
def _font_candidates(lang: str, bold: bool):
env = config.FONT_BOLD if bold else config.FONT_REGULAR
if env:
yield env, 0
yield str(NOTO_DIR / ("NotoSansCJK-Bold.ttc" if bold else "NotoSansCJK-Regular.ttc")), NOTO_INDEX[lang]
for name in WIN_FONTS[lang]:
yield os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts", name), 0
@lru_cache(maxsize=64)
def font(lang: str, size: int, bold: bool = False) -> ImageFont.FreeTypeFont:
for path, index in _font_candidates(lang, bold):
if os.path.exists(path):
try:
return ImageFont.truetype(path, size, index=index)
except OSError:
continue
return ImageFont.load_default(size)
def fit_text(draw: ImageDraw.ImageDraw, text: str, fnt, max_w: int) -> str:
if draw.textlength(text, font=fnt) <= max_w:
return text
while text and draw.textlength(text + "…", font=fnt) > max_w:
text = text[:-1]
return text + "…"
def rounded_mask(size, radius) -> Image.Image:
mask = Image.new("L", size, 0)
ImageDraw.Draw(mask).rounded_rectangle((0, 0, size[0] - 1, size[1] - 1), radius, fill=255)
return mask
def load_image(path: Path) -> Image.Image | None:
try:
with Image.open(path) as im:
im.seek(0) # gif 只取第一幀
im = ImageOps.exif_transpose(im)
return im.convert("RGB")
except Exception:
return None
def render(user: sqlite3.Row, day: str, meme: str | None, total: int, streak: int, clicks: int) -> Image.Image:
lang = norm_lang(user["lang"])
uid = user["uid"]
# 背景:上下漸層
img = Image.new("RGB", (W, H))
top, bottom = (70, 38, 12), (24, 13, 5)
d = ImageDraw.Draw(img)
for y in range(H):
k = y / (H - 1)
d.line([(0, y), (W, y)], fill=tuple(int(a + (b - a) * k) for a, b in zip(top, bottom)))
# 梗圖
box_w, box_h = W - 2 * PAD, 760
panel = Image.new("RGB", (box_w, box_h), (18, 10, 4))
pic = load_image(config.MEME_DIR / meme) if meme else None
pic = pic or load_image(DEFAULT_MEME) # 圖庫是空的(或圖被刪了)就用預設圖
if pic:
pic = ImageOps.contain(pic, (box_w, box_h), Image.LANCZOS)
panel.paste(pic, ((box_w - pic.width) // 2, (box_h - pic.height) // 2))
else:
pd = ImageDraw.Draw(panel)
f = font(lang, 48)
msg = t(lang, "card.no_meme")
pd.text((box_w / 2, box_h / 2), msg, font=f, fill=MUTED, anchor="mm")
img.paste(panel, (PAD, PAD), rounded_mask(panel.size, 28))
# 大頭貼
av_size, av_y = 168, PAD + box_h + 40
avatar = None
if user["avatar_ver"]:
avatar = load_image(config.DATA_DIR / "avatars" / f"{uid}.webp")
if avatar:
avatar = avatar.resize((av_size, av_size), Image.LANCZOS)
else:
avatar = Image.new("RGB", (av_size, av_size), ACCENT)
ad = ImageDraw.Draw(avatar)
initial = (user["display_name"] or "?")[0]
ad.text((av_size / 2, av_size / 2), initial, font=font(lang, 84, True), fill=INK, anchor="mm")
circle = Image.new("L", (av_size, av_size), 0)
ImageDraw.Draw(circle).ellipse((0, 0, av_size - 1, av_size - 1), fill=255)
img.paste(avatar, (PAD, av_y), circle)
# 名稱、UID、稱號(管理員指定的顏色或預設的特殊序號用背景色標示)
tx = PAD + av_size + 32
max_w = W - PAD - tx
f_name = font(lang, 54, True)
d.text((tx, av_y + 14), fit_text(d, user["display_name"], f_name, max_w), font=f_name, fill=TEXT)
uid_text = f"UID {fmt_uid(uid)}"
colors = badge_colors(user)
uid_y = av_y + 120 # UID 這一行的垂直中心
if colors:
bg, fg = colors
f_uid = font("en", 36, True)
tw = d.textlength(uid_text, font=f_uid)
d.rounded_rectangle((tx, uid_y - 28, tx + tw + 36, uid_y + 28), 14, fill=bg)
d.text((tx + 18, uid_y), uid_text, font=f_uid, fill=fg, anchor="lm")
if user["title"]: # 稱號:接在 UID 後面,同樣的顏色
x = tx + tw + 36 + 16
f_title = font(lang, 36, True)
title = fit_text(d, user["title"], f_title, int(W - PAD - x - 36))
ttw = d.textlength(title, font=f_title)
d.rounded_rectangle((x, uid_y - 28, x + ttw + 36, uid_y + 28), 14, fill=bg)
d.text((x + 18, uid_y), title, font=f_title, fill=fg, anchor="lm")
else:
d.text((tx, uid_y), uid_text, font=font("en", 36), fill=MUTED, anchor="lm")
# 左:簽到天數、連續天數;右:吱吱次數(兩個數字各自獨立)
line_y = av_y + av_size + 36
d.line([(PAD, line_y), (W - PAD, line_y)], fill=(110, 72, 36), width=2)
f_num = font("en", 92, True)
num = f"{clicks:,}"
num_w = d.textlength(num, font=f_num)
d.text((W - PAD, line_y + 24), num, font=f_num, fill=ACCENT, anchor="ra")
d.text((W - PAD, line_y + 148), t(lang, "card.clicks"), font=font(lang, 36), fill=MUTED, anchor="ra")
f_day = font(lang, 92, True)
d.text((PAD, line_y + 24), fit_text(d, t(lang, "card.day", n=total), f_day, int(W - 2 * PAD - num_w - 40)),
font=f_day, fill=TEXT)
sub = f"{t(lang, 'card.streak', n=streak)} · {day}"
d.text((PAD, line_y + 148), sub, font=font(lang, 36), fill=MUTED)
host = urlparse(config.PUBLIC_URL).netloc or config.PUBLIC_URL
footer = f"{host} · Beta" if config.BETA else host
d.text((W - PAD, H - PAD), footer, font=font("en", 30, True), fill=ACCENT, anchor="rs")
return img
def card_dir(uid: int) -> Path:
return config.DATA_DIR / "cards" / str(uid)
def invalidate(uid: int) -> None:
"""名稱、大頭貼、語言改了之後,舊的小卡重畫。"""
shutil.rmtree(card_dir(uid), ignore_errors=True)
def card_path(conn: sqlite3.Connection, uid: int, day: str) -> Path | None:
row = conn.execute("SELECT meme FROM checkins WHERE uid = ? AND day = ?", (uid, day)).fetchone()
if row is None:
return None
user = conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone()
folder = card_dir(uid)
path = folder / f"{day}.v{CARD_VERSION}.c{user['clicks']}.png"
if path.exists():
return path
total, streak = stats(conn, uid, day)
img = render(user, day, row["meme"], total, streak, user["clicks"])
folder.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
with os.fdopen(fd, "wb") as f:
img.save(f, "PNG", optimize=True)
os.replace(tmp, path)
# 同一天舊次數的小卡不會再用到
for old in folder.glob(f"{day}.v*.png"):
if old != path:
try:
old.unlink()
except OSError:
pass # Windows 上別的請求正在讀,下次再刪
return path
@router.get("/card/{uid}/{day}.png")
def get_card(uid: int, day: str, conn: sqlite3.Connection = Depends(get_db)):
if not DAY_RE.match(day):
fail(404, "not_found")
path = card_path(conn, uid, day)
if path is None:
fail(404, "not_found")
return FileResponse(path, media_type="image/png", headers={"Cache-Control": "public, max-age=60"})
+133
View File
@@ -0,0 +1,133 @@
import secrets
import sqlite3
import time
from datetime import date, timedelta
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from . import clock, config
from .db import get_db, transaction
from .deps import current_user, fail
from .i18n import t
from .titles import fmt_uid
router = APIRouter()
MEME_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
def list_memes() -> list[str]:
if not config.MEME_DIR.is_dir():
return []
return sorted(
p.name for p in config.MEME_DIR.iterdir()
if p.is_file() and p.suffix.lower() in MEME_EXTS and not p.name.startswith(".")
)
def pick_meme() -> str | None:
memes = list_memes()
return secrets.choice(memes) if memes else None
def stats(conn: sqlite3.Connection, uid: int, upto: str | None = None, *, live: bool = False) -> tuple[int, int]:
"""回傳 (累計天數, 連續天數),只算 upto(含)以前的簽到。
live=True 用在個人資料:今天還沒簽到時,昨天以前的連續紀錄仍然算數。
"""
upto = upto or clock.today()
days = [r[0] for r in conn.execute(
"SELECT day FROM checkins WHERE uid = ? AND day <= ? ORDER BY day DESC", (uid, upto))]
expected = date.fromisoformat(upto)
if live and days and days[0] != upto:
expected -= timedelta(days=1)
streak = 0
for d in days:
if d != expected.isoformat():
break
streak += 1
expected -= timedelta(days=1)
return len(days), streak
def card_urls(uid: int, day: str) -> dict:
return {
# 前端會自己加 ?c=<吱吱次數>,次數變了就抓新的小卡
"card_url": f"/card/{fmt_uid(uid)}/{day}.png",
"share_url": f"{config.PUBLIC_URL}/c/{fmt_uid(uid)}/{day}",
}
def today_payload(conn: sqlite3.Connection, user: sqlite3.Row, day: str, already: bool | None = None) -> dict:
checked = conn.execute(
"SELECT 1 FROM checkins WHERE uid = ? AND day = ?", (user["uid"], day)).fetchone() is not None
total, streak = stats(conn, user["uid"], day, live=True)
clicks = conn.execute("SELECT clicks FROM users WHERE uid = ?", (user["uid"],)).fetchone()[0]
out = {
"day": day,
"checked_in": checked,
"total_days": total,
"streak": streak,
"clicks": clicks,
"next_reset": clock.next_reset().isoformat(),
}
if already is not None:
out["already"] = already
if checked:
out.update(card_urls(user["uid"], day))
out["share_text"] = t(user["lang"], "share.text", n=total)
return out
@router.post("/api/checkin")
def do_checkin(user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
day = clock.today() # 只取一次,避免剛好跨過換日時前後不一致
with transaction(conn):
# PRIMARY KEY(uid, day) 擋重複簽到:同時送出兩次也只會寫入一筆
cur = conn.execute(
"INSERT INTO checkins(uid, day, meme, created_at) VALUES (?, ?, ?, ?) "
"ON CONFLICT(uid, day) DO NOTHING",
(user["uid"], day, pick_meme(), clock.ts()),
)
already = cur.rowcount == 0
if not already:
# 簽到那一下也算一次吱吱
conn.execute("UPDATE users SET clicks = clicks + 1 WHERE uid = ?", (user["uid"],))
return today_payload(conn, user, day, already=already)
# ---------- 繼續吱吱:只加點擊次數,和簽到天數無關 ----------
_now = time.monotonic # 測試會換掉
_buckets: dict[int, tuple[float, float]] = {} # uid -> (剩餘額度, 上次更新時間)
def _take(uid: int, n: int) -> int:
"""token bucket:回傳這次實際可以加幾下(超過速率的部分直接丟掉)。"""
now = _now()
tokens, last = _buckets.get(uid, (float(config.ZHI_BURST), now))
tokens = min(float(config.ZHI_BURST), tokens + (now - last) * config.ZHI_RATE)
ok = min(n, int(tokens))
_buckets[uid] = (tokens - ok, now)
return ok
class ZhiIn(BaseModel):
n: int = 1
@router.post("/api/zhi")
def do_zhi(body: ZhiIn, user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
if not 1 <= body.n <= config.ZHI_BATCH_MAX:
fail(400, "bad_request")
added = _take(user["uid"], body.n)
if added:
conn.execute("UPDATE users SET clicks = clicks + ? WHERE uid = ?", (added, user["uid"]))
clicks = conn.execute("SELECT clicks FROM users WHERE uid = ?", (user["uid"],)).fetchone()[0]
return {"clicks": clicks, "added": added}
@router.get("/api/checkin/today")
def get_today(user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
return today_payload(conn, user, clock.today())
+27
View File
@@ -0,0 +1,27 @@
"""時間集中在這裡,測試只要 monkeypatch `clock.now` 就能模擬換日。"""
from datetime import datetime, timedelta, timezone
from . import config
def now() -> datetime:
return datetime.now(timezone.utc)
def ts() -> int:
return int(now().timestamp())
def today() -> str:
"""簽到日:台灣時間 04:00 換日,格式 YYYY-MM-DD。"""
local = now().astimezone(config.TZ) - timedelta(hours=config.DAY_START_HOUR)
return local.date().isoformat()
def next_reset() -> datetime:
"""下一個台灣時間 04:00(帶時區,前端換算成裝置時間)。"""
local = now().astimezone(config.TZ)
reset = local.replace(hour=config.DAY_START_HOUR, minute=0, second=0, microsecond=0)
if local >= reset:
reset += timedelta(days=1)
return reset
+82
View File
@@ -0,0 +1,82 @@
"""環境變數設定。其他模組一律用 `config.X` 取值(測試會直接改這裡的屬性)。"""
import os
from pathlib import Path
from zoneinfo import ZoneInfo
# 每日簽到的分界:台灣時間 04:00(程式一律明確用這個時區,不依賴容器的 TZ)
TZ = ZoneInfo("Asia/Taipei")
DAY_START_HOUR = 4
LANGS = ("zh-TW", "zh-CN", "ja", "ko", "en")
DEFAULT_LANG = "zh-TW"
_HERE = Path(__file__).resolve().parent
def _default_web_dir() -> Path:
# Docker 裡是 /app/web;本機開發是 <repo>/web
for p in (_HERE.parent / "web", _HERE.parent.parent / "web"):
if p.is_dir():
return p
return _HERE.parent / "web"
def _default_meme_dir() -> Path:
return _HERE.parent.parent / "image"
DATA_DIR = Path(os.environ.get("DATA_DIR", "/data"))
MEME_DIR = Path(os.environ.get("MEME_DIR") or _default_meme_dir())
WEB_DIR = Path(os.environ.get("WEB_DIR") or _default_web_dir())
PUBLIC_URL = os.environ.get("PUBLIC_URL", "http://127.0.0.1:2040").rstrip("/")
COOKIE_SECURE = os.environ.get("COOKIE_SECURE", "0") == "1"
# Beta 期間:網頁標題加 (Beta)、小卡右下角加 · Beta。正式上線設 BETA=0
BETA = os.environ.get("BETA", "0") == "1"
# 寄信用的 SMTP。預設 Gmail(帳號 + 應用程式密碼);換成其他寄信服務只要改這幾個值
SMTP_HOST = os.environ.get("SMTP_HOST") or "smtp.gmail.com"
SMTP_PORT = int(os.environ.get("SMTP_PORT") or 465) # 465 = SSL;587 = STARTTLS
SMTP_USER = os.environ.get("SMTP_USER", "")
SMTP_PASSWORD = os.environ.get("SMTP_PASSWORD", "")
MAIL_FROM = os.environ.get("MAIL_FROM") or "[email protected]"
# 小卡字型;沒設定時依序找 Noto Sans CJK(Docker)→ Windows 內建字型 → Pillow 預設字型
FONT_REGULAR = os.environ.get("FONT_REGULAR", "")
FONT_BOLD = os.environ.get("FONT_BOLD", "")
CODE_TTL = 5 * 60 # 驗證碼有效 5 分鐘
CODE_RESEND = 60 # 同一信箱 60 秒內不能重寄
CODE_MAX_ATTEMPTS = 5 # 錯 5 次作廢
IP_LIMIT = 10 # 同一 IP 10 分鐘最多寄 10 次
IP_WINDOW = 10 * 60
SESSION_TTL = 90 * 24 * 3600
ADMIN_SESSION_TTL = 7 * 24 * 3600
# 管理員:信箱欄輸入 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
ADMIN_MAX_FAILS = 3 # 錯 3 次就鎖
ADMIN_LOCK_BASE = 15 * 60 # 第一次鎖 15 分,之後每次加倍
ADMIN_LOCK_MAX = 24 * 3600
UID_MAX = 99_999_999 # UID 顯示成 8 碼
NAME_MAX = 32
TITLE_MAX = 16 # 管理員指定的稱號長度上限
BIO_MAX = 2000
AVATAR_MAX_BYTES = 5 * 1024 * 1024
AVATAR_SIZE = 1024
# 使用者投稿迷因圖:每個帳號每天(04:00 換日)最多 5 張,被拒絕的也算
SUBMIT_PER_DAY = 5
SUBMIT_MAX_BYTES = 5 * 1024 * 1024 # 和大頭貼一樣,錯誤訊息寫的是 5MB
SUBMIT_MAX_SIDE = 2048 # 長邊超過就等比例縮小
# 繼續吱吱:一個帳號一秒只能吱一次(token bucket,額度最多存 1 下,所以兩下之間至少隔 1 秒)
ZHI_BATCH_MAX = 200 # 一次請求的 n 上限(超過直接拒絕);實際加幾下由下面兩個值決定
ZHI_RATE = 1 # 每秒補充幾下
ZHI_BURST = 1 # 最多累積幾下
COOKIE_NAME = "zhiwu_session"
+170
View File
@@ -0,0 +1,170 @@
import sqlite3
import time
from contextlib import contextmanager
from . import config
# init() 檢查管理員設定後填入;False 時管理員登入完全停用
admin_ok = False
SCHEMA = """
CREATE TABLE IF NOT EXISTS meta (
key TEXT PRIMARY KEY,
value INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS users (
uid INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL,
bio_md TEXT NOT NULL DEFAULT '',
lang TEXT NOT NULL,
avatar_ver INTEGER NOT NULL DEFAULT 0,
clicks INTEGER NOT NULL DEFAULT 0, -- 吱吱(點擊)總次數,和簽到天數分開算
title TEXT NOT NULL DEFAULT '', -- 管理員指定的稱號(空字串 = 沒有)
title_color TEXT NOT NULL DEFAULT '', -- 管理員指定的 UID 底色 #rrggbb(空字串 = 沒有)
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS login_codes (
email TEXT PRIMARY KEY COLLATE NOCASE,
code_hash TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
expires_at INTEGER NOT NULL,
last_sent_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token_hash TEXT PRIMARY KEY,
uid INTEGER NOT NULL REFERENCES users(uid) ON DELETE CASCADE ON UPDATE CASCADE,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS sessions_uid ON sessions(uid);
CREATE TABLE IF NOT EXISTS checkins (
uid INTEGER NOT NULL REFERENCES users(uid) ON DELETE CASCADE ON UPDATE CASCADE,
day TEXT NOT NULL,
meme TEXT,
created_at INTEGER NOT NULL,
PRIMARY KEY (uid, day)
);
-- 使用者投稿的迷因圖。待審的檔案在 DATA_DIR/submissions/<id>.<ext>,同意後搬進迷因資料夾
CREATE TABLE IF NOT EXISTS submissions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uid INTEGER NOT NULL REFERENCES users(uid) ON DELETE CASCADE ON UPDATE CASCADE,
day TEXT NOT NULL, -- 上傳當天(clock.today()),算每日額度用
ext TEXT NOT NULL, -- jpg / png
status TEXT NOT NULL DEFAULT 'pending', -- pending / approved / rejected
meme TEXT, -- 同意後的檔名,例如 zhiwu_14.jpg
created_at INTEGER NOT NULL,
reviewed_at INTEGER
);
CREATE INDEX IF NOT EXISTS submissions_uid_day ON submissions(uid, day);
CREATE INDEX IF NOT EXISTS submissions_status ON submissions(status, id);
"""
def db_path():
return config.DATA_DIR / "zhiwu.db"
def connect() -> sqlite3.Connection:
# isolation_level=None:自動 commit,需要交易時自己下 BEGIN
conn = sqlite3.connect(db_path(), isolation_level=None, timeout=10, check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA busy_timeout = 10000")
return conn
def init():
config.DATA_DIR.mkdir(parents=True, exist_ok=True)
(config.DATA_DIR / "avatars").mkdir(exist_ok=True)
(config.DATA_DIR / "cards").mkdir(exist_ok=True)
(config.DATA_DIR / "submissions").mkdir(exist_ok=True)
conn = connect()
try:
conn.execute("PRAGMA journal_mode = WAL")
conn.executescript(SCHEMA)
conn.execute("INSERT OR IGNORE INTO meta(key, value) VALUES ('next_uid', 1)")
_migrate(conn)
_init_admin(conn)
finally:
conn.close()
# 後來才加的 users 欄位:舊的資料庫(CREATE TABLE IF NOT EXISTS 不會補欄位)啟動時自動補上
_USER_COLUMNS = {
"clicks": "INTEGER NOT NULL DEFAULT 0",
"title": "TEXT NOT NULL DEFAULT ''",
"title_color": "TEXT NOT NULL DEFAULT ''",
}
def _migrate(conn: sqlite3.Connection) -> None:
have = {r[1] for r in conn.execute("PRAGMA table_info(users)")}
for name, decl in _USER_COLUMNS.items():
if name not in have:
conn.execute(f"ALTER TABLE users ADD COLUMN {name} {decl}")
def _init_admin(conn: sqlite3.Connection) -> None:
"""建立或更新管理員帳號(uid 0)。改了 ADMIN_LOGIN 重啟就會生效。"""
global admin_ok
from . import totp
admin_ok = False
login, secret = config.ADMIN_LOGIN, config.ADMIN_TOTP
if not login or not secret:
return
try:
if len(totp.decode_secret(secret)) < 10:
raise ValueError("too short")
except Exception:
print("[ERROR] ADMIN_TOTP 不是合法的 base32 密鑰(至少 16 個字元),管理員登入停用", flush=True)
return
clash = conn.execute("SELECT uid FROM users WHERE email = ? AND uid != ?",
(login, config.ADMIN_UID)).fetchone()
if clash:
print(f"[ERROR] ADMIN_LOGIN 和 UID {clash[0]} 的信箱相同,管理員登入停用", flush=True)
return
conn.execute(
"INSERT INTO users(uid, email, display_name, lang, created_at) VALUES (?, ?, ?, ?, ?) "
"ON CONFLICT(uid) DO UPDATE SET email = excluded.email",
(config.ADMIN_UID, login, "管理員", config.DEFAULT_LANG, int(time.time())),
)
admin_ok = True
def get_meta(conn: sqlite3.Connection, key: str, default: int = 0) -> int:
row = conn.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone()
return row[0] if row else default
def set_meta(conn: sqlite3.Connection, key: str, value: int) -> None:
conn.execute("INSERT INTO meta(key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value", (key, value))
def get_db():
"""FastAPI dependency:每個請求一條連線。"""
conn = connect()
try:
yield conn
finally:
conn.close()
@contextmanager
def transaction(conn: sqlite3.Connection):
"""BEGIN IMMEDIATE:一開始就拿寫入鎖,避免兩個請求同時給號。"""
conn.execute("BEGIN IMMEDIATE")
try:
yield conn
except BaseException:
conn.execute("ROLLBACK")
raise
else:
conn.execute("COMMIT")
+52
View File
@@ -0,0 +1,52 @@
"""共用的 dependency:錯誤格式、session 驗證、取得使用者 IP。"""
import hashlib
import sqlite3
from fastapi import Depends, HTTPException, Request
from . import clock, config
from .db import get_db
def fail(status: int, code: str):
"""錯誤一律回 {"detail": "<code>"},前端用 err.<code> 翻譯。"""
raise HTTPException(status_code=status, detail=code)
def sha256(s: str) -> str:
return hashlib.sha256(s.encode()).hexdigest()
def client_ip(request: Request) -> str:
# port 只綁 127.0.0.1,外部流量都經過 cloudflared,所以可以信任 CF-Connecting-IP
return request.headers.get("cf-connecting-ip") or (request.client.host if request.client else "?")
def session_token(request: Request) -> str | None:
auth = request.headers.get("authorization", "")
if auth.lower().startswith("bearer "):
return auth[7:].strip() or None
return request.cookies.get(config.COOKIE_NAME)
def optional_user(request: Request, conn: sqlite3.Connection = Depends(get_db)) -> sqlite3.Row | None:
token = session_token(request)
if not token:
return None
return conn.execute(
"SELECT u.* FROM sessions s JOIN users u ON u.uid = s.uid "
"WHERE s.token_hash = ? AND s.expires_at > ?",
(sha256(token), clock.ts()),
).fetchone()
def current_user(user: sqlite3.Row | None = Depends(optional_user)) -> sqlite3.Row:
if user is None:
fail(401, "unauthorized")
return user
def admin_user(user: sqlite3.Row = Depends(current_user)) -> sqlite3.Row:
if user["uid"] != config.ADMIN_UID:
fail(403, "forbidden")
return user
+25
View File
@@ -0,0 +1,25 @@
"""伺服器端文字(信件、小卡、頭銜、分享文字)。前端介面文字在 web/i18n。"""
import json
from functools import lru_cache
from pathlib import Path
from .. import config
_DIR = Path(__file__).resolve().parent
@lru_cache(maxsize=None)
def _load(lang: str) -> dict:
with open(_DIR / f"{lang}.json", encoding="utf-8") as f:
return json.load(f)
def norm_lang(lang) -> str:
return lang if lang in config.LANGS else config.DEFAULT_LANG
def t(lang: str, key: str, **kw) -> str:
text = _load(norm_lang(lang)).get(key)
if text is None:
text = _load("en").get(key, key)
return text.format(**kw) if kw else text
+11
View File
@@ -0,0 +1,11 @@
{
"mail.subject": "Your 吱鼯計畫 code: {code}",
"mail.body": "Your 吱鼯計畫 verification code is:\n\n{code}\n\nIt expires in 5 minutes. If you didn't request this, you can ignore this email.\n\n{url}",
"card.day": "Day {n}",
"card.streak": "{n}-day streak",
"card.no_meme": "Meme coming soon",
"share.text": "Day {n} of squeaking on 吱鼯計畫. Have you squeaked today?",
"share.title": "{name}'s squeak card",
"share.open": "Let me squeak too",
"card.clicks": "squeaks"
}
+11
View File
@@ -0,0 +1,11 @@
{
"mail.subject": "吱鼯計畫 認証コード:{code}",
"mail.body": "吱鼯計畫 の認証コードは:\n\n{code}\n\n有効期限は 5 分です。お心当たりのない場合は、このメールを破棄してください。\n\n{url}",
"card.day": "ログイン {n} 日目",
"card.streak": "連続 {n} 日",
"card.no_meme": "画像準備中",
"share.text": "吱鼯計畫でチューチュー {n} 日目!今日はもうチューチューした?",
"share.title": "{name} のチューチューカード",
"share.open": "自分もチューチューする",
"card.clicks": "チューチュー回数"
}
+11
View File
@@ -0,0 +1,11 @@
{
"mail.subject": "吱鼯計畫 인증 코드: {code}",
"mail.body": "吱鼯計畫 인증 코드는:\n\n{code}\n\n5분 동안 유효합니다. 본인이 요청하지 않았다면 이 메일을 무시해 주세요.\n\n{url}",
"card.day": "출석 {n}일째",
"card.streak": "연속 {n}일",
"card.no_meme": "이미지 준비 중",
"share.text": "吱鼯計畫에서 찍찍 {n}일째! 오늘 찍찍 했어?",
"share.title": "{name}의 찍찍 카드",
"share.open": "나도 찍찍하기",
"card.clicks": "찍찍 횟수"
}
+11
View File
@@ -0,0 +1,11 @@
{
"mail.subject": "吱鼯計畫 验证码:{code}",
"mail.body": "你的 吱鼯計畫 验证码是:\n\n{code}\n\n5 分钟内有效。如果这不是你本人的操作,请直接忽略这封邮件。\n\n{url}",
"card.day": "签到第 {n} 天",
"card.streak": "连续 {n} 天",
"card.no_meme": "梗图准备中",
"share.text": "我在吱鼯計畫吱吱了 {n} 天,你今天吱吱了吗?",
"share.title": "{name} 的吱吱小卡",
"share.open": "我也要吱吱",
"card.clicks": "吱吱次数"
}
+11
View File
@@ -0,0 +1,11 @@
{
"mail.subject": "吱鼯計畫 驗證碼:{code}",
"mail.body": "你的 吱鼯計畫 驗證碼是:\n\n{code}\n\n5 分鐘內有效。如果這不是你本人的操作,請直接忽略這封信。\n\n{url}",
"card.day": "簽到第 {n} 天",
"card.streak": "連續 {n} 天",
"card.no_meme": "梗圖準備中",
"share.text": "我在吱鼯計畫吱吱了 {n} 天,你今天吱吱了嗎?",
"share.title": "{name} 的吱吱小卡",
"share.open": "我也要吱吱",
"card.clicks": "吱吱次數"
}
+36
View File
@@ -0,0 +1,36 @@
"""寄送驗證碼。改寫自 RhyculatorServer/Verify_email/main.py 的 send_email(),改成通用 SMTP。
寄信是容器主動連出去(smtp.gmail.com:465 等),不經過 cloudflared tunnel,不用額外開 port。
"""
import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr, make_msgid
from . import config
from .i18n import t
def send_code(to_email: str, code: str, lang: str) -> None:
# 本地開發沒有設定 SMTP 帳密時,直接把驗證碼印在 log
if not config.SMTP_USER or not config.SMTP_PASSWORD:
print(f"[DEV] verify code for {to_email}: {code}", flush=True)
return
msg = EmailMessage()
msg["Subject"] = t(lang, "mail.subject", code=code)
# Gmail:MAIL_FROM 要先在「以這個地址寄送郵件」加入別名,否則 Gmail 會改回帳號本身
msg["From"] = formataddr(("吱鼯計畫", config.MAIL_FROM))
msg["To"] = to_email
msg["Message-ID"] = make_msgid(domain=config.MAIL_FROM.rpartition("@")[2] or None)
msg.set_content(t(lang, "mail.body", code=code, url=config.PUBLIC_URL))
ctx = ssl.create_default_context()
if config.SMTP_PORT == 465:
smtp = smtplib.SMTP_SSL(config.SMTP_HOST, config.SMTP_PORT, timeout=15, context=ctx)
else:
smtp = smtplib.SMTP(config.SMTP_HOST, config.SMTP_PORT, timeout=15)
smtp.starttls(context=ctx)
with smtp:
smtp.login(config.SMTP_USER, config.SMTP_PASSWORD)
smtp.send_message(msg)
+92
View File
@@ -0,0 +1,92 @@
import hashlib
import mimetypes
from contextlib import asynccontextmanager
from functools import lru_cache
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from . import auth, card, checkin, config, db, 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"),
("image/svg+xml", ".svg"), ("image/x-icon", ".ico")):
mimetypes.add_type(_type, _ext)
CSP = ("default-src 'self'; img-src 'self' data: blob:; media-src 'self'; style-src 'self' 'unsafe-inline'; "
"script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
@asynccontextmanager
async def lifespan(app: FastAPI):
db.init()
if not config.SMTP_USER or not config.SMTP_PASSWORD:
print("[WARN] SMTP_USER / SMTP_PASSWORD 沒有設定:不會寄信,驗證碼只印在 log([DEV] verify code ...)",
flush=True)
else:
print(f"[mail] {config.SMTP_USER}@{config.SMTP_HOST}:{config.SMTP_PORT}, from {config.MAIL_FROM}", flush=True)
yield
app = FastAPI(title="吱鼯計畫", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
@app.middleware("http")
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.headers.get("x-zhiwu") != "1"
and not request.headers.get("authorization")):
return JSONResponse({"detail": "csrf"}, status_code=403)
response = await call_next(request)
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/"):
# 沒有這行時 Cloudflare 會自己快取 .js / .css,改版後使用者拿到舊檔。
# no-cache = 每次向伺服器確認,沒變就回 304
response.headers.setdefault("Cache-Control", "no-cache")
return response
for module in (auth, users, checkin, card, share, submissions):
app.include_router(module.router)
@app.get("/healthz")
def healthz():
return {"status": "ok"}
@lru_cache(maxsize=1)
def asset_version() -> str:
"""web/ 底下所有檔案內容的雜湊。檔案一改,網址的 ?v= 就變,Cloudflare 和瀏覽器都會抓新的。"""
h = hashlib.sha256()
for p in sorted(config.WEB_DIR.rglob("*")):
if p.is_file():
h.update(p.relative_to(config.WEB_DIR).as_posix().encode())
h.update(p.read_bytes())
return h.hexdigest()[:10]
def index():
html = (config.WEB_DIR / "index.html").read_text(encoding="utf-8")
html = html.replace("__ASSET_VERSION__", asset_version())
html = html.replace("<!--BETA_TITLE-->", " (Beta)" if config.BETA else "")
html = html.replace("<!--BETA_BADGE-->", ' <small class="beta">(Beta)</small>' if config.BETA else "")
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
@app.get("/favicon.ico", include_in_schema=False)
def favicon():
return FileResponse(config.WEB_DIR / "favicon.ico", headers={"Cache-Control": "public, max-age=86400"})
app.add_api_route("/", index, methods=["GET", "HEAD"], include_in_schema=False)
app.add_api_route("/u/{uid}", index, methods=["GET", "HEAD"], include_in_schema=False)
app.add_api_route("/upload", index, methods=["GET", "HEAD"], include_in_schema=False)
app.add_api_route("/review", index, methods=["GET", "HEAD"], include_in_schema=False)
app.mount("/assets", StaticFiles(directory=config.WEB_DIR, check_dir=False), name="assets")
+73
View File
@@ -0,0 +1,73 @@
"""分享頁 /c/<uid>/<day>:有 og:image,貼到 Discord、X、LINE 會出現小卡預覽。"""
import sqlite3
from html import escape
from fastapi import APIRouter, Depends
from fastapi.responses import HTMLResponse
from . import config
from .card import DAY_RE
from .checkin import stats
from .db import get_db
from .deps import fail
from .i18n import norm_lang, t
from .titles import fmt_uid
router = APIRouter()
PAGE = """<!DOCTYPE html>
<html lang="{lang}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title} · {site}</title>
<meta property="og:type" content="website">
<meta property="og:site_name" content="{site}">
<meta property="og:title" content="{title}">
<meta property="og:description" content="{desc}">
<meta property="og:image" content="{image}">
<meta property="og:image:width" content="1080">
<meta property="og:image:height" content="1350">
<meta property="og:url" content="{url}">
<meta name="twitter:card" content="summary_large_image">
<link rel="icon" href="/favicon.ico" sizes="48x48">
<link rel="icon" href="/assets/icon-192.png" type="image/png" sizes="192x192">
<link rel="apple-touch-icon" href="/assets/apple-touch-icon.png">
<style>
body {{ margin: 0; min-height: 100vh; display: flex; flex-direction: column; align-items: center;
justify-content: center; gap: 24px; background: #1a0f06; color: #fff6ea;
font-family: system-ui, "Noto Sans CJK TC", sans-serif; padding: 24px; box-sizing: border-box; }}
img {{ width: min(540px, 100%); border-radius: 16px; box-shadow: 0 12px 40px #0008; }}
a {{ background: #ff8a1f; color: #2a1400; padding: 12px 28px; border-radius: 999px;
text-decoration: none; font-weight: 700; }}
</style>
</head>
<body>
<img src="{image_path}" alt="{title}">
<a href="/">{open}</a>
</body>
</html>"""
@router.get("/c/{uid}/{day}", response_class=HTMLResponse)
def share_page(uid: int, day: str, conn: sqlite3.Connection = Depends(get_db)):
if not DAY_RE.match(day):
fail(404, "not_found")
user = conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone()
if user is None or conn.execute(
"SELECT 1 FROM checkins WHERE uid = ? AND day = ?", (uid, day)).fetchone() is None:
fail(404, "not_found")
lang = norm_lang(user["lang"])
total, _ = stats(conn, uid, day)
# ?c= 讓吱吱次數變了之後,預覽圖的網址也跟著變(小卡有 10 分鐘快取)
image_path = f"/card/{fmt_uid(uid)}/{day}.png?c={user['clicks']}"
return PAGE.format(
lang=lang,
site="吱鼯計畫 (Beta)" if config.BETA else "吱鼯計畫",
title=escape(t(lang, "share.title", name=user["display_name"])),
desc=escape(t(lang, "share.text", n=total)),
image=escape(config.PUBLIC_URL + image_path),
image_path=image_path,
url=escape(f"{config.PUBLIC_URL}/c/{fmt_uid(uid)}/{day}"),
open=escape(t(lang, "share.open")),
)
+216
View File
@@ -0,0 +1,216 @@
"""使用者投稿迷因圖,管理員審核。
流程:使用者上傳 → 重新編碼後存在 DATA_DIR/submissions/<id>.<ext>(pending)
→ 管理員同意:依 image/ 的命名規則存成 MEME_DIR/zhiwu_<下一號>.<ext>,之後的小卡就可能抽到
→ 管理員拒絕:刪掉檔案,紀錄保留(每日額度要算)
"""
import io
import os
import re
import shutil
import sqlite3
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from fastapi import APIRouter, Depends, File, UploadFile
from fastapi.responses import FileResponse
from PIL import Image, ImageOps
from . import clock, config
from .db import get_db, transaction
from .deps import admin_user, current_user, fail
from .titles import badge, fmt_uid
router = APIRouter()
MEME_NAME = re.compile(r"^zhiwu_(\d+)\.[A-Za-z0-9]+$")
MEDIA_TYPES = {"jpg": "image/jpeg", "png": "image/png", "jpeg": "image/jpeg",
"webp": "image/webp", "gif": "image/gif"}
def submission_dir() -> Path:
return config.DATA_DIR / "submissions"
def pending_path(row: sqlite3.Row) -> Path:
return submission_dir() / f"{row['id']}.{row['ext']}"
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")
if max(im.size) > config.SUBMIT_MAX_SIDE:
im.thumbnail((config.SUBMIT_MAX_SIDE, config.SUBMIT_MAX_SIDE), Image.LANCZOS)
out = io.BytesIO()
if has_alpha:
im.save(out, "PNG", optimize=True)
return out.getvalue(), "png"
im.save(out, "JPEG", quality=90, optimize=True)
return out.getvalue(), "jpg"
def write_atomic(path: Path, data: bytes) -> None:
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".", suffix=".tmp")
try:
with os.fdopen(fd, "wb") as f:
f.write(data)
os.replace(tmp, path)
except BaseException:
Path(tmp).unlink(missing_ok=True)
raise
def next_meme_number() -> int:
"""迷因資料夾裡 zhiwu_<n>.* 的最大編號 + 1。"""
nums = [int(m.group(1)) for p in config.MEME_DIR.iterdir() if (m := MEME_NAME.match(p.name))] \
if config.MEME_DIR.is_dir() else []
return max(nums, default=-1) + 1
def iso(ts: int | None) -> str | None:
return datetime.fromtimestamp(ts, timezone.utc).isoformat() if ts else None
def image_url(row: sqlite3.Row) -> str | None:
return None if row["status"] == "rejected" else f"/api/submissions/{row['id']}/image"
def used_today(conn: sqlite3.Connection, uid: int, day: str) -> int:
return conn.execute("SELECT COUNT(*) FROM submissions WHERE uid = ? AND day = ?", (uid, day)).fetchone()[0]
def quota(conn: sqlite3.Connection, uid: int) -> dict:
used = used_today(conn, uid, clock.today())
return {"used": used, "limit": config.SUBMIT_PER_DAY, "remaining": max(0, config.SUBMIT_PER_DAY - used)}
def item(row: sqlite3.Row) -> dict:
return {"id": row["id"], "status": row["status"], "created_at": iso(row["created_at"]),
"image_url": image_url(row)}
def pending_count(conn: sqlite3.Connection) -> int:
return conn.execute("SELECT COUNT(*) FROM submissions WHERE status = 'pending'").fetchone()[0]
# ---------- 使用者 ----------
@router.post("/api/submissions")
def upload(file: UploadFile = File(...), user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
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) # 先處理圖片,不佔用寫入鎖
day = clock.today()
submission_dir().mkdir(parents=True, exist_ok=True)
# BEGIN IMMEDIATE:同時上傳好幾張也不會超過額度;寫檔失敗會連同 INSERT 一起還原
with transaction(conn):
if used_today(conn, user["uid"], day) >= config.SUBMIT_PER_DAY:
fail(429, "quota_exceeded")
cur = conn.execute("INSERT INTO submissions(uid, day, ext, created_at) VALUES (?, ?, ?, ?)",
(user["uid"], day, ext, clock.ts()))
row = conn.execute("SELECT * FROM submissions WHERE id = ?", (cur.lastrowid,)).fetchone()
write_atomic(pending_path(row), body)
return {"item": item(row), **quota(conn, user["uid"])}
@router.get("/api/submissions")
def my_submissions(user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
rows = conn.execute("SELECT * FROM submissions WHERE uid = ? ORDER BY id DESC LIMIT 30", (user["uid"],))
return {**quota(conn, user["uid"]), "items": [item(r) for r in rows]}
@router.get("/api/submissions/{sid}/image")
def submission_image(sid: int, user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
row = conn.execute("SELECT * FROM submissions WHERE id = ?", (sid,)).fetchone()
# 只有上傳者本人和管理員看得到;別人一律當作不存在
if row is None or (row["uid"] != user["uid"] and user["uid"] != config.ADMIN_UID):
fail(404, "not_found")
if row["status"] == "pending":
path = pending_path(row)
elif row["status"] == "approved" and row["meme"]:
path = config.MEME_DIR / row["meme"]
else:
fail(404, "not_found")
if not path.is_file():
fail(404, "not_found")
ext = path.suffix.lower().lstrip(".")
return FileResponse(path, media_type=MEDIA_TYPES.get(ext, "application/octet-stream"),
headers={"Cache-Control": "private, max-age=3600"})
# ---------- 管理員審核 ----------
@router.get("/api/admin/submissions")
def next_pending(admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
"""最舊的一張待審投稿(一張一張審)。"""
row = conn.execute(
"SELECT s.*, u.display_name, u.title, u.title_color FROM submissions s JOIN users u ON u.uid = s.uid "
"WHERE s.status = 'pending' ORDER BY s.id LIMIT 1").fetchone()
left = pending_count(conn)
if row is None:
return {"item": None, "pending": left}
return {
"item": {
**item(row),
"uploader": {"uid": row["uid"], "uid_str": fmt_uid(row["uid"]), **badge(row),
"display_name": row["display_name"]},
},
"pending": left,
}
def _load_pending(conn: sqlite3.Connection, sid: int) -> sqlite3.Row:
row = conn.execute("SELECT * FROM submissions WHERE id = ?", (sid,)).fetchone()
if row is None:
fail(404, "not_found")
if row["status"] != "pending":
fail(409, "already_reviewed")
return row
@router.post("/api/admin/submissions/{sid}/approve")
def approve(sid: int, admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
with transaction(conn): # 寫入鎖確保兩次同意不會拿到同一個編號
row = _load_pending(conn, sid)
src = pending_path(row)
if not src.is_file():
fail(404, "not_found")
config.MEME_DIR.mkdir(parents=True, exist_ok=True)
n = next_meme_number()
while any(config.MEME_DIR.glob(f"zhiwu_{n}.*")):
n += 1
name = f"zhiwu_{n}.{row['ext']}"
# 先複製成 . 開頭的暫存檔(抽卡會略過),完整寫好再改名
fd, tmp = tempfile.mkstemp(dir=config.MEME_DIR, prefix=".", suffix=".tmp")
os.close(fd)
try:
shutil.copyfile(src, tmp)
os.replace(tmp, config.MEME_DIR / name)
except BaseException:
Path(tmp).unlink(missing_ok=True)
raise
conn.execute("UPDATE submissions SET status = 'approved', meme = ?, reviewed_at = ? WHERE id = ?",
(name, clock.ts(), sid))
src.unlink(missing_ok=True)
print(f"[review] approved #{sid} from UID {fmt_uid(row['uid'])} -> {name}", flush=True)
return {"id": sid, "status": "approved", "meme": name, "pending": pending_count(conn)}
@router.post("/api/admin/submissions/{sid}/reject")
def reject(sid: int, admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
with transaction(conn):
row = _load_pending(conn, sid)
conn.execute("UPDATE submissions SET status = 'rejected', reviewed_at = ? WHERE id = ?", (clock.ts(), sid))
pending_path(row).unlink(missing_ok=True)
print(f"[review] rejected #{sid} from UID {fmt_uid(row['uid'])}", flush=True)
return {"id": sid, "status": "rejected", "pending": pending_count(conn)}
+58
View File
@@ -0,0 +1,58 @@
"""UID 的底色與稱號。
- 管理員(UID 0)預設黃底
- 管理員可以幫任何 UID 指定一個顏色和一個稱號(users.title / users.title_color),會蓋過預設
都只是顯示用,不帶任何權限。顯示的地方:側欄、個人頁、審核頁、小卡。
"""
import re
import sqlite3
from . import config
# 預設的特殊序號:底色、文字色(網頁的 web/style.css .uid.tier-* 用同樣的顏色)
TIER_COLORS = {
"admin": ((255, 209, 102), (42, 20, 0)), # 黃 #FFD166
}
DEFAULT_TITLE_COLOR = "#ff8a1f" # 只給稱號沒給顏色時用主色
_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$")
_INK, _WHITE = (42, 20, 0), (255, 255, 255)
def fmt_uid(uid: int) -> str:
return f"{uid:08d}"
def uid_tier(uid: int) -> str | None:
return "admin" if uid == config.ADMIN_UID else None
def valid_color(color: str) -> bool:
return bool(_COLOR_RE.match(color))
def hex_rgb(color: str) -> tuple[int, int, int]:
return tuple(int(color[i:i + 2], 16) for i in (1, 3, 5))
def text_on(rgb: tuple[int, int, int]) -> tuple[int, int, int]:
"""底色上要用深色字還是白字(依亮度)。前端 web/app.js 的 textOn() 用同一條公式。"""
r, g, b = rgb
return _INK if (r * 299 + g * 587 + b * 114) / 1000 >= 150 else _WHITE
def badge(user: sqlite3.Row) -> dict:
"""API 回傳用:uid_tier(預設樣式)、title(稱號)、title_color(指定的顏色,#rrggbb 或 None)。"""
return {
"uid_tier": uid_tier(user["uid"]),
"title": user["title"],
"title_color": user["title_color"] or None,
}
def badge_colors(user: sqlite3.Row) -> tuple[tuple, tuple] | None:
"""小卡用:(底色, 文字色);沒有特殊樣式回 None。指定的顏色優先於預設。"""
if user["title_color"]:
bg = hex_rgb(user["title_color"])
return bg, text_on(bg)
tier = uid_tier(user["uid"])
return TIER_COLORS[tier] if tier else None
+40
View File
@@ -0,0 +1,40 @@
"""RFC 6238 TOTP(SHA1、6 碼、30 秒),和 Aegis / Google Authenticator 預設相同。只用標準函式庫。"""
import base64
import hashlib
import hmac
import struct
from urllib.parse import quote
PERIOD = 30
DIGITS = 6
def decode_secret(secret: str) -> bytes:
s = secret.replace(" ", "").upper()
return base64.b32decode(s + "=" * (-len(s) % 8))
def code_at(key: bytes, step: int) -> str:
digest = hmac.new(key, struct.pack(">Q", step), hashlib.sha1).digest()
offset = digest[-1] & 0x0F
value = struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7FFFFFFF
return f"{value % 10**DIGITS:0{DIGITS}d}"
def verify(secret: str, code: str, unix_time: int, window: int = 1) -> int | None:
"""比對前後各 window 個時間窗(容忍手機時鐘誤差),成功回傳符合的時間步。"""
if len(code) != DIGITS or not code.isdigit():
return None
key = decode_secret(secret)
current = unix_time // PERIOD
matched = None
for step in range(current - window, current + window + 1):
# 全部比完,不提早結束,避免從回應時間猜出哪個時間窗符合
if hmac.compare_digest(code_at(key, step), code) and matched is None:
matched = step
return matched
def uri(secret: str, account: str, issuer: str = "吱鼯計畫") -> str:
label = quote(f"{issuer}:{account}")
return f"otpauth://totp/{label}?secret={secret.replace(' ', '').upper()}&issuer={quote(issuer)}"
+229
View File
@@ -0,0 +1,229 @@
import io
import os
import sqlite3
import tempfile
import unicodedata
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, File, Query, UploadFile
from fastapi.responses import FileResponse
from markdown_it import MarkdownIt
from PIL import Image, ImageOps
from pydantic import BaseModel
from . import card, clock, config
from .checkin import stats
from .db import get_db, transaction
from .deps import admin_user, current_user, fail
from .i18n import norm_lang
from .titles import DEFAULT_TITLE_COLOR, badge, fmt_uid, valid_color
router = APIRouter()
# 關閉原始 HTML(輸入的 <script> 會被跳脫)與圖片(避免追蹤用的外部圖片)
_md = MarkdownIt("commonmark", {"html": False, "breaks": True}).enable(["table", "strikethrough"]).disable("image")
def _link_open(self, tokens, idx, options, env):
# add_render_rule 會把函式綁到 renderer 上,所以第一個參數是 self
tokens[idx].attrSet("rel", "nofollow noopener noreferrer")
tokens[idx].attrSet("target", "_blank")
return self.renderToken(tokens, idx, options, env)
_md.add_render_rule("link_open", _link_open)
def render_md(text: str) -> str:
return _md.render(text or "")
# ---------- 帳號建立與 UID 給號 ----------
def create_user(conn: sqlite3.Connection, email: str, lang: str) -> sqlite3.Row:
"""依序給號(從 1 開始;0 是管理員)。不用 AUTOINCREMENT:SQLite 會從現有最大 uid 往後給,
一旦有人被 grant-uid 指定成很大的號碼,之後的號碼就會全部跳過去。"""
with transaction(conn):
row = conn.execute("SELECT * FROM users WHERE email = ?", (email,)).fetchone()
if row:
return row
uid = conn.execute("SELECT value FROM meta WHERE key = 'next_uid'").fetchone()[0]
# 跳過已經被 grant-uid 指定出去的號碼
while conn.execute("SELECT 1 FROM users WHERE uid = ?", (uid,)).fetchone():
uid += 1
if uid > config.UID_MAX:
fail(503, "uid_exhausted")
conn.execute(
"INSERT INTO users(uid, email, display_name, lang, created_at) VALUES (?, ?, ?, ?, ?)",
(uid, email, f"吱鼯_{uid}", norm_lang(lang), clock.ts()),
)
conn.execute("UPDATE meta SET value = ? WHERE key = 'next_uid'", (uid + 1,))
return conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone()
# ---------- 個人資料 ----------
def avatar_url(user: sqlite3.Row) -> str | None:
return f"/avatars/{fmt_uid(user['uid'])}.webp?v={user['avatar_ver']}" if user["avatar_ver"] else None
def profile(conn: sqlite3.Connection, user: sqlite3.Row, lang: str, private: bool = False) -> dict:
total, streak = stats(conn, user["uid"], live=True)
out = {
"uid": user["uid"],
"uid_str": fmt_uid(user["uid"]),
"display_name": user["display_name"],
**badge(user),
"bio_md": user["bio_md"],
"bio_html": render_md(user["bio_md"]),
"avatar_url": avatar_url(user),
"total_days": total,
"streak": streak,
"clicks": user["clicks"],
"created_at": datetime.fromtimestamp(user["created_at"], timezone.utc).isoformat(),
}
if private:
out["email"] = user["email"]
out["lang"] = user["lang"]
out["is_admin"] = user["uid"] == config.ADMIN_UID
if out["is_admin"]:
out["pending_reviews"] = conn.execute(
"SELECT COUNT(*) FROM submissions WHERE status = 'pending'").fetchone()[0]
return out
def clean_name(name: str) -> str:
# 去掉換行等控制字元
name = "".join(ch for ch in name if unicodedata.category(ch) != "Cc").strip()
if not 1 <= len(name) <= config.NAME_MAX:
fail(400, "name_invalid")
return name
class ProfilePatch(BaseModel):
display_name: str | None = None
bio_md: str | None = None
lang: str | None = None
@router.get("/api/me")
def get_me(user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
return profile(conn, user, user["lang"], private=True)
@router.patch("/api/me")
def patch_me(body: ProfilePatch, user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
fields = {}
if body.display_name is not None:
fields["display_name"] = clean_name(body.display_name)
if body.bio_md is not None:
bio = body.bio_md.replace("\r\n", "\n")
if len(bio) > config.BIO_MAX:
fail(400, "bio_too_long")
fields["bio_md"] = bio
if body.lang is not None:
if body.lang not in config.LANGS:
fail(400, "invalid_lang")
fields["lang"] = body.lang
if fields:
sets = ", ".join(f"{k} = ?" for k in fields)
conn.execute(f"UPDATE users SET {sets} WHERE uid = ?", (*fields.values(), user["uid"]))
if {"display_name", "lang"} & fields.keys():
card.invalidate(user["uid"])
user = conn.execute("SELECT * FROM users WHERE uid = ?", (user["uid"],)).fetchone()
return profile(conn, user, user["lang"], private=True)
# ---------- 大頭貼 ----------
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")
size = config.AVATAR_SIZE
im = ImageOps.fit(im, (size, size), Image.LANCZOS)
out = io.BytesIO()
im.save(out, "WEBP", quality=90, method=4)
return out.getvalue()
@router.put("/api/me/avatar")
def put_avatar(file: UploadFile = File(...), user=Depends(current_user),
conn: sqlite3.Connection = Depends(get_db)):
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)
folder = config.DATA_DIR / "avatars"
folder.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
with os.fdopen(fd, "wb") as f:
f.write(webp)
os.replace(tmp, folder / f"{user['uid']}.webp")
conn.execute("UPDATE users SET avatar_ver = ? WHERE uid = ?", (clock.ts(), user["uid"]))
card.invalidate(user["uid"])
user = conn.execute("SELECT * FROM users WHERE uid = ?", (user["uid"],)).fetchone()
return profile(conn, user, user["lang"], private=True)
@router.get("/avatars/{uid}.webp")
def get_avatar(uid: int):
path = config.DATA_DIR / "avatars" / f"{uid}.webp"
if not path.exists():
fail(404, "not_found")
return FileResponse(path, media_type="image/webp", headers={"Cache-Control": "public, max-age=86400"})
# ---------- 公開資料 ----------
@router.get("/api/users/{uid}")
def get_user(uid: int, lang: str = Query(config.DEFAULT_LANG), conn: sqlite3.Connection = Depends(get_db)):
user = conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone()
if user is None:
fail(404, "user_not_found")
return profile(conn, user, lang)
# ---------- 管理員:指定 UID 的顏色與稱號 ----------
class TitleIn(BaseModel):
title: str = ""
color: str = ""
@router.put("/api/admin/users/{uid}/title")
def set_title(uid: int, body: TitleIn, admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
"""稱號和顏色都留空 = 清除。只給稱號沒給顏色時用主色;也可以只給顏色不給稱號。"""
title = "".join(ch for ch in body.title if unicodedata.category(ch) != "Cc").strip()
color = body.color.strip().lower()
if len(title) > config.TITLE_MAX:
fail(400, "title_too_long")
if color and not valid_color(color):
fail(400, "invalid_color")
if title and not color:
color = DEFAULT_TITLE_COLOR
cur = conn.execute("UPDATE users SET title = ?, title_color = ? WHERE uid = ?", (title, color, uid))
if cur.rowcount == 0:
fail(404, "user_not_found")
card.invalidate(uid)
print(f"[ADMIN] title uid={fmt_uid(uid)} title={title!r} color={color or '-'}", flush=True)
user = conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone()
return profile(conn, user, user["lang"])
class MarkdownIn(BaseModel):
md: str
@router.post("/api/markdown")
def preview_markdown(body: MarkdownIn, user=Depends(current_user)):
if len(body.md) > config.BIO_MAX:
fail(400, "bio_too_long")
return {"html": render_md(body.md)}
+3
View File
@@ -0,0 +1,3 @@
-r requirements.txt
pytest==8.*
httpx
+6
View File
@@ -0,0 +1,6 @@
fastapi==0.115.*
uvicorn[standard]==0.32.*
pillow==11.*
python-multipart==0.0.*
markdown-it-py==3.*
tzdata
View File
Whitespace-only changes.
+65
View File
@@ -0,0 +1,65 @@
from datetime import datetime, timezone
import pytest
from fastapi.testclient import TestClient
from PIL import Image
from app import auth, clock, config, mailer, totp
ADMIN_LOGIN = "sthkm3"
ADMIN_TOTP = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP" # 測試用密鑰
class Clock:
def __init__(self):
self.value = datetime(2026, 11, 21, 3, 0, tzinfo=timezone.utc) # 台灣時間 11:00
def set(self, iso: str):
self.value = datetime.fromisoformat(iso).astimezone(timezone.utc)
def __call__(self):
return self.value
@pytest.fixture
def fake_clock(monkeypatch):
c = Clock()
monkeypatch.setattr(clock, "now", c)
return c
@pytest.fixture
def sent(monkeypatch):
"""攔截寄信,回傳 {email: 最後一個驗證碼}。"""
box = {}
monkeypatch.setattr(mailer, "send_code", lambda email, code, lang: box.__setitem__(email, code))
return box
@pytest.fixture
def client(tmp_path, monkeypatch, fake_clock, sent):
memes = tmp_path / "memes"
memes.mkdir()
Image.new("RGB", (640, 480), (200, 80, 80)).save(memes / "test.png")
monkeypatch.setattr(config, "DATA_DIR", tmp_path / "data")
monkeypatch.setattr(config, "MEME_DIR", memes)
monkeypatch.setattr(config, "ADMIN_LOGIN", ADMIN_LOGIN)
monkeypatch.setattr(config, "ADMIN_TOTP", ADMIN_TOTP)
auth._ip_hits.clear()
from app.main import app
with TestClient(app, headers={"X-ZHIWU": "1"}) as c:
yield c
def login(client, sent, email="[email protected]", lang="zh-TW"):
r = client.post("/api/auth/request-code", json={"email": email, "lang": lang})
assert r.status_code == 200, r.text
r = client.post("/api/auth/verify", json={"email": email, "code": sent[email.lower()], "lang": lang})
assert r.status_code == 200, r.text
return r.json()
def admin_code(fake_clock, offset_steps=0):
"""用假時鐘算出管理員的 TOTP。"""
step = int(fake_clock.value.timestamp()) // totp.PERIOD + offset_steps
return totp.code_at(totp.decode_secret(ADMIN_TOTP), step)
+129
View File
@@ -0,0 +1,129 @@
from datetime import timedelta
import pytest
from app import admin, config, db, totp
from .conftest import ADMIN_LOGIN, admin_code, login
def admin_login(client, code, login_name=ADMIN_LOGIN):
return client.post("/api/auth/verify", json={"email": login_name, "code": code})
def test_totp_rfc6238_vector():
# RFC 6238 附錄 B(SHA1,密鑰 "12345678901234567890"),取後 6 碼
secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
assert totp.code_at(totp.decode_secret(secret), 59 // 30) == "287082"
assert totp.code_at(totp.decode_secret(secret), 1111111109 // 30) == "081804"
assert totp.verify(secret, "287082", 59) == 1
assert totp.verify(secret, "287082", 59 + 30) == 1 # 前一個時間窗也接受
assert totp.verify(secret, "287082", 59 + 90) is None # 太舊
assert totp.verify(secret, "abc", 59) is None
def test_admin_request_code_does_not_send(client, sent):
r = client.post("/api/auth/request-code", json={"email": "STHKM3"})
assert r.status_code == 200 and r.json()["status"] == "sent"
assert sent == {}
def test_admin_login(client, fake_clock):
r = admin_login(client, admin_code(fake_clock))
assert r.status_code == 200, r.text
user = r.json()["user"]
assert user["uid"] == 0 and user["uid_str"] == "00000000"
assert user["is_admin"] is True and user["uid_tier"] == "admin" and user["title"] == ""
assert "Max-Age=604800" in r.headers["set-cookie"] # 管理員 session 7 天
me = client.get("/api/me").json()
assert me["is_admin"] is True
# 管理員也能簽到,小卡會畫頭銜
c = client.post("/api/checkin").json()
assert c["card_url"].startswith("/card/00000000/")
assert client.get(c["card_url"]).status_code == 200
def test_admin_code_single_use(client, fake_clock):
code = admin_code(fake_clock)
assert admin_login(client, code).status_code == 200
# 登出後馬上用同一組碼再登入:拒絕,但不算失敗,重試幾次都不會鎖
for _ in range(5):
r = admin_login(client, code)
assert r.status_code == 400 and r.json()["detail"] == "code_used"
# 前一個時間窗的碼也不能用(時間步不能倒退)
assert admin_login(client, admin_code(fake_clock, -1)).json()["detail"] == "code_used"
conn = db.connect()
assert db.get_meta(conn, "admin_fails") == 0 and db.get_meta(conn, "admin_lock_until") == 0
# Aegis 換下一組碼就能登入
fake_clock.value += timedelta(seconds=30)
assert admin_login(client, admin_code(fake_clock)).status_code == 200
def test_admin_lockout(client, fake_clock):
good = admin_code(fake_clock)
wrong = "000000" if good != "000000" else "111111"
assert admin_login(client, wrong).json()["detail"] == "wrong_code"
assert admin_login(client, wrong).json()["detail"] == "wrong_code"
r = admin_login(client, wrong) # 第 3 次就鎖
assert r.status_code == 429
# 鎖定中,正確的碼也不行
assert admin_login(client, good).status_code == 429
# 15 分鐘後解鎖
fake_clock.value += timedelta(minutes=15)
assert admin_login(client, admin_code(fake_clock)).status_code == 200
def test_admin_lock_doubles(client, fake_clock):
for minutes in (15, 30, 60):
for _ in range(3):
admin_login(client, "000000" if admin_code(fake_clock) != "000000" else "111111")
fake_clock.value += timedelta(minutes=minutes) - timedelta(seconds=1)
assert admin_login(client, admin_code(fake_clock)).status_code == 429
fake_clock.value += timedelta(seconds=1)
conn = db.connect()
assert db.get_meta(conn, "admin_lock_level") == 3
def test_admin_unlock_command(client, fake_clock):
for _ in range(3):
admin_login(client, "000000" if admin_code(fake_clock) != "000000" else "111111")
assert admin_login(client, admin_code(fake_clock)).status_code == 429
admin.main(["unlock"])
assert admin_login(client, admin_code(fake_clock)).status_code == 200
def test_admin_disabled_without_secret(client, sent, fake_clock, monkeypatch):
monkeypatch.setattr(config, "ADMIN_TOTP", "")
db.init()
r = client.post("/api/auth/request-code", json={"email": ADMIN_LOGIN})
assert r.status_code == 400 and r.json()["detail"] == "invalid_email"
assert admin_login(client, admin_code(fake_clock)).json()["detail"] == "invalid_email"
def test_admin_login_renamed(client, fake_clock, monkeypatch):
monkeypatch.setattr(config, "ADMIN_LOGIN", "boss")
db.init()
assert admin_login(client, admin_code(fake_clock), "sthkm3").json()["detail"] == "invalid_email"
r = admin_login(client, admin_code(fake_clock), "boss")
assert r.status_code == 200 and r.json()["user"]["uid"] == 0
def test_admin_login_clash_disables(client, sent, fake_clock, monkeypatch):
login(client, sent, "[email protected]")
monkeypatch.setattr(config, "ADMIN_LOGIN", "[email protected]")
db.init()
assert db.admin_ok is False
def test_totp_uri(capsys, client):
admin.main(["totp-uri"])
last = capsys.readouterr().out.strip().splitlines()[-1]
assert last.startswith("otpauth://totp/%E5%90%B1%E9%BC%AF%E8%A8%88%E7%95%AB%3Asthkm3?secret=")
@pytest.mark.parametrize("uid", ["0", "-1"])
def test_cannot_grant_admin_uid(client, sent, uid):
login(client, sent)
with pytest.raises(SystemExit):
admin.main(["grant-uid", "[email protected]", uid])
+241
View File
@@ -0,0 +1,241 @@
import io
from datetime import timedelta
from fastapi.testclient import TestClient
from PIL import Image
from app import db
from app.main import app
from .conftest import login
# ---------- 登入 ----------
def test_register_and_login(client, sent):
data = login(client, sent, "[email protected]")
assert data["user"]["uid"] == 1
assert data["user"]["uid_str"] == "00000001"
assert data["user"]["display_name"] == "吱鼯_1"
assert data["user"]["is_admin"] is False
assert data["user"]["email"] == "[email protected]"
assert data["token"]
assert client.get("/api/me").json()["uid"] == 1
# 同一個信箱再登入一次是同一個帳號
client.cookies.clear()
client.post("/api/auth/request-code", json={"email": "[email protected]"}) # 別人註冊不影響
assert login(client, sent, "[email protected]")["user"]["uid"] == 1
def test_bearer_token(client, sent):
token = login(client, sent)["token"]
client.cookies.clear()
assert client.get("/api/me").status_code == 401
# Bearer 不需要 X-ZHIWU
bare = TestClient(app)
r = bare.post("/api/checkin", headers={"Authorization": f"Bearer {token}"})
assert r.status_code == 200
def test_csrf_header_required(client, sent):
login(client, sent)
r = client.post("/api/checkin", headers={"X-ZHIWU": ""})
assert r.status_code == 403
def test_resend_limit(client, sent, fake_clock):
client.post("/api/auth/request-code", json={"email": "[email protected]"})
r = client.post("/api/auth/request-code", json={"email": "[email protected]"})
assert r.status_code == 429
fake_clock.value += timedelta(seconds=61)
assert client.post("/api/auth/request-code", json={"email": "[email protected]"}).status_code == 200
def test_wrong_code_five_times(client, sent):
client.post("/api/auth/request-code", json={"email": "[email protected]"})
right = sent["[email protected]"]
wrong = "000000" if right != "000000" else "111111"
for _ in range(4):
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": wrong})
assert r.json()["detail"] == "wrong_code"
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": wrong})
assert r.json()["detail"] == "expired"
# 作廢後正確的碼也不能用
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": right})
assert r.json()["detail"] == "not_requested"
def test_code_expires(client, sent, fake_clock):
client.post("/api/auth/request-code", json={"email": "[email protected]"})
fake_clock.value += timedelta(minutes=5, seconds=1)
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": sent["[email protected]"]})
assert r.json()["detail"] == "expired"
def test_invalid_email(client):
r = client.post("/api/auth/request-code", json={"email": "not-an-email"})
assert r.status_code == 400 and r.json()["detail"] == "invalid_email"
def test_logout(client, sent):
login(client, sent)
assert client.post("/api/auth/logout").status_code == 200
client.cookies.clear()
assert client.get("/api/me").status_code == 401
# ---------- 簽到 ----------
def test_checkin_once_per_jst_day(client, sent, fake_clock):
login(client, sent)
fake_clock.set("2026-11-21T12:00:00+08:00")
r = client.post("/api/checkin").json()
assert r["already"] is False and r["total_days"] == 1 and r["streak"] == 1
assert r["day"] == "2026-11-21"
assert r["card_url"] == "/card/00000001/2026-11-21.png"
assert r["share_url"].endswith("/c/00000001/2026-11-21")
r = client.post("/api/checkin").json()
assert r["already"] is True and r["total_days"] == 1
# 台灣時間隔天 03:59 還算同一天
fake_clock.set("2026-11-22T03:59:59+08:00")
assert client.post("/api/checkin").json()["already"] is True
# 日本時間 00:00 換日
fake_clock.set("2026-11-22T04:00:00+08:00")
r = client.post("/api/checkin").json()
assert r["already"] is False and r["total_days"] == 2 and r["streak"] == 2
def test_streak_breaks(client, sent, fake_clock):
login(client, sent)
for day in ("2026-11-01", "2026-11-02", "2026-11-04"):
fake_clock.set(f"{day}T09:00:00+08:00")
client.post("/api/checkin")
r = client.get("/api/checkin/today").json()
assert r["total_days"] == 3 and r["streak"] == 1
# 隔天還沒簽到時,連續天數保留昨天的紀錄
fake_clock.set("2026-11-05T09:00:00+08:00")
r = client.get("/api/checkin/today").json()
assert r["checked_in"] is False and r["streak"] == 1
assert r["next_reset"] == "2026-11-06T04:00:00+08:00"
# 凌晨 02:00 時還沒換日,下次換日是當天 04:00
fake_clock.set("2026-11-06T02:00:00+08:00")
r = client.get("/api/checkin/today").json()
assert r["day"] == "2026-11-05" and r["next_reset"] == "2026-11-06T04:00:00+08:00"
def test_checkin_requires_login(client):
assert client.post("/api/checkin").status_code == 401
# ---------- UID ----------
def test_uid_sequence_skips_granted(client, sent):
from app import admin
login(client, sent, "[email protected]")
admin.main(["grant-uid", "[email protected]", "99999999"])
# 下一位仍然拿到正常的下一號
assert login(client, sent, "[email protected]")["user"]["uid"] == 2
def test_only_admin_has_uid_tier(client, sent):
conn = db.connect()
conn.execute("UPDATE meta SET value = 114514 WHERE key = 'next_uid'")
u = login(client, sent, "[email protected]")["user"]
assert u["uid_str"] == "00114514" and u["uid_tier"] is None
assert client.get("/api/users/0").json()["uid_tier"] == "admin"
def test_grant_uid_range(client, sent):
import pytest
from app import admin
login(client, sent, "[email protected]")
for bad in ("0", "100000000"):
with pytest.raises(SystemExit):
admin.main(["grant-uid", "[email protected]", bad])
def test_granted_uid_keeps_checkins(client, sent):
from app import admin
login(client, sent, "[email protected]")
client.post("/api/checkin")
admin.main(["grant-uid", "[email protected]", "114514"])
me = client.get("/api/me").json() # session 也跟著改 uid
assert me["uid_str"] == "00114514" and me["total_days"] == 1
def _png(w, h, color=(10, 200, 30)):
buf = io.BytesIO()
Image.new("RGB", (w, h), color).save(buf, "PNG")
return buf.getvalue()
def test_avatar_resized(client, sent):
login(client, sent)
r = client.put("/api/me/avatar", files={"file": ("a.png", _png(1600, 900), "image/png")})
assert r.status_code == 200, r.text
url = r.json()["avatar_url"]
img = Image.open(io.BytesIO(client.get(url).content))
assert img.format == "WEBP" and img.size == (1024, 1024)
def test_avatar_rejects_non_image(client, sent):
login(client, sent)
r = client.put("/api/me/avatar", files={"file": ("a.png", b"<script>alert(1)</script>", "image/png")})
assert r.status_code == 400 and r.json()["detail"] == "invalid_image"
def test_profile_patch_and_markdown_escape(client, sent):
login(client, sent)
r = client.patch("/api/me", json={"display_name": " 野獸\n先輩 ", "bio_md": "**hi** <script>x</script>"})
data = r.json()
assert data["display_name"] == "野獸先輩"
assert "<strong>hi</strong>" in data["bio_html"]
assert "<script>" not in data["bio_html"]
assert client.patch("/api/me", json={"display_name": "x" * 33}).json()["detail"] == "name_invalid"
assert client.patch("/api/me", json={"bio_md": "x" * 2001}).json()["detail"] == "bio_too_long"
assert client.patch("/api/me", json={"lang": "fr"}).json()["detail"] == "invalid_lang"
def test_public_profile_hides_email(client, sent):
login(client, sent)
data = client.get("/api/users/1").json()
assert "email" not in data and data["uid"] == 1
assert client.get("/api/users/999").status_code == 404
# ---------- 小卡與分享 ----------
def test_card_and_share_page(client, sent):
login(client, sent)
r = client.post("/api/checkin").json()
png = client.get(r["card_url"])
assert png.status_code == 200
img = Image.open(io.BytesIO(png.content))
assert img.size == (1080, 1350)
page = client.get(f"/c/1/{r['day']}")
assert page.status_code == 200 and 'property="og:image"' in page.text
assert client.get("/card/1/2000-01-01.png").status_code == 404
assert client.get("/c/1/not-a-day").status_code == 404
def test_card_rerendered_after_rename(client, sent):
login(client, sent)
r = client.post("/api/checkin").json()
first = client.get(r["card_url"]).content
client.patch("/api/me", json={"display_name": "New Name"})
assert client.get(r["card_url"]).content != first
def test_index_served(client):
assert client.get("/").status_code == 200
assert client.get("/u/1").status_code == 200
assert client.get("/healthz").json() == {"status": "ok"}
+59
View File
@@ -0,0 +1,59 @@
import pytest
from app import admin, config, db
from app.titles import uid_tier
from .conftest import login
@pytest.mark.parametrize("uid,tier", [
(0, "admin"), (1, None), (114514, None), (99999999, None),
])
def test_uid_tier(uid, tier):
assert uid_tier(uid) == tier
@pytest.mark.parametrize("beta", [True, False])
def test_beta_switch(client, sent, monkeypatch, beta):
monkeypatch.setattr(config, "BETA", beta)
html = client.get("/").text
assert ("(Beta)" in html) is beta
assert "<!--BETA" not in html
login(client, sent)
r = client.post("/api/checkin").json()
page = client.get(f"/c/00000001/{r['day']}").text
assert ('content="吱鼯計畫 (Beta)"' in page) is beta
assert client.get(r["card_url"]).status_code == 200
def test_reset_progress(client, sent, capsys):
login(client, sent)
client.patch("/api/me", json={"display_name": "Beta tester"})
first = client.post("/api/checkin").json()
assert client.get(first["card_url"]).status_code == 200
# 沒有 --yes 不做任何事
admin.main(["reset-progress"])
assert client.get("/api/checkin/today").json()["total_days"] == 1
admin.main(["reset-progress", "--yes"])
today = client.get("/api/checkin/today").json()
assert today["total_days"] == 0 and today["checked_in"] is False
me = client.get("/api/me").json() # 帳號、名稱、session 都還在
assert me["display_name"] == "Beta tester" and me["uid_str"] == "00000001"
assert list(config.DATA_DIR.glob("zhiwu.db.bak-*"))
assert not any((config.DATA_DIR / "cards").iterdir())
# 同一天可以重新簽到
again = client.post("/api/checkin").json()
assert again["already"] is False and again["total_days"] == 1
assert db.connect().execute("SELECT value FROM meta WHERE key = 'next_uid'").fetchone()[0] == 2
def test_assets_versioned_and_not_cached_by_proxies(client):
html = client.get("/").text
assert "__ASSET_VERSION__" not in html
assert '/assets/app.js?v=' in html and '/assets/style.css?v=' in html
r = client.get("/assets/app.js")
assert r.headers["cache-control"] == "no-cache"
etag = r.headers["etag"]
assert client.get("/assets/app.js", headers={"If-None-Match": etag}).status_code == 304
+59
View File
@@ -0,0 +1,59 @@
from app import config, mailer
class FakeSMTP:
instances = []
def __init__(self, host, port, timeout=None, context=None):
self.host, self.port, self.sent, self.tls = host, port, [], False
FakeSMTP.instances.append(self)
def starttls(self, context=None):
self.tls = True
def login(self, user, password):
self.login_as = (user, password)
def send_message(self, msg):
self.sent.append(msg)
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def _setup(monkeypatch, port):
FakeSMTP.instances.clear()
monkeypatch.setattr(mailer.smtplib, "SMTP_SSL", FakeSMTP)
monkeypatch.setattr(mailer.smtplib, "SMTP", FakeSMTP)
monkeypatch.setattr(config, "SMTP_HOST", "smtp.example.com")
monkeypatch.setattr(config, "SMTP_PORT", port)
monkeypatch.setattr(config, "SMTP_USER", "[email protected]")
monkeypatch.setattr(config, "SMTP_PASSWORD", "app-password")
monkeypatch.setattr(config, "MAIL_FROM", "[email protected]")
def test_sends_from_noreply(monkeypatch):
_setup(monkeypatch, 465)
mailer.send_code("[email protected]", "123456", "ja")
smtp = FakeSMTP.instances[0]
assert (smtp.host, smtp.port, smtp.tls) == ("smtp.example.com", 465, False)
msg = smtp.sent[0]
assert msg["From"] == "吱鼯計畫 <[email protected]>"
assert msg["To"] == "[email protected]"
assert "123456" in msg["Subject"] and "認証コード" in msg["Subject"]
assert msg["Message-ID"].endswith("@zhiwu-project.sthkm3.org>")
def test_starttls_on_587(monkeypatch):
_setup(monkeypatch, 587)
mailer.send_code("[email protected]", "123456", "en")
assert FakeSMTP.instances[0].tls is True
def test_dev_mode_prints(monkeypatch, capsys):
monkeypatch.setattr(config, "SMTP_USER", "")
mailer.send_code("[email protected]", "654321", "en")
assert "654321" in capsys.readouterr().out
+178
View File
@@ -0,0 +1,178 @@
import io
from PIL import Image
from app import admin, checkin, config, db
from .conftest import ADMIN_LOGIN, admin_code, login
def _img(fmt="PNG", color=(10, 200, 30), size=(300, 200), **kw):
buf = io.BytesIO()
Image.new("RGB", size, color).save(buf, fmt, **kw)
return buf.getvalue()
def bearer(token):
return {"Authorization": f"Bearer {token}"}
def upload(client, token, data=None, name="a.png"):
return client.post("/api/submissions", headers=bearer(token),
files={"file": (name, data or _img(), "image/png")})
def admin_token(client, fake_clock):
r = client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": admin_code(fake_clock)})
assert r.status_code == 200, r.text
return r.json()["token"]
def test_upload_and_daily_quota(client, sent, fake_clock):
tok = login(client, sent)["token"]
r = upload(client, tok)
assert r.status_code == 200, r.text
data = r.json()
assert data["item"]["status"] == "pending" and data["remaining"] == 4 and data["limit"] == 5
for _ in range(4):
assert upload(client, tok).status_code == 200
r = upload(client, tok)
assert r.status_code == 429 and r.json()["detail"] == "quota_exceeded"
# 台灣時間隔天 03:59 還是同一天,04:00 才重置
fake_clock.set("2026-11-22T03:59:00+08:00")
assert upload(client, tok).status_code == 429
fake_clock.set("2026-11-22T04:00:00+08:00")
assert upload(client, tok).json()["remaining"] == 4
mine = client.get("/api/submissions", headers=bearer(tok)).json()
assert mine["used"] == 1 and len(mine["items"]) == 6
def test_rejected_still_counts(client, sent, fake_clock):
tok = login(client, sent)["token"]
adm = admin_token(client, fake_clock)
for _ in range(5):
sid = upload(client, tok).json()["item"]["id"]
assert client.post(f"/api/admin/submissions/{sid}/reject", headers=bearer(adm)).status_code == 200
assert upload(client, tok).json()["detail"] == "quota_exceeded"
def test_upload_validation(client, sent):
tok = login(client, sent)["token"]
r = upload(client, tok, b"<script>alert(1)</script>")
assert r.status_code == 400 and r.json()["detail"] == "invalid_image"
r = upload(client, tok, b"x" * (config.SUBMIT_MAX_BYTES + 1))
assert r.status_code == 413 and r.json()["detail"] == "file_too_large"
# 失敗的不算額度
assert client.get("/api/submissions", headers=bearer(tok)).json()["used"] == 0
def test_upload_strips_exif_and_shrinks(client, sent):
tok = login(client, sent)["token"]
exif = Image.Exif()
exif[0x010F] = "SecretCam"
item = upload(client, tok, _img("JPEG", size=(4000, 1000), exif=exif), "a.jpg").json()["item"]
saved = config.DATA_DIR / "submissions" / f"{item['id']}.jpg"
with Image.open(saved) as im:
assert im.format == "JPEG" and len(im.getexif()) == 0
assert im.size == (2048, 512)
def test_png_with_alpha_stays_png(client, sent):
tok = login(client, sent)["token"]
buf = io.BytesIO()
Image.new("RGBA", (50, 50), (0, 0, 0, 0)).save(buf, "PNG")
item = upload(client, tok, buf.getvalue()).json()["item"]
assert (config.DATA_DIR / "submissions" / f"{item['id']}.png").is_file()
def test_permissions(client, sent, fake_clock):
a = login(client, sent, "[email protected]")["token"]
b = login(client, sent, "[email protected]")["token"]
sid = upload(client, a).json()["item"]["id"]
url = f"/api/submissions/{sid}/image"
assert client.get(url, headers=bearer(a)).status_code == 200
assert client.get(url, headers=bearer(b)).status_code == 404 # 別人的投稿當作不存在
for method, path in (("get", "/api/admin/submissions"),
("post", f"/api/admin/submissions/{sid}/approve"),
("post", f"/api/admin/submissions/{sid}/reject")):
assert getattr(client, method)(path, headers=bearer(b)).status_code == 403
adm = admin_token(client, fake_clock)
assert client.get(url, headers=bearer(adm)).status_code == 200
assert "pending_reviews" not in client.get("/api/me", headers=bearer(a)).json()
assert client.get("/api/me", headers=bearer(adm)).json()["pending_reviews"] == 1
def test_approve_names_like_image_folder(client, sent, fake_clock):
for name in ("zhiwu_0.png", "zhiwu_7.jpg"):
Image.new("RGB", (10, 10)).save(config.MEME_DIR / name)
tok = login(client, sent)["token"]
first = upload(client, tok).json()["item"]["id"]
second = upload(client, tok).json()["item"]["id"]
adm = admin_token(client, fake_clock)
# 一張一張審:先拿到最舊的
r = client.get("/api/admin/submissions", headers=bearer(adm)).json()
assert r["pending"] == 2 and r["item"]["id"] == first
assert r["item"]["uploader"]["uid_str"] == "00000001"
r = client.post(f"/api/admin/submissions/{first}/approve", headers=bearer(adm))
assert r.status_code == 200 and r.json()["meme"] == "zhiwu_8.jpg" and r.json()["pending"] == 1
assert (config.MEME_DIR / "zhiwu_8.jpg").is_file()
assert not (config.DATA_DIR / "submissions" / f"{first}.jpg").exists()
assert "zhiwu_8.jpg" in checkin.list_memes()
assert client.post(f"/api/admin/submissions/{first}/approve", headers=bearer(adm)).status_code == 409
assert client.post(f"/api/admin/submissions/{first}/reject", headers=bearer(adm)).status_code == 409
assert client.post(f"/api/admin/submissions/{second}/approve",
headers=bearer(adm)).json()["meme"] == "zhiwu_9.jpg"
assert client.get("/api/admin/submissions", headers=bearer(adm)).json() == {"item": None, "pending": 0}
# 已同意的投稿,本人還是看得到圖
assert client.get(f"/api/submissions/{first}/image", headers=bearer(tok)).status_code == 200
# 沒有暫存檔留在迷因資料夾
assert not [p for p in config.MEME_DIR.iterdir() if p.name.startswith(".")]
def test_approved_meme_shows_on_card(client, sent, fake_clock, monkeypatch):
for p in config.MEME_DIR.iterdir():
p.unlink()
tok = login(client, sent)["token"]
sid = upload(client, tok).json()["item"]["id"]
adm = admin_token(client, fake_clock)
client.post(f"/api/admin/submissions/{sid}/approve", headers=bearer(adm))
assert checkin.list_memes() == ["zhiwu_0.jpg"]
r = client.post("/api/checkin", headers=bearer(tok)).json()
conn = db.connect()
assert conn.execute("SELECT meme FROM checkins WHERE uid = 1").fetchone()[0] == "zhiwu_0.jpg"
assert client.get(r["card_url"]).status_code == 200
def test_reject_deletes_file(client, sent, fake_clock):
tok = login(client, sent)["token"]
sid = upload(client, tok).json()["item"]["id"]
adm = admin_token(client, fake_clock)
assert client.post(f"/api/admin/submissions/{sid}/reject", headers=bearer(adm)).json()["status"] == "rejected"
assert not (config.DATA_DIR / "submissions" / f"{sid}.png").exists()
item = client.get("/api/submissions", headers=bearer(tok)).json()["items"][0]
assert item["status"] == "rejected" and item["image_url"] is None
assert client.get(f"/api/submissions/{sid}/image", headers=bearer(tok)).status_code == 404
assert client.post("/api/admin/submissions/9999/reject", headers=bearer(adm)).status_code == 404
def test_reset_progress_keeps_submissions(client, sent):
tok = login(client, sent)["token"]
upload(client, tok)
admin.main(["reset-progress", "--yes"])
assert client.get("/api/submissions", headers=bearer(tok)).json()["used"] == 1
def test_upload_and_review_pages_served(client):
assert client.get("/upload").status_code == 200
assert client.get("/review").status_code == 200
def test_media_content_types(client):
for path, ctype in (("/assets/media/zhizhi-poster.webp", "image/webp"), ("/assets/media/zhizhi.mp4", "video/mp4")):
r = client.get(path)
assert r.status_code == 200 and r.headers["content-type"].startswith(ctype)
+116
View File
@@ -0,0 +1,116 @@
"""管理員指定 UID 的顏色與稱號。"""
import sqlite3
from app import admin, config, db
from app.titles import text_on
from .conftest import ADMIN_LOGIN, admin_code, login
def bearer(tok):
return {"Authorization": f"Bearer {tok}"}
def admin_token(client, fake_clock):
client.post("/api/auth/request-code", json={"email": ADMIN_LOGIN, "lang": "zh-TW"})
r = client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": admin_code(fake_clock), "lang": "zh-TW"})
assert r.status_code == 200, r.text
client.cookies.clear()
return r.json()["token"]
def test_default_has_no_title(client, sent):
u = login(client, sent)["user"]
assert u["title"] == "" and u["title_color"] is None and u["uid_tier"] is None
assert client.get("/api/users/0").json()["uid_tier"] == "admin" # 管理員預設樣式還在
def test_admin_sets_and_clears_title(client, sent, fake_clock):
login(client, sent)
card_url = client.post("/api/checkin").json()["card_url"]
plain = client.get(card_url).content
adm = admin_token(client, fake_clock)
r = client.put("/api/admin/users/1/title", json={"title": " 首席鼠黑 ", "color": "#3366FF"}, headers=bearer(adm))
assert r.status_code == 200, r.text
assert r.json()["title"] == "首席鼠黑" and r.json()["title_color"] == "#3366ff"
# 公開資料看得到,小卡也重畫了
u = client.get("/api/users/1").json()
assert u["title"] == "首席鼠黑" and u["title_color"] == "#3366ff"
titled = client.get(card_url).content
assert titled != plain
# 清除
r = client.put("/api/admin/users/1/title", json={"title": "", "color": ""}, headers=bearer(adm))
assert r.json()["title"] == "" and r.json()["title_color"] is None
assert client.get(card_url).content == plain
def test_title_or_color_alone(client, sent, fake_clock):
login(client, sent)
adm = admin_token(client, fake_clock)
# 只給稱號:顏色用主色
r = client.put("/api/admin/users/1/title", json={"title": "吱吱"}, headers=bearer(adm)).json()
assert r["title"] == "吱吱" and r["title_color"] == "#ff8a1f"
# 只給顏色:沒有稱號
r = client.put("/api/admin/users/1/title", json={"color": "#000000"}, headers=bearer(adm)).json()
assert r["title"] == "" and r["title_color"] == "#000000"
# 管理員自己也可以改
r = client.put("/api/admin/users/0/title", json={"title": "鼠王", "color": "#ff0000"}, headers=bearer(adm)).json()
assert r["title"] == "鼠王" and r["uid_tier"] == "admin"
def test_title_validation_and_permission(client, sent, fake_clock):
tok = login(client, sent)["token"]
client.cookies.clear()
# 一般使用者不能設(自己的也不行),沒登入也不行
assert client.put("/api/admin/users/1/title", json={"title": "x"}, headers=bearer(tok)).status_code == 403
assert client.put("/api/admin/users/1/title", json={"title": "x"}).status_code == 401
adm = admin_token(client, fake_clock)
for body, code in (({"title": "字" * (config.TITLE_MAX + 1)}, "title_too_long"),
({"color": "red"}, "invalid_color"), ({"color": "#12345"}, "invalid_color"),
({"color": "#12345g"}, "invalid_color")):
r = client.put("/api/admin/users/1/title", json=body, headers=bearer(adm))
assert r.status_code == 400 and r.json()["detail"] == code, body
r = client.put("/api/admin/users/999/title", json={"title": "x"}, headers=bearer(adm))
assert r.status_code == 404 and r.json()["detail"] == "user_not_found"
assert client.get("/api/users/1").json()["title"] == ""
def test_review_page_shows_uploader_title(client, sent, fake_clock):
from .test_submissions import upload
tok = login(client, sent)["token"]
client.cookies.clear()
upload(client, tok)
adm = admin_token(client, fake_clock)
client.put("/api/admin/users/1/title", json={"title": "投稿王", "color": "#00aa55"}, headers=bearer(adm))
up = client.get("/api/admin/submissions", headers=bearer(adm)).json()["item"]["uploader"]
assert up["title"] == "投稿王" and up["title_color"] == "#00aa55"
def test_set_title_cli(client, sent, capsys):
login(client, sent)
admin.main(["set-title", "1", "--title", "測試", "--color", "#ABCDEF"])
assert client.get("/api/users/1").json()["title_color"] == "#abcdef"
admin.main(["set-title", "1", "--clear"])
u = client.get("/api/users/1").json()
assert u["title"] == "" and u["title_color"] is None
def test_text_colour_follows_brightness():
assert text_on((255, 209, 102)) == (42, 20, 0) # 亮底用深色字
assert text_on((0, 0, 0)) == (255, 255, 255) # 暗底用白字
assert text_on((51, 102, 255)) == (255, 255, 255)
def test_old_database_gets_new_columns(client, sent):
"""已經在跑的資料庫(沒有 title 欄位)重啟後自動補欄位,資料不動。"""
login(client, sent)
conn = sqlite3.connect(db.db_path(), isolation_level=None)
conn.execute("ALTER TABLE users DROP COLUMN title")
conn.execute("ALTER TABLE users DROP COLUMN title_color")
conn.close()
db.init()
u = client.get("/api/me").json()
assert u["title"] == "" and u["title_color"] is None and u["uid_str"] == "00000001"
+129
View File
@@ -0,0 +1,129 @@
"""吱吱(點擊)次數:和簽到天數分開記錄,簽到那一下也算一次。"""
import pytest
from app import checkin, config
from .conftest import login
@pytest.fixture
def frozen(monkeypatch):
"""固定限流用的時鐘,測試自己決定時間前進多少。"""
now = [1000.0]
monkeypatch.setattr(checkin, "_now", lambda: now[0])
checkin._buckets.clear()
return now
def test_checkin_counts_one_click_per_day(client, sent, frozen, fake_clock):
login(client, sent)
assert client.get("/api/checkin/today").json()["clicks"] == 0
r = client.post("/api/checkin").json()
assert r["already"] is False and r["total_days"] == 1 and r["clicks"] == 1
# 同一天再簽到:不會再加
r = client.post("/api/checkin").json()
assert r["already"] is True and r["total_days"] == 1 and r["clicks"] == 1
# 隔天簽到再加一次
fake_clock.set("2026-11-22T12:00:00+08:00")
r = client.post("/api/checkin").json()
assert r["total_days"] == 2 and r["clicks"] == 2
def test_zhi_adds_clicks_but_not_days(client, sent, frozen):
login(client, sent)
client.post("/api/checkin")
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 2, "added": 1}
frozen[0] += 1
assert client.post("/api/zhi", json={}).json()["clicks"] == 3 # 預設一下
today = client.get("/api/checkin/today").json()
assert today["clicks"] == 3 and today["total_days"] == 1 and today["streak"] == 1
me = client.get("/api/me").json()
assert me["clicks"] == 3 and me["total_days"] == 1
assert client.get("/api/users/1").json()["clicks"] == 3
def test_zhi_works_before_checkin(client, sent, frozen):
"""次數和簽到互相獨立:沒簽到也能加(API 不擋,前端只在簽到後才開放)。"""
login(client, sent)
assert client.post("/api/zhi", json={"n": 1}).json()["clicks"] == 1
today = client.get("/api/checkin/today").json()
assert today["checked_in"] is False and today["total_days"] == 0
@pytest.mark.parametrize("n", [0, -1, config.ZHI_BATCH_MAX + 1])
def test_zhi_rejects_bad_batch(client, sent, frozen, n):
login(client, sent)
r = client.post("/api/zhi", json={"n": n})
assert r.status_code == 400 and r.json()["detail"] == "bad_request"
assert client.get("/api/me").json()["clicks"] == 0
def test_zhi_once_per_second(client, sent, frozen):
"""一個帳號一秒只能吱一次:同一秒內多的、一次送很多下的,都只算一下。"""
login(client, sent)
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 1, "added": 1}
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 1, "added": 0}
frozen[0] += 0.9
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 1, "added": 0}
frozen[0] += 0.1
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 2, "added": 1}
# 等再久額度也只存 1 下;一次送 200 下也只加 1
frozen[0] += 3600
assert client.post("/api/zhi", json={"n": 200}).json() == {"clicks": 3, "added": 1}
assert client.post("/api/zhi", json={"n": 200}).json() == {"clicks": 3, "added": 0}
def test_zhi_limit_is_per_account(client, sent, frozen):
login(client, sent, "[email protected]")
assert client.post("/api/zhi", json={"n": 1}).json()["added"] == 1
client.cookies.clear()
login(client, sent, "[email protected]")
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 1, "added": 1}
def test_zhi_requires_login_and_csrf(client, sent, frozen):
assert client.post("/api/zhi", json={"n": 1}).status_code == 401
login(client, sent)
assert client.post("/api/zhi", json={"n": 1}, headers={"X-ZHIWU": ""}).status_code == 403
def test_card_redrawn_when_clicks_change(client, sent, frozen):
login(client, sent)
r = client.post("/api/checkin").json()
cards = config.DATA_DIR / "cards" / "1"
first = client.get(r["card_url"])
assert first.status_code == 200
assert [p.name for p in cards.iterdir()] == [f"{r['day']}.v1.c1.png"]
client.post("/api/zhi", json={"n": 1})
second = client.get(r["card_url"] + "?c=2")
assert second.status_code == 200 and second.content != first.content
# 舊次數的快取會被清掉,只留最新的一張
assert [p.name for p in cards.iterdir()] == [f"{r['day']}.v1.c2.png"]
# 次數沒變就直接用快取
assert client.get(r["card_url"] + "?c=2").content == second.content
def test_card_uses_default_image_when_gallery_empty(client, sent, frozen):
for p in config.MEME_DIR.iterdir():
p.unlink()
login(client, sent)
r = client.post("/api/checkin").json()
assert client.get(r["card_url"]).status_code == 200
def test_reset_progress_clears_clicks(client, sent, frozen):
from app import admin
login(client, sent)
client.post("/api/checkin")
client.post("/api/zhi", json={"n": 1})
admin.main(["reset-progress", "--yes"])
today = client.get("/api/checkin/today").json()
assert today["clicks"] == 0 and today["total_days"] == 0
def test_video_served_with_range(client):
r = client.get("/assets/media/zhizhi.mp4", headers={"Range": "bytes=0-99"})
assert r.status_code == 206 and r.headers["content-type"] == "video/mp4" and len(r.content) == 100
assert "media-src 'self'" in r.headers["content-security-policy"]