Skip to content

Commit 8283f7d

Browse files
committed
v0.2.25: 11128 抓现行——被拒请求体落盘 ~/.wbspy/denials(保留5份)+ /api/denials 查看/下载/清理
1 parent 2e91147 commit 8283f7d

5 files changed

Lines changed: 143 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,15 @@
22

33
全部 notable 变更按版本倒序记录。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/)。
44

5+
## [0.2.25] — 2026-11-08
6+
7+
### 新增
8+
- **11128 抓现行:被拒请求体落盘**。v0.2.21~0.2.23 三枚指纹中和后仍有大会话被拒(403KB 级请求、system 降级重试也挂)——上游显然换了词或启用了新规则,盲猜没有意义,改为让网关自己保存证据:
9+
- 11128 类内容审查被拒时,把**出站后的完整请求体**(已过中和管线,与真实发送内容一致)写到 `~/.wbspy/denials/`,仅保留最近 5 份(带时间戳+随机后缀防同秒覆盖),落盘失败静默不影响对话;
10+
- token 不在请求体里,落盘无凭据泄露;错误消息附留存文件路径;
11+
- 管理面板新增 `GET /api/denials`(列表)/ `GET /api/denials/{name}`(下载)/ `DELETE /api/denials/{name}`(清理),带路径穿越防护;
12+
- 下载后发回来即可逐枚比对定位新指纹——中和对策的可迭代闭环从「猜」变成「看」。
13+
514
## [0.2.24] — 2026-11-09
615

716
### 新增

‎tests/test_wbspy.py‎

Lines changed: 71 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2728,9 +2728,14 @@ def test_medium_body_flags_kb(self):
27282728
self.assertNotIn("降级", out.message) # 没试过降级不冒功
27292729

27302730
def test_small_body_no_size_section(self):
2731+
import tempfile
2732+
from pathlib import Path
2733+
from unittest.mock import patch
27312734
from wbspy.upstream import annotate_denial
2732-
out = annotate_denial(self._err(), "短消息", demoted=False)
2733-
self.assertNotIn("请求体", out.message)
2735+
with tempfile.TemporaryDirectory() as tmp: # 落盘到临时目录,不污染 home
2736+
with patch("wbspy.upstream.DENIALS_DIR", Path(tmp)):
2737+
out = annotate_denial(self._err(), "短消息", demoted=False)
2738+
self.assertNotIn("KB", out.message)
27342739
self.assertIn("新开会话", out.message)
27352740

27362741
def test_chat_integrates_annotation(self):
@@ -3251,3 +3256,67 @@ def test_lane_wipeout_alert(self):
32513256
self.assertEqual(wipe[0]["level"], "error")
32523257
self.assertIn("重新授权", wipe[0]["action"])
32533258
self.assertEqual(out["alive"], 0)
3259+
3260+
3261+
class TestDenialCapture(unittest.TestCase):
3262+
"""11128 抓现行:被拒请求体落盘 + 面板端点可查看/下载/删除。"""
3263+
3264+
def test_capture_writes_and_prunes(self):
3265+
"""落盘 JSON、仅保留最近 DENIALS_KEEP 份。"""
3266+
import tempfile
3267+
from pathlib import Path
3268+
from unittest.mock import patch
3269+
from wbspy import upstream
3270+
with tempfile.TemporaryDirectory() as tmp:
3271+
with patch.object(upstream, "DENIALS_DIR", Path(tmp)):
3272+
name = upstream.capture_denial_body('{"messages":[]}', 403)
3273+
self.assertTrue(name and "-403-" in name)
3274+
self.assertEqual((Path(tmp) / name).read_text(encoding="utf-8"),
3275+
'{"messages":[]}')
3276+
for i in range(upstream.DENIALS_KEEP + 3):
3277+
upstream.capture_denial_body(f'{{"n":{i}}}', 403)
3278+
time.sleep(0.01)
3279+
files = sorted(Path(tmp).glob("*.json"))
3280+
self.assertEqual(len(files), upstream.DENIALS_KEEP)
3281+
# 落盘失败静默:DIR 指向文件
3282+
with patch.object(upstream, "DENIALS_DIR", Path(tmp) / "f"):
3283+
(Path(tmp) / "f").write_text("x")
3284+
self.assertIsNone(upstream.capture_denial_body("{}", 403))
3285+
3286+
def test_annotate_mentions_saved_file(self):
3287+
"""annotate_denial 附上留存文件名,指引面板下载。"""
3288+
import tempfile
3289+
from pathlib import Path
3290+
from unittest.mock import patch
3291+
from wbspy import upstream
3292+
with tempfile.TemporaryDirectory() as tmp:
3293+
with patch.object(upstream, "DENIALS_DIR", Path(tmp)):
3294+
err = upstream.annotate_denial(
3295+
upstream.UpstreamError(403, "11128", "denied"), "x" * 100, False)
3296+
self.assertIn("~/.wbspy/denials/", err.message)
3297+
self.assertTrue((Path(tmp)).is_dir())
3298+
3299+
def test_webui_denial_endpoints(self):
3300+
"""/api/denials 列表 + 下载 + 路径穿越拒绝。"""
3301+
import tempfile
3302+
from pathlib import Path
3303+
from unittest.mock import patch
3304+
from fastapi.testclient import TestClient
3305+
from wbspy import upstream
3306+
from wbspy.pool import AccountPool
3307+
from wbspy.webui import create_web_app
3308+
with tempfile.TemporaryDirectory() as tmp:
3309+
(Path(tmp) / "20261108-114500-403.json").write_text('{"a":1}')
3310+
with patch.object(upstream, "DENIALS_DIR", Path(tmp)):
3311+
c = TestClient(create_web_app(AccountPool([]), api_key=""))
3312+
rows = c.get("/api/denials").json()["data"]["items"]
3313+
self.assertEqual(len(rows), 1)
3314+
self.assertIn("403", rows[0]["name"])
3315+
r = c.get(f"/api/denials/{rows[0]['name']}")
3316+
self.assertEqual(r.status_code, 200)
3317+
self.assertEqual(r.json(), {"a": 1})
3318+
self.assertEqual(c.get("/api/denials/..%2Fetc").status_code, 404)
3319+
self.assertEqual(c.get("/api/denials/nope.json").status_code, 404)
3320+
self.assertEqual(
3321+
c.delete(f"/api/denials/{rows[0]['name']}").status_code, 200)
3322+
self.assertEqual(c.get("/api/denials").json()["data"]["items"], [])

‎wbspy/_version.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@
55
导致 0.2.5~0.2.12 运行时始终自报 0.2.4(更新弹窗永远显示 v0.2.4 → vX.Y.Z)。
66
"""
77

8-
__version__ = "0.2.24"
8+
__version__ = "0.2.25"

‎wbspy/upstream.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import re
2626
import time
2727
import uuid
28+
from pathlib import Path
2829
from typing import Any, Iterable
2930

3031
import requests
@@ -348,6 +349,30 @@ def normalize_payload(raw: dict) -> dict:
348349
return payload
349350

350351

352+
def capture_denial_body(body_text: str, status: int) -> str | None:
353+
"""11128 类内容审查被拒时,把出站请求体落盘「抓现行」。
354+
355+
关键词中和管不到上游新换的词——盲猜没有意义,直接保存被拒的完整
356+
请求体供下载分析(token 不在请求体里,落盘无凭据泄露)。仅保留
357+
最近 DENIALS_KEEP 份,磁盘占用可控。失败静默(不能因落盘挂掉对话)。
358+
"""
359+
try:
360+
DENIALS_DIR.mkdir(parents=True, exist_ok=True)
361+
name = (time.strftime("%Y%m%d-%H%M%S") + f"-{status}"
362+
+ f"-{uuid.uuid4().hex[:6]}.json")
363+
(DENIALS_DIR / name).write_text(body_text, encoding="utf-8")
364+
olds = sorted(DENIALS_DIR.glob("*.json"))
365+
for old in olds[:-DENIALS_KEEP]:
366+
old.unlink(missing_ok=True)
367+
return name
368+
except Exception:
369+
return None
370+
371+
372+
DENIALS_DIR = Path.home() / ".wbspy" / "denials"
373+
DENIALS_KEEP = 5
374+
375+
351376
def annotate_denial(error: UpstreamError, body_text: str, demoted: bool) -> UpstreamError:
352377
"""11128 错误消息附诊断注解:请求体大小 + 已试过的对策 + 行动指引。
353378
@@ -368,6 +393,10 @@ def annotate_denial(error: UpstreamError, body_text: str, demoted: bool) -> Upst
368393
"unapproved channel 文案是误导;网关出站已默认用零宽空格中和关键词,"
369394
"仍被拒说明上游换了词或命中其他内容规则")
370395
tips.append("建议新开会话;若仍被拒则调整本次发送的内容")
396+
saved = capture_denial_body(body_text, error.status)
397+
if saved:
398+
tips.append(f"本次被拒请求体已留存:~/.wbspy/denials/{saved},"
399+
"管理面板「诊断」可查看/下载,发回来即可定位新指纹")
371400
return UpstreamError(error.status, error.code,
372401
error.message + "(" + ";".join(tips) + ")",
373402
retry_after=error.retry_after,

‎wbspy/webui.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,39 @@ def api_logs():
402402
"""全局运行日志(悬浮面板用):最近日志行 + 累计行数(未读徽标依据)。"""
403403
return _ok({"log": app.state.auto_log[-200:], "total": app.state.auto_total})
404404

405+
# -- 11128 抓现行(被拒请求体留存) -----------------------------------------
406+
407+
@app.get("/api/denials")
408+
def api_denials():
409+
from .upstream import DENIALS_DIR, DENIALS_KEEP
410+
items = []
411+
if DENIALS_DIR.is_dir():
412+
for p in sorted(DENIALS_DIR.glob("*.json"), reverse=True):
413+
items.append({"name": p.name, "size": p.stat().st_size,
414+
"at": time.strftime("%m-%d %H:%M:%S",
415+
time.localtime(p.stat().st_mtime))})
416+
return _ok({"items": items[:DENIALS_KEEP], "dir": str(DENIALS_DIR)})
417+
418+
@app.get("/api/denials/{name}")
419+
def api_denial_body(name: str):
420+
from .upstream import DENIALS_DIR
421+
if "/" in name or "\\" in name or ".." in name:
422+
raise HTTPException(404, "not found")
423+
p = DENIALS_DIR / name
424+
if not p.is_file():
425+
raise HTTPException(404, "not found")
426+
return FileResponse(p, media_type="application/json", filename=name)
427+
428+
@app.delete("/api/denials/{name}")
429+
def api_denial_delete(name: str):
430+
from .upstream import DENIALS_DIR
431+
if "/" in name or "\\" in name or ".." in name:
432+
return _err("bad name", 404)
433+
p = DENIALS_DIR / name
434+
if p.is_file():
435+
p.unlink()
436+
return _ok()
437+
405438
@app.get("/api/automation/status")
406439
def automation_status():
407440
auto = load_config().get("automation") or {}

0 commit comments

Comments
 (0)