wechatbridge-cli 1.7.2__tar.gz → 1.8.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/PKG-INFO +6 -4
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/README.md +5 -3
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/tests/test_codex.py +13 -2
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/tests/test_dsh.py +3 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/tests/test_hardening.py +262 -7
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/tests/test_price.py +96 -27
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/__init__.py +1 -1
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/agy.py +3 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/codex.py +5 -3
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/config.py +5 -2
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/main.py +122 -36
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/price.py +29 -22
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/runner_common.py +58 -17
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/PKG-INFO +6 -4
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/LICENSE +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/pyproject.toml +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/setup.cfg +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/tests/test_codex_auth.py +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/tests/test_grok_auth.py +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/__main__.py +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/dsh.py +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/grok.py +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/ilink.py +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge/update_check.py +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/SOURCES.txt +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/dependency_links.txt +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/entry_points.txt +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/requires.txt +0 -0
- {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: wechatbridge-cli
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.8.0
|
|
4
4
|
Summary: Bridge WeChat messages to agy, Grok Build, or Codex CLIs — text/image/file/voice in, CLI replies and generated files back.
|
|
5
5
|
Author: WeChatBridge contributors
|
|
6
6
|
License: MIT
|
|
@@ -54,7 +54,7 @@ The bridge process stays up and long-polls iLink. For prompts that go to a CLI,
|
|
|
54
54
|
- Runtime backend switch: `/backend agy`, `/backend grok`, `/backend codex`, or `/backend dsh` (clears that backend's continuation state — the agy/grok continuation flag and the codex `thread_id`/resume state — so the next CLI turn starts a fresh session; history files on disk are not wiped immediately)
|
|
55
55
|
- Slash commands for model, session reset, persona, and more (see below)
|
|
56
56
|
- Dangerous-prompt gate: a **keyword list** of concrete destructive patterns asks for confirmation before run
|
|
57
|
-
- Sender whitelist (`WECHATBRIDGE_ALLOWED_SENDERS`; empty = allow all)
|
|
57
|
+
- Sender whitelist (`WECHATBRIDGE_ALLOWED_SENDERS`; non-empty = listed users only, `*` = allow all; empty = admins only, deny all when no admins)
|
|
58
58
|
- `/mcp` returns short usage text; `/agent` rewrites into a natural-language subagent prompt for the CLI (not a native MCP bridge)
|
|
59
59
|
- Media over WeChat CDN with AES-128-ECB encrypt/decrypt
|
|
60
60
|
- Multi-instance: one codebase, set `WECHATBRIDGE_INSTANCE` per process (state / session / QR paths derive from it)
|
|
@@ -191,7 +191,7 @@ Key variables (all have defaults):
|
|
|
191
191
|
| `WECHATBRIDGE_DSH_STATE_DIR` | _derived_ | bridge-private dsh state directory (memory JSONL and persistent session IDs; defaults to `~/.local/share/wechatbridge/<instance>/dsh_state`) |
|
|
192
192
|
| `WECHATBRIDGE_BACKEND` | `agy` | global default backend (`agy` / `grok` / `codex` / `dsh`; overridable per user via `/backend`) |
|
|
193
193
|
| `WECHATBRIDGE_INSTANCE` | `default` | instance name; state / session / QR paths derive from it |
|
|
194
|
-
| `WECHATBRIDGE_ALLOWED_SENDERS` | _empty_ | comma-separated WeChat IDs
|
|
194
|
+
| `WECHATBRIDGE_ALLOWED_SENDERS` | _empty_ | comma-separated WeChat IDs; `*` = allow all; empty = only `WECHATBRIDGE_ADMINS` users (deny all if that is empty too) |
|
|
195
195
|
| `AGY_TIMEOUT` | `600` | CLI run timeout in seconds (agy / grok / codex backends) |
|
|
196
196
|
| `WECHATBRIDGE_MAX_OUTBOUND_BYTES` | `104857600` | max file size sent back to WeChat (100 MB) |
|
|
197
197
|
| `WECHATBRIDGE_MAX_INBOUND_BYTES` | `20971520` | max inbound image/file after download (20 MB) |
|
|
@@ -234,6 +234,8 @@ Data lives under `~/.local/share/wechatbridge/<instance>/` (sessions, SQLite his
|
|
|
234
234
|
|
|
235
235
|
Before upgrading a **major** or **minor** version (e.g. 1.2 → 1.3), check the corresponding section in [`CHANGELOG.md`](CHANGELOG.md) for breaking changes and migration steps.
|
|
236
236
|
|
|
237
|
+
> **Before upgrading to 1.8.0:** configure `WECHATBRIDGE_ADMINS` or `WECHATBRIDGE_ALLOWED_SENDERS` in your `.env` — since 1.8.0 the whitelist denies everyone when both are empty (set `WECHATBRIDGE_ALLOWED_SENDERS=*` to keep allowing all users).
|
|
238
|
+
|
|
237
239
|
## Deploy
|
|
238
240
|
|
|
239
241
|
### Linux (systemd)
|
|
@@ -330,7 +332,7 @@ Other `/…` commands are either rejected (e.g. `/exit`), reported as unsupporte
|
|
|
330
332
|
|
|
331
333
|
## Ops & security (what the bridge actually enforces)
|
|
332
334
|
|
|
333
|
-
- **Whitelist first.** Empty `WECHATBRIDGE_ALLOWED_SENDERS` means
|
|
335
|
+
- **Whitelist first.** Empty `WECHATBRIDGE_ALLOWED_SENDERS` means only `WECHATBRIDGE_ADMINS` members can use the bridge (everyone when the list is `*`, no one when both are empty).
|
|
334
336
|
- **Auto-approve CLIs.** agy runs with `--dangerously-skip-permissions`; grok with `--always-approve` (unless planning mode); dsh tools run without host path restrictions. Treat this as trusted-user tooling, not a multi-tenant sandbox.
|
|
335
337
|
- **Danger gate is keyword-based**, not full intent understanding. Defaults target concrete patterns (`rm -rf /`, pipe-to-shell, `mkfs`, `format c:`, a few heavy Chinese phrases, …). Everyday wording like bare “delete” is **not** gated. Override list via `WECHATBRIDGE_CONFIRM_KEYWORDS`; approve with `WECHATBRIDGE_CONFIRM_TOKEN` (default `y`), TTL `WECHATBRIDGE_PENDING_TTL`.
|
|
336
338
|
- **Inbound media** is size-capped (default 20 MB), streamed, and CDN hosts are allowlisted. Missing `aes_key` returns a clear error.
|
|
@@ -22,7 +22,7 @@ The bridge process stays up and long-polls iLink. For prompts that go to a CLI,
|
|
|
22
22
|
- Runtime backend switch: `/backend agy`, `/backend grok`, `/backend codex`, or `/backend dsh` (clears that backend's continuation state — the agy/grok continuation flag and the codex `thread_id`/resume state — so the next CLI turn starts a fresh session; history files on disk are not wiped immediately)
|
|
23
23
|
- Slash commands for model, session reset, persona, and more (see below)
|
|
24
24
|
- Dangerous-prompt gate: a **keyword list** of concrete destructive patterns asks for confirmation before run
|
|
25
|
-
- Sender whitelist (`WECHATBRIDGE_ALLOWED_SENDERS`; empty = allow all)
|
|
25
|
+
- Sender whitelist (`WECHATBRIDGE_ALLOWED_SENDERS`; non-empty = listed users only, `*` = allow all; empty = admins only, deny all when no admins)
|
|
26
26
|
- `/mcp` returns short usage text; `/agent` rewrites into a natural-language subagent prompt for the CLI (not a native MCP bridge)
|
|
27
27
|
- Media over WeChat CDN with AES-128-ECB encrypt/decrypt
|
|
28
28
|
- Multi-instance: one codebase, set `WECHATBRIDGE_INSTANCE` per process (state / session / QR paths derive from it)
|
|
@@ -159,7 +159,7 @@ Key variables (all have defaults):
|
|
|
159
159
|
| `WECHATBRIDGE_DSH_STATE_DIR` | _derived_ | bridge-private dsh state directory (memory JSONL and persistent session IDs; defaults to `~/.local/share/wechatbridge/<instance>/dsh_state`) |
|
|
160
160
|
| `WECHATBRIDGE_BACKEND` | `agy` | global default backend (`agy` / `grok` / `codex` / `dsh`; overridable per user via `/backend`) |
|
|
161
161
|
| `WECHATBRIDGE_INSTANCE` | `default` | instance name; state / session / QR paths derive from it |
|
|
162
|
-
| `WECHATBRIDGE_ALLOWED_SENDERS` | _empty_ | comma-separated WeChat IDs
|
|
162
|
+
| `WECHATBRIDGE_ALLOWED_SENDERS` | _empty_ | comma-separated WeChat IDs; `*` = allow all; empty = only `WECHATBRIDGE_ADMINS` users (deny all if that is empty too) |
|
|
163
163
|
| `AGY_TIMEOUT` | `600` | CLI run timeout in seconds (agy / grok / codex backends) |
|
|
164
164
|
| `WECHATBRIDGE_MAX_OUTBOUND_BYTES` | `104857600` | max file size sent back to WeChat (100 MB) |
|
|
165
165
|
| `WECHATBRIDGE_MAX_INBOUND_BYTES` | `20971520` | max inbound image/file after download (20 MB) |
|
|
@@ -202,6 +202,8 @@ Data lives under `~/.local/share/wechatbridge/<instance>/` (sessions, SQLite his
|
|
|
202
202
|
|
|
203
203
|
Before upgrading a **major** or **minor** version (e.g. 1.2 → 1.3), check the corresponding section in [`CHANGELOG.md`](CHANGELOG.md) for breaking changes and migration steps.
|
|
204
204
|
|
|
205
|
+
> **Before upgrading to 1.8.0:** configure `WECHATBRIDGE_ADMINS` or `WECHATBRIDGE_ALLOWED_SENDERS` in your `.env` — since 1.8.0 the whitelist denies everyone when both are empty (set `WECHATBRIDGE_ALLOWED_SENDERS=*` to keep allowing all users).
|
|
206
|
+
|
|
205
207
|
## Deploy
|
|
206
208
|
|
|
207
209
|
### Linux (systemd)
|
|
@@ -298,7 +300,7 @@ Other `/…` commands are either rejected (e.g. `/exit`), reported as unsupporte
|
|
|
298
300
|
|
|
299
301
|
## Ops & security (what the bridge actually enforces)
|
|
300
302
|
|
|
301
|
-
- **Whitelist first.** Empty `WECHATBRIDGE_ALLOWED_SENDERS` means
|
|
303
|
+
- **Whitelist first.** Empty `WECHATBRIDGE_ALLOWED_SENDERS` means only `WECHATBRIDGE_ADMINS` members can use the bridge (everyone when the list is `*`, no one when both are empty).
|
|
302
304
|
- **Auto-approve CLIs.** agy runs with `--dangerously-skip-permissions`; grok with `--always-approve` (unless planning mode); dsh tools run without host path restrictions. Treat this as trusted-user tooling, not a multi-tenant sandbox.
|
|
303
305
|
- **Danger gate is keyword-based**, not full intent understanding. Defaults target concrete patterns (`rm -rf /`, pipe-to-shell, `mkfs`, `format c:`, a few heavy Chinese phrases, …). Everyday wording like bare “delete” is **not** gated. Override list via `WECHATBRIDGE_CONFIRM_KEYWORDS`; approve with `WECHATBRIDGE_CONFIRM_TOKEN` (default `y`), TTL `WECHATBRIDGE_PENDING_TTL`.
|
|
304
306
|
- **Inbound media** is size-capped (default 20 MB), streamed, and CDN hosts are allowlisted. Missing `aes_key` returns a clear error.
|
|
@@ -43,14 +43,24 @@ class TestBuildCodexCommand(unittest.TestCase):
|
|
|
43
43
|
self.assertEqual(
|
|
44
44
|
cmd,
|
|
45
45
|
["codex", "exec", "--json", "--skip-git-repo-check",
|
|
46
|
-
"--dangerously-bypass-approvals-and-sandbox", "hello"],
|
|
46
|
+
"--dangerously-bypass-approvals-and-sandbox", "--", "hello"],
|
|
47
47
|
)
|
|
48
48
|
|
|
49
49
|
def test_prompt_is_last_positional(self):
|
|
50
50
|
cmd = self._cmd(prompt="a b c")
|
|
51
51
|
self.assertEqual(cmd[-1], "a b c")
|
|
52
|
+
self.assertEqual(cmd[-2], "--")
|
|
52
53
|
self.assertNotIn("resume", cmd)
|
|
53
54
|
|
|
55
|
+
def test_dash_prompt_after_separator(self):
|
|
56
|
+
# 以 '-' 开头的 prompt 必须跟在 "--" 之后,否则被 codex CLI 当选项。
|
|
57
|
+
cmd = self._cmd(prompt="--help")
|
|
58
|
+
self.assertEqual(cmd[-1], "--help")
|
|
59
|
+
self.assertEqual(cmd[-2], "--")
|
|
60
|
+
# prompt 本身就是 "--" 时也必须保留(fake_codex 只删第一个分隔符)
|
|
61
|
+
cmd = self._cmd(prompt="--")
|
|
62
|
+
self.assertEqual(cmd[-2:], ["--", "--"])
|
|
63
|
+
|
|
54
64
|
def test_plan_mode_uses_readonly_sandbox(self):
|
|
55
65
|
cmd = self._cmd(prefs={"mode": "plan"})
|
|
56
66
|
self.assertIn("--sandbox", cmd)
|
|
@@ -92,9 +102,10 @@ class TestBuildCodexCommand(unittest.TestCase):
|
|
|
92
102
|
cmd = self._cmd(first=False, thread_id="tid-123")
|
|
93
103
|
self.assertIn("resume", cmd)
|
|
94
104
|
self.assertIn("tid-123", cmd)
|
|
95
|
-
# resume 是子命令,options 在前,prompt
|
|
105
|
+
# resume 是子命令,options 在前,"--" 分隔符之后是 prompt
|
|
96
106
|
self.assertEqual(cmd[cmd.index("resume") + 1], "tid-123")
|
|
97
107
|
self.assertEqual(cmd[-1], "hello")
|
|
108
|
+
self.assertEqual(cmd[-2], "--")
|
|
98
109
|
|
|
99
110
|
def test_resume_no_yolo_skip_when_plan(self):
|
|
100
111
|
cmd = self._cmd(first=False, thread_id="tid", prefs={"mode": "plan"})
|
|
@@ -411,6 +411,9 @@ class _DshIntegrationBase:
|
|
|
411
411
|
p4.start(); self._patchers.append(p4)
|
|
412
412
|
p_ck = mock.patch.object(config, "confirm_keywords", [])
|
|
413
413
|
p_ck.start(); self._patchers.append(p_ck)
|
|
414
|
+
# fail-closed 白名单下,集成用例走 process_message 需显式放开
|
|
415
|
+
p_as = mock.patch.object(config, "allowed_senders", ["*"])
|
|
416
|
+
p_as.start(); self._patchers.append(p_as)
|
|
414
417
|
p_env = mock.patch.dict(os.environ, {"WECHATBRIDGE_CONFIRM_KEYWORDS": ""}, clear=False)
|
|
415
418
|
p_env.start(); self._patchers.append(p_env)
|
|
416
419
|
|
|
@@ -1218,6 +1218,19 @@ class TestPerUserLockContract(unittest.IsolatedAsyncioTestCase):
|
|
|
1218
1218
|
m["_kind"] = kind
|
|
1219
1219
|
return m
|
|
1220
1220
|
|
|
1221
|
+
async def _pump_until(self, predicate, tries=100):
|
|
1222
|
+
"""Yield to the loop until predicate() holds (bounded).
|
|
1223
|
+
|
|
1224
|
+
A single sleep(0) is not enough on Python <= 3.11: the pre-3.12
|
|
1225
|
+
asyncio.wait_for in _safe_process_message costs extra loop passes
|
|
1226
|
+
before process_message is entered, so first-entry assertions must
|
|
1227
|
+
pump instead of assuming one yield suffices.
|
|
1228
|
+
"""
|
|
1229
|
+
for _ in range(tries):
|
|
1230
|
+
if predicate():
|
|
1231
|
+
return
|
|
1232
|
+
await asyncio.sleep(0)
|
|
1233
|
+
|
|
1221
1234
|
async def test_same_user_serializes(self):
|
|
1222
1235
|
"""同 user 两条消息:第一条阻塞期间,第二条必须排队等待。"""
|
|
1223
1236
|
released = asyncio.Event()
|
|
@@ -1234,7 +1247,7 @@ class TestPerUserLockContract(unittest.IsolatedAsyncioTestCase):
|
|
|
1234
1247
|
with mock.patch.object(self.main, "process_message", new=_pm):
|
|
1235
1248
|
t1 = asyncio.create_task(self.main._safe_process_message(client, msg1))
|
|
1236
1249
|
t2 = asyncio.create_task(self.main._safe_process_message(client, msg2))
|
|
1237
|
-
await
|
|
1250
|
+
await self._pump_until(lambda: len(started) >= 1)
|
|
1238
1251
|
# 仅第一条进入 process_message;第二条被同 user 锁串行化阻塞
|
|
1239
1252
|
self.assertEqual(started, ["alice"])
|
|
1240
1253
|
self.assertEqual(ended, [])
|
|
@@ -1286,7 +1299,7 @@ class TestPerUserLockContract(unittest.IsolatedAsyncioTestCase):
|
|
|
1286
1299
|
t_clear = asyncio.create_task(
|
|
1287
1300
|
self.main._safe_process_message(client, msg_clear)
|
|
1288
1301
|
)
|
|
1289
|
-
await
|
|
1302
|
+
await self._pump_until(lambda: "run_start" in order)
|
|
1290
1303
|
# run 仍阻塞时,clear 被同 user 锁串行化阻塞,尚未删除 thread_id
|
|
1291
1304
|
self.assertIn("run_start", order)
|
|
1292
1305
|
self.assertNotIn("clear", order)
|
|
@@ -1334,6 +1347,52 @@ class TestPerUserLockContract(unittest.IsolatedAsyncioTestCase):
|
|
|
1334
1347
|
rel_b.set()
|
|
1335
1348
|
await asyncio.gather(t_a, t_b, return_exceptions=True)
|
|
1336
1349
|
|
|
1350
|
+
async def test_prune_keeps_lock_for_queued_user(self):
|
|
1351
|
+
"""同 user:一条处理中、一条等锁时,prune 不得删除该用户的锁。
|
|
1352
|
+
|
|
1353
|
+
回归:锁刚释放、等待者还没被唤醒时 lock.locked() 为 False,此时删锁
|
|
1354
|
+
会让后来者拿到新锁、打破串行。用 Lock 子类在 release() 里同步调
|
|
1355
|
+
prune——release() 在事件循环内同步执行,正好落在「已释放、等待者
|
|
1356
|
+
尚未被唤醒」的空隙,无需手动 release。
|
|
1357
|
+
"""
|
|
1358
|
+
release = asyncio.Event()
|
|
1359
|
+
started, observed, entered = [], [], []
|
|
1360
|
+
main = self.main
|
|
1361
|
+
|
|
1362
|
+
class _ProbingLock(asyncio.Lock):
|
|
1363
|
+
async def acquire(self):
|
|
1364
|
+
entered.append(1) # t2 已抵达锁等待点(t1 仍持有锁)
|
|
1365
|
+
return await super().acquire()
|
|
1366
|
+
|
|
1367
|
+
def release(self):
|
|
1368
|
+
super().release()
|
|
1369
|
+
# 同步调用:此刻等待者必然还没被唤醒
|
|
1370
|
+
main._prune_user_locks()
|
|
1371
|
+
observed.append("alice" in main.user_locks)
|
|
1372
|
+
|
|
1373
|
+
async def _pm(client, msg):
|
|
1374
|
+
started.append(msg.get("from_user_id"))
|
|
1375
|
+
await release.wait()
|
|
1376
|
+
|
|
1377
|
+
main.user_locks["alice"] = _ProbingLock()
|
|
1378
|
+
client = self._client()
|
|
1379
|
+
with mock.patch.object(main, "process_message", new=_pm):
|
|
1380
|
+
t1 = asyncio.create_task(main._safe_process_message(client, self._msg("alice")))
|
|
1381
|
+
t2 = asyncio.create_task(main._safe_process_message(client, self._msg("alice")))
|
|
1382
|
+
try:
|
|
1383
|
+
await self._pump_until(lambda: len(started) >= 1)
|
|
1384
|
+
# 确定性等待:t1、t2 都已进入 acquire——t1 持锁,t2 在等锁
|
|
1385
|
+
await self._pump_until(lambda: len(entered) >= 2)
|
|
1386
|
+
finally:
|
|
1387
|
+
release.set()
|
|
1388
|
+
await asyncio.gather(t1, t2)
|
|
1389
|
+
# 每次 release 后的空隙里,alice 的锁都必须存活
|
|
1390
|
+
self.assertTrue(observed)
|
|
1391
|
+
self.assertTrue(all(observed), "等待者未唤醒时 prune 不得删除该锁")
|
|
1392
|
+
# 全部完成后 prune 可以清掉空闲锁
|
|
1393
|
+
main._prune_user_locks()
|
|
1394
|
+
self.assertNotIn("alice", main.user_locks)
|
|
1395
|
+
|
|
1337
1396
|
|
|
1338
1397
|
class TestFormatCliErrorRateQuota(unittest.TestCase):
|
|
1339
1398
|
"""Split eligibility/429/quota so users are not told they spam when
|
|
@@ -1934,6 +1993,12 @@ class TestGrokThrottlePreserve(unittest.IsolatedAsyncioTestCase):
|
|
|
1934
1993
|
mock.patch(
|
|
1935
1994
|
"wechatbridge.grok._sync_grok_auth", return_value=True
|
|
1936
1995
|
),
|
|
1996
|
+
# run_grok gates on _grok_has_credentials(), which reads the real
|
|
1997
|
+
# host auth.json / XAI_API_KEY; without this the subprocess tests
|
|
1998
|
+
# only pass on machines where grok is already signed in.
|
|
1999
|
+
mock.patch(
|
|
2000
|
+
"wechatbridge.grok._grok_has_credentials", return_value=True
|
|
2001
|
+
),
|
|
1937
2002
|
]
|
|
1938
2003
|
for p in self._patchers:
|
|
1939
2004
|
p.start()
|
|
@@ -2155,11 +2220,6 @@ class TestPreflightBeforeSlot(unittest.IsolatedAsyncioTestCase):
|
|
|
2155
2220
|
self.assertTrue(any("🔔" in t for t in sent))
|
|
2156
2221
|
|
|
2157
2222
|
|
|
2158
|
-
if __name__ == "__main__":
|
|
2159
|
-
unittest.main()
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
2223
|
class TestClassifyCliError(unittest.TestCase):
|
|
2164
2224
|
"""_classify_cli_error returns correct category for each error pattern."""
|
|
2165
2225
|
|
|
@@ -2830,6 +2890,54 @@ class TestUpdateScriptPackageMatch(unittest.TestCase):
|
|
|
2830
2890
|
finally:
|
|
2831
2891
|
shutil.rmtree(td, ignore_errors=True)
|
|
2832
2892
|
|
|
2893
|
+
def test_access_control_env_warning(self):
|
|
2894
|
+
"""Extract check_access_control_env from update.sh and run it against
|
|
2895
|
+
temp env files: warn when no active whitelist/admin line, stay quiet
|
|
2896
|
+
when ADMINS is configured."""
|
|
2897
|
+
import re
|
|
2898
|
+
import subprocess
|
|
2899
|
+
m = re.search(
|
|
2900
|
+
r"(?ms)^(check_access_control_env\(\)\s*\{.*?^\})",
|
|
2901
|
+
self.script_content,
|
|
2902
|
+
)
|
|
2903
|
+
self.assertIsNotNone(
|
|
2904
|
+
m, "Could not extract check_access_control_env from update.sh"
|
|
2905
|
+
)
|
|
2906
|
+
func_src = m.group(1)
|
|
2907
|
+
with tempfile.TemporaryDirectory() as td:
|
|
2908
|
+
home = os.path.join(td, "home")
|
|
2909
|
+
cfg = os.path.join(home, ".config", "wechatbridge")
|
|
2910
|
+
os.makedirs(cfg)
|
|
2911
|
+
env_file = os.path.join(cfg, ".env")
|
|
2912
|
+
# Stub `eval` so `eval echo "~user"` returns our temp home
|
|
2913
|
+
# (the real expansion would point at the caller's home).
|
|
2914
|
+
wrapper = (
|
|
2915
|
+
func_src
|
|
2916
|
+
+ '\nTARGET_USER="t_wb_user"'
|
|
2917
|
+
+ f"\neval() {{ echo {home!r}; }}"
|
|
2918
|
+
+ "\ncheck_access_control_env"
|
|
2919
|
+
)
|
|
2920
|
+
|
|
2921
|
+
def _run():
|
|
2922
|
+
return subprocess.run(
|
|
2923
|
+
["bash", "-c", wrapper],
|
|
2924
|
+
capture_output=True, text=True,
|
|
2925
|
+
).stdout
|
|
2926
|
+
|
|
2927
|
+
# 两项都未有效配置 → 打印警告
|
|
2928
|
+
with open(env_file, "w", encoding="utf-8") as f:
|
|
2929
|
+
f.write(
|
|
2930
|
+
"# WECHATBRIDGE_ALLOWED_SENDERS=wxid_a\n"
|
|
2931
|
+
"WECHATBRIDGE_ALLOWED_SENDERS=\n"
|
|
2932
|
+
"WECHATBRIDGE_ADMINS=\n"
|
|
2933
|
+
)
|
|
2934
|
+
self.assertIn("WARNING", _run())
|
|
2935
|
+
|
|
2936
|
+
# 已配 ADMINS → 不警告
|
|
2937
|
+
with open(env_file, "w", encoding="utf-8") as f:
|
|
2938
|
+
f.write("WECHATBRIDGE_ADMINS=wxid_admin\n")
|
|
2939
|
+
self.assertNotIn("WARNING", _run())
|
|
2940
|
+
|
|
2833
2941
|
|
|
2834
2942
|
class _FakeAgyProc:
|
|
2835
2943
|
def __init__(self, stdout: str, stderr: str, rc: int = 0, pid: int = 4242):
|
|
@@ -3239,5 +3347,152 @@ class TestAuditHardeningFixes(unittest.IsolatedAsyncioTestCase):
|
|
|
3239
3347
|
)
|
|
3240
3348
|
|
|
3241
3349
|
|
|
3350
|
+
class TestAccessControlFailClosed(unittest.IsolatedAsyncioTestCase):
|
|
3351
|
+
"""Fail-closed whitelist regression (v1.8.0 breaking change).
|
|
3352
|
+
|
|
3353
|
+
Empty WECHATBRIDGE_ALLOWED_SENDERS no longer means allow-all:
|
|
3354
|
+
only WECHATBRIDGE_ADMINS members pass; both empty = deny everyone.
|
|
3355
|
+
"*" remains the explicit opt-in for open access.
|
|
3356
|
+
"""
|
|
3357
|
+
|
|
3358
|
+
def setUp(self):
|
|
3359
|
+
from wechatbridge import main as main_mod
|
|
3360
|
+
self.main = main_mod
|
|
3361
|
+
self._orig_allowed = main_mod.config.allowed_senders
|
|
3362
|
+
self._orig_admins = main_mod.config.admin_users
|
|
3363
|
+
|
|
3364
|
+
def tearDown(self):
|
|
3365
|
+
self.main.config.allowed_senders = self._orig_allowed
|
|
3366
|
+
self.main.config.admin_users = self._orig_admins
|
|
3367
|
+
|
|
3368
|
+
def _client(self):
|
|
3369
|
+
client = MagicMock()
|
|
3370
|
+
client.state = MagicMock()
|
|
3371
|
+
client.state.baseurl = "https://example.test"
|
|
3372
|
+
client.state.bot_token = "tok"
|
|
3373
|
+
client.send_message = AsyncMock(return_value=True)
|
|
3374
|
+
return client
|
|
3375
|
+
|
|
3376
|
+
def _msg(self, uid):
|
|
3377
|
+
return {
|
|
3378
|
+
"from_user_id": uid,
|
|
3379
|
+
"context_token": "ctx-" + uid,
|
|
3380
|
+
"item_list": [{"type": 1, "text_item": {"text": "hello"}}],
|
|
3381
|
+
}
|
|
3382
|
+
|
|
3383
|
+
async def test_empty_whitelist_fail_closed(self):
|
|
3384
|
+
"""空白名单 + 空管理员 → 非管理员被拒;顺带断言管理员放行与 '*' 放行。"""
|
|
3385
|
+
from wechatbridge import main as main_mod
|
|
3386
|
+
|
|
3387
|
+
sent_texts = []
|
|
3388
|
+
|
|
3389
|
+
async def _cap(**kwargs):
|
|
3390
|
+
sent_texts.append(kwargs.get("text") or "")
|
|
3391
|
+
return True
|
|
3392
|
+
|
|
3393
|
+
client = self._client()
|
|
3394
|
+
client.send_message = AsyncMock(side_effect=_cap)
|
|
3395
|
+
|
|
3396
|
+
# 空白名单 + 空管理员:拒绝所有人
|
|
3397
|
+
self.main.config.allowed_senders = []
|
|
3398
|
+
self.main.config.admin_users = []
|
|
3399
|
+
await main_mod.process_message(client, self._msg("random-user"))
|
|
3400
|
+
self.assertTrue(any("未授权用户" in t for t in sent_texts))
|
|
3401
|
+
|
|
3402
|
+
# 空白名单 + 有管理员:管理员放行、非管理员被拒
|
|
3403
|
+
sent_texts.clear()
|
|
3404
|
+
self.main.config.admin_users = ["admin-1"]
|
|
3405
|
+
with mock.patch.object(
|
|
3406
|
+
main_mod, "gate_and_run", new=AsyncMock(return_value=("ok", []))
|
|
3407
|
+
) as gr:
|
|
3408
|
+
await main_mod.process_message(client, self._msg("admin-1"))
|
|
3409
|
+
gr.assert_awaited()
|
|
3410
|
+
await main_mod.process_message(client, self._msg("random-user"))
|
|
3411
|
+
self.assertTrue(any("未授权用户" in t for t in sent_texts))
|
|
3412
|
+
|
|
3413
|
+
# "*" 显式放开:任何人放行
|
|
3414
|
+
sent_texts.clear()
|
|
3415
|
+
self.main.config.allowed_senders = ["*"]
|
|
3416
|
+
self.main.config.admin_users = []
|
|
3417
|
+
with mock.patch.object(
|
|
3418
|
+
main_mod, "gate_and_run", new=AsyncMock(return_value=("ok", []))
|
|
3419
|
+
) as gr:
|
|
3420
|
+
await main_mod.process_message(client, self._msg("random-user"))
|
|
3421
|
+
gr.assert_awaited()
|
|
3422
|
+
self.assertFalse(any("未授权用户" in t for t in sent_texts))
|
|
3423
|
+
|
|
3424
|
+
|
|
3425
|
+
class TestDshHostCredentialContentMatch(unittest.TestCase):
|
|
3426
|
+
"""Regression: host credential content blocks renamed artifacts.
|
|
3427
|
+
|
|
3428
|
+
The dsh child process reads the machine-wide DSH_HOME, and grok/codex
|
|
3429
|
+
children read the host ~/.grok / ~/.codex — all under the same UID as
|
|
3430
|
+
the bridge. A file copied out of any of them under an innocent name
|
|
3431
|
+
must still be rejected, even when the session dir contributes no
|
|
3432
|
+
secret files.
|
|
3433
|
+
"""
|
|
3434
|
+
|
|
3435
|
+
def test_host_credentials_content_blocks_renamed_artifact(self):
|
|
3436
|
+
from wechatbridge import runner_common as rc
|
|
3437
|
+
|
|
3438
|
+
with tempfile.TemporaryDirectory() as td:
|
|
3439
|
+
host_home = os.path.join(td, "dsh_home")
|
|
3440
|
+
sess_dir = os.path.join(td, "session")
|
|
3441
|
+
os.makedirs(host_home)
|
|
3442
|
+
os.makedirs(sess_dir)
|
|
3443
|
+
fake_dsh_cred = b"\n".join([
|
|
3444
|
+
b"provider: deepseek",
|
|
3445
|
+
b"model: fake-dsh-model",
|
|
3446
|
+
b"base_url: https://api.example.invalid/v1",
|
|
3447
|
+
b"token: t-" + b"x" * 20,
|
|
3448
|
+
]) + b"\n"
|
|
3449
|
+
with open(os.path.join(host_home, ".credentials.yaml"), "wb") as f:
|
|
3450
|
+
f.write(fake_dsh_cred)
|
|
3451
|
+
# dsh 子进程复制/改名后的文件,落在会话目录内
|
|
3452
|
+
out_txt = os.path.join(sess_dir, "out.txt")
|
|
3453
|
+
with open(out_txt, "wb") as f:
|
|
3454
|
+
f.write(b"prefix\n" + fake_dsh_cred + b"suffix\n")
|
|
3455
|
+
|
|
3456
|
+
with mock.patch.object(rc, "host_dsh_home", return_value=host_home):
|
|
3457
|
+
self.assertTrue(rc.is_sensitive_artifact_path(out_txt, sess_dir))
|
|
3458
|
+
# 会话目录为空串时宿主凭据内容匹配仍生效
|
|
3459
|
+
self.assertTrue(rc.is_sensitive_artifact_path(out_txt, ""))
|
|
3460
|
+
|
|
3461
|
+
def test_host_grok_codex_credentials_block_renamed_artifact(self):
|
|
3462
|
+
"""Host ~/.grok/auth.json and ~/.codex/auth.json content must also
|
|
3463
|
+
block renamed artifacts (children share the bridge UID and can copy
|
|
3464
|
+
host files into the session dir)."""
|
|
3465
|
+
from wechatbridge import runner_common as rc
|
|
3466
|
+
|
|
3467
|
+
with tempfile.TemporaryDirectory() as td:
|
|
3468
|
+
host_home = os.path.join(td, "host")
|
|
3469
|
+
sess_dir = os.path.join(td, "session")
|
|
3470
|
+
os.makedirs(os.path.join(host_home, ".grok"))
|
|
3471
|
+
os.makedirs(os.path.join(host_home, ".codex"))
|
|
3472
|
+
os.makedirs(sess_dir)
|
|
3473
|
+
grok_secret = b"{" + b"grok" * 40 + b"}"
|
|
3474
|
+
codex_secret = b"{" + b"codex" * 40 + b"}"
|
|
3475
|
+
with open(os.path.join(host_home, ".grok", "auth.json"), "wb") as f:
|
|
3476
|
+
f.write(grok_secret)
|
|
3477
|
+
with open(os.path.join(host_home, ".codex", "auth.json"), "wb") as f:
|
|
3478
|
+
f.write(codex_secret)
|
|
3479
|
+
# grok/codex 子进程改名复制后的文件
|
|
3480
|
+
g_out = os.path.join(sess_dir, "notes.txt")
|
|
3481
|
+
c_out = os.path.join(sess_dir, "result.md")
|
|
3482
|
+
with open(g_out, "wb") as f:
|
|
3483
|
+
f.write(b"x\n" + grok_secret + b"\n")
|
|
3484
|
+
with open(c_out, "wb") as f:
|
|
3485
|
+
f.write(codex_secret + b"\nend")
|
|
3486
|
+
|
|
3487
|
+
with mock.patch.dict(
|
|
3488
|
+
os.environ, {"WECHATBRIDGE_HOST_HOME": host_home}, clear=False
|
|
3489
|
+
):
|
|
3490
|
+
self.assertTrue(rc.is_sensitive_artifact_path(g_out, sess_dir))
|
|
3491
|
+
self.assertTrue(rc.is_sensitive_artifact_path(c_out, sess_dir))
|
|
3492
|
+
# 会话目录为空串时宿主凭据内容匹配仍生效
|
|
3493
|
+
self.assertTrue(rc.is_sensitive_artifact_path(g_out, ""))
|
|
3494
|
+
self.assertTrue(rc.is_sensitive_artifact_path(c_out, ""))
|
|
3495
|
+
|
|
3496
|
+
|
|
3242
3497
|
if __name__ == "__main__":
|
|
3243
3498
|
unittest.main()
|
|
@@ -1,28 +1,43 @@
|
|
|
1
1
|
"""Price module contract tests (stdlib unittest only).
|
|
2
2
|
|
|
3
3
|
These pin the *external* contracts that cannot be exercised without real
|
|
4
|
-
API keys: the JD gateway signature rule
|
|
5
|
-
correct Dataoke endpoints/params for
|
|
6
|
-
|
|
4
|
+
API keys: the JD gateway signature rule (empty values excluded), the
|
|
5
|
+
Dataoke signRan rule, the correct Dataoke endpoints/params/versions for
|
|
6
|
+
taokouling parsing and goods detail, and response parsing against sample
|
|
7
|
+
payloads shaped like the real APIs.
|
|
8
|
+
|
|
9
|
+
Credentials are injected by patching the module-level constants so the
|
|
10
|
+
tests never read the host's real JDUNION_*/DATAOKE_* environment.
|
|
7
11
|
"""
|
|
8
12
|
|
|
9
13
|
from __future__ import annotations
|
|
10
14
|
|
|
15
|
+
import asyncio
|
|
11
16
|
import hashlib
|
|
12
|
-
import os
|
|
13
17
|
import unittest
|
|
14
18
|
from unittest import mock
|
|
15
19
|
|
|
16
|
-
os.environ.setdefault("JDUNION_APP_KEY", "test_jd_key")
|
|
17
|
-
os.environ.setdefault("JDUNION_APP_SECRET", "test_jd_secret")
|
|
18
|
-
os.environ.setdefault("DATAOKE_APP_KEY", "test_dt_key")
|
|
19
|
-
os.environ.setdefault("DATAOKE_APP_SECRET", "test_dt_secret")
|
|
20
|
-
|
|
21
20
|
from wechatbridge import price as price_mod
|
|
22
21
|
|
|
23
22
|
|
|
24
|
-
class
|
|
25
|
-
|
|
23
|
+
class _PriceCredentialsMixin:
|
|
24
|
+
"""Patch price.py's module-level credentials; never touch os.environ."""
|
|
25
|
+
|
|
26
|
+
def setUp(self):
|
|
27
|
+
super().setUp()
|
|
28
|
+
for name, value in (
|
|
29
|
+
("_JD_APP_KEY", "test_jd_key"),
|
|
30
|
+
("_JD_SECRET_KEY", "test_jd_secret"),
|
|
31
|
+
("_DT_APP_KEY", "test_dt_key"),
|
|
32
|
+
("_DT_APP_SECRET", "test_dt_secret"),
|
|
33
|
+
):
|
|
34
|
+
patcher = mock.patch.object(price_mod, name, value)
|
|
35
|
+
patcher.start()
|
|
36
|
+
self.addCleanup(patcher.stop)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class TestJdSign(_PriceCredentialsMixin, unittest.TestCase):
|
|
40
|
+
def test_secret_wraps_both_ends_and_skips_empty_values(self):
|
|
26
41
|
params = {
|
|
27
42
|
"method": "jd.union.open.goods.query",
|
|
28
43
|
"app_key": "test_jd_key",
|
|
@@ -33,12 +48,47 @@ class TestJdSign(unittest.TestCase):
|
|
|
33
48
|
"sign_method": "md5",
|
|
34
49
|
"360buy_param_json": '{"skuIds":["123"]}',
|
|
35
50
|
}
|
|
36
|
-
|
|
51
|
+
# Official SDK areNotEmpty semantic: empty values are excluded from
|
|
52
|
+
# the signature input entirely (not concatenated as "k").
|
|
53
|
+
plain = "".join(
|
|
54
|
+
f"{k}{v}" for k, v in sorted(params.items()) if v != ""
|
|
55
|
+
)
|
|
37
56
|
expected = hashlib.md5(
|
|
38
57
|
("test_jd_secret" + plain + "test_jd_secret").encode("utf-8")
|
|
39
58
|
).hexdigest().upper()
|
|
40
59
|
self.assertEqual(price_mod._jd_sign(dict(params)), expected)
|
|
41
60
|
|
|
61
|
+
def test_jd_call_drops_access_token_and_sends_gmt8_timestamp(self):
|
|
62
|
+
captured = {}
|
|
63
|
+
|
|
64
|
+
class FakeResp:
|
|
65
|
+
def raise_for_status(self):
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
def json(self):
|
|
69
|
+
return {"ok": True}
|
|
70
|
+
|
|
71
|
+
def fake_post(url, data=None, timeout=None):
|
|
72
|
+
captured["url"] = url
|
|
73
|
+
captured["data"] = dict(data or {})
|
|
74
|
+
return FakeResp()
|
|
75
|
+
|
|
76
|
+
with mock.patch.object(price_mod.httpx, "post", side_effect=fake_post):
|
|
77
|
+
price_mod._jd_call("jd.union.open.goods.query", {"skuIds": ["123"]})
|
|
78
|
+
sent = captured["data"]
|
|
79
|
+
self.assertNotIn("access_token", sent)
|
|
80
|
+
# GMT+8 Beijing time, "yyyy-MM-dd HH:mm:ss"
|
|
81
|
+
from datetime import datetime, timedelta, timezone
|
|
82
|
+
|
|
83
|
+
ts = datetime.strptime(sent["timestamp"], "%Y-%m-%d %H:%M:%S").replace(
|
|
84
|
+
tzinfo=timezone(timedelta(hours=8))
|
|
85
|
+
)
|
|
86
|
+
delta = abs(
|
|
87
|
+
(datetime.now(timezone.utc) - ts).total_seconds()
|
|
88
|
+
)
|
|
89
|
+
self.assertLess(delta, 60)
|
|
90
|
+
self.assertIn("sign", sent)
|
|
91
|
+
|
|
42
92
|
def test_jd_query_parses_sample_payload(self):
|
|
43
93
|
sample = {
|
|
44
94
|
"jd_union_open_goods_query_reslt": {
|
|
@@ -70,16 +120,8 @@ class TestJdSign(unittest.TestCase):
|
|
|
70
120
|
self.assertIn("历史最低: ¥99", card)
|
|
71
121
|
|
|
72
122
|
|
|
73
|
-
class TestDataokeSignAndCalls(unittest.TestCase):
|
|
74
|
-
def
|
|
75
|
-
params = {"goodsId": "789", "appKey": "test_dt_key", "version": "v2.0.0"}
|
|
76
|
-
plain = "&".join(f"{k}={v}" for k, v in sorted(params.items()))
|
|
77
|
-
expected = hashlib.md5(
|
|
78
|
-
(plain + "&key=test_dt_secret").encode("utf-8")
|
|
79
|
-
).hexdigest().upper()
|
|
80
|
-
self.assertEqual(price_mod._dt_sign(dict(params)), expected)
|
|
81
|
-
|
|
82
|
-
def test_dt_call_attaches_appkey_version_and_sign(self):
|
|
123
|
+
class TestDataokeSignAndCalls(_PriceCredentialsMixin, unittest.TestCase):
|
|
124
|
+
def test_dt_call_sends_signran_and_no_legacy_sign(self):
|
|
83
125
|
captured = {}
|
|
84
126
|
|
|
85
127
|
class FakeResp:
|
|
@@ -97,10 +139,19 @@ class TestDataokeSignAndCalls(unittest.TestCase):
|
|
|
97
139
|
with mock.patch.object(price_mod.httpx, "get", side_effect=fake_get):
|
|
98
140
|
out = price_mod._dt_call("/goods/get-goods-details", {"goodsId": "789"})
|
|
99
141
|
self.assertEqual(out, {"ok": True})
|
|
100
|
-
|
|
101
|
-
self.assertEqual(
|
|
102
|
-
|
|
103
|
-
self.
|
|
142
|
+
sent = captured["params"]
|
|
143
|
+
self.assertEqual(sent["appKey"], "test_dt_key")
|
|
144
|
+
self.assertIn("timer", sent)
|
|
145
|
+
self.assertIn("nonce", sent)
|
|
146
|
+
self.assertIn("signRan", sent)
|
|
147
|
+
self.assertNotIn("sign", sent)
|
|
148
|
+
expected = hashlib.md5(
|
|
149
|
+
(
|
|
150
|
+
f"appKey=test_dt_key&timer={sent['timer']}"
|
|
151
|
+
f"&nonce={sent['nonce']}&key=test_dt_secret"
|
|
152
|
+
).encode("utf-8")
|
|
153
|
+
).hexdigest().upper()
|
|
154
|
+
self.assertEqual(sent["signRan"], expected)
|
|
104
155
|
|
|
105
156
|
def test_dt_call_raises_on_nonzero_code(self):
|
|
106
157
|
class FakeResp:
|
|
@@ -126,6 +177,7 @@ class TestDataokeSignAndCalls(unittest.TestCase):
|
|
|
126
177
|
out = price_mod.resolve_tkl("CZ0001 aBcd12")
|
|
127
178
|
self.assertEqual(captured["path"], "/tb-service/parse-content")
|
|
128
179
|
self.assertEqual(captured["params"]["content"], "CZ0001 aBcd12")
|
|
180
|
+
self.assertEqual(captured["params"]["version"], "v1.0.0")
|
|
129
181
|
self.assertEqual(out["goodsId"], "789456")
|
|
130
182
|
|
|
131
183
|
def test_query_tb_item_sends_goods_id_and_parses(self):
|
|
@@ -151,11 +203,28 @@ class TestDataokeSignAndCalls(unittest.TestCase):
|
|
|
151
203
|
|
|
152
204
|
with mock.patch.object(price_mod, "_dt_call", side_effect=fake_call):
|
|
153
205
|
res = price_mod.query_tb_item("789")
|
|
154
|
-
self.assertEqual(
|
|
206
|
+
self.assertEqual(
|
|
207
|
+
captured["params"], {"goodsId": "789", "version": "v1.2.4"}
|
|
208
|
+
)
|
|
155
209
|
self.assertEqual(res.title, "TB Sample")
|
|
156
210
|
self.assertEqual(res.price, 59.9)
|
|
157
211
|
self.assertEqual(res.net_price(), 49.9)
|
|
158
212
|
|
|
213
|
+
def test_handle_price_query_ignores_internal_id_field(self):
|
|
214
|
+
# parse-content returns goodsId/itemId; a bare dataoke-internal `id`
|
|
215
|
+
# must NOT be used as a Taobao item id — reply with the
|
|
216
|
+
# "no goods info" fallback instead of querying garbage.
|
|
217
|
+
with mock.patch.object(
|
|
218
|
+
price_mod, "resolve_tkl", return_value={"id": "12345"}
|
|
219
|
+
), mock.patch.object(
|
|
220
|
+
price_mod, "query_tb_item"
|
|
221
|
+
) as mock_query:
|
|
222
|
+
reply = asyncio.run(
|
|
223
|
+
price_mod.handle_price_query({"kind": "tkl", "token": "tk"})
|
|
224
|
+
)
|
|
225
|
+
self.assertIn("没拿到商品信息", reply)
|
|
226
|
+
mock_query.assert_not_called()
|
|
227
|
+
|
|
159
228
|
def test_dt_configured_requires_secret(self):
|
|
160
229
|
with mock.patch.object(price_mod, "_DT_APP_SECRET", ""):
|
|
161
230
|
self.assertFalse(price_mod.dt_configured())
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"""WeChatBridge — bridge WeChat messages to agy, Grok Build, or Codex CLIs."""
|
|
2
|
-
__version__ = "1.
|
|
2
|
+
__version__ = "1.8.0"
|
|
@@ -247,6 +247,7 @@ async def run_agy(prompt: str, user_id: str, timeout: int = None) -> tuple[str,
|
|
|
247
247
|
process = await asyncio.create_subprocess_exec(
|
|
248
248
|
|
|
249
249
|
*cmd,
|
|
250
|
+
stdin=asyncio.subprocess.DEVNULL,
|
|
250
251
|
stdout=asyncio.subprocess.PIPE,
|
|
251
252
|
stderr=asyncio.subprocess.PIPE,
|
|
252
253
|
cwd=session_dir,
|
|
@@ -304,6 +305,7 @@ async def run_agy(prompt: str, user_id: str, timeout: int = None) -> tuple[str,
|
|
|
304
305
|
await asyncio.sleep(3)
|
|
305
306
|
retry_process = await asyncio.create_subprocess_exec(
|
|
306
307
|
*cmd,
|
|
308
|
+
stdin=asyncio.subprocess.DEVNULL,
|
|
307
309
|
stdout=asyncio.subprocess.PIPE,
|
|
308
310
|
stderr=asyncio.subprocess.PIPE,
|
|
309
311
|
cwd=session_dir,
|
|
@@ -414,6 +416,7 @@ async def _run_agy_subcommand(subcmd_args: list, user_id: str) -> str:
|
|
|
414
416
|
env = sanitize_env(session_dir)
|
|
415
417
|
process = await asyncio.create_subprocess_exec(
|
|
416
418
|
*cmd,
|
|
419
|
+
stdin=asyncio.subprocess.DEVNULL,
|
|
417
420
|
stdout=asyncio.subprocess.PIPE,
|
|
418
421
|
stderr=asyncio.subprocess.PIPE,
|
|
419
422
|
cwd=session_dir,
|
|
@@ -497,11 +497,13 @@ def _build_codex_command(prompt: str, prefs: dict, first: bool, thread_id: str =
|
|
|
497
497
|
if d:
|
|
498
498
|
cmd += ["--add-dir", d]
|
|
499
499
|
|
|
500
|
-
# Session continuation: resume is a subcommand, options must precede it
|
|
500
|
+
# Session continuation: resume is a subcommand, options must precede it.
|
|
501
|
+
# "--" before the prompt keeps messages that start with '-' (e.g. "--help")
|
|
502
|
+
# from being parsed as CLI options.
|
|
501
503
|
if not first:
|
|
502
|
-
cmd += ["resume", thread_id, prompt]
|
|
504
|
+
cmd += ["resume", thread_id, "--", prompt]
|
|
503
505
|
else:
|
|
504
|
-
cmd += [prompt]
|
|
506
|
+
cmd += ["--", prompt]
|
|
505
507
|
return cmd
|
|
506
508
|
|
|
507
509
|
|
|
@@ -278,14 +278,17 @@ class AppConfig:
|
|
|
278
278
|
# CDN upload timeout (seconds)
|
|
279
279
|
cdn_upload_timeout: int = _env_int("CDN_UPLOAD_TIMEOUT", 120)
|
|
280
280
|
|
|
281
|
-
# Access control: comma-separated wxid list
|
|
281
|
+
# Access control: comma-separated wxid list.
|
|
282
|
+
# Non-empty = only listed users; single "*" = explicit allow-all.
|
|
283
|
+
# Empty = fail-closed: only WECHATBRIDGE_ADMINS members (both empty = deny all).
|
|
282
284
|
allowed_senders: list = [
|
|
283
285
|
s.strip()
|
|
284
286
|
for s in os.getenv("WECHATBRIDGE_ALLOWED_SENDERS", "").split(",")
|
|
285
287
|
if s.strip()
|
|
286
288
|
]
|
|
287
289
|
|
|
288
|
-
# Admin users: comma-separated wxid list
|
|
290
|
+
# Admin users: comma-separated wxid list; also the fallback allowlist when
|
|
291
|
+
# WECHATBRIDGE_ALLOWED_SENDERS is empty (fail-closed default).
|
|
289
292
|
admin_users: list = [
|
|
290
293
|
s.strip()
|
|
291
294
|
for s in os.getenv("WECHATBRIDGE_ADMINS", "").split(",")
|
|
@@ -873,6 +873,65 @@ async def send_artifacts_back(client, from_user, context_token, artifacts) -> No
|
|
|
873
873
|
logger.exception("Failed to notify user about artifact error: %s", art_name)
|
|
874
874
|
|
|
875
875
|
|
|
876
|
+
# ---------------------------------------------------------------------------
|
|
877
|
+
# Access control (fail-closed whitelist)
|
|
878
|
+
# ---------------------------------------------------------------------------
|
|
879
|
+
def _sender_allowed(from_user: str) -> bool:
|
|
880
|
+
"""Whitelist decision.
|
|
881
|
+
|
|
882
|
+
- Non-empty ``WECHATBRIDGE_ALLOWED_SENDERS`` → only listed users
|
|
883
|
+
(single item ``*`` = explicit allow-all).
|
|
884
|
+
- Empty whitelist → only ``WECHATBRIDGE_ADMINS`` members.
|
|
885
|
+
- Both empty → deny everyone (fail-closed).
|
|
886
|
+
"""
|
|
887
|
+
allowed = config.allowed_senders
|
|
888
|
+
if allowed:
|
|
889
|
+
if len(allowed) == 1 and allowed[0] == "*":
|
|
890
|
+
return True
|
|
891
|
+
return from_user in allowed
|
|
892
|
+
admins = config.admin_users
|
|
893
|
+
if admins:
|
|
894
|
+
return from_user in admins
|
|
895
|
+
return False
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def _log_access_control_state() -> None:
|
|
899
|
+
"""One startup log line describing the active access-control mode.
|
|
900
|
+
|
|
901
|
+
Never prints raw wxid lists — counts only.
|
|
902
|
+
"""
|
|
903
|
+
allowed = config.allowed_senders
|
|
904
|
+
admins = config.admin_users
|
|
905
|
+
if allowed and len(allowed) == 1 and allowed[0] == "*":
|
|
906
|
+
logger.warning(
|
|
907
|
+
"访问控制:WECHATBRIDGE_ALLOWED_SENDERS='*',已显式放开给所有用户——"
|
|
908
|
+
"任何能私聊机器人的人都可使用,请确认这是预期配置"
|
|
909
|
+
)
|
|
910
|
+
elif allowed:
|
|
911
|
+
if "*" in allowed:
|
|
912
|
+
logger.warning(
|
|
913
|
+
"访问控制:WECHATBRIDGE_ALLOWED_SENDERS 中 '*' 与其它项混用——"
|
|
914
|
+
"'*' 仅在单独配置时表示放开所有人,混用时被当成一个字面 wxid "
|
|
915
|
+
"(永远匹配不到真实用户),请检查配置"
|
|
916
|
+
)
|
|
917
|
+
logger.info(
|
|
918
|
+
"访问控制:白名单已启用(%d 个用户),管理员 %d 个",
|
|
919
|
+
len(allowed), len(admins),
|
|
920
|
+
)
|
|
921
|
+
elif admins:
|
|
922
|
+
logger.info(
|
|
923
|
+
"访问控制:白名单为空,仅 %d 个管理员可用;"
|
|
924
|
+
"如需放开请配置 WECHATBRIDGE_ALLOWED_SENDERS 或显式设 '*'",
|
|
925
|
+
len(admins),
|
|
926
|
+
)
|
|
927
|
+
else:
|
|
928
|
+
logger.warning(
|
|
929
|
+
"访问控制:WECHATBRIDGE_ALLOWED_SENDERS 与 WECHATBRIDGE_ADMINS 均为空,"
|
|
930
|
+
"当前拒绝所有用户;请配置白名单/管理员,或显式设 "
|
|
931
|
+
"WECHATBRIDGE_ALLOWED_SENDERS=* 放开"
|
|
932
|
+
)
|
|
933
|
+
|
|
934
|
+
|
|
876
935
|
# ---------------------------------------------------------------------------
|
|
877
936
|
# Message processing
|
|
878
937
|
# ---------------------------------------------------------------------------
|
|
@@ -931,7 +990,7 @@ async def process_message(client: ILinkClient, msg: dict) -> None:
|
|
|
931
990
|
return
|
|
932
991
|
|
|
933
992
|
# ---- Whitelist check (before any processing) ----
|
|
934
|
-
if
|
|
993
|
+
if not _sender_allowed(from_user):
|
|
935
994
|
await client.send_message(
|
|
936
995
|
to_user_id=from_user,
|
|
937
996
|
text="⛔ **未授权用户** ⛔\n联系管理员添加白名单。",
|
|
@@ -1209,7 +1268,9 @@ def clean_scratch():
|
|
|
1209
1268
|
removed = clean_session_media() # images/files + safe session temps (A+C)
|
|
1210
1269
|
if removed:
|
|
1211
1270
|
logger.info("Session temp cleanup: removed %d files", removed)
|
|
1212
|
-
_prune_user_locks()
|
|
1271
|
+
# NOTE: _prune_user_locks() must NOT run here — clean_scratch() executes in a
|
|
1272
|
+
# worker thread (asyncio.to_thread) while user_locks is event-loop state.
|
|
1273
|
+
# Callers run the prune synchronously after the to_thread await returns.
|
|
1213
1274
|
|
|
1214
1275
|
|
|
1215
1276
|
# ---------------------------------------------------------------------------
|
|
@@ -1222,6 +1283,8 @@ async def periodic_clean_scratch():
|
|
|
1222
1283
|
await asyncio.sleep(3600)
|
|
1223
1284
|
# 同步文件遍历放到线程池,避免阻塞事件循环卡死长轮询心跳
|
|
1224
1285
|
await asyncio.to_thread(clean_scratch)
|
|
1286
|
+
# user_locks 是事件循环状态:prune 只能在协程里同步做
|
|
1287
|
+
_prune_user_locks()
|
|
1225
1288
|
except Exception as e:
|
|
1226
1289
|
logger.exception("periodic_clean_scratch error: %s", e)
|
|
1227
1290
|
|
|
@@ -1229,8 +1292,11 @@ async def periodic_clean_scratch():
|
|
|
1229
1292
|
async def main_loop() -> None:
|
|
1230
1293
|
"""Main daemon loop: manages state, QR login, and message receiving."""
|
|
1231
1294
|
ensure_runtime_dirs()
|
|
1295
|
+
_log_access_control_state()
|
|
1232
1296
|
# 同步文件遍历放到线程池,避免阻塞事件循环
|
|
1233
1297
|
await asyncio.to_thread(clean_scratch)
|
|
1298
|
+
# user_locks 是事件循环状态:prune 只能在协程里同步做
|
|
1299
|
+
_prune_user_locks()
|
|
1234
1300
|
if config.update_check_enabled:
|
|
1235
1301
|
_spawn_bg(update_check_loop())
|
|
1236
1302
|
_spawn_bg(periodic_clean_scratch())
|
|
@@ -1334,6 +1400,9 @@ async def main_loop() -> None:
|
|
|
1334
1400
|
# Per-user async execution lock, global concurrency gate, background spawner
|
|
1335
1401
|
# ---------------------------------------------------------------------------
|
|
1336
1402
|
user_locks: dict = {}
|
|
1403
|
+
# Per-user pending-task refcount: +1 before taking the lock, -1 in finally.
|
|
1404
|
+
# _prune_user_locks may only remove entries whose count is 0.
|
|
1405
|
+
_user_lock_refs: dict = {}
|
|
1337
1406
|
_global_task_sem: asyncio.Semaphore | None = None
|
|
1338
1407
|
|
|
1339
1408
|
|
|
@@ -1346,8 +1415,19 @@ def _get_global_sem() -> asyncio.Semaphore:
|
|
|
1346
1415
|
|
|
1347
1416
|
|
|
1348
1417
|
def _prune_user_locks() -> None:
|
|
1349
|
-
"""Drop idle per-user locks so the dict does not grow forever.
|
|
1350
|
-
|
|
1418
|
+
"""Drop idle per-user locks so the dict does not grow forever.
|
|
1419
|
+
|
|
1420
|
+
Event-loop thread only. A lock counts as busy when it is held OR when any
|
|
1421
|
+
message task for that user is queued waiting for it — the refcount below
|
|
1422
|
+
covers the gap where the previous holder already released but the waiter
|
|
1423
|
+
has not been scheduled yet (``lock.locked()`` is False there, and deleting
|
|
1424
|
+
the lock would let the next message for that user create a fresh lock and
|
|
1425
|
+
break serialization).
|
|
1426
|
+
"""
|
|
1427
|
+
idle = [
|
|
1428
|
+
uid for uid, lock in user_locks.items()
|
|
1429
|
+
if not lock.locked() and _user_lock_refs.get(uid, 0) == 0
|
|
1430
|
+
]
|
|
1351
1431
|
for uid in idle:
|
|
1352
1432
|
user_locks.pop(uid, None)
|
|
1353
1433
|
|
|
@@ -1376,40 +1456,46 @@ async def _safe_process_message(client: ILinkClient, msg: dict) -> None:
|
|
|
1376
1456
|
if from_user not in user_locks:
|
|
1377
1457
|
user_locks[from_user] = asyncio.Lock()
|
|
1378
1458
|
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1459
|
+
_user_lock_refs[from_user] = _user_lock_refs.get(from_user, 0) + 1
|
|
1460
|
+
try:
|
|
1461
|
+
async with user_locks[from_user]:
|
|
1462
|
+
# C/B before global slot — do not sleep while holding a concurrent slot
|
|
1463
|
+
await _await_upstream_preflight(client, from_user, context_token)
|
|
1382
1464
|
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1465
|
+
try:
|
|
1466
|
+
await asyncio.wait_for(sem.acquire(), timeout=0.05)
|
|
1467
|
+
except asyncio.TimeoutError:
|
|
1468
|
+
logger.warning("并发已满,拒绝处理 from=%s", from_user)
|
|
1469
|
+
if context_token and from_user:
|
|
1470
|
+
try:
|
|
1471
|
+
await client.send_message(
|
|
1472
|
+
to_user_id=from_user,
|
|
1473
|
+
text=_BUSY_USER_TEXT,
|
|
1474
|
+
context_token=context_token,
|
|
1475
|
+
baseurl=client.state.baseurl,
|
|
1476
|
+
bot_token=client.state.bot_token,
|
|
1477
|
+
)
|
|
1478
|
+
except Exception as e:
|
|
1479
|
+
logger.warning("发送繁忙提示失败: %s", e)
|
|
1480
|
+
return
|
|
1399
1481
|
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1482
|
+
slot = _GlobalSlot(sem)
|
|
1483
|
+
token = _global_slot_ctx.set(slot)
|
|
1484
|
+
try:
|
|
1485
|
+
await process_message(client, msg)
|
|
1486
|
+
except Exception as e:
|
|
1487
|
+
logger.exception("处理消息异常 (from=%s): %s", from_user, e)
|
|
1488
|
+
finally:
|
|
1489
|
+
_global_slot_ctx.reset(token)
|
|
1490
|
+
# Only release if this task still owns the slot (A backoff may have
|
|
1491
|
+
# temporarily released; sleep_released re-acquires before return).
|
|
1492
|
+
if slot.held:
|
|
1493
|
+
sem.release()
|
|
1494
|
+
slot.held = False
|
|
1495
|
+
finally:
|
|
1496
|
+
_user_lock_refs[from_user] = _user_lock_refs.get(from_user, 1) - 1
|
|
1497
|
+
if _user_lock_refs.get(from_user, 0) <= 0:
|
|
1498
|
+
_user_lock_refs.pop(from_user, None)
|
|
1413
1499
|
|
|
1414
1500
|
|
|
1415
1501
|
# ---------------------------------------------------------------------------
|
|
@@ -19,9 +19,11 @@ import hashlib
|
|
|
19
19
|
import json
|
|
20
20
|
import logging
|
|
21
21
|
import os
|
|
22
|
+
import random
|
|
22
23
|
import re
|
|
23
24
|
import time
|
|
24
25
|
from dataclasses import dataclass, field
|
|
26
|
+
from datetime import datetime, timedelta, timezone
|
|
25
27
|
from urllib.parse import urljoin, urlparse
|
|
26
28
|
|
|
27
29
|
import httpx
|
|
@@ -50,7 +52,7 @@ def jd_configured() -> bool:
|
|
|
50
52
|
|
|
51
53
|
def dt_configured() -> bool:
|
|
52
54
|
# Dataoke rejects unsigned requests: both the appKey and the appSecret
|
|
53
|
-
# (used only locally to compute `
|
|
55
|
+
# (used only locally to compute `signRan`, never sent) are required.
|
|
54
56
|
return bool(_DT_APP_KEY and _DT_APP_SECRET)
|
|
55
57
|
|
|
56
58
|
|
|
@@ -185,11 +187,12 @@ def detect_price_trigger(text: str) -> dict | None:
|
|
|
185
187
|
|
|
186
188
|
|
|
187
189
|
def _jd_sign(params: dict) -> str:
|
|
188
|
-
# JD gateway rule
|
|
189
|
-
#
|
|
190
|
-
# signature the
|
|
190
|
+
# JD gateway rule (per the official SDK's areNotEmpty semantic): MD5 of
|
|
191
|
+
# secret + sorted non-empty key+value concat + secret, upper. Params with
|
|
192
|
+
# empty values participate in NEITHER the signature NOR the request — the
|
|
193
|
+
# secret wraps both ends.
|
|
191
194
|
plain = "".join(
|
|
192
|
-
f"{k}{v}" for k, v in sorted(params.items()) if k != "sign"
|
|
195
|
+
f"{k}{v}" for k, v in sorted(params.items()) if k != "sign" and v != ""
|
|
193
196
|
)
|
|
194
197
|
return hashlib.md5(
|
|
195
198
|
(_JD_SECRET_KEY + plain + _JD_SECRET_KEY).encode("utf-8")
|
|
@@ -198,18 +201,22 @@ def _jd_sign(params: dict) -> str:
|
|
|
198
201
|
|
|
199
202
|
def _jd_call(method: str, param_json: dict) -> dict:
|
|
200
203
|
# JD gateway contract: form field is `360buy_param_json`; the signature
|
|
201
|
-
# covers every field except `sign` itself
|
|
204
|
+
# covers every non-empty field except `sign` itself. access_token="" is
|
|
205
|
+
# dropped (empty values are neither signed nor sent). timestamp must be
|
|
206
|
+
# Beijing time (GMT+8) — the gateway tolerance is only ~6–10 minutes, so
|
|
207
|
+
# a UTC-local server clock would fail verification by 8 hours.
|
|
202
208
|
params = {
|
|
203
209
|
"method": method,
|
|
204
210
|
"app_key": _JD_APP_KEY,
|
|
205
211
|
"access_token": "",
|
|
206
|
-
"timestamp":
|
|
212
|
+
"timestamp": datetime.now(timezone(timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S"),
|
|
207
213
|
"format": "json",
|
|
208
214
|
"v": "1.0",
|
|
209
215
|
"sign_method": "md5",
|
|
210
216
|
"360buy_param_json": json.dumps(param_json, ensure_ascii=False, separators=(",", ":")),
|
|
211
217
|
}
|
|
212
218
|
params["sign"] = _jd_sign(params)
|
|
219
|
+
params = {k: v for k, v in params.items() if v != ""}
|
|
213
220
|
resp = httpx.post(JD_API_URL, data=params, timeout=_DT_TIMEOUT)
|
|
214
221
|
resp.raise_for_status()
|
|
215
222
|
return resp.json()
|
|
@@ -251,23 +258,21 @@ def query_jd_sku(sku: str) -> PriceResult:
|
|
|
251
258
|
# 大淘客 (Taobao/Tmall proxy) API
|
|
252
259
|
# ---------------------------------------------------------------------------
|
|
253
260
|
|
|
254
|
-
def _dt_sign(params: dict) -> str:
|
|
255
|
-
# Dataoke rule (per the official SDK): sort every request parameter
|
|
256
|
-
# (appKey and version included, sign excluded) by key, join as
|
|
257
|
-
# "k1=v1&k2=v2&...", append "&key=<appSecret>", MD5, uppercase.
|
|
258
|
-
plain = "&".join(
|
|
259
|
-
f"{k}={v}" for k, v in sorted(params.items()) if k != "sign"
|
|
260
|
-
)
|
|
261
|
-
return hashlib.md5(
|
|
262
|
-
(plain + "&key=" + _DT_APP_SECRET).encode("utf-8")
|
|
263
|
-
).hexdigest().upper()
|
|
264
|
-
|
|
265
|
-
|
|
266
261
|
def _dt_call(path: str, params: dict) -> dict:
|
|
262
|
+
# Dataoke signRan rule (official SDK): business params are NOT signed.
|
|
263
|
+
# signRan = MD5("appKey=<appKey>&timer=<ms>&nonce=<rand6>&key=<appSecret>")
|
|
264
|
+
# upper; the request carries appKey/version/timer/nonce/signRan plus the
|
|
265
|
+
# business params — no legacy `sign` field is sent.
|
|
267
266
|
params = dict(params)
|
|
268
267
|
params["appKey"] = _DT_APP_KEY
|
|
269
268
|
params["version"] = params.get("version", "v2.0.0")
|
|
270
|
-
|
|
269
|
+
timer = int(time.time() * 1000)
|
|
270
|
+
nonce = str(random.randint(100000, 999999))
|
|
271
|
+
params["timer"] = timer
|
|
272
|
+
params["nonce"] = nonce
|
|
273
|
+
params["signRan"] = hashlib.md5(
|
|
274
|
+
f"appKey={_DT_APP_KEY}&timer={timer}&nonce={nonce}&key={_DT_APP_SECRET}".encode("utf-8")
|
|
275
|
+
).hexdigest().upper()
|
|
271
276
|
resp = httpx.get(f"{DT_API_URL}{path}", params=params, timeout=_DT_TIMEOUT)
|
|
272
277
|
resp.raise_for_status()
|
|
273
278
|
data = resp.json()
|
|
@@ -294,7 +299,10 @@ def query_tb_item(item_id: str) -> PriceResult:
|
|
|
294
299
|
"""Query Taobao/Tmall item via dataoke goods detail API."""
|
|
295
300
|
# get-goods-details takes the Taobao item id as `goodsId`, not `id`
|
|
296
301
|
# (`id` is dataoke's own internal goods id and matches nothing here).
|
|
297
|
-
data = _dt_call(
|
|
302
|
+
data = _dt_call(
|
|
303
|
+
"/goods/get-goods-details",
|
|
304
|
+
{"goodsId": str(item_id), "version": "v1.2.4"},
|
|
305
|
+
)
|
|
298
306
|
goods = data.get("goods", data)
|
|
299
307
|
quan_price = float(goods.get("quanPrice", 0) or 0)
|
|
300
308
|
actual_price = float(goods.get("actualPrice", goods.get("originalPrice", 0)) or 0)
|
|
@@ -431,7 +439,6 @@ async def handle_price_query(trigger: dict) -> str:
|
|
|
431
439
|
goods_id = str(
|
|
432
440
|
data.get("goodsId", "")
|
|
433
441
|
or data.get("itemId", "")
|
|
434
|
-
or data.get("id", "")
|
|
435
442
|
)
|
|
436
443
|
if not goods_id:
|
|
437
444
|
return "❓ 口令解析出来了但没拿到商品信息,可能商品未收录。"
|
|
@@ -156,12 +156,36 @@ _SENSITIVE_ARTIFACT_DIR_NAMES = frozenset({
|
|
|
156
156
|
})
|
|
157
157
|
|
|
158
158
|
|
|
159
|
+
def _host_home() -> str:
|
|
160
|
+
"""Bridge process home (machine-wide), not a per-user session HOME.
|
|
161
|
+
|
|
162
|
+
Same resolution as ``grok._host_grok_dir`` / ``codex._host_codex_dir`` —
|
|
163
|
+
kept here (no import) to avoid a module cycle.
|
|
164
|
+
"""
|
|
165
|
+
return os.environ.get("WECHATBRIDGE_HOST_HOME") or os.path.expanduser("~")
|
|
166
|
+
|
|
167
|
+
|
|
159
168
|
def _matches_session_secret_content(candidate_real: str, sess_real: str) -> bool:
|
|
160
169
|
"""Return True if *candidate_real* contains the raw bytes of any session
|
|
161
170
|
credential / state file (defending against copy/rename to an innocent filename
|
|
162
|
-
such as ``token.copy`` or ``scratch/out.txt``).
|
|
163
|
-
|
|
164
|
-
|
|
171
|
+
such as ``token.copy`` or ``scratch/out.txt``).
|
|
172
|
+
|
|
173
|
+
The host dsh ``.credentials.yaml`` and host grok/codex ``auth.json`` are
|
|
174
|
+
checked even when *sess_real* is empty/missing: those child processes run
|
|
175
|
+
with the machine-wide host home (``WECHATBRIDGE_HOST_HOME`` or ``~``),
|
|
176
|
+
same UID as the bridge, and can copy those files under innocent names.
|
|
177
|
+
|
|
178
|
+
Per-session files are only consulted when *sess_real* is non-empty:
|
|
179
|
+
joining onto an empty base yields relative paths (``AGENTS.md``,
|
|
180
|
+
``prefs.json``, …) that ``os.path.exists`` resolves against the bridge
|
|
181
|
+
process CWD, which could match unrelated files.
|
|
182
|
+
|
|
183
|
+
Inherent boundary: this check only blocks whole-file verbatim copies,
|
|
184
|
+
renames, or splices. It does not stop exfiltration of a single extracted
|
|
185
|
+
field, an encoded/transformed variant, or a credential that is truncated
|
|
186
|
+
before matching — secrets are read up to 64KiB and candidates up to
|
|
187
|
+
256KiB, so anything beyond those caps is never compared.
|
|
188
|
+
"""
|
|
165
189
|
try:
|
|
166
190
|
st = os.lstat(candidate_real)
|
|
167
191
|
if not stat.S_ISREG(st.st_mode) or st.st_size <= 0 or st.st_size > 256 * 1024:
|
|
@@ -169,19 +193,36 @@ def _matches_session_secret_content(candidate_real: str, sess_real: str) -> bool
|
|
|
169
193
|
except OSError:
|
|
170
194
|
return False
|
|
171
195
|
|
|
172
|
-
secret_files =
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
196
|
+
secret_files = []
|
|
197
|
+
if sess_real:
|
|
198
|
+
secret_files += [
|
|
199
|
+
os.path.join(sess_real, ".gemini", "antigravity-cli", "antigravity-oauth-token"),
|
|
200
|
+
os.path.join(sess_real, ".gemini", "antigravity-oauth-token"),
|
|
201
|
+
os.path.join(sess_real, ".grok", "auth.json"),
|
|
202
|
+
os.path.join(sess_real, ".codex", "auth.json"),
|
|
203
|
+
os.path.join(sess_real, "prefs.json"),
|
|
204
|
+
os.path.join(sess_real, ".codex_thread_id"),
|
|
205
|
+
os.path.join(sess_real, "grok_persona.txt"),
|
|
206
|
+
os.path.join(sess_real, ".gemini", "GEMINI.md"),
|
|
207
|
+
os.path.join(sess_real, "GEMINI.md"),
|
|
208
|
+
os.path.join(sess_real, "AGENTS.md"),
|
|
209
|
+
]
|
|
210
|
+
# Real dsh per-user session id lives under dsh_state_dir
|
|
211
|
+
# (<dsh_state>/<sanitize_user_id(uid)>/dsh_session_id), not under
|
|
212
|
+
# session_dir — sess_real's basename IS sanitize_user_id(uid) since
|
|
213
|
+
# session_dir = session_base_dir/<sanitize_user_id(uid)>.
|
|
214
|
+
secret_files.append(
|
|
215
|
+
os.path.join(
|
|
216
|
+
get_dsh_state_dir(), os.path.basename(sess_real), "dsh_session_id"
|
|
217
|
+
)
|
|
218
|
+
)
|
|
219
|
+
# Machine-wide host credentials — independent of session dir: the dsh
|
|
220
|
+
# child reads the host DSH_HOME, and grok/codex children read the host
|
|
221
|
+
# ~/.grok / ~/.codex (same UID as the bridge).
|
|
222
|
+
host_home = _host_home()
|
|
223
|
+
secret_files.append(os.path.join(host_dsh_home(), ".credentials.yaml"))
|
|
224
|
+
secret_files.append(os.path.join(host_home, ".grok", "auth.json"))
|
|
225
|
+
secret_files.append(os.path.join(host_home, ".codex", "auth.json"))
|
|
185
226
|
cand_bytes: bytes | None = None
|
|
186
227
|
for sf in secret_files:
|
|
187
228
|
try:
|
|
@@ -252,7 +293,7 @@ def is_sensitive_artifact_path(path: str, session_dir: str) -> bool:
|
|
|
252
293
|
if any(p.startswith(".") or p in _SENSITIVE_ARTIFACT_DIR_NAMES for p in norm_parts[:-1] if p == ".gemini"):
|
|
253
294
|
return True
|
|
254
295
|
|
|
255
|
-
if
|
|
296
|
+
if _matches_session_secret_content(real, sess_real):
|
|
256
297
|
return True
|
|
257
298
|
return False
|
|
258
299
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: wechatbridge-cli
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.8.0
|
|
4
4
|
Summary: Bridge WeChat messages to agy, Grok Build, or Codex CLIs — text/image/file/voice in, CLI replies and generated files back.
|
|
5
5
|
Author: WeChatBridge contributors
|
|
6
6
|
License: MIT
|
|
@@ -54,7 +54,7 @@ The bridge process stays up and long-polls iLink. For prompts that go to a CLI,
|
|
|
54
54
|
- Runtime backend switch: `/backend agy`, `/backend grok`, `/backend codex`, or `/backend dsh` (clears that backend's continuation state — the agy/grok continuation flag and the codex `thread_id`/resume state — so the next CLI turn starts a fresh session; history files on disk are not wiped immediately)
|
|
55
55
|
- Slash commands for model, session reset, persona, and more (see below)
|
|
56
56
|
- Dangerous-prompt gate: a **keyword list** of concrete destructive patterns asks for confirmation before run
|
|
57
|
-
- Sender whitelist (`WECHATBRIDGE_ALLOWED_SENDERS`; empty = allow all)
|
|
57
|
+
- Sender whitelist (`WECHATBRIDGE_ALLOWED_SENDERS`; non-empty = listed users only, `*` = allow all; empty = admins only, deny all when no admins)
|
|
58
58
|
- `/mcp` returns short usage text; `/agent` rewrites into a natural-language subagent prompt for the CLI (not a native MCP bridge)
|
|
59
59
|
- Media over WeChat CDN with AES-128-ECB encrypt/decrypt
|
|
60
60
|
- Multi-instance: one codebase, set `WECHATBRIDGE_INSTANCE` per process (state / session / QR paths derive from it)
|
|
@@ -191,7 +191,7 @@ Key variables (all have defaults):
|
|
|
191
191
|
| `WECHATBRIDGE_DSH_STATE_DIR` | _derived_ | bridge-private dsh state directory (memory JSONL and persistent session IDs; defaults to `~/.local/share/wechatbridge/<instance>/dsh_state`) |
|
|
192
192
|
| `WECHATBRIDGE_BACKEND` | `agy` | global default backend (`agy` / `grok` / `codex` / `dsh`; overridable per user via `/backend`) |
|
|
193
193
|
| `WECHATBRIDGE_INSTANCE` | `default` | instance name; state / session / QR paths derive from it |
|
|
194
|
-
| `WECHATBRIDGE_ALLOWED_SENDERS` | _empty_ | comma-separated WeChat IDs
|
|
194
|
+
| `WECHATBRIDGE_ALLOWED_SENDERS` | _empty_ | comma-separated WeChat IDs; `*` = allow all; empty = only `WECHATBRIDGE_ADMINS` users (deny all if that is empty too) |
|
|
195
195
|
| `AGY_TIMEOUT` | `600` | CLI run timeout in seconds (agy / grok / codex backends) |
|
|
196
196
|
| `WECHATBRIDGE_MAX_OUTBOUND_BYTES` | `104857600` | max file size sent back to WeChat (100 MB) |
|
|
197
197
|
| `WECHATBRIDGE_MAX_INBOUND_BYTES` | `20971520` | max inbound image/file after download (20 MB) |
|
|
@@ -234,6 +234,8 @@ Data lives under `~/.local/share/wechatbridge/<instance>/` (sessions, SQLite his
|
|
|
234
234
|
|
|
235
235
|
Before upgrading a **major** or **minor** version (e.g. 1.2 → 1.3), check the corresponding section in [`CHANGELOG.md`](CHANGELOG.md) for breaking changes and migration steps.
|
|
236
236
|
|
|
237
|
+
> **Before upgrading to 1.8.0:** configure `WECHATBRIDGE_ADMINS` or `WECHATBRIDGE_ALLOWED_SENDERS` in your `.env` — since 1.8.0 the whitelist denies everyone when both are empty (set `WECHATBRIDGE_ALLOWED_SENDERS=*` to keep allowing all users).
|
|
238
|
+
|
|
237
239
|
## Deploy
|
|
238
240
|
|
|
239
241
|
### Linux (systemd)
|
|
@@ -330,7 +332,7 @@ Other `/…` commands are either rejected (e.g. `/exit`), reported as unsupporte
|
|
|
330
332
|
|
|
331
333
|
## Ops & security (what the bridge actually enforces)
|
|
332
334
|
|
|
333
|
-
- **Whitelist first.** Empty `WECHATBRIDGE_ALLOWED_SENDERS` means
|
|
335
|
+
- **Whitelist first.** Empty `WECHATBRIDGE_ALLOWED_SENDERS` means only `WECHATBRIDGE_ADMINS` members can use the bridge (everyone when the list is `*`, no one when both are empty).
|
|
334
336
|
- **Auto-approve CLIs.** agy runs with `--dangerously-skip-permissions`; grok with `--always-approve` (unless planning mode); dsh tools run without host path restrictions. Treat this as trusted-user tooling, not a multi-tenant sandbox.
|
|
335
337
|
- **Danger gate is keyword-based**, not full intent understanding. Defaults target concrete patterns (`rm -rf /`, pipe-to-shell, `mkfs`, `format c:`, a few heavy Chinese phrases, …). Everyday wording like bare “delete” is **not** gated. Override list via `WECHATBRIDGE_CONFIRM_KEYWORDS`; approve with `WECHATBRIDGE_CONFIRM_TOKEN` (default `y`), TTL `WECHATBRIDGE_PENDING_TTL`.
|
|
336
338
|
- **Inbound media** is size-capped (default 20 MB), streamed, and CDN hosts are allowlisted. Missing `aes_key` returns a clear error.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{wechatbridge_cli-1.7.2 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/entry_points.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|