wechatbridge-cli 1.7.4__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.4 → wechatbridge_cli-1.8.0}/PKG-INFO +6 -4
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/README.md +5 -3
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/tests/test_codex.py +13 -2
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/tests/test_dsh.py +3 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/tests/test_hardening.py +241 -5
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/__init__.py +1 -1
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/agy.py +3 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/codex.py +5 -3
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/config.py +5 -2
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/main.py +122 -36
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/runner_common.py +58 -17
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/PKG-INFO +6 -4
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/LICENSE +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/pyproject.toml +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/setup.cfg +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/tests/test_codex_auth.py +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/tests/test_grok_auth.py +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/tests/test_price.py +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/__main__.py +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/dsh.py +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/grok.py +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/ilink.py +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/price.py +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge/update_check.py +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/SOURCES.txt +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/dependency_links.txt +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/entry_points.txt +0 -0
- {wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/requires.txt +0 -0
- {wechatbridge_cli-1.7.4 → 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
|
|
|
@@ -1347,6 +1347,52 @@ class TestPerUserLockContract(unittest.IsolatedAsyncioTestCase):
|
|
|
1347
1347
|
rel_b.set()
|
|
1348
1348
|
await asyncio.gather(t_a, t_b, return_exceptions=True)
|
|
1349
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
|
+
|
|
1350
1396
|
|
|
1351
1397
|
class TestFormatCliErrorRateQuota(unittest.TestCase):
|
|
1352
1398
|
"""Split eligibility/429/quota so users are not told they spam when
|
|
@@ -2174,11 +2220,6 @@ class TestPreflightBeforeSlot(unittest.IsolatedAsyncioTestCase):
|
|
|
2174
2220
|
self.assertTrue(any("🔔" in t for t in sent))
|
|
2175
2221
|
|
|
2176
2222
|
|
|
2177
|
-
if __name__ == "__main__":
|
|
2178
|
-
unittest.main()
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
2223
|
class TestClassifyCliError(unittest.TestCase):
|
|
2183
2224
|
"""_classify_cli_error returns correct category for each error pattern."""
|
|
2184
2225
|
|
|
@@ -2849,6 +2890,54 @@ class TestUpdateScriptPackageMatch(unittest.TestCase):
|
|
|
2849
2890
|
finally:
|
|
2850
2891
|
shutil.rmtree(td, ignore_errors=True)
|
|
2851
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
|
+
|
|
2852
2941
|
|
|
2853
2942
|
class _FakeAgyProc:
|
|
2854
2943
|
def __init__(self, stdout: str, stderr: str, rc: int = 0, pid: int = 4242):
|
|
@@ -3258,5 +3347,152 @@ class TestAuditHardeningFixes(unittest.IsolatedAsyncioTestCase):
|
|
|
3258
3347
|
)
|
|
3259
3348
|
|
|
3260
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
|
+
|
|
3261
3497
|
if __name__ == "__main__":
|
|
3262
3498
|
unittest.main()
|
|
@@ -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
|
# ---------------------------------------------------------------------------
|
|
@@ -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
|
|
File without changes
|
|
File without changes
|
{wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{wechatbridge_cli-1.7.4 → wechatbridge_cli-1.8.0}/wechatbridge_cli.egg-info/entry_points.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|