新增网站值班确认和按钮测试邮件入口,修复活动邮件跨站确认
This commit is contained in:
@@ -18,6 +18,7 @@ def connect(path):
|
||||
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)")
|
||||
con.execute("CREATE TABLE IF NOT EXISTS mail_button_tests (digest TEXT PRIMARY KEY, kind TEXT NOT NULL, expires REAL NOT NULL, confirmed REAL NOT NULL DEFAULT 0)")
|
||||
return con
|
||||
|
||||
|
||||
@@ -69,6 +70,18 @@ def mark_sent(path, day, names, now):
|
||||
con.commit()
|
||||
|
||||
|
||||
def confirm_on_site(path, day, slot, name, email, now, end_at):
|
||||
if now >= end_at:
|
||||
return None
|
||||
with closing(connect(path)) as con:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
ensure(con, day, slot, name, email)
|
||||
con.execute("UPDATE duty_receipts SET confirmed=CASE WHEN confirmed=0 THEN ? ELSE confirmed END WHERE day=? AND slot=? AND name=?", (now, day, slot, name))
|
||||
confirmed = con.execute("SELECT confirmed FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day, slot, name)).fetchone()[0]
|
||||
con.commit()
|
||||
return int(confirmed * 1000)
|
||||
|
||||
|
||||
def issue_confirmation_form(path, token, now):
|
||||
with closing(connect(path)) as con:
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
@@ -81,6 +94,24 @@ def issue_confirmation_form(path, token, now):
|
||||
return nonce
|
||||
|
||||
|
||||
def issue_activity_form(path, token, namespace='activity'):
|
||||
digest = hashlib.sha256((namespace + ':' + token).encode()).hexdigest()
|
||||
nonce = secrets.token_urlsafe(32)
|
||||
with closing(connect(path)) as con:
|
||||
con.execute("INSERT OR REPLACE INTO duty_confirmation_forms VALUES (?,?)", (digest, hashlib.sha256(nonce.encode()).hexdigest()))
|
||||
con.commit()
|
||||
return nonce
|
||||
|
||||
|
||||
def validate_activity_form(path, token, nonce, namespace='activity'):
|
||||
if not nonce:
|
||||
return False
|
||||
digest = hashlib.sha256((namespace + ':' + token).encode()).hexdigest()
|
||||
with closing(connect(path)) as con:
|
||||
row = con.execute("SELECT nonce_hash FROM duty_confirmation_forms WHERE digest=?", (digest,)).fetchone()
|
||||
return bool(row and secrets.compare_digest(row[0], hashlib.sha256(nonce.encode()).hexdigest()))
|
||||
|
||||
|
||||
def confirmation(path, token, now, consume=False, form_token=None, require_form=False):
|
||||
with closing(connect(path)) as con:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
@@ -111,6 +142,26 @@ def reserve_test(path, email, now):
|
||||
return True
|
||||
|
||||
|
||||
def create_button_test(path, kind, now):
|
||||
token = secrets.token_urlsafe(32)
|
||||
with closing(connect(path)) as con:
|
||||
con.execute("INSERT INTO mail_button_tests(digest,kind,expires) VALUES (?,?,?)", (hashlib.sha256(token.encode()).hexdigest(), kind, now + 86400))
|
||||
con.commit()
|
||||
return token
|
||||
|
||||
|
||||
def button_test(path, token, now, consume=False):
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
with closing(connect(path)) as con:
|
||||
row = con.execute("SELECT * FROM mail_button_tests WHERE digest=? AND expires>?", (digest, now)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
if consume:
|
||||
con.execute("UPDATE mail_button_tests SET confirmed=CASE WHEN confirmed=0 THEN ? ELSE confirmed END WHERE digest=?", (now, digest))
|
||||
con.commit()
|
||||
return row['kind']
|
||||
|
||||
|
||||
def sync_absences(path, schedule, now):
|
||||
from .duty import BEIJING, duties_on
|
||||
now = now.astimezone(BEIJING)
|
||||
|
||||
+88
-12
@@ -647,8 +647,8 @@ async def security_headers(request: Request, call_next):
|
||||
trusted_origin = BASE_URL or own_origin
|
||||
# 此独立回执入口依赖不可猜测的邮件令牌及 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 (
|
||||
token_confirmation_post = request.method == "POST" and re.fullmatch(r"/(?:duty-confirm|join|mail-test)/[A-Za-z0-9_-]{32,128}", request.url.path)
|
||||
if not token_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"
|
||||
):
|
||||
@@ -663,8 +663,14 @@ async def security_headers(request: Request, call_next):
|
||||
"img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; "
|
||||
"frame-ancestors 'none'; form-action 'self'"
|
||||
)
|
||||
if request.url.path.startswith(("/api/", "/join/", "/duty-confirm/")):
|
||||
if request.url.path.startswith(("/api/", "/join/", "/duty-confirm/", "/mail-test/")):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
if request.url.path.startswith(("/join/", "/duty-confirm/", "/mail-test/")):
|
||||
kind = "test" if request.url.path.startswith("/mail-test/") else ("duty" if request.url.path.startswith("/duty-confirm/") else "activity")
|
||||
origin_kind = "none" if not origin else ("null" if origin == "null" else ("trusted" if origin in (own_origin, trusted_origin) else "other"))
|
||||
site = request.headers.get("sec-fetch-site", "none")
|
||||
site = site if site in ("none", "same-origin", "same-site", "cross-site") else "other"
|
||||
print(f"[confirmation] {datetime.now(BEIJING):%Y-%m-%d %H:%M:%S} kind={kind} method={request.method} status={response.status_code} origin={origin_kind} site={site}", flush=True)
|
||||
return response
|
||||
|
||||
|
||||
@@ -1245,7 +1251,7 @@ async def current_duty(_viewer: dict = Depends(current_user), db: AsyncSession =
|
||||
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()]
|
||||
accounts = [dict(r) for r in (await db.execute(select(users.c.id, users.c.display_name, users.c.email))).mappings()]
|
||||
overrides = _duty_overrides()
|
||||
for shift in (data["current"], data["next"]):
|
||||
if not shift:
|
||||
@@ -1254,6 +1260,10 @@ async def current_duty(_viewer: dict = Depends(current_user), db: AsyncSession =
|
||||
emails = {name: email for email, names in recipients.items() for name in names}
|
||||
day = datetime.fromtimestamp(shift["start_at"] / 1000, BEIJING).date().isoformat()
|
||||
shift["reminders"] = [await asyncio.to_thread(duty_receipts.status, _duty_state(), day, shift["slot"], name, emails.get(name), time.time()) for name in shift["names"]]
|
||||
for receipt in shift["reminders"]:
|
||||
owners = [a for a in accounts if a["display_name"].strip() == receipt["name"]]
|
||||
receipt["is_self"] = len(owners) == 1 and owners[0]["id"] == _viewer["id"]
|
||||
receipt["can_confirm"] = receipt["is_self"] and not receipt["confirmed_at"] and time.time() < shift["end_at"] / 1000
|
||||
return data
|
||||
except (ValueError, KeyError, TypeError, OSError) as exc:
|
||||
raise HTTPException(status_code=503, detail="值班安排暂时无法读取") from exc
|
||||
@@ -1296,6 +1306,66 @@ class DutyRemindIn(BaseModel):
|
||||
start_at: int
|
||||
|
||||
|
||||
class ButtonTestIn(BaseModel):
|
||||
kind: Literal["duty", "activity"]
|
||||
|
||||
|
||||
@app.post("/api/auth/test-button-email")
|
||||
async def test_button_email(payload: ButtonTestIn, viewer: dict = Depends(current_user)):
|
||||
email = viewer.get('email', '').strip()
|
||||
if not email:
|
||||
raise HTTPException(status_code=409, detail="当前账号尚未绑定邮箱")
|
||||
if not await asyncio.to_thread(duty_receipts.reserve_test, _duty_state(), email, time.time()):
|
||||
raise HTTPException(status_code=429, detail="同一邮箱2分钟内只能测试一次,请稍后重试")
|
||||
token = await asyncio.to_thread(duty_receipts.create_button_test, _duty_state(), payload.kind, time.time())
|
||||
label = '值班确认' if payload.kind == 'duty' else '活动参加'
|
||||
url = _site_base_url() + '/mail-test/' + token
|
||||
text = f'这是{label}按钮测试邮件。打开链接后请点击页面中的确认按钮。仅用于测试,不改变正式活动、值班或缺勤记录。链接24小时内有效。\n{url}'
|
||||
html = f'<div style="font-family:sans-serif;line-height:1.8"><h2>{label}按钮测试</h2><p>仅测试邮件按钮跳转和确认,不改变正式记录。链接24小时内有效。</p><a href="{escape(url, quote=True)}" style="display:inline-block;padding:12px 24px;background:#28664f;color:white;border-radius:8px;text-decoration:none">{label}(测试)</a></div>'
|
||||
await _send_email(email, f'【WorkLog测试】{label}按钮', text, html)
|
||||
return {'ok': True, 'retry_after': 120}
|
||||
|
||||
|
||||
@app.get('/mail-test/{token}', include_in_schema=False)
|
||||
@app.post('/mail-test/{token}', include_in_schema=False)
|
||||
async def confirm_button_test(token: str, request: Request):
|
||||
from urllib.parse import parse_qs
|
||||
kind = await asyncio.to_thread(duty_receipts.button_test, _duty_state(), token, time.time())
|
||||
if not kind:
|
||||
return HTMLResponse(_confirmation_page('测试链接无效或已过期。', title='邮件按钮测试'), status_code=410)
|
||||
label = '值班确认' if kind == 'duty' else '活动参加'
|
||||
if request.method == 'GET':
|
||||
nonce = await asyncio.to_thread(duty_receipts.issue_activity_form, _duty_state(), token, 'mail-test')
|
||||
return HTMLResponse(_confirmation_page('此操作仅用于按钮测试,不改变正式记录。', nonce, title=label + '测试', button_label='确认测试'))
|
||||
body = await request.body()
|
||||
nonce = parse_qs(body.decode('utf-8', errors='replace')).get('confirmation_token', [None])[0] if len(body) <= 4096 else None
|
||||
if not await asyncio.to_thread(duty_receipts.validate_activity_form, _duty_state(), token, nonce, 'mail-test'):
|
||||
return HTMLResponse(_confirmation_page('请重新打开测试邮件,再点击确认。', title='邮件按钮测试'), status_code=403)
|
||||
await asyncio.to_thread(duty_receipts.button_test, _duty_state(), token, time.time(), True)
|
||||
return HTMLResponse(_confirmation_page('按钮测试确认成功,正式活动、值班和缺勤记录未发生变化。', title=label + '测试'))
|
||||
|
||||
|
||||
class DutySiteConfirmIn(BaseModel):
|
||||
model_config = {"extra": "forbid"}
|
||||
start_at: int
|
||||
|
||||
|
||||
@app.post("/api/duty/confirm")
|
||||
async def confirm_own_duty(payload: DutySiteConfirmIn, viewer: dict = Depends(current_user), db: AsyncSession = Depends(get_db)):
|
||||
data = await current_duty(viewer, db)
|
||||
shift = next((s for s in (data["current"], data["next"]) if s and s["start_at"] == payload.start_at), None)
|
||||
if shift is None:
|
||||
raise HTTPException(status_code=409, detail="值班安排已变化或本轮已结束,请刷新页面")
|
||||
receipt = next((r for r in shift["reminders"] if r["is_self"]), None)
|
||||
if receipt is None:
|
||||
raise HTTPException(status_code=403, detail="只能确认自己的值班;同名账号请先联系负责人核对")
|
||||
day = datetime.fromtimestamp(shift["start_at"] / 1000, BEIJING).date().isoformat()
|
||||
confirmed = await asyncio.to_thread(duty_receipts.confirm_on_site, _duty_state(), day, shift["slot"], receipt["name"], viewer["email"], time.time(), shift["end_at"] / 1000)
|
||||
if confirmed is None:
|
||||
raise HTTPException(status_code=409, detail="本轮值班已结束,不能补确认")
|
||||
return {"ok": True, "confirmed_at": confirmed}
|
||||
|
||||
|
||||
@app.post("/api/duty/remind")
|
||||
async def remind_duty(payload: DutyRemindIn, viewer: dict = Depends(current_user), db: AsyncSession = Depends(get_db)):
|
||||
data = await current_duty(viewer, db)
|
||||
@@ -1330,19 +1400,19 @@ async def confirm_duty(token: str, request: Request):
|
||||
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(_duty_confirmation_page("确认链接无效、表单已更新或本轮值班已结束,请重新打开邮件链接。"), status_code=410)
|
||||
return HTMLResponse(_confirmation_page("确认链接无效、表单已更新或本轮值班已结束,请重新打开邮件链接。"), status_code=410)
|
||||
text = ";".join(f"{day} {slot} {name}" for day, slot, name in targets)
|
||||
if request.method == "GET":
|
||||
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("已确认值班安排,谢谢。本次确认仅记录值班回执。"))
|
||||
return HTMLResponse(_confirmation_page("本轮确认链接已失效。"), status_code=410)
|
||||
return HTMLResponse(_confirmation_page("请确认已知晓:" + text, nonce))
|
||||
return HTMLResponse(_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>'
|
||||
def _confirmation_page(message: str, nonce: str | None = None, title='值班邮件确认', button_label='确认已知晓值班安排'):
|
||||
form = f'<form method="post"><input type="hidden" name="confirmation_token" value="{escape(nonce, quote=True)}"><button type="submit">{escape(button_label)}</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>{escape(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>{escape(title)}</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:
|
||||
@@ -1774,10 +1844,16 @@ async def join_by_email_link(token: str, request: Request, db: AsyncSession = De
|
||||
if request.method == "GET":
|
||||
if await _require_participant(db, row["id"], user["id"]) is not None:
|
||||
return HTMLResponse(_join_page("你已经在那条记录里了,无需重复添加。", "ok", row["title"]))
|
||||
nonce = await asyncio.to_thread(duty_receipts.issue_activity_form, _duty_state(), token)
|
||||
return HTMLResponse(_join_page(
|
||||
"确认将你记为该活动的参加人。", "confirm", row["title"],
|
||||
'<form method="post"><button class="btn" type="submit">确认我也参加过</button></form>',
|
||||
f'<form method="post"><input type="hidden" name="confirmation_token" value="{escape(nonce, quote=True)}"><button class="btn" type="submit">确认我也参加过</button></form>',
|
||||
))
|
||||
from urllib.parse import parse_qs
|
||||
body = await request.body()
|
||||
nonce = parse_qs(body.decode('utf-8', errors='replace')).get('confirmation_token', [None])[0] if len(body) <= 4096 else None
|
||||
if not await asyncio.to_thread(duty_receipts.validate_activity_form, _duty_state(), token, nonce):
|
||||
return HTMLResponse(_join_page("确认页面已更新,请重新打开邮件链接,再点击页面中的确认按钮。", "err"), status_code=403)
|
||||
claimed = await db.execute(update(join_links).where(
|
||||
join_links.c.id == link["id"], join_links.c.used == 0, join_links.c.expires_at > now_ms(),
|
||||
).values(used=1))
|
||||
|
||||
Reference in New Issue
Block a user