commit e50b59d88a1aaa62b46ec6326b9f026d7f8548f1 Author: sthkm3 Date: Sun Nov 22 01:04:28 2026 +0800 upload to gitea diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ce82217 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.env +.git +**/__pycache__ +**/.pytest_cache +server/.venv +server/tests +data +image +icon +tools diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..89f1e8b --- /dev/null +++ b/.env.example @@ -0,0 +1,26 @@ +# 對外網址:分享連結、og:image、信件裡的連結都用這個 +PUBLIC_URL=https://inmu.sthkm3.org +# 經 cloudflared(https)對外時設 1,登入 cookie 只走 https(本機 http://127.0.0.1 也能用) +COOKIE_SECURE=1 +# Beta 期間設 1(網頁標題加 (Beta)、小卡右下角加 · Beta);正式上線改 0,並執行 reset-progress +BETA=1 +# 本機 port(只綁 127.0.0.1,cloudflared 指到 http://localhost:2040) +PORT=2040 + +# ---- 寄信(SMTP,容器主動連出去,不經過 tunnel)---- +# 帳密留空 = 不寄信,驗證碼印在 log(docker compose logs app) +# Resend(先在後台驗證 inmu.sthkm3.org):USER=resend,PASSWORD=API key +# 臨時用 Gmail:HOST=smtp.gmail.com,USER=Gmail 帳號,PASSWORD=應用程式密碼(寄件人會變成那個 Gmail) +SMTP_HOST=smtp.resend.com +SMTP_PORT=465 +SMTP_USER=resend +SMTP_PASSWORD= +# 寄件人,網域要和寄信服務驗證過的網域相同 +MAIL_FROM=noreply@inmu.sthkm3.org + +# ---- 管理員(UID 00000000)---- +# 登入框的信箱欄輸入 ADMIN_LOGIN,驗證碼用 Aegis 等 TOTP App 算(SHA1、6 位、30 秒) +# ADMIN_TOTP 是 base32 密鑰;兩個都留空 = 停用管理員登入。改完執行 docker compose up -d +# 換手機時:docker compose exec app python -m app.admin totp-uri +ADMIN_LOGIN= +ADMIN_TOTP= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bd3eecb --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.env +*.ipynb +__pycache__/ +.pytest_cache/ +.venv/ +data/ + +# 梗圖(使用者自己提供) +image/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..e35f2f6 --- /dev/null +++ b/README.md @@ -0,0 +1,179 @@ +# My INMU + +每天簽到一次,產生一張 INMU 小卡(累計天數 + 隨機梗圖),可以圖文分享。 +用信箱驗證碼註冊、登入(沒有密碼)。介面支援繁中、簡中、日、韓、英。網址預定為 `inmu.sthkm3.org`。 + +| 服務 | 內容 | port | +|---|---|---| +| `app` | FastAPI + SQLite:API、網站、小卡圖片(Pillow + Noto Sans CJK) | `127.0.0.1:2040` | + +port 只綁本機,正式上線由 cloudflared tunnel 對外。 + +## 啟動 + +``` +cp .env.example .env # SMTP_USER / SMTP_PASSWORD 留空時驗證碼印在 log +docker compose up -d --build +``` + +打開 `http://127.0.0.1:2040`,輸入信箱後用 `docker compose logs app` 找驗證碼(`[DEV] verify code for ...`)。 + +| 指令 | 用途 | +|---|---| +| `docker compose logs -f app` | log(SMTP 帳密沒填時,驗證碼印在這裡) | +| `docker compose down` | 停止(資料保留) | +| `docker compose down -v` | 停止並刪除 volume `myinmu_inmu-data`(清空帳號與簽到紀錄) | +| `docker compose exec app python -m app.admin info ` | 查看帳號 | +| `docker compose exec app python -m app.admin grant-uid 114514` | 把帳號的 UID 換成指定號碼(1–99999999) | +| `docker compose exec app python -m app.admin unlock` | 解除管理員登入鎖定 | +| `docker compose exec app python -m app.admin totp-uri` | 印出 Aegis 用的 `otpauth://` 連結(換手機時用) | +| `docker compose exec app python -m app.admin reset-progress --yes` | 清空所有簽到進度(保留帳號;不加 `--yes` 只顯示會刪什麼) | + +## 梗圖 + +放在 `image/`(jpg / png / webp / gif 取第一幀),容器掛載成 `/memes`。 +每次簽到時隨機抽一張,檔名存進資料庫,所以同一天的小卡重畫也一樣。新增圖片不用重啟;**已經被抽過的圖片不要改名或刪除**,否則舊的小卡會變成「梗圖準備中」。 + +### 使用者投稿 + +- 登入後側欄的「投稿圖片」(`/upload`):每個帳號每天最多 5 張(台灣時間 04:00 重置,被拒絕的也算),每張上限 5MB +- 上傳的圖會重新編碼成 JPEG(有透明度就用 PNG),去掉 EXIF / GPS;長邊超過 2048 會縮小 +- 待審的檔案放在 volume 的 `/data/submissions/.` +- 管理員側欄的「審核投稿 (N)」(`/review`)一次顯示一張,按同意或拒絕: + - 同意:存成 `image/inmu_<目前最大編號 + 1>.jpg`(所以 `image/` 要可寫入),馬上加入抽卡 + - 拒絕:刪掉檔案,紀錄保留(用來算額度) +- 審核結果記在 log(`[review] ...`) + +## 簽到按鈕 + +- 按鈕原圖是 `icon/checkin/0.png`(按下前)和 `1.png`(按下後),由 `tools/make_icons.py` 縮成 `web/media/checkin-0.webp`、`checkin-1.webp` +- 音效是 `web/media/114514.m4a`(約 1.5 秒) +- 按下去會換圖、播音效、噴粒子;音效播完、小卡也下載好之後才亮出小卡並停掉音效 + +## 網頁圖標 + +原圖放在 `icon/`,換圖後執行下面的指令重新產生 `web/` 裡的 favicon.ico、icon-192/512.png、apple-touch-icon.png、logo.png(以及簽到按鈕的兩張 webp),再重新 build: + +``` +server/.venv/Scripts/python tools/make_icons.py +docker compose up -d --build +``` + +## UID 與頭銜 + +- UID 顯示成 8 碼(`00000001`),資料庫存整數。`00000000` 是管理員,一般使用者從 `00000001` 開始依序給號 +- 預設名稱是 `INMU_`(例如 `INMU_1`) +- 給號用 `meta.next_uid`,不用 `AUTOINCREMENT`:否則 `grant-uid` 給出很大的號碼之後,之後的號碼會全部跳過去 +- 特殊序號用 UID 的背景色標示(側欄、個人頁、小卡),不帶任何權限: + - `00000000`(管理員):黃底 + - 8 碼裡包含 `1919810`(例如 `51919810`):橘底 + - 8 碼裡包含 `114514`(例如 `00114514`):藍底 +- API 回傳 `uid_tier`:`"admin"`、`"1919810"`、`"114514"` 或 `null`。顏色定義在 `server/app/titles.py` 的 `TIER_COLORS`(小卡)和 `web/style.css` 的 `.uid.tier-*`(網頁),兩邊要一起改 + +## 管理員 + +- `.env` 設定 `ADMIN_LOGIN`(信箱欄要輸入的字,例如 `sthkm3`)和 `ADMIN_TOTP`(base32 密鑰),改完執行 `docker compose up -d`。兩個都留空就停用管理員登入 +- 登入:在網頁的信箱欄輸入 `ADMIN_LOGIN`,按「寄送驗證碼」(不會真的寄信),再輸入 Aegis 上的 6 位數 +- Aegis 設定:TOTP、SHA1、6 位、30 秒 +- 防護: + - 錯 3 次就鎖定,鎖定時間依序是 15 分、30 分、1 小時…上限 24 小時;成功登入後歸零 + - 鎖定是全域的,換 IP 也繞不過 + - 每組碼只能用一次 + - 管理員 session 有效 7 天 +- 登入成功和失敗都會記在 log(`[ADMIN] ...`) +- 被自己鎖住時,執行 `python -m app.admin unlock` + +## Beta 與正式上線 + +`.env` 的 `BETA=1`(預設)時,網頁標題顯示「My INMU (Beta)」,小卡右下角加「· Beta」。正式上線時: + +1. `.env` 設 `BETA=0` +2. `docker compose up -d` +3. `docker compose exec app python -m app.admin reset-progress --yes` + +`reset-progress` 會先把資料庫備份成 `/data/inmu.db.bak-<日期時間>`,再清空所有簽到紀錄和小卡快取。帳號、UID、名稱、大頭貼、自介都保留,Beta 玩家不用重新註冊。 + +## 對外部署(inmu.sthkm3.org) + +1. `.env`(`.env.example` 已經是正式環境的值):`PUBLIC_URL=https://inmu.sthkm3.org`、`COOKIE_SECURE=1` +2. cloudflared 的 ingress 加一條 `inmu.sthkm3.org → http://localhost:2040` +3. 寄信(寄件人 `noreply@inmu.sthkm3.org`)。寄信是容器主動連到 SMTP 伺服器,**不經過 tunnel,不用開任何 port**; + 也**不需要收信**,所以不用 MX、不用 Email Routing。 + + 用寄信服務(以 Resend 為例,免費方案每天 100 封): + 1. 註冊 Resend → Domains → Add Domain → 輸入 `inmu.sthkm3.org` + 2. 把它列出的 DNS 記錄加到 Cloudflare(`sthkm3.org` 這個 zone),通常是: + - TXT `resend._domainkey.inmu`(DKIM) + - MX 與 TXT `send.inmu`(退信用的子網域與 SPF) + + 名稱都和 tunnel 的 `inmu` CNAME 不同,不會衝突。這些記錄都設成 **DNS only**(灰色雲) + 3. (建議)加 TXT `_dmarc.inmu`:`v=DMARC1; p=none;` + 4. 等 Resend 顯示 Verified → API Keys 建一把只能寄信(Sending access)的 key + 5. `.env`:`SMTP_HOST=smtp.resend.com`、`SMTP_PORT=465`、`SMTP_USER=resend`、`SMTP_PASSWORD=` + (以 Resend 後台 SMTP 頁面為準),然後 `docker compose up -d` + + 其他會幫網域簽 DKIM 的服務(Amazon SES、Brevo、SMTP2GO 等)做法相同:驗證網域、加 DNS、填 SMTP 設定,程式不用改。 + + 不建議用 Gmail「以這個地址寄送郵件」別名:要能在 `inmu.sthkm3.org` 收信(MX 和 tunnel 的 CNAME 不能放在同一個名稱), + 簽名是 gmail.com 容易進垃圾信件,而且 Google 據報將停止對外部網域地址的這項功能。 + 只用 Gmail 帳號本身寄(`SMTP_USER` = Gmail、`SMTP_PASSWORD` = 應用程式密碼)可以當臨時方案,但寄件人會變成那個 Gmail。 + +備份:volume `myinmu_inmu-data` 裡的 `inmu.db`、`avatars/`、`submissions/`(`cards/` 是快取,可以刪),以及 `image/`。 + +## API + +會改資料的 `/api` 請求要帶 header `X-INMU: 1`(防 CSRF);用 `Authorization: Bearer ` 的客戶端不需要。 +錯誤一律回 `{"detail": ""}`。 + +| 方法 路徑 | 說明 | +|---|---| +| `POST /api/auth/request-code {email, lang}` | 寄 6 碼,5 分鐘有效;同信箱 60 秒一次、同 IP 10 分鐘 10 次 | +| `POST /api/auth/verify {email, code, lang}` | 錯 5 次作廢。沒有帳號就自動註冊。回傳 `{token, user}` 並設定 HttpOnly cookie | +| `POST /api/auth/logout` | 登出 | +| `GET /api/me`、`PATCH /api/me {display_name?, bio_md?, lang?}` | 名稱 1–32 字、自介 2000 字 | +| `PUT /api/me/avatar`(multipart `file`) | 上限 5MB,裁成 1024×1024 WebP | +| `POST /api/checkin`、`GET /api/checkin/today` | `{day, checked_in, already?, total_days, streak, next_reset, card_url?, share_url?, share_text?}` | +| `GET /api/users/{uid}?lang=` | 公開個人資料(`bio_html` 已在伺服器端轉好,原始 HTML 會被跳脫) | +| `POST /api/markdown {md}` | 自介預覽 | +| `GET /card/{uid}/{day}.png` | 小卡(第一次請求時才畫,快取在 `/data/cards/`) | +| `GET /c/{uid}/{day}` | 分享頁(`og:image`) | +| `GET /avatars/{uid}.webp`、`GET /healthz` | | +| `POST /api/submissions`(multipart `file`) | 投稿迷因圖,每天 5 張(超過回 429 `quota_exceeded`) | +| `GET /api/submissions` | `{used, limit, remaining, items: [{id, status, created_at, image_url}]}`,自己最近 30 筆 | +| `GET /api/submissions/{id}/image` | 只有上傳者本人和管理員看得到 | +| `GET /api/admin/submissions` | 管理員:最舊的一張待審 `{item, pending}` | +| `POST /api/admin/submissions/{id}/approve`、`/reject` | 管理員:同意/拒絕(已審過回 409 `already_reviewed`) | + +每日分界是**台灣時間 04:00**(程式固定用 `Asia/Taipei`;容器的 `TZ` 也設成台灣,只影響 log 時間)。 +`next_reset` 是帶時區的 ISO 時間,網頁會換算成裝置的當地時間顯示。 + +## 開發 + +``` +cd server +python -m venv .venv +.venv/Scripts/python -m pip install -r requirements-dev.txt # Windows +.venv/Scripts/python -m pytest -q +DATA_DIR=../data .venv/Scripts/python -m uvicorn app.main:app --port 2040 --reload +``` + +本機沒有 Noto Sans CJK 時,小卡會改用 Windows 內建字型(`FONT_REGULAR` / `FONT_BOLD` 可以指定)。 + +## 檔案 + +``` +server/app/ + main.py 路由、CSRF header 檢查、靜態檔 + auth.py 驗證碼登入、session + users.py UID 給號、個人資料、大頭貼、自介 Markdown + checkin.py 簽到、累計 / 連續天數、抽梗圖 + submissions.py 使用者投稿迷因圖、管理員審核 + card.py 畫小卡 + share.py 分享頁 + admin.py 管理指令 + mailer.py Gmail SMTP(沿用 RhyculatorServer/Verify_email) + i18n/ 信件、小卡、頭銜文字 +web/ 網站(純 HTML/JS);i18n/ 是介面文字,media/ 是簽到按鈕的圖和音效 +image/ 梗圖(管理員同意的投稿也會寫進來) +icon/ 圖標與簽到按鈕的原圖(不打包進 Docker) +``` diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..d586c12 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,36 @@ +# My INMU:簽到伺服器(FastAPI + SQLite)與網站 +# 用法:複製 .env.example 成 .env 後執行 docker compose up -d --build + +name: myinmu + +services: + app: + build: + context: . + dockerfile: server/Dockerfile + environment: + PUBLIC_URL: ${PUBLIC_URL:-http://127.0.0.1:2040} + COOKIE_SECURE: ${COOKIE_SECURE:-0} + BETA: ${BETA:-1} # 1 = 網頁標題與小卡標示 Beta;正式上線設 0 + SMTP_HOST: ${SMTP_HOST:-smtp.gmail.com} + SMTP_PORT: ${SMTP_PORT:-465} + SMTP_USER: ${SMTP_USER:-} + SMTP_PASSWORD: ${SMTP_PASSWORD:-} + MAIL_FROM: ${MAIL_FROM:-noreply@inmu.sthkm3.org} + ADMIN_LOGIN: ${ADMIN_LOGIN:-} + ADMIN_TOTP: ${ADMIN_TOTP:-} + TZ: Asia/Taipei # 容器時區(log、date);換日邏輯在程式裡固定用台灣時間 04:00 + volumes: + - inmu-data:/data # inmu.db、avatars/、cards/ + - ./image:/memes # 迷因圖放在 image/;管理員同意的投稿也會寫進這裡(inmu_.jpg) + ports: + - "127.0.0.1:${PORT:-2040}:2040" + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:2040/healthz')"] + interval: 30s + timeout: 5s + retries: 3 + +volumes: + inmu-data: diff --git a/icon/artworks-qlBBYWBrv54xdfKm-ui3lXg-t500x500.jpg b/icon/artworks-qlBBYWBrv54xdfKm-ui3lXg-t500x500.jpg new file mode 100644 index 0000000..0e598a0 Binary files /dev/null and b/icon/artworks-qlBBYWBrv54xdfKm-ui3lXg-t500x500.jpg differ diff --git a/icon/checkin/0.png b/icon/checkin/0.png new file mode 100644 index 0000000..32f6793 Binary files /dev/null and b/icon/checkin/0.png differ diff --git a/icon/checkin/1.png b/icon/checkin/1.png new file mode 100644 index 0000000..1eb1c76 Binary files /dev/null and b/icon/checkin/1.png differ diff --git a/server/Dockerfile b/server/Dockerfile new file mode 100644 index 0000000..d80436e --- /dev/null +++ b/server/Dockerfile @@ -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"] diff --git a/server/app/__init__.py b/server/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/app/admin.py b/server/app/admin.py new file mode 100644 index 0000000..b93505a --- /dev/null +++ b/server/app/admin.py @@ -0,0 +1,131 @@ +"""管理指令(在容器裡執行): + + docker compose exec app python -m app.admin info + docker compose exec app python -m app.admin grant-uid 114514 + docker compose exec app python -m app.admin test-mail + docker compose exec app python -m app.admin unlock # 解除管理員登入鎖定 + docker compose exec app python -m app.admin totp-uri # 印出 Aegis 用的 otpauth:// 連結 + docker compose exec app 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_grant_uid(args): + """把某個帳號的 UID 換成指定號碼(1–99999999,例如 114514)。不會影響之後的依序給號。""" + 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"inmu.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") + 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("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() diff --git a/server/app/auth.py b/server/app/auth.py new file mode 100644 index 0000000..b0e6395 --- /dev/null +++ b/server/app/auth.py @@ -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 + 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"} diff --git a/server/app/card.py b/server/app/card.py new file mode 100644 index 0000000..88f2224 --- /dev/null +++ b/server/app/card.py @@ -0,0 +1,199 @@ +"""用 Pillow 畫 INMU 小卡(1080×1350 PNG),第一次被請求時才畫,之後快取在 /data/cards//.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 TIER_COLORS, fmt_uid, uid_tier + +Image.MAX_IMAGE_PIXELS = 40_000_000 # 擋解壓縮炸彈 + +router = APIRouter() + +W, H = 1080, 1350 +PAD = 48 +ACCENT = (240, 164, 58) +TEXT = (245, 243, 250) +MUTED = (185, 179, 201) +CARD_VERSION = 3 # 版面改了就加 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) -> Image.Image: + lang = norm_lang(user["lang"]) + uid = user["uid"] + + # 背景:上下漸層 + img = Image.new("RGB", (W, H)) + top, bottom = (38, 33, 48), (16, 14, 21) + 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), (10, 10, 13)) + pic = load_image(config.MEME_DIR / meme) if meme else None + 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=(30, 26, 36), 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)}" + tier = uid_tier(uid) + uid_y = av_y + 120 # UID 這一行的垂直中心 + if tier: + bg, fg = TIER_COLORS[tier] + 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") + 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=(70, 64, 84), width=2) + f_day = font(lang, 92, True) + d.text((PAD, line_y + 24), fit_text(d, t(lang, "card.day", n=total), f_day, W - 2 * PAD), + 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 + path = card_dir(uid) / f"{day}.v{CARD_VERSION}.png" + if path.exists(): + return path + user = conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone() + total, streak = stats(conn, uid, day) + img = render(user, day, row["meme"], total, streak) + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp") + with os.fdopen(fd, "wb") as f: + img.save(f, "PNG", optimize=True) + os.replace(tmp, path) + 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=600"}) diff --git a/server/app/checkin.py b/server/app/checkin.py new file mode 100644 index 0000000..28758c5 --- /dev/null +++ b/server/app/checkin.py @@ -0,0 +1,92 @@ +import secrets +import sqlite3 +from datetime import date, timedelta + +from fastapi import APIRouter, Depends + +from . import clock, config +from .db import get_db +from .deps import current_user +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 { + "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) + out = { + "day": day, + "checked_in": checked, + "total_days": total, + "streak": streak, + "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() # 只取一次,避免剛好跨過 00:00 時前後不一致 + # 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()), + ) + return today_payload(conn, user, day, already=cur.rowcount == 0) + + +@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()) diff --git a/server/app/clock.py b/server/app/clock.py new file mode 100644 index 0000000..14ecd5e --- /dev/null +++ b/server/app/clock.py @@ -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 diff --git a/server/app/config.py b/server/app/config.py new file mode 100644 index 0000000..0a6df21 --- /dev/null +++ b/server/app/config.py @@ -0,0 +1,76 @@ +"""環境變數設定。其他模組一律用 `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;本機開發是 /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", "1") == "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 "noreply@inmu.sthkm3.org" + +# 小卡字型;沒設定時依序找 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 +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 # 長邊超過就等比例縮小 + +COOKIE_NAME = "inmu_session" diff --git a/server/app/db.py b/server/app/db.py new file mode 100644 index 0000000..5ce4a0a --- /dev/null +++ b/server/app/db.py @@ -0,0 +1,161 @@ +import shutil +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, + 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/.,同意後搬進迷因資料夾 +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, -- 同意後的檔名,例如 inmu_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 / "inmu.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_default_names(conn) + _init_admin(conn) + finally: + conn.close() + + +def _migrate_default_names(conn: sqlite3.Connection) -> None: + """舊的預設名稱 INMU1 → INMU_1(可以重複執行)。""" + rows = conn.execute("SELECT uid FROM users WHERE display_name = 'INMU' || uid").fetchall() + for (uid,) in rows: + conn.execute("UPDATE users SET display_name = ? WHERE uid = ?", (f"INMU_{uid}", uid)) + shutil.rmtree(config.DATA_DIR / "cards" / str(uid), ignore_errors=True) + + +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") diff --git a/server/app/deps.py b/server/app/deps.py new file mode 100644 index 0000000..f15d15b --- /dev/null +++ b/server/app/deps.py @@ -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": ""},前端用 err. 翻譯。""" + 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 diff --git a/server/app/i18n/__init__.py b/server/app/i18n/__init__.py new file mode 100644 index 0000000..a9ba364 --- /dev/null +++ b/server/app/i18n/__init__.py @@ -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 diff --git a/server/app/i18n/en.json b/server/app/i18n/en.json new file mode 100644 index 0000000..fa80d75 --- /dev/null +++ b/server/app/i18n/en.json @@ -0,0 +1,10 @@ +{ + "mail.subject": "Your My INMU code: {code}", + "mail.body": "Your My INMU 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 checking in on My INMU!", + "share.title": "{name}'s INMU card", + "share.open": "Check in too" +} diff --git a/server/app/i18n/ja.json b/server/app/i18n/ja.json new file mode 100644 index 0000000..bdd9517 --- /dev/null +++ b/server/app/i18n/ja.json @@ -0,0 +1,10 @@ +{ + "mail.subject": "My INMU 認証コード:{code}", + "mail.body": "My INMU の認証コードは:\n\n{code}\n\n有効期限は 5 分です。お心当たりのない場合は、このメールを破棄してください。\n\n{url}", + "card.day": "ログイン {n} 日目", + "card.streak": "連続 {n} 日", + "card.no_meme": "画像準備中", + "share.text": "My INMU でログイン {n} 日目!", + "share.title": "{name} の INMU カード", + "share.open": "自分もログインする" +} diff --git a/server/app/i18n/ko.json b/server/app/i18n/ko.json new file mode 100644 index 0000000..be26044 --- /dev/null +++ b/server/app/i18n/ko.json @@ -0,0 +1,10 @@ +{ + "mail.subject": "My INMU 인증 코드: {code}", + "mail.body": "My INMU 인증 코드는:\n\n{code}\n\n5분 동안 유효합니다. 본인이 요청하지 않았다면 이 메일을 무시해 주세요.\n\n{url}", + "card.day": "출석 {n}일째", + "card.streak": "연속 {n}일", + "card.no_meme": "이미지 준비 중", + "share.text": "My INMU 출석 {n}일째!", + "share.title": "{name}의 INMU 카드", + "share.open": "나도 출석하기" +} diff --git a/server/app/i18n/zh-CN.json b/server/app/i18n/zh-CN.json new file mode 100644 index 0000000..d8ac866 --- /dev/null +++ b/server/app/i18n/zh-CN.json @@ -0,0 +1,10 @@ +{ + "mail.subject": "My INMU 验证码:{code}", + "mail.body": "你的 My INMU 验证码是:\n\n{code}\n\n5 分钟内有效。如果这不是你本人的操作,请直接忽略这封邮件。\n\n{url}", + "card.day": "签到第 {n} 天", + "card.streak": "连续 {n} 天", + "card.no_meme": "梗图准备中", + "share.text": "我在 My INMU 签到第 {n} 天!", + "share.title": "{name} 的 INMU 小卡", + "share.open": "我也要签到" +} diff --git a/server/app/i18n/zh-TW.json b/server/app/i18n/zh-TW.json new file mode 100644 index 0000000..b353d5d --- /dev/null +++ b/server/app/i18n/zh-TW.json @@ -0,0 +1,10 @@ +{ + "mail.subject": "My INMU 驗證碼:{code}", + "mail.body": "你的 My INMU 驗證碼是:\n\n{code}\n\n5 分鐘內有效。如果這不是你本人的操作,請直接忽略這封信。\n\n{url}", + "card.day": "簽到第 {n} 天", + "card.streak": "連續 {n} 天", + "card.no_meme": "梗圖準備中", + "share.text": "我在 My INMU 簽到第 {n} 天!", + "share.title": "{name} 的 INMU 小卡", + "share.open": "我也要簽到" +} diff --git a/server/app/mailer.py b/server/app/mailer.py new file mode 100644 index 0000000..4a170da --- /dev/null +++ b/server/app/mailer.py @@ -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(("My INMU", 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) diff --git a/server/app/main.py b/server/app/main.py new file mode 100644 index 0000000..2a45f12 --- /dev/null +++ b/server/app/main.py @@ -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"), ("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:; 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="My INMU", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) + + +@app.middleware("http") +async def guard(request: Request, call_next): + # 防 CSRF:會改資料的 /api 請求要帶 X-INMU: 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-inmu") != "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)" if config.BETA else "") + html = html.replace("", ' (Beta)' 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") diff --git a/server/app/share.py b/server/app/share.py new file mode 100644 index 0000000..b3f30dd --- /dev/null +++ b/server/app/share.py @@ -0,0 +1,72 @@ +"""分享頁 /c//:有 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 = """ + + + + +{title} · {site} + + + + + + + + + + + + + + + +{title} +{open} + +""" + + +@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) + image_path = f"/card/{fmt_uid(uid)}/{day}.png" + return PAGE.format( + lang=lang, + site="My INMU (Beta)" if config.BETA else "My INMU", + 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")), + ) diff --git a/server/app/submissions.py b/server/app/submissions.py new file mode 100644 index 0000000..a6f7789 --- /dev/null +++ b/server/app/submissions.py @@ -0,0 +1,216 @@ +"""使用者投稿迷因圖,管理員審核。 + +流程:使用者上傳 → 重新編碼後存在 DATA_DIR/submissions/.(pending) + → 管理員同意:依 image/ 的命名規則存成 MEME_DIR/inmu_<下一號>.,之後的小卡就可能抽到 + → 管理員拒絕:刪掉檔案,紀錄保留(每日額度要算) +""" +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 fmt_uid, uid_tier + +router = APIRouter() + +MEME_NAME = re.compile(r"^inmu_(\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: + """迷因資料夾裡 inmu_.* 的最大編號 + 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 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"]), "uid_tier": uid_tier(row["uid"]), + "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"inmu_{n}.*")): + n += 1 + name = f"inmu_{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)} diff --git a/server/app/titles.py b/server/app/titles.py new file mode 100644 index 0000000..8277c2a --- /dev/null +++ b/server/app/titles.py @@ -0,0 +1,25 @@ +from . import config + +# 特殊序號:UID 用背景色標示,不帶任何權限。8 碼 UID 只要包含這些號碼就算(例如 00114514、51919810) +TIER_PATTERNS = ("1919810", "114514") + +# 底色、文字色(網頁的 web/style.css 用同樣的顏色) +TIER_COLORS = { + "admin": ((245, 197, 24), (30, 26, 36)), # 黃 #F5C518 + "1919810": ((240, 124, 42), (30, 26, 36)), # 橘 #F07C2A + "114514": ((47, 123, 235), (255, 255, 255)), # 藍 #2F7BEB +} + + +def fmt_uid(uid: int) -> str: + return f"{uid:08d}" + + +def uid_tier(uid: int) -> str | None: + if uid == config.ADMIN_UID: + return "admin" + s = fmt_uid(uid) + for pattern in TIER_PATTERNS: + if pattern in s: + return pattern + return None diff --git a/server/app/totp.py b/server/app/totp.py new file mode 100644 index 0000000..54bacde --- /dev/null +++ b/server/app/totp.py @@ -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 = "My INMU") -> str: + label = quote(f"{issuer}:{account}") + return f"otpauth://totp/{label}?secret={secret.replace(' ', '').upper()}&issuer={quote(issuer)}" diff --git a/server/app/users.py b/server/app/users.py new file mode 100644 index 0000000..7db31e3 --- /dev/null +++ b/server/app/users.py @@ -0,0 +1,201 @@ +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 current_user, fail +from .i18n import norm_lang +from .titles import fmt_uid, uid_tier + +router = APIRouter() + +# 關閉原始 HTML(輸入的 ", "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** "}) + data = r.json() + assert data["display_name"] == "野獸先輩" + assert "hi" in data["bio_html"] + assert " + + + +
+ + +
+ + + + + + + +
+
+ + +
+

+
+ +
+ + +

+
+
+ + + + +
+ + + + +
+
+
+ + + + diff --git a/web/logo.png b/web/logo.png new file mode 100644 index 0000000..cd6aa6d Binary files /dev/null and b/web/logo.png differ diff --git a/web/manifest.webmanifest b/web/manifest.webmanifest new file mode 100644 index 0000000..dbafb06 --- /dev/null +++ b/web/manifest.webmanifest @@ -0,0 +1,12 @@ +{ + "name": "My INMU", + "short_name": "My INMU", + "start_url": "/", + "display": "standalone", + "background_color": "#121016", + "theme_color": "#121016", + "icons": [ + { "src": "/assets/icon-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "/assets/icon-512.png", "sizes": "512x512", "type": "image/png" } + ] +} diff --git a/web/media/114514.m4a b/web/media/114514.m4a new file mode 100644 index 0000000..4e25b8c Binary files /dev/null and b/web/media/114514.m4a differ diff --git a/web/media/checkin-0.webp b/web/media/checkin-0.webp new file mode 100644 index 0000000..b0289ac Binary files /dev/null and b/web/media/checkin-0.webp differ diff --git a/web/media/checkin-1.webp b/web/media/checkin-1.webp new file mode 100644 index 0000000..54dfdbd Binary files /dev/null and b/web/media/checkin-1.webp differ diff --git a/web/style.css b/web/style.css new file mode 100644 index 0000000..0d054bf --- /dev/null +++ b/web/style.css @@ -0,0 +1,281 @@ +:root { + --bg: #121016; + --panel: #1c1922; + --panel-2: #26222e; + --line: #3a3448; + --text: #f5f3fa; + --muted: #b9b3c9; + --accent: #f0a43a; + --accent-ink: #1e1a24; + --error: #ff7a7a; + --radius: 12px; + color-scheme: dark; +} + +* { box-sizing: border-box; } +[hidden] { display: none !important; } + +html, body { margin: 0; height: 100%; } +body { + background: var(--bg); + color: var(--text); + font: 16px/1.6 system-ui, -apple-system, "Segoe UI", "Noto Sans TC", "Noto Sans JP", "Noto Sans KR", + "Microsoft JhengHei", "PingFang TC", sans-serif; +} +a { color: var(--accent); } + +.layout { display: flex; min-height: 100vh; } + +/* ---------- 側邊欄 ---------- */ +#sidebar { + width: 280px; + flex-shrink: 0; + background: var(--panel); + border-right: 1px solid var(--line); + padding: 20px; + display: flex; + flex-direction: column; + gap: 20px; +} +.brand { display: flex; align-items: center; justify-content: space-between; } +.brand a { display: flex; align-items: center; gap: 10px; color: var(--text); text-decoration: none; + font-weight: 800; font-size: 20px; } +.brand .logo { border-radius: 8px; object-fit: cover; } +#sidebar-body { display: flex; flex-direction: column; gap: 24px; flex: 1; } +#sidebar h2 { font-size: 18px; margin: 0 0 4px; } + +form { display: flex; flex-direction: column; gap: 12px; } +label { display: flex; flex-direction: column; gap: 4px; font-size: 14px; color: var(--muted); } +input, textarea, select { + font: inherit; + color: var(--text); + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: 8px; + padding: 10px 12px; + width: 100%; +} +input:focus, textarea:focus, select:focus { outline: 2px solid var(--accent); outline-offset: 0; } +#code { letter-spacing: .4em; font-size: 20px; text-align: center; } +textarea { resize: vertical; min-height: 120px; } + +button, .button { + font: inherit; + cursor: pointer; + border: 1px solid var(--line); + background: var(--panel-2); + color: var(--text); + border-radius: 999px; + padding: 9px 20px; + text-decoration: none; + display: inline-flex; + align-items: center; + justify-content: center; +} +button:disabled { opacity: .5; cursor: default; } +button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 700; } +button.link { background: none; border: none; padding: 0; color: var(--accent); border-radius: 0; } +button.link:disabled { color: var(--muted); } +.icon-btn { padding: 4px 10px; border-radius: 8px; font-size: 20px; } + +.row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; } +.spacer { flex: 1; } +.hint { font-size: 13px; color: var(--muted); margin: 0; } +.muted { color: var(--muted); } +.error { color: var(--error); font-size: 14px; margin: 0; } + +#me-box { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; } +.me-name { font-size: 20px; font-weight: 700; word-break: break-word; } +.me-nav { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; margin-top: 12px; } +.me-nav a { text-decoration: none; } + +.avatar { border-radius: 50%; object-fit: cover; background: var(--panel-2); width: 96px; height: 96px; } +.avatar.large { width: 160px; height: 160px; } + +.beta { font-size: 12px; font-weight: 600; color: var(--muted); } + +/* UID:特殊序號用背景色標示(和小卡的 server/app/titles.py TIER_COLORS 一致) */ +.uid { color: var(--muted); font-variant-numeric: tabular-nums; } +.uid.tier-admin, .uid.tier-1919810, .uid.tier-114514 { + display: inline-block; + font-weight: 700; + padding: 2px 10px; + border-radius: 8px; + margin-top: 2px; +} +.uid.tier-admin { background: #f5c518; color: #1e1a24; } +.uid.tier-1919810 { background: #f07c2a; color: #1e1a24; } +.uid.tier-114514 { background: #2f7beb; color: #fff; } + +.lang { margin-top: auto; } + +/* ---------- 主畫面 ---------- */ +#main { flex: 1; padding: 40px 24px; display: flex; justify-content: center; } +#view-checkin, #view-user, #view-upload, #view-review { width: 100%; max-width: 560px; } +#view-upload h1, #view-review h1 { font-size: 24px; margin: 0 0 8px; } +#view-upload h2 { font-size: 18px; margin: 28px 0 12px; } +.center { display: flex; flex-direction: column; align-items: center; gap: 16px; text-align: center; } +.center-text { text-align: center; } + +.big-mark { font-size: 72px; font-weight: 900; letter-spacing: .1em; color: var(--accent); margin-top: 10vh; } + +/* 簽到按鈕:圓角方形,平常是 checkin-0,按下去換成 checkin-1 + 音效 + 粒子 */ +.checkin-btn { + position: relative; + width: 220px; + height: 220px; + margin-top: 8vh; + padding: 0; + overflow: hidden; + border-radius: 28%; + border: 3px solid var(--accent); + background: var(--panel-2); + box-shadow: 0 16px 48px #f0a43a44; + transition: transform .15s; +} +.checkin-btn img { width: 100%; height: 100%; object-fit: cover; display: block; user-select: none; } +.checkin-label { + position: absolute; + left: 0; right: 0; bottom: 0; + padding: 6px 0 8px; + background: linear-gradient(transparent, #000c 70%); + color: #fff; + font-size: 22px; + font-weight: 900; + letter-spacing: .1em; +} +.checkin-btn:hover:not(:disabled) { transform: scale(1.04); } +.checkin-btn:active:not(:disabled) { transform: scale(.97); } +.checkin-btn:disabled { opacity: 1; } +.checkin-btn.pressed { animation: press-pop .45s ease-out; } +@keyframes press-pop { + 0% { transform: scale(.92); } + 45% { transform: scale(1.1) rotate(-2deg); } + 100% { transform: scale(1); } +} + +/* 粒子:位置、方向、距離、顏色由 app.js 用 CSS 變數指定 */ +.particle { + position: fixed; + left: var(--x); + top: var(--y); + width: var(--s); + height: var(--s); + border-radius: 50%; + background: var(--c); + pointer-events: none; + z-index: 20; + animation: burst var(--d, .9s) cubic-bezier(.12, .75, .3, 1) forwards; +} +.particle.digit { + width: auto; + height: auto; + background: none; + color: var(--c); + font-size: var(--s); + font-weight: 900; + line-height: 1; + text-shadow: 0 2px 6px #0008; +} +@keyframes burst { + from { transform: translate(-50%, -50%) scale(1); opacity: 1; } + 70% { opacity: 1; } + to { transform: translate(calc(-50% + var(--dx)), calc(-50% + var(--dy))) scale(.3) rotate(var(--r)); opacity: 0; } +} +@media (prefers-reduced-motion: reduce) { + .particle { display: none; } + .checkin-btn.pressed { animation: none; } +} + +.checkin-msg { font-size: 22px; font-weight: 700; margin: 0; } +.card-img { width: 100%; height: auto; border-radius: 16px; box-shadow: 0 12px 40px #0008; background: var(--panel); } +.stats { color: var(--muted); margin: 0; font-size: 15px; } +.actions { justify-content: center; } + +/* ---------- 投稿 / 審核 ---------- */ +.upload-bar { margin-top: 16px; } +.upload-bar label.button { color: var(--accent-ink); background: var(--accent); border-color: var(--accent); font-weight: 700; } +.upload-bar label.button.busy { opacity: .5; pointer-events: none; } +.sub-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 12px; } +.sub-item { position: relative; border-radius: 10px; overflow: hidden; background: var(--panel-2); aspect-ratio: 1; } +.sub-item img { width: 100%; height: 100%; object-fit: cover; display: block; } +.sub-status { + position: absolute; + left: 6px; bottom: 6px; + font-size: 12px; + font-weight: 700; + padding: 1px 8px; + border-radius: 999px; + background: #000b; + color: var(--text); +} +.sub-status.approved { background: #2f9e5a; color: #fff; } +.sub-status.rejected { background: #6b3a3a; color: #fff; } +.review-img { max-width: 100%; max-height: 60vh; border-radius: 12px; background: var(--panel); box-shadow: 0 12px 40px #0008; } +.review-meta { margin: 0; line-height: 1.9; } +#review-name { font-weight: 700; text-decoration: none; } + +.profile { display: flex; flex-direction: column; align-items: center; gap: 6px; text-align: center; } +.profile h1 { margin: 12px 0 0; font-size: 28px; word-break: break-word; } + +.bio { + width: 100%; + text-align: left; + background: var(--panel); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 4px 20px; + margin-top: 16px; + overflow-wrap: anywhere; +} +.bio pre { overflow-x: auto; background: var(--panel-2); padding: 12px; border-radius: 8px; } +.bio code { background: var(--panel-2); padding: 1px 5px; border-radius: 4px; } +.bio pre code { padding: 0; } +.bio blockquote { margin: 0; padding-left: 12px; border-left: 3px solid var(--line); color: var(--muted); } +.bio table { border-collapse: collapse; } +.bio th, .bio td { border: 1px solid var(--line); padding: 4px 8px; } +.bio.empty { color: var(--muted); padding: 16px 20px; } + +/* ---------- 編輯個人資料 ---------- */ +dialog { + width: min(560px, calc(100vw - 32px)); + background: var(--panel); + color: var(--text); + border: 1px solid var(--line); + border-radius: 16px; + padding: 24px; +} +dialog::backdrop { background: #000a; } +dialog h2 { margin: 0 0 4px; } +.avatar-edit { display: flex; gap: 16px; align-items: center; } +.avatar-edit .button { margin-bottom: 6px; } +.preview { margin-top: 0; max-height: 300px; overflow-y: auto; } +.dialog-actions { margin-top: 8px; } + +#toast { + position: fixed; + left: 50%; + bottom: 32px; + transform: translateX(-50%); + background: var(--panel-2); + border: 1px solid var(--line); + padding: 10px 20px; + border-radius: 999px; + box-shadow: 0 8px 24px #0008; + z-index: 10; +} + +.only-mobile { display: none; } + +/* ---------- 手機:側欄收到上方 ---------- */ +@media (max-width: 760px) { + .layout { flex-direction: column; } + #sidebar { width: 100%; border-right: none; border-bottom: 1px solid var(--line); padding: 12px 16px; gap: 12px; } + .only-mobile { display: inline-flex; } + #sidebar:not(.open) #sidebar-body { display: none; } + #sidebar-body { padding-bottom: 8px; } + #main { padding: 24px 16px; } + .checkin-btn { width: 180px; height: 180px; margin-top: 6vh; } + .checkin-label { font-size: 18px; } + .big-mark { font-size: 56px; margin-top: 6vh; } +}