wechatbridge-cli 1.7.2__tar.gz → 1.7.4__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.
Files changed (29) hide show
  1. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/PKG-INFO +1 -1
  2. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/tests/test_hardening.py +21 -2
  3. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/tests/test_price.py +96 -27
  4. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/__init__.py +1 -1
  5. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/price.py +29 -22
  6. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge_cli.egg-info/PKG-INFO +1 -1
  7. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/LICENSE +0 -0
  8. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/README.md +0 -0
  9. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/pyproject.toml +0 -0
  10. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/setup.cfg +0 -0
  11. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/tests/test_codex.py +0 -0
  12. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/tests/test_codex_auth.py +0 -0
  13. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/tests/test_dsh.py +0 -0
  14. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/tests/test_grok_auth.py +0 -0
  15. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/__main__.py +0 -0
  16. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/agy.py +0 -0
  17. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/codex.py +0 -0
  18. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/config.py +0 -0
  19. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/dsh.py +0 -0
  20. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/grok.py +0 -0
  21. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/ilink.py +0 -0
  22. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/main.py +0 -0
  23. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/runner_common.py +0 -0
  24. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge/update_check.py +0 -0
  25. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge_cli.egg-info/SOURCES.txt +0 -0
  26. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge_cli.egg-info/dependency_links.txt +0 -0
  27. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge_cli.egg-info/entry_points.txt +0 -0
  28. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/wechatbridge_cli.egg-info/requires.txt +0 -0
  29. {wechatbridge_cli-1.7.2 → wechatbridge_cli-1.7.4}/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.7.2
3
+ Version: 1.7.4
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
@@ -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 asyncio.sleep(0)
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 asyncio.sleep(0)
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)
@@ -1934,6 +1947,12 @@ class TestGrokThrottlePreserve(unittest.IsolatedAsyncioTestCase):
1934
1947
  mock.patch(
1935
1948
  "wechatbridge.grok._sync_grok_auth", return_value=True
1936
1949
  ),
1950
+ # run_grok gates on _grok_has_credentials(), which reads the real
1951
+ # host auth.json / XAI_API_KEY; without this the subprocess tests
1952
+ # only pass on machines where grok is already signed in.
1953
+ mock.patch(
1954
+ "wechatbridge.grok._grok_has_credentials", return_value=True
1955
+ ),
1937
1956
  ]
1938
1957
  for p in self._patchers:
1939
1958
  p.start()
@@ -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, the Dataoke signature rule, the
5
- correct Dataoke endpoints/params for taokouling parsing and goods detail,
6
- and response parsing against sample payloads shaped like the real APIs.
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 TestJdSign(unittest.TestCase):
25
- def test_secret_wraps_both_ends(self):
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
- plain = "".join(f"{k}{v}" for k, v in sorted(params.items()))
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 test_dt_sign_matches_sdk_algorithm(self):
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
- self.assertEqual(captured["params"]["appKey"], "test_dt_key")
101
- self.assertEqual(captured["params"]["version"], "v2.0.0")
102
- unsigned = {k: v for k, v in captured["params"].items() if k != "sign"}
103
- self.assertEqual(captured["params"]["sign"], price_mod._dt_sign(unsigned))
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(captured["params"], {"goodsId": "789"})
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.7.2"
2
+ __version__ = "1.7.4"
@@ -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 `sign`, never sent) are required.
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: MD5(secret + sorted key+value concat + secret), upper.
189
- # The secret wraps BOTH ends — appending it only at the end produces a
190
- # signature the gateway always rejects.
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 (access_token="" participates).
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": time.strftime("%Y-%m-%d %H:%M:%S"),
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
- params["sign"] = _dt_sign(params)
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("/goods/get-goods-details", {"goodsId": str(item_id)})
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 "❓ 口令解析出来了但没拿到商品信息,可能商品未收录。"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wechatbridge-cli
3
- Version: 1.7.2
3
+ Version: 1.7.4
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