-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathmcp_server.py
More file actions
3809 lines (3224 loc) · 146 KB
/
mcp_server.py
File metadata and controls
3809 lines (3224 loc) · 146 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r"""
WeChat MCP Server - query WeChat messages, contacts via Claude
Based on FastMCP (stdio transport), reuses existing decryption.
Runs on Windows Python (needs access to D:\ WeChat databases).
"""
import io
import os, sys, json, time, sqlite3, tempfile, struct, hashlib, atexit, re, threading, subprocess
import glob
import wave
import hmac as hmac_mod
from contextlib import closing
from datetime import datetime, timedelta
import xml.etree.ElementTree as ET
from Crypto.Cipher import AES
from mcp.server.fastmcp import FastMCP
import zstandard as zstd
from config import _config_file_path, _DEFAULT
from decode_image import ImageResolver
from key_utils import get_key_info, key_path_variants, strip_key_metadata
# ============ 加密常量 ============
PAGE_SZ = 4096
KEY_SZ = 32
SALT_SZ = 16
RESERVE_SZ = 80
SQLITE_HDR = b'SQLite format 3\x00'
WAL_HEADER_SZ = 32
WAL_FRAME_HEADER_SZ = 24
# ============ 配置加载 ============
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE = _config_file_path()
try:
with open(CONFIG_FILE, encoding="utf-8") as f:
_cfg = json.load(f)
except FileNotFoundError:
_cfg = dict(_DEFAULT)
for _key in ("keys_file", "decrypted_dir"):
if _key in _cfg and not os.path.isabs(_cfg[_key]):
_cfg[_key] = os.path.join(os.path.dirname(CONFIG_FILE), _cfg[_key])
DB_DIR = _cfg["db_dir"]
KEYS_FILE = _cfg["keys_file"]
DECRYPTED_DIR = _cfg["decrypted_dir"]
# 图片相关路径
_db_dir = _cfg["db_dir"]
if os.path.basename(_db_dir) == "db_storage":
WECHAT_BASE_DIR = os.path.dirname(_db_dir)
else:
WECHAT_BASE_DIR = _db_dir
DECODED_IMAGE_DIR = _cfg.get("decoded_image_dir")
if not DECODED_IMAGE_DIR:
DECODED_IMAGE_DIR = os.path.join(SCRIPT_DIR, "decoded_images")
elif not os.path.isabs(DECODED_IMAGE_DIR):
DECODED_IMAGE_DIR = os.path.join(SCRIPT_DIR, DECODED_IMAGE_DIR)
try:
with open(KEYS_FILE, encoding="utf-8") as f:
ALL_KEYS = strip_key_metadata(json.load(f))
except FileNotFoundError:
ALL_KEYS = {}
# ============ 解密函数 ============
def decrypt_page(enc_key, page_data, pgno):
iv = page_data[PAGE_SZ - RESERVE_SZ : PAGE_SZ - RESERVE_SZ + 16]
if pgno == 1:
encrypted = page_data[SALT_SZ : PAGE_SZ - RESERVE_SZ]
cipher = AES.new(enc_key, AES.MODE_CBC, iv)
decrypted = cipher.decrypt(encrypted)
return bytes(bytearray(SQLITE_HDR + decrypted + b'\x00' * RESERVE_SZ))
else:
encrypted = page_data[: PAGE_SZ - RESERVE_SZ]
cipher = AES.new(enc_key, AES.MODE_CBC, iv)
decrypted = cipher.decrypt(encrypted)
return decrypted + b'\x00' * RESERVE_SZ
def full_decrypt(db_path, out_path, enc_key):
file_size = os.path.getsize(db_path)
total_pages = file_size // PAGE_SZ
os.makedirs(os.path.dirname(out_path), exist_ok=True)
with open(db_path, 'rb') as fin, open(out_path, 'wb') as fout:
for pgno in range(1, total_pages + 1):
page = fin.read(PAGE_SZ)
if len(page) < PAGE_SZ:
if len(page) > 0:
page = page + b'\x00' * (PAGE_SZ - len(page))
else:
break
fout.write(decrypt_page(enc_key, page, pgno))
return total_pages
def decrypt_wal(wal_path, out_path, enc_key):
if not os.path.exists(wal_path):
return 0
wal_size = os.path.getsize(wal_path)
if wal_size <= WAL_HEADER_SZ:
return 0
frame_size = WAL_FRAME_HEADER_SZ + PAGE_SZ
patched = 0
with open(wal_path, 'rb') as wf, open(out_path, 'r+b') as df:
wal_hdr = wf.read(WAL_HEADER_SZ)
wal_salt1 = struct.unpack('>I', wal_hdr[16:20])[0]
wal_salt2 = struct.unpack('>I', wal_hdr[20:24])[0]
while wf.tell() + frame_size <= wal_size:
fh = wf.read(WAL_FRAME_HEADER_SZ)
if len(fh) < WAL_FRAME_HEADER_SZ:
break
pgno = struct.unpack('>I', fh[0:4])[0]
frame_salt1 = struct.unpack('>I', fh[8:12])[0]
frame_salt2 = struct.unpack('>I', fh[12:16])[0]
ep = wf.read(PAGE_SZ)
if len(ep) < PAGE_SZ:
break
if pgno == 0 or pgno > 1000000:
continue
if frame_salt1 != wal_salt1 or frame_salt2 != wal_salt2:
continue
dec = decrypt_page(enc_key, ep, pgno)
df.seek((pgno - 1) * PAGE_SZ)
df.write(dec)
patched += 1
return patched
# ============ DB 缓存 ============
class DBCache:
"""缓存解密后的 DB,通过 mtime 检测变化。使用固定文件名,重启后可复用。"""
CACHE_DIR = os.path.join(tempfile.gettempdir(), "wechat_mcp_cache")
MTIME_FILE = os.path.join(tempfile.gettempdir(), "wechat_mcp_cache", "_mtimes.json")
def __init__(self):
self._cache = {} # rel_key -> (db_mtime, wal_mtime, tmp_path)
os.makedirs(self.CACHE_DIR, exist_ok=True)
self._load_persistent_cache()
def _cache_path(self, rel_key):
"""rel_key -> 固定的缓存文件路径"""
h = hashlib.md5(rel_key.encode()).hexdigest()[:12]
return os.path.join(self.CACHE_DIR, f"{h}.db")
def _load_persistent_cache(self):
"""启动时从磁盘恢复缓存映射,验证 mtime 后复用"""
if not os.path.exists(self.MTIME_FILE):
return
try:
with open(self.MTIME_FILE, encoding="utf-8") as f:
saved = json.load(f)
except (json.JSONDecodeError, OSError):
return
reused = 0
for rel_key, info in saved.items():
tmp_path = info["path"]
if not os.path.exists(tmp_path):
continue
rel_path = rel_key.replace('\\', os.sep)
db_path = os.path.join(DB_DIR, rel_path)
wal_path = db_path + "-wal"
try:
db_mtime = os.path.getmtime(db_path)
wal_mtime = os.path.getmtime(wal_path) if os.path.exists(wal_path) else 0
except OSError:
continue
if db_mtime == info["db_mt"] and wal_mtime == info["wal_mt"]:
self._cache[rel_key] = (db_mtime, wal_mtime, tmp_path)
reused += 1
if reused:
print(f"[DBCache] reused {reused} cached decrypted DBs from previous run", flush=True)
def _save_persistent_cache(self):
"""持久化缓存映射到磁盘"""
data = {}
for rel_key, (db_mt, wal_mt, path) in self._cache.items():
data[rel_key] = {"db_mt": db_mt, "wal_mt": wal_mt, "path": path}
try:
with open(self.MTIME_FILE, 'w', encoding="utf-8") as f:
json.dump(data, f)
except OSError:
pass
def get(self, rel_key):
key_info = get_key_info(ALL_KEYS, rel_key)
if not key_info:
return None
rel_path = rel_key.replace('\\', '/').replace('/', os.sep)
db_path = os.path.join(DB_DIR, rel_path)
wal_path = db_path + "-wal"
if not os.path.exists(db_path):
return None
try:
db_mtime = os.path.getmtime(db_path)
wal_mtime = os.path.getmtime(wal_path) if os.path.exists(wal_path) else 0
except OSError:
return None
if rel_key in self._cache:
c_db_mt, c_wal_mt, c_path = self._cache[rel_key]
if c_db_mt == db_mtime and c_wal_mt == wal_mtime and os.path.exists(c_path):
return c_path
tmp_path = self._cache_path(rel_key)
enc_key = bytes.fromhex(key_info["enc_key"])
full_decrypt(db_path, tmp_path, enc_key)
if os.path.exists(wal_path):
decrypt_wal(wal_path, tmp_path, enc_key)
self._cache[rel_key] = (db_mtime, wal_mtime, tmp_path)
self._save_persistent_cache()
return tmp_path
def cleanup(self):
"""正常退出时保存缓存映射(不删文件,下次启动可复用)"""
self._save_persistent_cache()
_cache = DBCache()
atexit.register(_cache.cleanup)
# ============ 联系人缓存 ============
_contact_names = None # {username: display_name}
_contact_full = None # [{username, nick_name, remark, alias, description, phone}]
_contact_tags = None # {label_id: {name, sort_order, members: [{username, display_name}]}}
_self_username = None
_contact_db_mtime = 0 # mtime of the decrypted contact.db when caches were last populated
def _invalidate_contact_caches():
global _contact_names, _contact_full, _contact_tags, _self_username
_contact_names = None
_contact_full = None
_contact_tags = None
_self_username = None
_XML_UNSAFE_RE = re.compile(r'<!DOCTYPE|<!ENTITY', re.IGNORECASE)
_XML_PARSE_MAX_LEN = 20000
_QUERY_LIMIT_MAX = 500
_HISTORY_QUERY_BATCH_SIZE = 500
def _load_contacts_from(db_path):
names = {}
full = []
conn = sqlite3.connect(db_path)
try:
columns = {
row[1] for row in conn.execute("PRAGMA table_info(contact)").fetchall()
}
optional_columns = {
"alias": "",
"description": "",
"phone": "",
"phone_number": "",
"mobile": "",
"mobile_phone": "",
"telephone": "",
}
select_columns = ["username", "nick_name", "remark"]
select_columns.extend(
col for col in optional_columns
if col in columns and col not in select_columns
)
rows = conn.execute(
"SELECT " + ", ".join(f"[{col}]" for col in select_columns)
+ " FROM contact"
).fetchall()
for r in rows:
data = dict(zip(select_columns, r))
uname = data.get("username")
nick = data.get("nick_name")
remark = data.get("remark")
display = remark if remark else nick if nick else uname
names[uname] = display
phone = ""
for col in ("phone", "phone_number", "mobile", "mobile_phone", "telephone"):
if data.get(col):
phone = data.get(col) or ""
break
full.append({
'username': uname,
'nick_name': nick or '',
'remark': remark or '',
'alias': data.get("alias") or '',
'description': data.get("description") or '',
'phone': phone,
})
finally:
conn.close()
return names, full
def _get_contact_db_path():
"""获取 contact.db 路径并按 mtime 决定是否清缓存。
优先实时解密路径(DBCache 已经按源 mtime 触发重解密),其次回退到
静态已解密副本。任何一次 mtime 变化都使内存缓存失效,避免新增联系人
或改名/改备注后 MCP 查询仍读到旧数据。
"""
global _contact_db_mtime
path = _cache.get(os.path.join("contact", "contact.db"))
if not path:
pre = os.path.join(DECRYPTED_DIR, "contact", "contact.db")
path = pre if os.path.exists(pre) else None
if not path:
return None
try:
mt = os.path.getmtime(path)
except OSError:
return path
if mt != _contact_db_mtime:
_invalidate_contact_caches()
_contact_db_mtime = mt
return path
def get_contact_names():
global _contact_names, _contact_full
path = _get_contact_db_path()
if not path:
return {}
if _contact_names is not None:
return _contact_names
try:
_contact_names, _contact_full = _load_contacts_from(path)
return _contact_names
except Exception:
return {}
def get_contact_full():
get_contact_names()
return _contact_full or []
def get_contact_tag_names_by_username():
tags = _load_contact_tags()
by_username = {}
for tag in tags.values():
name = tag.get('name') or ''
if not name:
continue
for member in tag.get('members', []):
username = member.get('username')
if username:
by_username.setdefault(username, []).append(name)
return by_username
def _extract_pb_field_30(data):
"""从 extra_buffer (protobuf) 中提取 Field #30 的字符串值(联系人标签ID)"""
if not data:
return None
pos = 0
n = len(data)
while pos < n:
# 读 varint tag
tag = 0
shift = 0
while pos < n:
b = data[pos]; pos += 1
tag |= (b & 0x7f) << shift
if not (b & 0x80):
break
shift += 7
field_num = tag >> 3
wire_type = tag & 0x07
if wire_type == 0: # varint
while pos < n and data[pos] & 0x80:
pos += 1
pos += 1
elif wire_type == 2: # length-delimited
length = 0; shift = 0
while pos < n:
b = data[pos]; pos += 1
length |= (b & 0x7f) << shift
if not (b & 0x80):
break
shift += 7
if field_num == 30:
try:
return data[pos:pos + length].decode('utf-8')
except Exception:
return None
pos += length
elif wire_type == 1: # 64-bit
pos += 8
elif wire_type == 5: # 32-bit
pos += 4
else:
break
return None
def _load_contact_tags():
"""加载并缓存联系人标签数据"""
global _contact_tags
db_path = _get_contact_db_path()
if not db_path:
return {}
if _contact_tags is not None:
return _contact_tags
try:
conn = sqlite3.connect(db_path)
except Exception:
return {}
try:
# 1. 加载标签定义
try:
label_rows = conn.execute(
"SELECT label_id_, label_name_, sort_order_ FROM contact_label ORDER BY sort_order_"
).fetchall()
except sqlite3.OperationalError:
return {}
if not label_rows:
return {}
labels = {}
for lid, lname, sort_order in label_rows:
labels[lid] = {'name': lname, 'sort_order': sort_order, 'members': []}
# 2. 扫描联系人的标签关联
names = get_contact_names()
rows = conn.execute(
"SELECT username, extra_buffer FROM contact WHERE extra_buffer IS NOT NULL"
).fetchall()
for username, buf in rows:
label_str = _extract_pb_field_30(buf)
if not label_str:
continue
display = names.get(username, username)
for lid_s in label_str.split(','):
try:
lid = int(lid_s.strip())
except (ValueError, AttributeError):
continue
if lid in labels:
labels[lid]['members'].append({'username': username, 'display_name': display})
_contact_tags = labels
return _contact_tags
except Exception:
return {}
finally:
conn.close()
# ============ 辅助函数 ============
def format_msg_type(t):
base_type, _ = _split_msg_type(t)
return {
1: '文本', 3: '图片', 34: '语音', 42: '名片',
43: '视频', 47: '表情', 48: '位置', 49: '链接/文件',
50: '通话', 10000: '系统', 10002: '撤回',
}.get(base_type, f'type={t}')
def _split_msg_type(t):
try:
t = int(t)
except (TypeError, ValueError):
return 0, 0
# WeChat packs the base type into the low 32 bits and app subtype into the high 32 bits.
if t > 0xFFFFFFFF:
return t & 0xFFFFFFFF, t >> 32
return t, 0
def resolve_username(chat_name):
"""将聊天名/备注名/wxid 解析为 username"""
names = get_contact_names()
# 直接是 username
if chat_name in names or chat_name.startswith('wxid_') or '@chatroom' in chat_name:
return chat_name
# 模糊匹配(优先精确包含)
chat_lower = chat_name.lower()
for uname, display in names.items():
if chat_lower == display.lower():
return uname
for uname, display in names.items():
if chat_lower in display.lower():
return uname
return None
_zstd_dctx = zstd.ZstdDecompressor()
def _decompress_content(content, ct):
"""解压 zstd 压缩的消息内容"""
if ct and ct == 4 and isinstance(content, bytes):
try:
return _zstd_dctx.decompress(content).decode('utf-8', errors='replace')
except Exception:
return None
if isinstance(content, bytes):
try:
return content.decode('utf-8', errors='replace')
except Exception:
return None
return content
def _parse_message_content(content, local_type, is_group):
"""解析消息内容,返回 (sender_id, text)。
群消息 content 形如 'wxid_xxx:\n<xml...>';某些 type=19 合并转发也会
写成 'wxid_xxx:<?xml...' 或 'wxid_xxx:<msg...' 不带换行——剥离逻辑两种都要处理。
"""
if content is None:
return '', ''
if isinstance(content, bytes):
return '', '(二进制内容)'
sender = ''
text = content
if is_group:
if ':\n' in content:
sender, text = content.split(':\n', 1)
else:
# 'sender:<?xml...' / 'sender:<msg...' 等无换行 case
m = re.match(r'^([A-Za-z0-9_\-@.]+):(<\?xml|<msg|<msglist|<voipmsg|<sysmsg)', content)
if m:
sender = m.group(1)
text = content[len(sender) + 1:]
return sender, text
def _collapse_text(text):
if not text:
return ''
return re.sub(r'\s+', ' ', text).strip()
def _get_self_username():
global _self_username
if not DB_DIR:
return ''
names = get_contact_names()
if _self_username:
return _self_username
account_dir = os.path.basename(os.path.dirname(DB_DIR))
candidates = [account_dir]
m = re.fullmatch(r'(.+)_([0-9a-fA-F]{4,})', account_dir)
if m:
candidates.insert(0, m.group(1))
for candidate in candidates:
if candidate and candidate in names:
_self_username = candidate
return _self_username
return ''
def _load_name2id_maps(conn):
id_to_username = {}
try:
rows = conn.execute("SELECT rowid, user_name FROM Name2Id").fetchall()
except sqlite3.Error:
return id_to_username
for rowid, user_name in rows:
if not user_name:
continue
id_to_username[rowid] = user_name
return id_to_username
def _display_name_for_username(username, names):
if not username:
return ''
if username == _get_self_username():
return 'me'
return names.get(username, username)
def _resolve_sender_label(real_sender_id, sender_from_content, is_group, chat_username, chat_display_name, names, id_to_username):
sender_username = id_to_username.get(real_sender_id, '')
if is_group:
if sender_username and sender_username != chat_username:
return _display_name_for_username(sender_username, names)
if sender_from_content:
return _display_name_for_username(sender_from_content, names)
return ''
if sender_username == chat_username:
return chat_display_name
if sender_username:
return _display_name_for_username(sender_username, names)
return ''
def _resolve_quote_sender_label(ref_user, ref_display_name, is_group, chat_username, chat_display_name, names):
if is_group:
if ref_user:
return _display_name_for_username(ref_user, names)
return ref_display_name or ''
self_username = _get_self_username()
if ref_user:
if ref_user == chat_username:
return chat_display_name
if self_username and ref_user == self_username:
return 'me'
return names.get(ref_user, ref_display_name or ref_user)
if ref_display_name:
if ref_display_name == chat_display_name:
return chat_display_name
self_display_name = names.get(self_username, self_username) if self_username else ''
if self_display_name and ref_display_name == self_display_name:
return 'me'
return ref_display_name
return ''
# 合并转发消息(含 recorditem 内嵌 XML)在 dataitem 数量多时显著超过默认 20K 上限,
# 实测真实 outer XML 可达 ~500KB。caller 可通过 max_len 参数为 type=19 类大消息放宽限制。
_RECORD_XML_PARSE_MAX_LEN = 500_000
def _safe_basename(name):
"""对 user-derived filename(从消息 XML 来,不可信)做严格 sanitize。
Reject 而不是 normalize:哪怕 os.path.basename 把 '../foo' 剥成 'foo' 是
safe 的,意图依然可疑,应该显式失败让用户看到。
"""
if not name:
return ''
if '\x00' in name:
return ''
if os.path.isabs(name):
return ''
# 任何 path separator 或 .. component 直接拒(不做 normalize)
parts = name.replace('\\', '/').split('/')
if any(p in ('', '.', '..') for p in parts) and len(parts) > 1:
return ''
if len(parts) > 1:
return ''
if name in ('.', '..'):
return ''
return name
def _path_under_root(path, root):
"""resolve realpath 后确认仍在 root 下(防 symlink 跳出)。"""
try:
real_path = os.path.realpath(path)
real_root = os.path.realpath(root)
except OSError:
return False
return real_path == real_root or real_path.startswith(real_root + os.sep)
# 大附件 md5 校验时的安全上限:超过此 size 直接拒绝校验(避免 MCP 进程
# 在 100MB+ 视频/附件上一次性 read() 整文件爆内存或长时间阻塞)。
_MD5_VERIFY_MAX_SIZE = 500 * 1024 * 1024 # 500 MB
_MD5_CHUNK_SIZE = 64 * 1024 # 64 KB
def _md5_file_chunked(path, max_size=_MD5_VERIFY_MAX_SIZE):
"""流式分块计算文件 md5,避免大文件一次读完爆内存。
超过 max_size 直接拒绝(DoS 防御 + 大附件 md5 校验现实意义不大)。
返回 (md5_hex, error);成功时 error 为 None。
"""
try:
size = os.path.getsize(path)
except OSError as e:
return None, f"无法读取文件 size: {e}"
if size > max_size:
return None, f"文件 size {size:,} 超过 md5 校验上限 {max_size:,}(防 DoS)"
h = hashlib.md5()
try:
with open(path, 'rb') as f:
while True:
chunk = f.read(_MD5_CHUNK_SIZE)
if not chunk:
break
h.update(chunk)
except OSError as e:
return None, f"读取文件失败: {e}"
return h.hexdigest().lower(), None
def _parse_xml_root(content, max_len=_XML_PARSE_MAX_LEN):
if not content or len(content) > max_len or _XML_UNSAFE_RE.search(content):
return None
try:
return ET.fromstring(content)
except ET.ParseError:
return None
def _parse_int(value, fallback=0):
try:
return int(value)
except (TypeError, ValueError):
return fallback
def _parse_app_message_outer(content):
"""Parse outer appmsg XML,对 type=19 合并卡片自动放宽到 _RECORD_XML_PARSE_MAX_LEN。
所有解析 outer appmsg 的 caller(get_chat_history 渲染 / decode_file_message /
decode_record_item)共用此 helper,避免同一条大消息在不同 caller 上行为不一致。
Substring 短路保证非 type=19 的大 appmsg 不付出 500K parse 代价。"""
root = _parse_xml_root(content)
if root is None and content and len(content) <= _RECORD_XML_PARSE_MAX_LEN:
if '<type>19</type>' in content:
root = _parse_xml_root(content, max_len=_RECORD_XML_PARSE_MAX_LEN)
return root
def _format_namecard_text(content):
"""Parse type=42 (名片) XML into a compact human-readable line.
Source XML carries dozens of fields (antispamticket, biznamecardinfo,
brand URLs, image MD5s) but the useful signal is just three attrs:
``nickname`` (display name), ``username`` (wxid; ``gh_*`` for 公众号),
and ``certinfo`` (the user-authored bio). Everything else is either
auth tokens that should not be piped to downstream systems, or
rendering metadata that bloats the chat log without helping a human
or an LLM understand the conversation.
"""
root = _parse_xml_root(content)
if root is None:
return None
nickname = (root.get("nickname") or "").strip()
username = (root.get("username") or "").strip()
certinfo = _collapse_text(root.get("certinfo") or "")
if not nickname and not username:
return None
head = nickname or username
if username.startswith("gh_"):
head = f"{head} (公众号 {username})"
return f"[名片] {head}: {certinfo}" if certinfo else f"[名片] {head}"
def _format_app_message_text(content, local_type, is_group, chat_username, chat_display_name, names):
if not content or '<appmsg' not in content:
return None
_, sub_type = _split_msg_type(local_type)
root = _parse_app_message_outer(content)
if root is None:
return None
appmsg = root.find('.//appmsg')
if appmsg is None:
return None
title = _collapse_text(appmsg.findtext('title') or '')
app_type_text = (appmsg.findtext('type') or '').strip()
app_type = _parse_int(app_type_text, _parse_int(sub_type, 0))
if app_type == 57:
return _format_refer_message_text(
appmsg, is_group, chat_username, chat_display_name, names
)
if app_type == 19:
return _format_record_message_text(appmsg, title)
if app_type == 2000:
return _format_transfer_message_text(appmsg, title)
if app_type == 6:
return f"[文件] {title}" if title else "[文件]"
if app_type == 5:
return f"[链接] {title}" if title else "[链接]"
if app_type in (33, 36, 44):
return f"[小程序] {title}" if title else "[小程序]"
if title:
return f"[链接/文件] {title}"
return "[链接/文件]"
_RECORD_MAX_ITEMS = 50
_RECORD_MAX_LINE_LEN = 200
# 合并转发 dataitem 的 datatype → wechat 缓存子目录映射。仅这 4 类有真本地
# binary 文件;其他 datatype(链接/名片/小程序/视频号 等)只有 metadata。
_RECORD_BINARY_SUBDIR = {'8': 'F', '2': 'Img', '5': 'V', '4': 'A'}
# datatype → 中文标签,散在多处使用:渲染合并卡片 / decode_record_item 的
# 错误提示 / 单元测试。统一在模块顶部维护避免漂移。
_RECORD_DATATYPE_LABEL = {
'1': '文本', '2': '图片', '3': '名片', '4': '语音',
'5': '视频', '6': '链接', '7': '位置', '8': '文件',
'17': '聊天记录', '19': '小程序', '22': '视频号',
'23': '视频号直播', '29': '音乐', '36': '小程序/H5',
'37': '表情包',
}
def _format_record_dataitem(item):
"""格式化合并记录中的单个 dataitem,返回展示文本。"""
datatype = (item.get('datatype') or '').strip()
if datatype == '1':
return _collapse_text(item.findtext('datadesc') or '') or '[文本]'
if datatype in ('2', '3', '4', '5', '7', '23', '37'):
return f"[{_RECORD_DATATYPE_LABEL[datatype]}]"
if datatype in ('6', '36'):
link_title = _collapse_text(item.findtext('datatitle') or '')
label = _RECORD_DATATYPE_LABEL[datatype]
return f"[{label}] {link_title}" if link_title else f"[{label}]"
if datatype == '8':
file_title = _collapse_text(item.findtext('datatitle') or '')
return f"[文件] {file_title}" if file_title else '[文件]'
if datatype == '17':
nested_title = _collapse_text(item.findtext('datatitle') or '')
return f"[聊天记录] {nested_title}" if nested_title else '[聊天记录]'
if datatype == '19':
# 小程序:appbranditem/sourcedisplayname 是直接子代,不需要 .// 递归
app_name = _collapse_text(item.findtext('appbranditem/sourcedisplayname') or '')
item_title = _collapse_text(item.findtext('datatitle') or '')
label = item_title or app_name or '小程序'
return f"[小程序] {label}"
if datatype == '22':
feed_desc = _collapse_text(item.findtext('finderFeed/desc') or '')
return f"[视频号] {feed_desc[:80]}" if feed_desc else '[视频号]'
if datatype == '29':
song = _collapse_text(item.findtext('datatitle') or '')
artist = _collapse_text(item.findtext('datadesc') or '')
if song and artist:
return f"[音乐] {song} - {artist}"
return f"[音乐] {song}" if song else '[音乐]'
desc = _collapse_text(item.findtext('datadesc') or '')
title_text = _collapse_text(item.findtext('datatitle') or '')
fallback = desc or title_text
return fallback if fallback else f"[未知类型 {datatype}]"
def _format_record_message_text(appmsg, title):
"""解析合并转发的聊天记录卡片(appmsg type=19, recorditem)。"""
fallback_title = title or '聊天记录'
record_node = appmsg.find('recorditem')
if record_node is None or not record_node.text:
return f"[聊天记录] {fallback_title}(待加载)"
inner = _parse_xml_root(record_node.text, max_len=_RECORD_XML_PARSE_MAX_LEN)
if inner is None:
return f"[聊天记录] {fallback_title}"
record_title = _collapse_text(inner.findtext('title') or '') or fallback_title
is_chatroom = (inner.findtext('isChatRoom') or '').strip() == '1'
datalist = inner.find('datalist')
items = list(datalist.findall('dataitem')) if datalist is not None else []
if not items:
suffix = "(群聊转发,待加载)" if is_chatroom else "(待加载)"
return f"[聊天记录] {record_title}{suffix}"
header = f"[聊天记录] {record_title}"
if is_chatroom:
header += "(群聊转发)"
header += f",共 {len(items)} 条"
lines = [header + ":"]
for idx, item in enumerate(items[:_RECORD_MAX_ITEMS]):
sender = _collapse_text(item.findtext('sourcename') or '')
when = _collapse_text(item.findtext('sourcetime') or '')
content = _format_record_dataitem(item)
if len(content) > _RECORD_MAX_LINE_LEN:
content = content[:_RECORD_MAX_LINE_LEN] + '…'
# 0-based index 让用户能用 decode_record_item(chat, local_id, item_index) 引用
prefix_parts = [f"[{idx}]"] + [p for p in (when, sender) if p]
prefix = ' '.join(prefix_parts)
lines.append(f" {prefix}: {content}")
if len(items) > _RECORD_MAX_ITEMS:
lines.append(f" …(还有 {len(items) - _RECORD_MAX_ITEMS} 条未显示)")
return "\n".join(lines)
# 微信转账 (appmsg type=2000, <wcpayinfo>) paysubtype 含义。
# 微信官方无公开文档,此表来自社区抓包归纳。1/3/4 在所有已知版本一致;
# 5/7/8 在不同版本存在变体("过期已退还"在某些抓包里也归为 4),所以遇到
# 未识别值时降级显示原始数字,方便用户自行核对。
_TRANSFER_PAYSUBTYPE_LABEL = {
'1': '发起转账', # 发送方记录:等待对方收钱
'3': '已收款', # 双向:发送方看到"对方已收",接收方看到"已收钱"
'4': '已退还', # 主动退还或被退还
'5': '过期已退还', # 24h 未收,自动退还(发送方记录)
'7': '待领取', # 已发起未接收
'8': '已领取', # 部分版本:转账被领取(接收方记录)
}
# 微信引用回复(appmsg type=57, <refermsg>)内层 <type> 的标签映射。
# refermsg/<type> 用的是顶层 base_type 数字(跟 format_msg_type 重合),
# 但语义不同:format_msg_type 给"消息类型 chip",这里给"被引用消息的一行摘要",
# 不展开 cdn url / aeskey / md5 等二进制元数据(直接截断 XML 字符串当摘要是
# 现状的 bug,会把"图片/语音/视频/动画表情/嵌套卡片"渲染成乱码——见 issue #44 #45)。
_REFER_INNER_TYPE_LABEL = {
'1': '文本', # 特殊:直接展开 content
'3': '图片',
'34': '语音',
'42': '名片',
'43': '视频',
'47': '动画表情',
'48': '位置',
'49': '链接/卡片', # 特殊:嵌套 appmsg,进一步解 inner type
'50': '通话',
}
# refer_type=49 时 content 是嵌套 <msg><appmsg>...,inner appmsg/<type> → 标签。
# 跟合并转发 _RECORD_DATATYPE_LABEL 的数字含义不同(datatype 是 recorditem 的私有
# schema),独立维护。
_INNER_APPMSG_TYPE_LABEL = {
'5': '链接', '6': '文件', '8': '动画表情卡',
'19': '聊天记录', '33': '小程序', '36': '小程序',
'51': '视频号', '57': '引用消息',
'2000': '转账', '2001': '红包',
}
def _extract_refer_info(appmsg):
"""从 appmsg type=57 解出 refermsg 各字段,返回 dict 或 None。
refermsg/<content> 是 escape 后的字符串,内层 type 决定其 schema:
type=1 (纯文本) / 3 (img cdn) / 34 (voicemsg) / 47 (emoji)
/ 49 (嵌套 appmsg) / ...
refer_content 保留原始字符串(不 collapse),让 _summarize_refer_content
按 type 进一步处理(type=49 还要再解一层 XML)。其他字段过 _collapse_text
清掉换行/前后空白。
"""
refer = appmsg.find('refermsg')
if refer is None:
return None
return {
'reply_text': _collapse_text(appmsg.findtext('title') or ''),
'refer_type': _collapse_text(refer.findtext('type') or ''),
'refer_svrid': _collapse_text(refer.findtext('svrid') or ''),
'refer_fromusr': _collapse_text(refer.findtext('fromusr') or ''),
'refer_chatusr': _collapse_text(refer.findtext('chatusr') or ''),
'refer_displayname': _collapse_text(refer.findtext('displayname') or ''),
'refer_content': refer.findtext('content') or '',
'refer_createtime': _collapse_text(refer.findtext('createtime') or ''),
}
def _summarize_refer_content(refer_type, content, max_len=160):
"""把被引用消息的 content 摘要成一行可读文本。
分支规则:
type=1 (文本): 取原文,截断到 max_len
type=3/34/43/47/...: 给标签兜底,不展开 cdn url / aeskey / md5
type=49 (嵌套 appmsg): 解一层 inner appmsg/type + title,给"[链接] xxx"
未识别 type: 给 [type=N] 兜底,方便用户自查
max_len 只对 type=1 文本生效;标签型摘要本身就短。
"""
refer_type = (refer_type or '').strip()
if not content:
label = _REFER_INNER_TYPE_LABEL.get(refer_type)
if label:
return f'[{label}]'
return f'[type={refer_type}]' if refer_type else '[引用消息]'