diff --git a/dist/assets/styles.css b/dist/assets/styles.css index cef7847..4ed8254 100644 --- a/dist/assets/styles.css +++ b/dist/assets/styles.css @@ -578,3 +578,6 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s #change-email-result:empty { display: none; } .duty-absence-row { display: flex; align-items: center; gap: 10px 16px; flex-wrap: wrap; padding: 12px 0; border-bottom: 1px solid var(--line); } .duty-absence-row b { color: var(--ink); } +.duty-row-actions { display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; } +.settings-divider { border: 0; border-top: 1px solid var(--line); margin: 24px 0; } +@media (max-width: 520px) { .duty-reminder-row { flex-wrap: wrap; } .duty-row-actions { width: 100%; } } diff --git a/dist/index.html b/dist/index.html index dc595e1..1826366 100644 --- a/dist/index.html +++ b/dist/index.html @@ -5,7 +5,7 @@ WorkLog · 活动记录 - +
@@ -133,7 +133,7 @@
值班缺勤记录 -

本轮结束仍未确认邮件,记为“未确认缺勤”。此记录不代表实际到岗核验,值班不计入活动统计。

+

本轮结束仍未在网站或邮件中确认,记为“未确认缺勤”。此记录不代表实际到岗核验,值班不计入活动统计。

@@ -248,6 +248,11 @@

向当前账号绑定的邮箱发送测试邮件,同一邮箱每 2 分钟可测试一次。

+
+ +

测试按钮跳转和确认,不改变正式活动、值班和缺勤记录。与连通性测试共用 2 分钟冷却。

+ +

登录方式

@@ -273,7 +278,7 @@ - +
diff --git a/dist/js/app.js b/dist/js/app.js index 8efe10a..de6f71c 100644 --- a/dist/js/app.js +++ b/dist/js/app.js @@ -547,7 +547,8 @@ $("#duty-reminders").innerHTML = !shift || expired ? "" : (shift.reminders || []).map((r) => `
${esc(r.name)} ${r.confirmed_at ? '已确认' : '未确认'} ${r.last_sent_at ? `已提醒 ${dutyDate(r.last_sent_at, true)}` : '尚未成功发送'} · ${r.attempts}/3 次${r.confirmed_at ? ` · 确认于 ${dutyDate(r.confirmed_at, true)}` : ''}${r.matched ? '' : ' · 未匹配邮箱'}
- ${!r.confirmed_at ? `` : ''}
`).join(""); +
${r.can_confirm ? `` : ''} + ${!r.confirmed_at ? `` : ''}
`).join(""); } $("#duty-banner").classList.toggle("on-duty", !!active); $("#duty-clock").classList.toggle("hidden", !shift || !!expired); @@ -601,6 +602,16 @@ }, 1000); document.addEventListener("visibilitychange", () => { if (!document.hidden) loadDutyStatus(); }); $("#duty-reminders").addEventListener("click", async (event) => { + const confirmButton = event.target.closest("[data-duty-confirm]"); + if (confirmButton && !confirmButton.disabled) { + confirmButton.disabled = true; + try { + await api("/duty/confirm", { method: "POST", body: { start_at: Number(confirmButton.dataset.dutyConfirm) } }); + toast("已确认你的值班安排"); + } catch (error) { toast(error.message, true); } + finally { await loadDutyStatus(); } + return; + } const button = event.target.closest("[data-duty-remind]"); if (!button || button.disabled) return; button.disabled = true; @@ -617,7 +628,18 @@ const left = Math.max(0, Math.ceil((until - Date.now()) / 1000)); $("#pf-test-email").disabled = left > 0; $("#pf-test-email").textContent = left ? `${left} 秒后可再次测试` : "发送测试邮件"; + $("#pf-test-button-email").disabled = left > 0; + $("#pf-test-button-email").textContent = left ? `${left} 秒后可再次测试` : "发送按钮测试邮件"; } + $("#pf-test-button-email").addEventListener("click", async () => { + testEmailCooldowns.set(state.me.email.toLowerCase(), Date.now() + 120000); + updateTestEmailButton(); + $("#pf-test-button-status").textContent = "正在发送…"; + try { + await api("/auth/test-button-email", { method: "POST", body: { kind: $("#pf-test-button-kind").value } }); + $("#pf-test-button-status").textContent = "按钮测试邮件已发送,请打开邮件按钮并在页面中确认。"; + } catch (error) { $("#pf-test-button-status").textContent = error.message; } + }); $("#pf-test-email").addEventListener("click", async () => { testEmailCooldowns.set(state.me.email.toLowerCase(), Date.now() + 120000); updateTestEmailButton(); diff --git a/duty/README.md b/duty/README.md index a742108..8c17320 100644 --- a/duty/README.md +++ b/duty/README.md @@ -47,6 +47,10 @@ python -m server.duty --date 2026-11-09 --db /app/data/worklog.db --emails /app/ 每人每轮自动和手动提醒合计最多尝试 3 次,失败尝试也计入上限。手动补发仅限活动墙正在展示的本轮或下一轮,距上次尝试至少 1 分钟。已确认后该轮不再发送。状态保存在 duty-reminders.db 中,刷新、重启和并发点击均不会重置限额。 +轮到值班的同学也可登录网站,在活动墙点击本人排班旁的“确认我的值班”。仅允许确认当前或下一轮、尚未结束的本人排班;同名账号不自动认领。网站与邮件使用同一份确认回执,无需先收到邮件,确认不增加邮件次数或活动记录。确认链接的请求结果会输出到服务日志 `[confirmation]`,仅记录类型、方法、状态码和来源类别,不记录链接中的秘密令牌。 + +设置页可选择“值班确认按钮”或“活动参加按钮”并发送一封按钮测试邮件。测试邮件只发给当前账号绑定邮箱,与普通连通性测试共用 120 秒限制。按钮使用 `/mail-test/` 独立测试记录,打开并确认不会创建正式活动、参加记录或值班回执,24 小时内有效。正式活动邮件的 `/join/` 入口也使用页面签发的表单凭据,兼容邮件客户端的跨站标记。 + 账号设置中可发送连通性测试邮件,仅发送到本人当前绑定邮箱。同一邮箱(忽略大小写)每 120 秒最多尝试一次,服务端持久化限流;发送失败也需等待冷却结束。此测试独立于值班提醒次数。 线上确认按钮使用配置的 `server.base_url`(当前为 https://worklog.bansonic.top),`WORKLOG_BASE_URL` 可覆盖。本地预览请覆盖为 http://127.0.0.1:37777,以便确认本机保存的回执。 diff --git a/server/duty_receipts.py b/server/duty_receipts.py index 522515b..4b2ae17 100644 --- a/server/duty_receipts.py +++ b/server/duty_receipts.py @@ -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) diff --git a/server/main.py b/server/main.py index b0c4797..0130893 100644 --- a/server/main.py +++ b/server/main.py @@ -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'

{label}按钮测试

仅测试邮件按钮跳转和确认,不改变正式记录。链接24小时内有效。

{label}(测试)
' + 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'
' if nonce else '' - return f'值班邮件确认 · WorkLog

值班邮件确认

{escape(message)}

{form}
' +def _confirmation_page(message: str, nonce: str | None = None, title='值班邮件确认', button_label='确认已知晓值班安排'): + form = f'
' if nonce else '' + return f'{escape(title)} · WorkLog

{escape(title)}

{escape(message)}

{form}
' @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"], - '
', + f'
', )) + 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)) diff --git a/tests/test_api.py b/tests/test_api.py index cfef6c1..a0df747 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -90,6 +90,86 @@ class ApiTestCase(unittest.IsolatedAsyncioTestCase): class WorkLogApiTests(ApiTestCase): + async def test_button_test_emails_are_private_throttled_and_do_not_change_real_records(self): + from unittest.mock import AsyncMock + import re + self.assertEqual((await self.client.post('/api/auth/test-button-email', json={'kind':'duty'})).status_code, 401) + owner = await register(self.client, 'buttontester') + for kind in ('duty', 'activity'): + with tempfile.TemporaryDirectory() as directory: + with patch.object(self.m, '_duty_state', return_value=Path(directory) / 'state.db'), patch.object(self.m, '_send_email', new_callable=AsyncMock) as send: + response = await self.client.post('/api/auth/test-button-email', headers=auth(owner['token']), json={'kind':kind,'email':'other@example.test'}) + self.assertEqual(response.status_code, 200) + self.assertEqual(send.await_args.args[0], owner['user']['email']) + token = send.await_args.args[2].split('/mail-test/')[1].split()[0] + url = '/mail-test/' + token + page = await self.client.get(url) + self.assertEqual(page.status_code, 200) + nonce = re.search(r'name="confirmation_token" value="([^"]+)"', page.text).group(1) + self.assertEqual((await self.client.post(url, headers={'Origin':'null','Sec-Fetch-Site':'cross-site'})).status_code, 403) + response = await self.client.post(url, data={'confirmation_token':nonce}, headers={'Origin':'null','Sec-Fetch-Site':'cross-site'}) + self.assertEqual(response.status_code, 200) + self.assertIn('按钮测试确认成功', response.text) + self.assertEqual((await self.client.post('/api/auth/test-email', headers=auth(owner['token']))).status_code, 429) + self.assertEqual((await self.client.post('/api/auth/test-button-email', headers=auth(owner['token']), json={'kind':kind})).status_code, 429) + self.assertEqual(send.await_count, 1) + async with self.sessions() as db: + self.assertFalse((await db.execute(select(self.m.activities))).all()) + self.assertFalse((await db.execute(select(self.m.participations))).all()) + + async def test_confirm_own_duty_on_site_without_email(self): + from datetime import datetime, timedelta + from unittest.mock import AsyncMock + from server.duty import BEIJING, ROOT, load_schedule, duty_status + from server import duty_receipts + schedule = load_schedule(ROOT / 'duty/schedule.json') + data = duty_status(schedule, datetime.now(BEIJING)) + shift = data['current'] or data['next'] + name = shift['names'][0] + owner = await register(self.client, name) + other = await register(self.client, '非本轮同学') + request = {'start_at': shift['start_at']} + with tempfile.TemporaryDirectory() as directory: + with patch.object(self.m, '_duty_state', return_value=Path(directory) / 'state.db'), patch.object(self.m, '_send_email', new_callable=AsyncMock) as send: + self.assertEqual((await self.client.post('/api/duty/confirm', json=request)).status_code, 401) + self.assertEqual((await self.client.post('/api/duty/confirm', headers=auth(other['token']), json=request)).status_code, 403) + self.assertEqual((await self.client.post('/api/duty/confirm', headers=auth(owner['token']), json={**request, 'name': other['user']['display_name']})).status_code, 422) + self.assertEqual((await self.client.post('/api/duty/confirm', headers=auth(owner['token']), json={'start_at': 1})).status_code, 409) + before = (await self.client.get('/api/duty/current', headers=auth(owner['token']))).json() + own_shift = next(s for s in (before['current'], before['next']) if s and s['start_at'] == shift['start_at']) + self.assertTrue(next(r for r in own_shift['reminders'] if r['name'] == name)['can_confirm']) + response = await self.client.post('/api/duty/confirm', headers=auth(owner['token']), json=request) + self.assertEqual(response.status_code, 200, response.text) + repeat = await self.client.post('/api/duty/confirm', headers=auth(owner['token']), json=request) + self.assertEqual(response.json()['confirmed_at'], repeat.json()['confirmed_at']) + after = (await self.client.get('/api/duty/current', headers=auth(owner['token']))).json() + own_shift = next(s for s in (after['current'], after['next']) if s and s['start_at'] == shift['start_at']) + receipt = next(r for r in own_shift['reminders'] if r['name'] == name) + self.assertFalse(receipt['can_confirm']) + self.assertFalse(receipt['can_remind']) + self.assertEqual(receipt['attempts'], 0) + self.assertEqual(receipt['sent_count'], 0) + send.assert_not_called() + end = datetime.fromtimestamp(shift['end_at'] / 1000, BEIJING) + duty_receipts.sync_absences(Path(directory) / 'state.db', schedule, end + timedelta(seconds=1)) + self.assertNotIn(name, [r['name'] for r in duty_receipts.absence_records(Path(directory) / 'state.db')]) + async with self.sessions() as db: + self.assertFalse((await db.execute(select(self.m.activities))).all()) + self.assertFalse((await db.execute(select(self.m.participations))).all()) + + async def test_same_named_accounts_cannot_claim_duty(self): + from datetime import datetime + from server.duty import BEIJING, ROOT, load_schedule, duty_status + data = duty_status(load_schedule(ROOT / 'duty/schedule.json'), datetime.now(BEIJING)) + shift = data['current'] or data['next'] + name = shift['names'][0] + first = await register(self.client, name) + await register(self.client, name, email='same-name@example.test', phone='13900009999') + with tempfile.TemporaryDirectory() as directory: + with patch.object(self.m, '_duty_state', return_value=Path(directory) / 'state.db'): + response = await self.client.post('/api/duty/confirm', headers=auth(first['token']), json={'start_at': shift['start_at']}) + self.assertEqual(response.status_code, 403) + async def test_duty_reminder_and_confirmation_flow(self): from datetime import datetime from unittest.mock import AsyncMock diff --git a/tests/test_duty_receipts.py b/tests/test_duty_receipts.py index 524a1fe..6b6f017 100644 --- a/tests/test_duty_receipts.py +++ b/tests/test_duty_receipts.py @@ -7,6 +7,13 @@ from server import duty_receipts as r class ReceiptsTests(unittest.IsolatedAsyncioTestCase): + def test_site_confirmation_is_idempotent_and_blocks_late_confirmation(self): + args = (self.path, '2026-11-06', '一二节', '同学', 'a@example.test') + self.assertEqual(r.confirm_on_site(*args, 1000, 1100), 1000000) + self.assertEqual(r.confirm_on_site(*args, 1001, 1100), 1000000) + self.assertIsNone(r.confirm_on_site(*args, 1100, 1100)) + self.assertEqual(r.reserve(self.path, '2026-11-06', {'同学': ['一二节']}, 'a@example.test', 2000, 1001), (None, {})) + def test_absence_only_after_end_and_separate_from_confirmation(self): from datetime import datetime from server.duty import BEIJING, ROOT, load_schedule diff --git a/tests/test_notify.py b/tests/test_notify.py index af25c50..9c9c6bb 100644 --- a/tests/test_notify.py +++ b/tests/test_notify.py @@ -124,7 +124,9 @@ class NotifyTests(unittest.IsolatedAsyncioTestCase): async with self.sessions() as db: people = await self.m._require_participant(db, self.m_activity_id, bob["user"]["id"]) self.assertIsNone(people) - r = await c.post(f"/join/{token}") + import re + nonce = re.search(r'name="confirmation_token" value="([^"]+)"', r.text).group(1) + r = await c.post(f"/join/{token}", data={'confirmation_token': nonce}, headers={'Origin': 'null', 'Sec-Fetch-Site': 'cross-site'}) self.assertIn("记录成功", r.text) self.assertIn("客户答谢会", r.text) @@ -142,7 +144,9 @@ class NotifyTests(unittest.IsolatedAsyncioTestCase): # 丙的链接仍可用(每人一个独立 token) carol_url = self.join_url(mail_to("c@example.test")) - r = await c.post(carol_url) + page = await c.get(carol_url) + nonce = re.search(r'name="confirmation_token" value="([^"]+)"', page.text).group(1) + r = await c.post(carol_url, data={'confirmation_token': nonce}) self.assertIn("记录成功", r.text) async def test_private_activity_no_notify(self): diff --git a/tests/test_security.py b/tests/test_security.py index 82a99f3..5c60b37 100644 --- a/tests/test_security.py +++ b/tests/test_security.py @@ -163,13 +163,30 @@ class SecurityTests(ApiTestCase): async def test_private_leave_response_does_not_expose_activity(self): owner, viewer, activity, token = await self.make_link() - await self.client.post(f"/join/{token}") + import re + page = await self.client.get(f"/join/{token}") + nonce = re.search(r'name="confirmation_token" value="([^"]+)"', page.text).group(1) + await self.client.post(f"/join/{token}", data={'confirmation_token': nonce}) await self.client.patch(f"/api/activities/{activity['id']}", headers=auth(owner["token"]), json={"visibility": "private"}) response = await self.client.post(f"/api/activities/{activity['id']}/leave", headers=auth(viewer["token"])) self.assertEqual(response.json(), {"ok": True}) response = await self.client.get(f"/api/activities/{activity['id']}", headers=auth(viewer["token"])) self.assertEqual(response.status_code, 403) + async def test_activity_mail_confirmation_requires_form_even_with_valid_link(self): + import re + owner, viewer, activity, token = await self.make_link() + url = f'/join/{token}' + page = await self.client.get(url) + nonce = re.search(r'name="confirmation_token" value="([^"]+)"', page.text).group(1) + response = await self.client.post(url, headers={'Origin':'null','Sec-Fetch-Site':'cross-site'}) + self.assertEqual(response.status_code, 403) + async with self.sessions() as db: + self.assertIsNone(await self.m._require_participant(db, activity['id'], viewer['user']['id'])) + response = await self.client.post(url, data={'confirmation_token':nonce}, headers={'Origin':'null','Sec-Fetch-Site':'cross-site'}) + self.assertEqual(response.status_code, 200) + self.assertIn('记录成功', response.text) + async def test_path_traversal_cannot_read_sibling_directory(self): frontend = self.directory / "dist" frontend.mkdir() @@ -196,7 +213,10 @@ class SecurityTests(ApiTestCase): self.client.post("/api/auth/login", json={"email": email, "email_code": code}) for _ in range(2) ]) self.assertEqual(sorted(r.status_code for r in replies), [200, 400]) - replies = await asyncio.gather(*[self.client.post(f"/join/{token}") for _ in range(2)]) + import re + page = await self.client.get(f"/join/{token}") + nonce = re.search(r'name="confirmation_token" value="([^"]+)"', page.text).group(1) + replies = await asyncio.gather(*[self.client.post(f"/join/{token}", data={'confirmation_token': nonce}) for _ in range(2)]) self.assertEqual(sum("记录成功" in r.text for r in replies), 1) async with file_sessions() as db: rows = (await db.execute(select(self.m.participations).where(