dsh-qqbot-muu 0.1.15 → 0.1.21

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 (171) hide show
  1. package/CHANGELOG.md +168 -85
  2. package/client/qqbot-settings.js +13401 -12024
  3. package/config/modules.json +212 -0
  4. package/dist/channel-tools.js +21 -10
  5. package/dist/config.d.ts +14 -0
  6. package/dist/config.js +573 -449
  7. package/dist/features/contextless-store.js +247 -247
  8. package/dist/features/contextless-trim.js +455 -34
  9. package/dist/features/four-source.js +338 -336
  10. package/dist/features/group-join-request.js +289 -287
  11. package/dist/features/local-models.js +1494 -0
  12. package/dist/features/rotate-summarizer.js +438 -0
  13. package/dist/features/scenario-detect.js +321 -0
  14. package/dist/features/scheduler.js +8 -1
  15. package/dist/features/session-rotate.js +499 -0
  16. package/dist/features/session-title.js +199 -0
  17. package/dist/features/style-layer.js +501 -0
  18. package/dist/features/thinking-log.js +71 -69
  19. package/dist/gateway/bootstrap.js +1704 -1388
  20. package/dist/gateway/data-root.js +77 -3
  21. package/dist/gateway/middleware-setup.js +6 -3
  22. package/dist/index.js +4 -2
  23. package/dist/model/settings-reader.js +193 -102
  24. package/dist/session/session-manager.js +1730 -1587
  25. package/dist/shared/paths.js +128 -0
  26. package/dist/shared/settings-io.js +79 -0
  27. package/dist/transport/inbound.js +20 -1
  28. package/dist/transport/outbound.js +56 -4
  29. package/docs/RELEASE_CHECKLIST.md +24 -2
  30. package/dshqqbot/.qqbot-extensions/hooks/interview-panel.mjs +41 -1
  31. package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
  32. package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -689
  33. package/dshqqbot/.qqbot-extensions/inbound/ac-image-see.mjs +1 -1
  34. package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
  35. package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
  36. package/dshqqbot/.qqbot-extensions/lib/.pet-form.json +1 -1
  37. package/dshqqbot/.qqbot-extensions/lib/draw-core.mjs +238 -7
  38. package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -394
  39. package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
  40. package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
  41. package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
  42. package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
  43. package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
  44. package/dshqqbot/.qqbot-extensions/lib/plugin-dir.mjs +14 -4
  45. package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
  46. package/dshqqbot/.qqbot-extensions/lib/vision.mjs +1 -1
  47. package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
  48. package/dshqqbot/.qqbot-extensions/outbound/ac-media-fix.mjs +5 -1
  49. package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
  50. package/dshqqbot/.qqbot-extensions/outbound/split-reply.mjs +18 -2
  51. package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
  52. package/dshqqbot/.qqbot-extensions/tools/draw.mjs +22 -1
  53. package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
  54. package/dshqqbot/.qqbot-extensions/tools/pet_card.mjs +3 -2
  55. package/dshqqbot/.qqbot-extensions/tools/storyboard.mjs +3 -1
  56. package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
  57. package/package.json +119 -111
  58. package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
  59. package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
  60. package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
  61. package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
  62. package/scripts/_add_maintenance_cfg.py +20 -0
  63. package/scripts/_bench_keeplease.sh +10 -0
  64. package/scripts/_dbg_purge.py +15 -0
  65. package/scripts/_elev.sh +6 -0
  66. package/scripts/_fix_all_admin.cmd +16 -0
  67. package/scripts/_livecheck-image.mjs +33 -0
  68. package/scripts/_livecheck-llm.mjs +34 -0
  69. package/scripts/_livecheck-tts.mjs +37 -0
  70. package/scripts/_patch_curve.py +88 -0
  71. package/scripts/_patch_fan_thermal.py +24 -0
  72. package/scripts/_tag_tmp.py +13 -0
  73. package/scripts/adb-broker-client.mjs +87 -0
  74. package/scripts/adb-broker.mjs +205 -0
  75. package/scripts/ai-mode.cmd +6 -0
  76. package/scripts/ai-mode.py +387 -0
  77. package/scripts/ai-toolkit.py +607 -0
  78. package/scripts/apply-fan-gpu45.py +51 -0
  79. package/scripts/bench-fans.py +515 -0
  80. package/scripts/bench-load-direct.py +63 -0
  81. package/scripts/boot-tasks-hidden.vbs +20 -0
  82. package/scripts/boot-tasks.cmd +277 -0
  83. package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
  84. package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
  85. package/scripts/chat-archive/build-sft-v4.py +566 -0
  86. package/scripts/chat-archive/build-sft.py +390 -0
  87. package/scripts/chat-archive/eval-sft.py +155 -0
  88. package/scripts/chat-archive/extract-memory.py +143 -0
  89. package/scripts/chat-archive/inventory.py +182 -0
  90. package/scripts/chat-archive/merge-sft.py +114 -0
  91. package/scripts/chat-archive/qce-pull.py +217 -0
  92. package/scripts/chat-archive/qqheader.py +110 -0
  93. package/scripts/chat-archive/qqkey2.py +113 -0
  94. package/scripts/chat-archive/qqprobe.py +153 -0
  95. package/scripts/chat-archive/screen-collect.py +163 -0
  96. package/scripts/chat-archive/sqlcipher_probe.py +444 -0
  97. package/scripts/comfy_gen.py +209 -0
  98. package/scripts/compose-video.py +168 -0
  99. package/scripts/dl_models.py +45 -0
  100. package/scripts/draw-now.cmd +18 -0
  101. package/scripts/dsh-instance-guard.mjs +20 -2
  102. package/scripts/elev-extra.cmd +25 -0
  103. package/scripts/episode.py +529 -0
  104. package/scripts/fan-curve.py +218 -0
  105. package/scripts/fan-guard.cmd +8 -0
  106. package/scripts/fan-mode.py +380 -0
  107. package/scripts/fan_manual_safe.py +33 -0
  108. package/scripts/fan_restore_manual.py +46 -0
  109. package/scripts/fc_curves.py +359 -0
  110. package/scripts/fix-fan-and-timers.cmd +39 -0
  111. package/scripts/fix_admin_all.py +94 -0
  112. package/scripts/flows.mjs +224 -0
  113. package/scripts/gateway.cmd +126 -0
  114. package/scripts/gen-image.py +420 -0
  115. package/scripts/gen-video.py +186 -0
  116. package/scripts/git-askpass.cmd +2 -2
  117. package/scripts/gpu-mode.py +195 -0
  118. package/scripts/hw-profile.py +175 -0
  119. package/scripts/install-schedule.cmd +37 -0
  120. package/scripts/install-watch.cmd +29 -0
  121. package/scripts/matte-cutout.py +106 -0
  122. package/scripts/media-enhance.py +402 -0
  123. package/scripts/memory-audit.py +581 -0
  124. package/scripts/migrate-scope.mjs +140 -139
  125. package/scripts/model-registry.py +519 -0
  126. package/scripts/openid-audit.mjs +219 -0
  127. package/scripts/pull-gguf.py +127 -0
  128. package/scripts/purge-standby.py +151 -0
  129. package/scripts/qq-connect-login.py +133 -0
  130. package/scripts/qq-ip-sync-hidden.vbs +5 -0
  131. package/scripts/qq-ip-sync.py +300 -0
  132. package/scripts/qq-login-once.cmd +20 -0
  133. package/scripts/qq-login-qr.py +72 -0
  134. package/scripts/qq-whitelist-fix.cmd +27 -0
  135. package/scripts/qq-whitelist-login.cmd +26 -0
  136. package/scripts/qq-whitelist.cmd +12 -0
  137. package/scripts/qq-whitelist.py +1452 -0
  138. package/scripts/quality-compare.py +134 -0
  139. package/scripts/release-all.mjs +636 -430
  140. package/scripts/release-check.mjs +244 -226
  141. package/scripts/resume-coder.cmd +38 -0
  142. package/scripts/secure-room/index.html +334 -0
  143. package/scripts/secure-room/server.py +582 -0
  144. package/scripts/security-check.mjs +164 -0
  145. package/scripts/selftest-local-llm.mjs +20 -0
  146. package/scripts/selftest-local-models.mjs +754 -0
  147. package/scripts/selftest-rotate-style.mjs +308 -0
  148. package/scripts/shutdown-s5-optional.cmd +21 -0
  149. package/scripts/sleep-2325.cmd +75 -0
  150. package/scripts/start-comfyui.cmd +5 -0
  151. package/scripts/start-strata.cmd +17 -0
  152. package/scripts/start-strata.vbs +11 -0
  153. package/scripts/start-watch-hidden.vbs +3 -0
  154. package/scripts/stickers/auto-tag.mjs +161 -0
  155. package/scripts/storage.mjs +236 -0
  156. package/scripts/sync-plugin-copies.mjs +98 -23
  157. package/scripts/tests/test-qq-whitelist.py +192 -0
  158. package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
  159. package/scripts/train/gguf-quantize.py +92 -0
  160. package/scripts/train/gguf-to-hf.py +112 -0
  161. package/scripts/train/merge-lora.py +51 -0
  162. package/scripts/train/probe-mirrors.sh +12 -0
  163. package/scripts/train/probe-mirrors2.sh +20 -0
  164. package/scripts/train/setup-wsl.sh +23 -0
  165. package/scripts/train/setup-wsl2.sh +25 -0
  166. package/scripts/train/setup-wsl3.sh +22 -0
  167. package/scripts/train/setup-wsl4.sh +22 -0
  168. package/scripts/train/train-lora.py +319 -0
  169. package/scripts/vram-free.py +104 -0
  170. package/scripts/wechat-full-pull.mjs +1 -1
  171. package/settings-host.js +1047 -12
@@ -0,0 +1,444 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ sqlcipher_probe.py — 本机聊天库「钥匙探测 + 解密」原型(全部本地,不联网)
5
+
6
+ 用途:微信 4.x / QQNT 的 message db 都是 SQLCipher 变体。想离线备份聊天记录,
7
+ 第一步是拿到进程里那把 key(不动网络、不上传任何东西)。
8
+
9
+ 做法:
10
+ 1. 用 ReadProcessMemory 扫目标进程的私有内存,只找「db 文件名」附近的内存块
11
+ (连接对象通常把 路径 和 key 放在一起,这样候选量从几千万降到几千)
12
+ 2. 对候选 32 字节做 SQLCipher4 校验:PBKDF2-SHA512(raw, salt, 256000, 32)
13
+ → AES-256-CBC 解第一页 → 看是不是 "SQLite format 3\\0"
14
+ 3. 命中后可按页解密整库(流式,边解边写,不一次性吃内存)
15
+
16
+ 用法:
17
+ python scripts/chat-archive/sqlcipher_probe.py find --exe Weixin.exe --db <db路径>
18
+ python scripts/chat-archive/sqlcipher_probe.py decrypt --db <db> --key <hex> --out <输出>
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import ctypes
24
+ import ctypes.wintypes as wt
25
+ import hashlib
26
+ import os
27
+ import struct
28
+ import sys
29
+ import time
30
+
31
+ PAGE = 4096
32
+ RESERVE = 80
33
+ SALT = 16
34
+ KDF_ITER = 256000
35
+
36
+ k32 = ctypes.WinDLL('kernel32', use_last_error=True)
37
+ PROCESS_VM_READ = 0x0010
38
+ PROCESS_QUERY_INFORMATION = 0x0400
39
+
40
+ MEM_COMMIT = 0x1000
41
+ PAGE_NOACCESS = 0x01
42
+ PAGE_GUARD = 0x100
43
+ MEM_PRIVATE = 0x20000
44
+ MEM_IMAGE = 0x1000000
45
+
46
+
47
+ class MEMORY_BASIC_INFORMATION(ctypes.Structure):
48
+ _fields_ = [
49
+ ('BaseAddress', ctypes.c_void_p),
50
+ ('AllocationBase', ctypes.c_void_p),
51
+ ('AllocationProtect', wt.DWORD),
52
+ ('RegionSize', ctypes.c_size_t),
53
+ ('State', wt.DWORD),
54
+ ('Protect', wt.DWORD),
55
+ ('Type', wt.DWORD),
56
+ ]
57
+
58
+
59
+ def pids_of(exe: str):
60
+ out = []
61
+ import subprocess
62
+ try:
63
+ r = subprocess.run(['tasklist', '/FI', f'IMAGENAME eq {exe}', '/FO', 'CSV', '/NH'],
64
+ capture_output=True, text=True, timeout=15)
65
+ for line in r.stdout.splitlines():
66
+ parts = [x.strip('"') for x in line.split('","')]
67
+ if len(parts) >= 2 and parts[0].lower() == exe.lower():
68
+ out.append(int(parts[1]))
69
+ except Exception as e:
70
+ print('tasklist 失败:', e)
71
+ return out
72
+
73
+
74
+ def read_regions(pid: int, max_bytes: int = 3 * 1024 ** 3):
75
+ """枚举目标进程可读的私有内存,逐块 yield (base, bytes)"""
76
+ h = k32.OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, False, pid)
77
+ if not h:
78
+ raise OSError(f'OpenProcess({pid}) 失败: {ctypes.get_last_error()}')
79
+ addr = 0
80
+ total = 0
81
+ mbi = MEMORY_BASIC_INFORMATION()
82
+ while total < max_bytes:
83
+ got = k32.VirtualQueryEx(wt.HANDLE(h), ctypes.c_void_p(addr), ctypes.byref(mbi), ctypes.sizeof(mbi))
84
+ if not got:
85
+ break
86
+ size = int(mbi.RegionSize)
87
+ if size <= 0:
88
+ break
89
+ if (mbi.State == MEM_COMMIT and mbi.Type == MEM_PRIVATE
90
+ and (mbi.Protect & PAGE_NOACCESS) == 0 and (mbi.Protect & PAGE_GUARD) == 0):
91
+ buf = ctypes.create_string_buffer(size)
92
+ read = ctypes.c_size_t(0)
93
+ if k32.ReadProcessMemory(wt.HANDLE(h), ctypes.c_void_p(addr), buf, size, ctypes.byref(read)):
94
+ data = buf.raw[:read.value]
95
+ if data:
96
+ total += len(data)
97
+ yield addr, data
98
+ addr += size
99
+ k32.CloseHandle(wt.HANDLE(h))
100
+
101
+
102
+ def derive(salt: bytes, raw: bytes) -> bytes:
103
+ return hashlib.pbkdf2_hmac('sha512', raw, salt, KDF_ITER, 32)
104
+
105
+
106
+ def page1_ok(salt: bytes, raw: bytes, cipher_page: bytes, mode: str = 'kdf') -> bool:
107
+ """mode=kdf: SQLCipher 常规(先 PBKDF2);mode=raw: PRAGMA key="x'..'" 的裸密钥模式(不做 KDF)"""
108
+ try:
109
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
110
+ key = raw if mode == 'raw' else derive(salt, raw)
111
+ iv = cipher_page[PAGE - RESERVE:PAGE - RESERVE + 16]
112
+ body = cipher_page[SALT:PAGE - RESERVE]
113
+ dec = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
114
+ pt = dec.update(body) + dec.finalize()
115
+ return pt[:16] == b'SQLite format 3\x00'
116
+ except Exception:
117
+ return False
118
+
119
+
120
+ def collect_candidates(exe: str, needles: list[str], span: int = 0x800, cap: int = 40000) -> list[bytes]:
121
+ """只读内存,收集「db 文件名附近」的 32 字节窗口(不做 KDF,很快)"""
122
+ import re
123
+ hexre = re.compile(rb'[0-9a-fA-F]{64}')
124
+ cands: list[bytes] = []
125
+ seen = set()
126
+ for pid in pids_of(exe):
127
+ try:
128
+ for _base, data in read_regions(pid):
129
+ for nd in needles:
130
+ for enc in (nd.encode('utf-8'), nd.encode('utf-16le')):
131
+ start = 0
132
+ while True:
133
+ i = data.find(enc, start)
134
+ if i < 0:
135
+ break
136
+ start = i + 1
137
+ lo, hi = max(0, i - span), min(len(data), i + span)
138
+ chunk = data[lo:hi]
139
+ # ① 优先:附近如果有 64 位 hex 串,很可能就是 key(先测它)
140
+ for m in hexre.finditer(chunk):
141
+ try:
142
+ b = bytes.fromhex(m.group(0).decode())
143
+ except Exception:
144
+ continue
145
+ if b not in seen:
146
+ seen.add(b); cands.insert(0, b)
147
+ # ② 兜底:附近 1 字节对齐的 32 字节窗口
148
+ for off in range(0, max(0, len(chunk) - 32)):
149
+ b = chunk[off:off + 32]
150
+ if b in seen:
151
+ continue
152
+ seen.add(b); cands.append(b)
153
+ if len(cands) >= cap:
154
+ return cands
155
+ except OSError as e:
156
+ print(f' pid {pid} 读不了: {e}', flush=True)
157
+ return cands
158
+
159
+
160
+ def _kdf_worker(args):
161
+ salt, head, chunk, halg, iters, reserve = args
162
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
163
+ iv_pos = PAGE - reserve
164
+ iv = head[iv_pos:iv_pos + 16]
165
+ ct = head[SALT:iv_pos]
166
+ if len(ct) < 16:
167
+ return []
168
+ hits = []
169
+ for cand in chunk:
170
+ for it in iters:
171
+ try:
172
+ key = hashlib.pbkdf2_hmac(halg, cand, salt, it, 32)
173
+ d = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
174
+ if d.update(ct[:16]) == b'SQLite format 3\x00':
175
+ hits.append((cand.hex(), halg, it)); break
176
+ except Exception:
177
+ continue
178
+ return hits
179
+
180
+
181
+ def kdf_scan(exe: str, db_path: str, needles: list[str], page_start: int = 0,
182
+ reserve: int = RESERVE, halg: str = 'sha512', iters=(256000, 64000),
183
+ span: int = 0x800, cap: int = 20000, workers: int = 0) -> list:
184
+ with open(db_path, 'rb') as f:
185
+ f.seek(page_start)
186
+ head = f.read(PAGE)
187
+ salt = head[:SALT]
188
+ t0 = time.time()
189
+ cands = collect_candidates(exe, needles, span, cap)
190
+ print(f'候选 {len(cands)} 个,halg={halg} iters={iters} reserve={reserve}(收集 {time.time()-t0:.1f}s)', flush=True)
191
+ if not cands:
192
+ return []
193
+ import multiprocessing as mp
194
+ n = workers or max(2, (os.cpu_count() or 4) - 2)
195
+ step = 60
196
+ tasks = [(salt, head, cands[i:i + step], halg, iters, reserve) for i in range(0, len(cands), step)]
197
+ found = []
198
+ done = 0
199
+ with mp.Pool(n) as pool:
200
+ for hits in pool.imap_unordered(_kdf_worker, tasks):
201
+ done += step
202
+ if hits:
203
+ found.extend(hits)
204
+ print('★ 命中', hits, flush=True)
205
+ pool.terminate()
206
+ break
207
+ if done % 1200 == 0:
208
+ el = time.time() - t0
209
+ print(f' …{min(done, len(cands))}/{len(cands)} {el:.0f}s 预计 {el/max(done,1)*len(cands):.0f}s', flush=True)
210
+ print(f'完成 {time.time()-t0:.0f}s,命中 {len(found)}', flush=True)
211
+ return found
212
+
213
+
214
+ def _verify_chunk(args):
215
+ salt, head, chunk, _idx, mode = args
216
+ hit = []
217
+ for c in chunk:
218
+ try:
219
+ if page1_ok(salt, c, head, mode):
220
+ hit.append(c.hex())
221
+ except Exception:
222
+ pass
223
+ return hit
224
+
225
+
226
+ def _sweep_region(args):
227
+ """在指定进程的一段内存里按步长扫密钥窗口(raw 模式,单块 AES 校验,最便宜)"""
228
+ pid, base, size, salt, head, mode, stride, reserve, keylen = args
229
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
230
+ hits = []
231
+ h = k32.OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, False, pid)
232
+ if not h:
233
+ return hits
234
+ try:
235
+ buf = ctypes.create_string_buffer(size)
236
+ read = ctypes.c_size_t(0)
237
+ if not k32.ReadProcessMemory(wt.HANDLE(h), ctypes.c_void_p(base), buf, size, ctypes.byref(read)):
238
+ return hits
239
+ data = buf.raw[:read.value]
240
+ iv_pos = PAGE - reserve
241
+ iv = head[iv_pos:iv_pos + 16]
242
+ blk = head[SALT:SALT + 16]
243
+ n = len(data)
244
+ for off in range(0, n - keylen, stride):
245
+ raw = data[off:off + keylen]
246
+ if len(set(raw)) < 8: # 低熵窗口直接跳过(省时间)
247
+ continue
248
+ key = raw
249
+ try:
250
+ d = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor().update(blk)
251
+ except Exception:
252
+ continue
253
+ if d == b'SQLite format 3\x00':
254
+ hits.append(raw.hex())
255
+ finally:
256
+ k32.CloseHandle(wt.HANDLE(h))
257
+ return hits
258
+
259
+
260
+ def sweep_memory(exe: str, db_path: str, mode: str = 'raw', stride: int = 8,
261
+ workers: int = 0, max_mb: int = 900, page_start: int = 0,
262
+ reserve: int = RESERVE, keylen: int = 32) -> list[str]:
263
+ """全内存粗扫(只适合 raw 裸密钥模式:一次 AES 单块即可判定,非常便宜)
264
+
265
+ page_start: 第 1 页在文件里的偏移(QQNT = 1024,标准 SQLite = 0)
266
+ """
267
+ with open(db_path, 'rb') as f:
268
+ f.seek(page_start)
269
+ head = f.read(PAGE)
270
+ salt = head[:SALT]
271
+ n = workers or max(2, (os.cpu_count() or 4) - 2)
272
+ jobs = []
273
+ for pid in pids_of(exe):
274
+ h = k32.OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, False, pid)
275
+ if not h:
276
+ print('打不开 pid', pid); continue
277
+ addr = 0
278
+ mbi = MEMORY_BASIC_INFORMATION()
279
+ budget = max_mb * 1024 * 1024
280
+ while budget > 0:
281
+ got = k32.VirtualQueryEx(wt.HANDLE(h), ctypes.c_void_p(addr), ctypes.byref(mbi), ctypes.sizeof(mbi))
282
+ if not got:
283
+ break
284
+ size = int(mbi.RegionSize)
285
+ if size <= 0:
286
+ break
287
+ if (mbi.State == MEM_COMMIT and mbi.Type == MEM_PRIVATE
288
+ and (mbi.Protect & PAGE_NOACCESS) == 0 and (mbi.Protect & PAGE_GUARD) == 0
289
+ and size >= 4096 and size <= 256 * 1024 * 1024):
290
+ jobs.append((pid, addr, size, salt, head, mode, stride, reserve, keylen))
291
+ budget -= size
292
+ addr += size
293
+ k32.CloseHandle(wt.HANDLE(h))
294
+ total_mb = sum(j[2] for j in jobs) / 1048576
295
+ print(f'待扫 {len(jobs)} 段 / {total_mb:.0f}MB / {n} 进程并行 / stride={stride}', flush=True)
296
+ t0 = time.time()
297
+ found = []
298
+ import multiprocessing as mp
299
+ with mp.Pool(n) as pool:
300
+ done_mb = 0
301
+ for hits, job in zip(pool.imap_unordered(_sweep_region, jobs), jobs):
302
+ done_mb += job[2] / 1048576
303
+ if hits:
304
+ found.extend(hits)
305
+ print(f'★ 命中 {hits}', flush=True)
306
+ pool.terminate()
307
+ break
308
+ el = time.time() - t0
309
+ print(f'扫完 {done_mb:.0f}MB,用时 {el:.0f}s({(done_mb/max(el,1)):.1f}MB/s),命中 {len(found)}', flush=True)
310
+ return found
311
+
312
+
313
+ def find_keys(exe: str, db_path: str, needles: list[str], span: int = 0x800,
314
+ cap: int = 40000, workers: int = 0, mode: str = 'kdf') -> list[str]:
315
+ with open(db_path, 'rb') as f:
316
+ head = f.read(PAGE)
317
+ if len(head) < PAGE:
318
+ print('db 太小,跳过'); return []
319
+ salt = head[:SALT]
320
+ t0 = time.time()
321
+ cands = collect_candidates(exe, needles, span, cap)
322
+ print(f'候选 {len(cands)} 个(已去重,耗时 {time.time()-t0:.1f}s),开始并行校验 mode={mode}…', flush=True)
323
+ if not cands:
324
+ return []
325
+ import multiprocessing as mp
326
+ n = workers or max(2, (os.cpu_count() or 4) - 2)
327
+ step = 120
328
+ tasks = [(salt, head, cands[i:i + step], i, mode) for i in range(0, len(cands), step)]
329
+ found: list[str] = []
330
+ done = 0
331
+ with mp.Pool(n) as pool:
332
+ for hit in pool.imap_unordered(_verify_chunk, tasks):
333
+ done += step
334
+ if hit:
335
+ found.extend(hit)
336
+ print(f'★ 命中 key={hit}', flush=True)
337
+ pool.terminate()
338
+ break
339
+ if done % 2400 == 0:
340
+ el = time.time() - t0
341
+ print(f' …{min(done, len(cands))}/{len(cands)} 已用 {el:.0f}s 预计总 {el/max(done,1)*len(cands):.0f}s', flush=True)
342
+ print(f'校验完成,用时 {time.time()-t0:.1f}s,命中 {len(found)} 把', flush=True)
343
+ return found
344
+
345
+
346
+ def decrypt(db_path: str, key_hex: str, out_path: str) -> dict:
347
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
348
+ raw = bytes.fromhex(key_hex)
349
+ size = os.path.getsize(db_path)
350
+ pages = (size + PAGE - 1) // PAGE
351
+ t0 = time.time()
352
+ with open(db_path, 'rb') as src, open(out_path, 'wb') as dst:
353
+ head = src.read(PAGE)
354
+ salt = head[:SALT]
355
+ key = derive(salt, raw)
356
+ for n in range(pages):
357
+ if n == 0:
358
+ page = head
359
+ off, iv_pos = SALT, PAGE - RESERVE
360
+ else:
361
+ page = src.read(PAGE)
362
+ if len(page) < PAGE:
363
+ page = page + b'\x00' * (PAGE - len(page))
364
+ off, iv_pos = 0, PAGE - RESERVE
365
+ iv = page[iv_pos:iv_pos + 16]
366
+ if len(iv) < 16:
367
+ dst.write(b'\x00' * PAGE); continue
368
+ body = page[off:iv_pos]
369
+ try:
370
+ dec = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
371
+ dst.write(dec.update(body) + dec.finalize())
372
+ dst.write(b'\x00' * (PAGE - len(body)))
373
+ except Exception:
374
+ dst.write(b'\x00' * PAGE)
375
+ return {'pages': pages, 'ms': int((time.time() - t0) * 1000), 'out': out_path}
376
+
377
+
378
+ def main():
379
+ ap = argparse.ArgumentParser()
380
+ sub = ap.add_subparsers(dest='cmd')
381
+ f = sub.add_parser('find')
382
+ f.add_argument('--exe', default='Weixin.exe')
383
+ f.add_argument('--db', required=True)
384
+ f.add_argument('--needle', action='append', default=[])
385
+ f.add_argument('--span', type=int, default=0x800)
386
+ f.add_argument('--limit', type=int, default=40000)
387
+ f.add_argument('--workers', type=int, default=0)
388
+ f.add_argument('--mode', choices=['kdf', 'raw', 'both'], default='both')
389
+ s = sub.add_parser('sweep')
390
+ s.add_argument('--exe', default='Weixin.exe')
391
+ s.add_argument('--db', required=True)
392
+ s.add_argument('--mode', choices=['raw'], default='raw')
393
+ s.add_argument('--stride', type=int, default=8)
394
+ s.add_argument('--workers', type=int, default=0)
395
+ s.add_argument('--max-mb', type=int, default=900)
396
+ s.add_argument('--page-start', type=int, default=0)
397
+ s.add_argument('--reserve', type=int, default=RESERVE)
398
+ s.add_argument('--keylen', type=int, default=32)
399
+ k = sub.add_parser('kdfscan')
400
+ k.add_argument('--exe', default='QQ.exe')
401
+ k.add_argument('--db', required=True)
402
+ k.add_argument('--needle', action='append', default=[])
403
+ k.add_argument('--page-start', type=int, default=1024)
404
+ k.add_argument('--reserve', type=int, default=48)
405
+ k.add_argument('--halg', default='sha1')
406
+ k.add_argument('--iters', default='4000,64000')
407
+ k.add_argument('--span', type=int, default=0x800)
408
+ k.add_argument('--limit', type=int, default=20000)
409
+ k.add_argument('--workers', type=int, default=0)
410
+ d = sub.add_parser('decrypt')
411
+ d.add_argument('--db', required=True)
412
+ d.add_argument('--key', required=True)
413
+ d.add_argument('--out', required=True)
414
+ a = ap.parse_args()
415
+ if a.cmd == 'find':
416
+ needles = a.needle or [os.path.basename(a.db)]
417
+ modes = ['raw', 'kdf'] if a.mode == 'both' else [a.mode]
418
+ keys = []
419
+ for m in modes:
420
+ keys += find_keys(a.exe, a.db, needles, a.span, a.limit, a.workers, m)
421
+ if keys:
422
+ break
423
+ for k in keys:
424
+ print('KEY', k)
425
+ elif a.cmd == 'kdfscan':
426
+ needles = a.needle or [os.path.basename(a.db), 'nt_msg.db', 'message_0.db']
427
+ iters = tuple(int(x) for x in a.iters.split(',') if x.strip())
428
+ hits = kdf_scan(a.exe, a.db, needles, a.page_start, a.reserve, a.halg, iters,
429
+ a.span, a.limit, a.workers)
430
+ for h in hits:
431
+ print('KEY', h)
432
+ elif a.cmd == 'sweep':
433
+ keys = sweep_memory(a.exe, a.db, a.mode, a.stride, a.workers, a.max_mb, a.page_start,
434
+ a.reserve, a.keylen)
435
+ for k in keys:
436
+ print('KEY', k)
437
+ elif a.cmd == 'decrypt':
438
+ print(decrypt(a.db, a.key, a.out))
439
+ else:
440
+ ap.print_help()
441
+
442
+
443
+ if __name__ == '__main__':
444
+ sys.exit(main())
@@ -0,0 +1,209 @@
1
+ """Generate images / video through the qqbot ComfyUI instance (port 8191).
2
+
3
+ Usage:
4
+ python comfy_gen.py image --prompt "..." --width 768 --height 768 --steps 4 --out F:/qqbot/media/samples/x.png
5
+ python comfy_gen.py video --prompt "..." --width 832 --height 480 --length 49 --steps 30 --out F:/qqbot/media/samples/x.mp4
6
+
7
+ Prints one JSON line with real measured numbers (bytes / seconds / peak VRAM).
8
+ """
9
+ import argparse
10
+ import json
11
+ import os
12
+ import subprocess
13
+ import sys
14
+ import threading
15
+ import time
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+
20
+ FFMPEG = r"F:\qqbot\bin\ffmpeg\ffmpeg.exe"
21
+ HOST = "127.0.0.1"
22
+ PORT = int(__import__("os").environ.get("COMFY_PORT", "8191"))
23
+
24
+
25
+ def base():
26
+ return "http://%s:%d" % (HOST, PORT)
27
+
28
+
29
+ def post(path, payload):
30
+ data = json.dumps(payload).encode("utf-8")
31
+ req = urllib.request.Request(base() + path, data=data,
32
+ headers={"Content-Type": "application/json"})
33
+ with urllib.request.urlopen(req, timeout=60) as r:
34
+ return json.loads(r.read().decode("utf-8"))
35
+
36
+
37
+ def get(path):
38
+ with urllib.request.urlopen(base() + path, timeout=60) as r:
39
+ return json.loads(r.read().decode("utf-8"))
40
+
41
+
42
+ class VramSampler(threading.Thread):
43
+ def __init__(self):
44
+ super().__init__(daemon=True)
45
+ self.peak = 0
46
+ self.stop_flag = False
47
+
48
+ def run(self):
49
+ while not self.stop_flag:
50
+ try:
51
+ out = subprocess.run(
52
+ ["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"],
53
+ capture_output=True, text=True, timeout=10).stdout.strip().splitlines()
54
+ if out:
55
+ self.peak = max(self.peak, int(out[0]))
56
+ except Exception:
57
+ pass
58
+ time.sleep(0.4)
59
+
60
+
61
+ # ---------------------------------------------------------------- workflows
62
+ def wf_image(prompt, neg, width, height, steps, seed, prefix):
63
+ return {
64
+ "1": {"class_type": "UnetLoaderGGUF",
65
+ "inputs": {"unet_name": "flux1-schnell-Q6_K.gguf"}},
66
+ "2": {"class_type": "DualCLIPLoaderGGUF",
67
+ "inputs": {"clip_name1": "t5-v1_1-xxl-encoder-Q5_K_M.gguf",
68
+ "clip_name2": "clip_l.safetensors", "type": "flux"}},
69
+ "3": {"class_type": "VAELoader", "inputs": {"vae_name": "ae.safetensors"}},
70
+ "4": {"class_type": "CLIPTextEncode", "inputs": {"text": prompt, "clip": ["2", 0]}},
71
+ "5": {"class_type": "CLIPTextEncode", "inputs": {"text": neg, "clip": ["2", 0]}},
72
+ "6": {"class_type": "EmptySD3LatentImage",
73
+ "inputs": {"width": width, "height": height, "batch_size": 1}},
74
+ "7": {"class_type": "KSampler",
75
+ "inputs": {"model": ["1", 0], "positive": ["4", 0], "negative": ["5", 0],
76
+ "latent_image": ["6", 0], "seed": seed, "steps": steps,
77
+ "cfg": 1.0, "sampler_name": "euler", "scheduler": "simple",
78
+ "denoise": 1.0}},
79
+ "8": {"class_type": "VAEDecode", "inputs": {"samples": ["7", 0], "vae": ["3", 0]}},
80
+ "9": {"class_type": "SaveImage", "inputs": {"images": ["8", 0], "filename_prefix": prefix}},
81
+ }
82
+
83
+
84
+ def wf_video(prompt, neg, width, height, length, steps, seed, prefix, shift=8.0, cfg=5.0,
85
+ start_image=None):
86
+ wf = {
87
+ "1": {"class_type": "UNETLoader",
88
+ "inputs": {"unet_name": "wan2.2_ti2v_5B_fp16.safetensors", "weight_dtype": "default"}},
89
+ "2": {"class_type": "CLIPLoader",
90
+ "inputs": {"clip_name": "umt5_xxl_fp16.safetensors", "type": "wan"}},
91
+ "3": {"class_type": "VAELoader", "inputs": {"vae_name": "wan2.2_vae.safetensors"}},
92
+ "4": {"class_type": "CLIPTextEncode", "inputs": {"text": prompt, "clip": ["2", 0]}},
93
+ "5": {"class_type": "CLIPTextEncode", "inputs": {"text": neg, "clip": ["2", 0]}},
94
+ "6": {"class_type": "ModelSamplingSD3", "inputs": {"model": ["1", 0], "shift": shift}},
95
+ "7": {"class_type": "Wan22ImageToVideoLatent",
96
+ "inputs": {"vae": ["3", 0], "width": width, "height": height,
97
+ "length": length, "batch_size": 1}},
98
+ "8": {"class_type": "KSampler",
99
+ "inputs": {"model": ["6", 0], "positive": ["4", 0], "negative": ["5", 0],
100
+ "latent_image": ["7", 0], "seed": seed, "steps": steps,
101
+ "cfg": cfg, "sampler_name": "uni_pc", "scheduler": "simple",
102
+ "denoise": 1.0}},
103
+ "9": {"class_type": "VAEDecode", "inputs": {"samples": ["8", 0], "vae": ["3", 0]}},
104
+ "10": {"class_type": "SaveImage", "inputs": {"images": ["9", 0], "filename_prefix": prefix}},
105
+ }
106
+ if start_image:
107
+ wf["11"] = {"class_type": "LoadImage", "inputs": {"image": start_image}}
108
+ wf["7"]["inputs"]["start_image"] = ["11", 0]
109
+ return wf
110
+
111
+
112
+ def run_workflow(wf, timeout_s=3600):
113
+ sampler = VramSampler()
114
+ sampler.start()
115
+ t0 = time.time()
116
+ try:
117
+ r = post("/prompt", {"prompt": wf, "client_id": "qqbot-gen"})
118
+ if "prompt_id" not in r:
119
+ raise RuntimeError("queue rejected: %s" % json.dumps(r, ensure_ascii=False)[:2000])
120
+ pid = r["prompt_id"]
121
+ while True:
122
+ if time.time() - t0 > timeout_s:
123
+ raise RuntimeError("timeout after %ds" % timeout_s)
124
+ h = get("/history/%s" % pid)
125
+ if pid in h:
126
+ item = h[pid]
127
+ status = item.get("status", {})
128
+ if status.get("status_str") == "error":
129
+ raise RuntimeError("execution error: %s" % json.dumps(status, ensure_ascii=False)[:3000])
130
+ elapsed = time.time() - t0
131
+ images = []
132
+ for node in item.get("outputs", {}).values():
133
+ images.extend(node.get("images", []))
134
+ return images, elapsed, sampler.peak
135
+ time.sleep(1.0)
136
+ finally:
137
+ sampler.stop_flag = True
138
+
139
+
140
+ def fetch_image(img):
141
+ q = urllib.parse.urlencode({"filename": img["filename"],
142
+ "subfolder": img.get("subfolder", ""),
143
+ "type": img.get("type", "output")})
144
+ with urllib.request.urlopen(base() + "/view?" + q, timeout=120) as r:
145
+ return r.read()
146
+
147
+
148
+ def main():
149
+ ap = argparse.ArgumentParser()
150
+ ap.add_argument("mode", choices=["image", "video"])
151
+ ap.add_argument("--prompt", required=True)
152
+ ap.add_argument("--neg", default="")
153
+ ap.add_argument("--width", type=int, default=768)
154
+ ap.add_argument("--height", type=int, default=768)
155
+ ap.add_argument("--steps", type=int, default=0)
156
+ ap.add_argument("--length", type=int, default=49)
157
+ ap.add_argument("--fps", type=int, default=16)
158
+ ap.add_argument("--seed", type=int, default=0)
159
+ ap.add_argument("--cfg", type=float, default=5.0)
160
+ ap.add_argument("--shift", type=float, default=8.0)
161
+ ap.add_argument("--start-image", default=None)
162
+ ap.add_argument("--out", required=True)
163
+ a = ap.parse_args()
164
+
165
+ seed = a.seed or int(time.time()) % 1000000
166
+ os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True)
167
+
168
+ if a.mode == "image":
169
+ steps = a.steps or 4
170
+ wf = wf_image(a.prompt, a.neg, a.width, a.height, steps, seed, "qqbot/tmp/image")
171
+ images, elapsed, vram = run_workflow(wf, timeout_s=1800)
172
+ if not images:
173
+ raise RuntimeError("no images in history")
174
+ blob = fetch_image(images[0])
175
+ with open(a.out, "wb") as f:
176
+ f.write(blob)
177
+ from PIL import Image
178
+ import io
179
+ im = Image.open(io.BytesIO(blob))
180
+ print(json.dumps({"ok": True, "out": os.path.abspath(a.out), "width": im.width,
181
+ "height": im.height, "bytes": os.path.getsize(a.out),
182
+ "seconds": round(elapsed, 2), "vram_peak_mb": vram,
183
+ "steps": steps, "seed": seed}, ensure_ascii=False))
184
+ return
185
+
186
+ steps = a.steps or 30
187
+ wf = wf_video(a.prompt, a.neg, a.width, a.height, a.length, steps, seed,
188
+ "qqbot/tmp/vidframes", a.shift, a.cfg, a.start_image)
189
+ images, elapsed, vram = run_workflow(wf, timeout_s=5400)
190
+ if not images:
191
+ raise RuntimeError("no frames in history")
192
+ frames = sorted(images, key=lambda x: x["filename"])
193
+ tmpdir = os.path.join(os.path.dirname(a.out), "_frames_%d" % int(time.time()))
194
+ os.makedirs(tmpdir, exist_ok=True)
195
+ for i, img in enumerate(frames):
196
+ with open(os.path.join(tmpdir, "f%05d.png" % i), "wb") as f:
197
+ f.write(fetch_image(img))
198
+ cmd = [FFMPEG, "-y", "-framerate", str(a.fps), "-i", os.path.join(tmpdir, "f%05d.png"),
199
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", a.out]
200
+ subprocess.run(cmd, check=True, capture_output=True, text=True)
201
+ print(json.dumps({"ok": True, "out": os.path.abspath(a.out), "frames": len(frames),
202
+ "width": a.width, "height": a.height, "fps": a.fps,
203
+ "seconds_gen": round(elapsed, 2), "vram_peak_mb": vram,
204
+ "bytes": os.path.getsize(a.out), "steps": steps, "seed": seed,
205
+ "frames_dir": tmpdir}, ensure_ascii=False))
206
+
207
+
208
+ if __name__ == "__main__":
209
+ main()