修复值班邮件跨站确认,独立记录未确认缺勤并与活动统计隔离

This commit is contained in:
2026-11-06 16:30:25 +08:00
parent b32ef79384
commit 7584f5232e
9 changed files with 192 additions and 11 deletions
+2
View File
@@ -201,6 +201,8 @@ async def reminder_loop(schedule_path, state_path, get_accounts, send_email, ove
while True:
try:
schedule = load_schedule(schedule_path)
from .duty_receipts import sync_absences
await asyncio.to_thread(sync_absences, state_path, schedule, datetime.now(BEIJING))
if schedule["enabled"]:
overrides = json.loads(Path(overrides_path).read_text(encoding="utf-8-sig")) if overrides_path and Path(overrides_path).exists() else {}
result = await send_due(schedule, datetime.now(BEIJING), await get_accounts(), send_email, state_path, overrides, base_url)
+55 -1
View File
@@ -6,6 +6,7 @@ import sqlite3
import time
from contextlib import closing
from html import escape
from datetime import date, datetime, timedelta
def connect(path):
@@ -14,6 +15,9 @@ def connect(path):
con.row_factory = sqlite3.Row
con.execute("CREATE TABLE IF NOT EXISTS duty_receipts (day TEXT, slot TEXT, name TEXT, attempts INTEGER DEFAULT 0, sent_count INTEGER DEFAULT 0, last_attempt REAL DEFAULT 0, last_sent REAL DEFAULT 0, confirmed REAL DEFAULT 0, PRIMARY KEY(day,slot,name))")
con.execute("CREATE TABLE IF NOT EXISTS duty_confirmations (digest TEXT PRIMARY KEY, targets TEXT NOT NULL, expires REAL NOT NULL)")
con.execute("CREATE TABLE IF NOT EXISTS duty_confirmation_forms (digest TEXT PRIMARY KEY, nonce_hash TEXT NOT NULL)")
con.execute("CREATE TABLE IF NOT EXISTS duty_absences (day TEXT, slot TEXT, name TEXT, end_at REAL NOT NULL, recorded_at REAL NOT NULL, PRIMARY KEY(day,slot,name))")
con.execute("CREATE TABLE IF NOT EXISTS duty_audit_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
return con
@@ -65,12 +69,28 @@ def mark_sent(path, day, names, now):
con.commit()
def confirmation(path, token, now, consume=False):
def issue_confirmation_form(path, token, now):
with closing(connect(path)) as con:
digest = hashlib.sha256(token.encode()).hexdigest()
row = con.execute("SELECT expires FROM duty_confirmations WHERE digest=?", (digest,)).fetchone()
if row is None or row[0] <= now:
return None
nonce = secrets.token_urlsafe(32)
con.execute("INSERT OR REPLACE INTO duty_confirmation_forms VALUES (?,?)", (digest, hashlib.sha256(nonce.encode()).hexdigest()))
con.commit()
return nonce
def confirmation(path, token, now, consume=False, form_token=None, require_form=False):
with closing(connect(path)) as con:
con.execute("BEGIN IMMEDIATE")
row = con.execute("SELECT * FROM duty_confirmations WHERE digest=?", (hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
if row is None or row["expires"] <= now:
return None
if consume and require_form:
form = con.execute("SELECT nonce_hash FROM duty_confirmation_forms WHERE digest=?", (hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
if form is None or not form_token or not secrets.compare_digest(form[0], hashlib.sha256(form_token.encode()).hexdigest()):
return None
targets = json.loads(row["targets"])
if consume:
for day, slot, name in targets:
@@ -91,6 +111,40 @@ def reserve_test(path, email, now):
return True
def sync_absences(path, schedule, now):
from .duty import BEIJING, duties_on
now = now.astimezone(BEIJING)
with closing(connect(path)) as con:
con.execute("BEGIN IMMEDIATE")
cursor = con.execute("SELECT value FROM duty_audit_state WHERE key='day'").fetchone()
first = max(date.fromisoformat(schedule["anchor_date"]), date.fromisoformat(cursor[0]) if cursor else now.date())
if schedule["enabled"]:
day = first
while day <= now.date():
_, assignments = duties_on(schedule, day)
for name, slots in assignments.items():
for slot in slots:
clock = schedule.get("slot_times", {}).get(slot)
if not clock:
continue
end = datetime.combine(day, datetime.strptime(clock, '%H:%M').time(), BEIJING) + timedelta(minutes=schedule.get('duration_minutes', 105))
if end > now:
continue
ensure(con, day.isoformat(), slot, name, None)
row = con.execute("SELECT confirmed FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day.isoformat(), slot, name)).fetchone()
if not row[0] or row[0] > end.timestamp():
con.execute("INSERT OR IGNORE INTO duty_absences VALUES (?,?,?,?,?)", (day.isoformat(), slot, name, end.timestamp(), now.timestamp()))
day += timedelta(days=1)
con.execute("INSERT OR REPLACE INTO duty_audit_state VALUES ('day',?)", (now.date().isoformat(),))
con.commit()
def absence_records(path, limit=50, offset=0):
with closing(connect(path)) as con:
rows = con.execute("SELECT * FROM duty_absences ORDER BY day DESC,end_at DESC,name LIMIT ? OFFSET ?", (limit, offset)).fetchall()
return [{"day": r['day'], "slot": r['slot'], "name": r['name'], "end_at": int(r['end_at'] * 1000), "recorded_at": int(r['recorded_at'] * 1000), "reason": "未确认缺勤"} for r in rows]
async def send_notice(path, day, names, email, expires, send_email, subject, body, base_url, now=None):
import asyncio
now = time.time() if now is None else now
+38 -6
View File
@@ -645,7 +645,10 @@ async def security_headers(request: Request, call_next):
origin = request.headers.get("origin")
own_origin = str(request.base_url).rstrip("/")
trusted_origin = BASE_URL or own_origin
if request.method not in ("GET", "HEAD", "OPTIONS") and (
# 此独立回执入口依赖不可猜测的邮件令牌及 GET 页面签发的表单令牌;
# 邮件内置浏览器可能把合法表单提交标为 cross-site,其他入口仍严格检查。
duty_confirmation_post = request.method == "POST" and re.fullmatch(r"/duty-confirm/[A-Za-z0-9_-]{32,128}", request.url.path)
if not duty_confirmation_post and request.method not in ("GET", "HEAD", "OPTIONS") and (
(origin and origin not in (own_origin, trusted_origin))
or request.headers.get("sec-fetch-site") == "cross-site"
):
@@ -1239,7 +1242,9 @@ async def current_duty(_viewer: dict = Depends(current_user), db: AsyncSession =
if not path.exists():
return duty_status({"enabled": False}, datetime.now(BEIJING))
try:
data = duty_status(load_schedule(path), datetime.now(BEIJING))
schedule = load_schedule(path)
await asyncio.to_thread(duty_receipts.sync_absences, _duty_state(), schedule, datetime.now(BEIJING))
data = duty_status(schedule, datetime.now(BEIJING))
accounts = [dict(r) for r in (await db.execute(select(users.c.display_name, users.c.email))).mappings()]
overrides = _duty_overrides()
for shift in (data["current"], data["next"]):
@@ -1258,6 +1263,17 @@ def _duty_state():
return _db_path.with_name("duty-reminders.db")
@app.get("/api/duty/absences")
async def list_duty_absences(_viewer: dict = Depends(current_user), limit: int = Query(50, ge=1, le=100), offset: int = Query(0, ge=0)):
path = Path(os.getenv("WORKLOG_DUTY_SCHEDULE", str(PROJECT_DIR / "duty/schedule.json")))
if path.exists():
try:
await asyncio.to_thread(duty_receipts.sync_absences, _duty_state(), load_schedule(path), datetime.now(BEIJING))
except (ValueError, KeyError, TypeError, OSError) as exc:
raise HTTPException(status_code=503, detail="值班安排暂时无法读取") from exc
return {"items": await asyncio.to_thread(duty_receipts.absence_records, _duty_state(), limit, offset)}
@app.post("/api/auth/test-email")
async def test_account_email(viewer: dict = Depends(current_user)):
email = viewer.get("email", "").strip()
@@ -1304,13 +1320,29 @@ async def remind_duty(payload: DutyRemindIn, viewer: dict = Depends(current_user
@app.get("/duty-confirm/{token}", include_in_schema=False)
@app.post("/duty-confirm/{token}", include_in_schema=False)
async def confirm_duty(token: str, request: Request):
targets = await asyncio.to_thread(duty_receipts.confirmation, _duty_state(), token, time.time(), request.method == "POST")
from urllib.parse import parse_qs
now = time.time()
form_token = None
if request.method == "POST":
body = await request.body()
if len(body) > 4096:
raise HTTPException(status_code=400, detail="确认请求无效,请重新打开邮件链接")
form_token = parse_qs(body.decode("utf-8", errors="replace")).get("confirmation_token", [None])[0]
targets = await asyncio.to_thread(duty_receipts.confirmation, _duty_state(), token, now, request.method == "POST", form_token, True)
if targets is None:
return HTMLResponse(_join_page("确认链接无效或本轮值班已结束。", "err"), status_code=410)
return HTMLResponse(_duty_confirmation_page("确认链接无效、表单已更新或本轮值班已结束,请重新打开邮件链接。"), status_code=410)
text = ";".join(f"{day} {slot} {name}" for day, slot, name in targets)
if request.method == "GET":
return HTMLResponse(_join_page("请确认已知晓:" + text, "confirm", extra='<form method="post"><button class="btn" type="submit">确认已知晓值班安排</button></form>'))
return HTMLResponse(_join_page("已确认值班安排,谢谢。", "ok"))
nonce = await asyncio.to_thread(duty_receipts.issue_confirmation_form, _duty_state(), token, now)
if not nonce:
return HTMLResponse(_duty_confirmation_page("本轮确认链接已失效。"), status_code=410)
return HTMLResponse(_duty_confirmation_page("请确认已知晓:" + text, nonce))
return HTMLResponse(_duty_confirmation_page("已确认值班安排,谢谢。本次确认仅记录值班回执。"))
def _duty_confirmation_page(message: str, nonce: str | None = None):
form = f'<form method="post"><input type="hidden" name="confirmation_token" value="{escape(nonce, quote=True)}"><button type="submit">确认已知晓值班安排</button></form>' if nonce else ''
return f'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>值班邮件确认 · WorkLog</title><style>body{{font:16px/1.8 system-ui,sans-serif;background:#f5f7f5;color:#263c35;margin:0;padding:32px 20px}}main{{max-width:480px;margin:8vh auto;background:white;border:1px solid #e1e8e3;border-radius:16px;padding:28px}}h1{{font-size:24px}}button{{background:#28664f;color:white;border:0;border-radius:8px;padding:12px 20px;font:inherit;cursor:pointer}}p{{overflow-wrap:anywhere}}</style><main><h1>值班邮件确认</h1><p>{escape(message)}</p>{form}</main></html>'
@app.get("/api/stats/overview")
async def overview(db: AsyncSession = Depends(get_db), _viewer: dict = Depends(current_user)) -> dict: