@chainlesschain/personal-data-hub 0.2.1 → 0.2.3

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 (39) hide show
  1. package/__tests__/adapters/social-toutiao-kuaishou-scaffold.test.js +58 -16
  2. package/__tests__/adapters/wechat-frida-agent.test.js +132 -1
  3. package/__tests__/integration/social-bilibili-pipeline.test.js +261 -0
  4. package/__tests__/longtail-adapters.test.js +60 -14
  5. package/__tests__/messaging-qq-snapshot.test.js +294 -0
  6. package/__tests__/shopping-pinduoduo-snapshot.test.js +302 -0
  7. package/__tests__/shopping-snapshot.test.js +438 -0
  8. package/__tests__/social-adapters.test.js +91 -17
  9. package/__tests__/social-bilibili-snapshot.test.js +278 -0
  10. package/__tests__/social-douyin-snapshot.test.js +253 -0
  11. package/__tests__/social-kuaishou-snapshot.test.js +309 -0
  12. package/__tests__/social-toutiao-snapshot.test.js +314 -0
  13. package/__tests__/social-weibo-snapshot.test.js +234 -0
  14. package/__tests__/social-xiaohongshu-snapshot.test.js +232 -0
  15. package/__tests__/travel-maps-snapshot.test.js +426 -0
  16. package/__tests__/vault-driver-error.test.js +74 -0
  17. package/__tests__/wechat-adapter.test.js +118 -0
  18. package/lib/adapters/messaging-qq/index.js +498 -92
  19. package/lib/adapters/shopping-jd/index.js +228 -25
  20. package/lib/adapters/shopping-meituan/index.js +222 -26
  21. package/lib/adapters/shopping-pinduoduo/index.js +275 -0
  22. package/lib/adapters/social-bilibili/adapter.js +500 -0
  23. package/lib/adapters/social-bilibili/index.js +21 -169
  24. package/lib/adapters/social-douyin/index.js +454 -63
  25. package/lib/adapters/social-kuaishou/index.js +379 -127
  26. package/lib/adapters/social-toutiao/index.js +400 -130
  27. package/lib/adapters/social-weibo/index.js +393 -95
  28. package/lib/adapters/social-xiaohongshu/index.js +389 -49
  29. package/lib/adapters/travel-baidu-map/index.js +286 -26
  30. package/lib/adapters/travel-tencent-map/index.js +414 -0
  31. package/lib/adapters/wechat/content-parser.js +11 -2
  32. package/lib/adapters/wechat/db-reader.js +88 -10
  33. package/lib/adapters/wechat/frida-agent/loader.js +7 -0
  34. package/lib/adapters/wechat/frida-agent/wechat-key-hook.js +140 -18
  35. package/lib/adapters/wechat/key-providers/frida-key-provider.js +8 -0
  36. package/lib/adapters/wechat/normalize.js +12 -3
  37. package/lib/index.js +5 -1
  38. package/lib/vault.js +60 -8
  39. package/package.json +2 -1
@@ -0,0 +1,426 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect, beforeEach } from "vitest";
4
+
5
+ const fs = require("node:fs");
6
+ const path = require("node:path");
7
+ const os = require("node:os");
8
+
9
+ const {
10
+ BaiduMapAdapter,
11
+ SNAPSHOT_SCHEMA_VERSION: BAIDU_VERSION,
12
+ } = require("../lib/adapters/travel-baidu-map");
13
+ const {
14
+ TencentMapAdapter,
15
+ SNAPSHOT_SCHEMA_VERSION: TENCENT_VERSION,
16
+ } = require("../lib/adapters/travel-tencent-map");
17
+ const { validateBatch } = require("../lib/batch");
18
+
19
+ // §2.5b 地图三联 v0.2 — snapshot-mode tests, mirror of social-weibo-snapshot
20
+ // & social-bilibili-snapshot patterns.
21
+ //
22
+ // Snapshot mode is in-APK Android cc reading JSON written by the
23
+ // {Baidu,Tencent}MapLocalCollector (WebView cookie scrape). Sqlite/device-pull
24
+ // tests remain in travel-adapters.test.js. Three kinds: favourite / search /
25
+ // route — all 3 reuse normalizeTravelRecord via on-the-fly TravelRecord build.
26
+
27
+ function writeSnapshot(dir, fileName, snapshot) {
28
+ const p = path.join(dir, fileName);
29
+ fs.writeFileSync(p, JSON.stringify(snapshot), "utf-8");
30
+ return p;
31
+ }
32
+
33
+ describe("BaiduMapAdapter snapshot mode", () => {
34
+ let tmpDir;
35
+ beforeEach(() => {
36
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "baidu-map-snap-"));
37
+ });
38
+
39
+ it("exports SNAPSHOT_SCHEMA_VERSION = 1", () => {
40
+ expect(BAIDU_VERSION).toBe(1);
41
+ });
42
+
43
+ it("authenticate(inputPath) ok when readable + mode=snapshot-file", async () => {
44
+ const p = writeSnapshot(tmpDir, "travel-baidu-map.json", {
45
+ schemaVersion: 1,
46
+ snapshottedAt: Date.now(),
47
+ events: [],
48
+ });
49
+ const a = new BaiduMapAdapter();
50
+ const res = await a.authenticate({ inputPath: p });
51
+ expect(res.ok).toBe(true);
52
+ expect(res.mode).toBe("snapshot-file");
53
+ });
54
+
55
+ it("authenticate(inputPath) fails when path unreadable", async () => {
56
+ const a = new BaiduMapAdapter();
57
+ const res = await a.authenticate({ inputPath: path.join(tmpDir, "missing.json") });
58
+ expect(res.ok).toBe(false);
59
+ expect(res.reason).toBe("INPUT_PATH_UNREADABLE");
60
+ });
61
+
62
+ it("authenticate() with neither inputPath nor dbPath returns NO_INPUT", async () => {
63
+ const a = new BaiduMapAdapter();
64
+ const res = await a.authenticate({});
65
+ expect(res.ok).toBe(false);
66
+ expect(res.reason).toBe("NO_INPUT");
67
+ });
68
+
69
+ it("authenticate(dbPath) without account.deviceId returns NO_ACCOUNT_DEVICE_ID", async () => {
70
+ const a = new BaiduMapAdapter({ dbPath: path.join(tmpDir, "fake.db") });
71
+ const res = await a.authenticate({});
72
+ expect(res.ok).toBe(false);
73
+ expect(res.reason).toBe("NO_ACCOUNT_DEVICE_ID");
74
+ });
75
+
76
+ it("rejects schemaVersion mismatch", async () => {
77
+ const p = writeSnapshot(tmpDir, "travel-baidu-map.json", {
78
+ schemaVersion: 99,
79
+ snapshottedAt: Date.now(),
80
+ events: [],
81
+ });
82
+ const a = new BaiduMapAdapter();
83
+ let threw = null;
84
+ try {
85
+ for await (const _r of a.sync({ inputPath: p })) { /* drain */ }
86
+ } catch (err) {
87
+ threw = err;
88
+ }
89
+ expect(threw).toBeTruthy();
90
+ expect(String(threw.message)).toMatch(/schemaVersion mismatch/);
91
+ });
92
+
93
+ it("empty events array yields nothing (no crash)", async () => {
94
+ const p = writeSnapshot(tmpDir, "travel-baidu-map.json", {
95
+ schemaVersion: 1,
96
+ snapshottedAt: Date.now(),
97
+ events: [],
98
+ });
99
+ const a = new BaiduMapAdapter();
100
+ const raws = [];
101
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
102
+ expect(raws.length).toBe(0);
103
+ });
104
+
105
+ it("favourite + search + route round-trip normalize cleanly", async () => {
106
+ const now = Date.now();
107
+ const p = writeSnapshot(tmpDir, "travel-baidu-map.json", {
108
+ schemaVersion: 1,
109
+ snapshottedAt: now,
110
+ vendor: "baidu-map",
111
+ account: { uid: "12345", displayName: "alice" },
112
+ events: [
113
+ {
114
+ kind: "favourite",
115
+ id: "fav-R1",
116
+ capturedAt: now - 1000,
117
+ name: "公司",
118
+ address: "厦门市象屿路 93 号",
119
+ lat: 24.4781,
120
+ lng: 118.0894,
121
+ category: "company",
122
+ },
123
+ {
124
+ kind: "search",
125
+ id: "search-S1",
126
+ capturedAt: now - 2000,
127
+ query: "鼓浪屿",
128
+ city: "厦门",
129
+ },
130
+ {
131
+ kind: "route",
132
+ id: "route-RT1",
133
+ capturedAt: now - 3000,
134
+ from: { name: "厦门北站", lat: 24.6, lng: 118.0 },
135
+ to: { name: "厦门大学", lat: 24.43, lng: 118.09 },
136
+ mode: "drive",
137
+ },
138
+ ],
139
+ });
140
+ const a = new BaiduMapAdapter();
141
+ const raws = [];
142
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
143
+ expect(raws.length).toBe(3);
144
+
145
+ const kinds = raws.map((r) => r.kind);
146
+ expect(kinds).toEqual(["favourite", "search", "route"]);
147
+
148
+ // Each originalId namespaced under baidu-map:<kind>:<id>
149
+ expect(raws[0].originalId).toMatch(/^baidu-map:favourite:/);
150
+ expect(raws[1].originalId).toMatch(/^baidu-map:search:/);
151
+ expect(raws[2].originalId).toMatch(/^baidu-map:route:/);
152
+
153
+ // Normalize each + validate
154
+ for (const raw of raws) {
155
+ const batch = a.normalize(raw);
156
+ expect(validateBatch(batch).valid).toBe(true);
157
+ }
158
+
159
+ // Favourite: visit-type trip event + 1 place (to) + carrier merchant
160
+ const favBatch = a.normalize(raws[0]);
161
+ expect(favBatch.events.length).toBe(1);
162
+ expect(favBatch.events[0].subtype).toBe("trip");
163
+ // The to-place name flows through as the trip's destination
164
+ // (Place uses singular `name`; aliases array for redundant labels)
165
+ const favToPlace = favBatch.places.find(
166
+ (pl) => pl.name === "公司" || (pl.aliases && pl.aliases.includes("公司")),
167
+ );
168
+ expect(favToPlace).toBeTruthy();
169
+
170
+ // Route: from/to places (2) + carrier merchant
171
+ const routeBatch = a.normalize(raws[2]);
172
+ expect(routeBatch.places.length).toBeGreaterThanOrEqual(2);
173
+
174
+ // Carrier always "百度地图"
175
+ const allBatches = raws.map((r) => a.normalize(r));
176
+ const carriers = allBatches.flatMap((b) =>
177
+ b.persons.filter((p) => p.names.includes("百度地图")),
178
+ );
179
+ expect(carriers.length).toBe(3);
180
+ });
181
+
182
+ it("respects per-kind include opt-out", async () => {
183
+ const now = Date.now();
184
+ const p = writeSnapshot(tmpDir, "travel-baidu-map.json", {
185
+ schemaVersion: 1,
186
+ snapshottedAt: now,
187
+ events: [
188
+ { kind: "favourite", id: "f1", capturedAt: now, name: "家", lat: 24, lng: 118 },
189
+ { kind: "search", id: "s1", capturedAt: now, query: "餐厅" },
190
+ { kind: "route", id: "r1", capturedAt: now, from: { name: "A" }, to: { name: "B" }, mode: "walk" },
191
+ ],
192
+ });
193
+ const a = new BaiduMapAdapter();
194
+ const raws = [];
195
+ for await (const r of a.sync({ inputPath: p, include: { search: false } })) {
196
+ raws.push(r);
197
+ }
198
+ const kinds = raws.map((r) => r.kind);
199
+ expect(kinds).toEqual(["favourite", "route"]);
200
+ });
201
+
202
+ it("respects opts.limit", async () => {
203
+ const now = Date.now();
204
+ const events = Array.from({ length: 5 }, (_, i) => ({
205
+ kind: "favourite",
206
+ id: `f${i}`,
207
+ capturedAt: now - i * 100,
208
+ name: `place-${i}`,
209
+ lat: 24,
210
+ lng: 118,
211
+ }));
212
+ const p = writeSnapshot(tmpDir, "travel-baidu-map.json", {
213
+ schemaVersion: 1,
214
+ snapshottedAt: now,
215
+ events,
216
+ });
217
+ const a = new BaiduMapAdapter();
218
+ const raws = [];
219
+ for await (const r of a.sync({ inputPath: p, limit: 2 })) raws.push(r);
220
+ expect(raws.length).toBe(2);
221
+ });
222
+
223
+ it("filters out unknown kinds (forward compat)", async () => {
224
+ const now = Date.now();
225
+ const p = writeSnapshot(tmpDir, "travel-baidu-map.json", {
226
+ schemaVersion: 1,
227
+ snapshottedAt: now,
228
+ events: [
229
+ { kind: "favourite", id: "f1", capturedAt: now, name: "ok", lat: 1, lng: 2 },
230
+ { kind: "future-kind", id: "x", capturedAt: now },
231
+ { kind: "trip-summary", id: "ts", capturedAt: now }, // hypothetical future
232
+ ],
233
+ });
234
+ const a = new BaiduMapAdapter();
235
+ const raws = [];
236
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
237
+ expect(raws.length).toBe(1);
238
+ expect(raws[0].kind).toBe("favourite");
239
+ });
240
+
241
+ it("snapshottedAt fallback when event capturedAt missing", async () => {
242
+ const ts = 1700000000000;
243
+ const p = writeSnapshot(tmpDir, "travel-baidu-map.json", {
244
+ schemaVersion: 1,
245
+ snapshottedAt: ts,
246
+ events: [
247
+ { kind: "favourite", id: "f1", name: "no time", lat: 1, lng: 2 },
248
+ ],
249
+ });
250
+ const a = new BaiduMapAdapter();
251
+ const raws = [];
252
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
253
+ expect(raws[0].capturedAt).toBe(ts);
254
+ });
255
+
256
+ it("sync() without inputPath OR dbPath throws", async () => {
257
+ const a = new BaiduMapAdapter();
258
+ let threw = null;
259
+ try {
260
+ for await (const _r of a.sync({})) { /* drain */ }
261
+ } catch (err) {
262
+ threw = err;
263
+ }
264
+ expect(threw).toBeTruthy();
265
+ expect(String(threw.message)).toMatch(/needs opts.inputPath/);
266
+ });
267
+
268
+ it("snapshot mode does NOT require account.deviceId at construction", () => {
269
+ // The whole point of snapshot mode: stateless adapter, account from snapshot
270
+ expect(() => new BaiduMapAdapter()).not.toThrow();
271
+ expect(() => new BaiduMapAdapter({})).not.toThrow();
272
+ });
273
+ });
274
+
275
+ describe("TencentMapAdapter snapshot mode", () => {
276
+ let tmpDir;
277
+ beforeEach(() => {
278
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "tencent-map-snap-"));
279
+ });
280
+
281
+ it("exports SNAPSHOT_SCHEMA_VERSION = 1", () => {
282
+ expect(TENCENT_VERSION).toBe(1);
283
+ });
284
+
285
+ it("constructor allows missing account (stateless snapshot mode)", () => {
286
+ expect(() => new TencentMapAdapter()).not.toThrow();
287
+ expect(() => new TencentMapAdapter({})).not.toThrow();
288
+ });
289
+
290
+ it("authenticate(inputPath) ok", async () => {
291
+ const p = writeSnapshot(tmpDir, "travel-tencent-map.json", {
292
+ schemaVersion: 1,
293
+ snapshottedAt: Date.now(),
294
+ events: [],
295
+ });
296
+ const a = new TencentMapAdapter();
297
+ const res = await a.authenticate({ inputPath: p });
298
+ expect(res.ok).toBe(true);
299
+ expect(res.mode).toBe("snapshot-file");
300
+ });
301
+
302
+ it("authenticate(dbPath) without deviceId returns NO_ACCOUNT_DEVICE_ID", async () => {
303
+ const a = new TencentMapAdapter({ dbPath: "/tmp/fake.db" });
304
+ const res = await a.authenticate({});
305
+ expect(res.ok).toBe(false);
306
+ expect(res.reason).toBe("NO_ACCOUNT_DEVICE_ID");
307
+ });
308
+
309
+ it("rejects schemaVersion mismatch", async () => {
310
+ const p = writeSnapshot(tmpDir, "travel-tencent-map.json", {
311
+ schemaVersion: 99,
312
+ snapshottedAt: Date.now(),
313
+ events: [],
314
+ });
315
+ const a = new TencentMapAdapter();
316
+ let threw = null;
317
+ try {
318
+ for await (const _r of a.sync({ inputPath: p })) { /* drain */ }
319
+ } catch (err) {
320
+ threw = err;
321
+ }
322
+ expect(threw).toBeTruthy();
323
+ expect(String(threw.message)).toMatch(/schemaVersion mismatch/);
324
+ });
325
+
326
+ it("favourite + route normalize cleanly with carrier=腾讯地图", async () => {
327
+ const now = Date.now();
328
+ const p = writeSnapshot(tmpDir, "travel-tencent-map.json", {
329
+ schemaVersion: 1,
330
+ snapshottedAt: now,
331
+ vendor: "tencent-map",
332
+ account: { uid: "qq-12345", displayName: "alice" },
333
+ events: [
334
+ {
335
+ kind: "favourite",
336
+ id: "fav-T1",
337
+ capturedAt: now - 1000,
338
+ name: "公司",
339
+ address: "广州市天河区珠江新城",
340
+ lat: 23.12,
341
+ lng: 113.32,
342
+ category: "company",
343
+ },
344
+ {
345
+ kind: "route",
346
+ id: "route-T1",
347
+ capturedAt: now - 2000,
348
+ from: { name: "广州南站", lat: 22.99, lng: 113.27 },
349
+ to: { name: "天河客运站", lat: 23.16, lng: 113.36 },
350
+ mode: "transit",
351
+ },
352
+ ],
353
+ });
354
+ const a = new TencentMapAdapter();
355
+ const raws = [];
356
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
357
+ expect(raws.length).toBe(2);
358
+
359
+ expect(raws[0].originalId).toMatch(/^tencent-map:favourite:/);
360
+ expect(raws[1].originalId).toMatch(/^tencent-map:route:/);
361
+
362
+ for (const raw of raws) {
363
+ const batch = a.normalize(raw);
364
+ expect(validateBatch(batch).valid).toBe(true);
365
+ }
366
+
367
+ // Carrier must be 腾讯地图 (not 百度地图 or 高德地图 — paranoid catch
368
+ // copy-paste regression)
369
+ const allBatches = raws.map((r) => a.normalize(r));
370
+ for (const b of allBatches) {
371
+ const tencentCarrier = b.persons.find((p) => p.names.includes("腾讯地图"));
372
+ expect(tencentCarrier).toBeTruthy();
373
+ expect(b.persons.find((p) => p.names.includes("百度地图"))).toBeFalsy();
374
+ expect(b.persons.find((p) => p.names.includes("高德地图"))).toBeFalsy();
375
+ }
376
+
377
+ // Route mode "transit" maps to bus
378
+ const routeBatch = a.normalize(raws[1]);
379
+ const tripEvent = routeBatch.events[0];
380
+ expect(tripEvent.extra.vehicleType).toBe("bus");
381
+ });
382
+
383
+ it("empty events array yields nothing", async () => {
384
+ const p = writeSnapshot(tmpDir, "travel-tencent-map.json", {
385
+ schemaVersion: 1,
386
+ snapshottedAt: Date.now(),
387
+ events: [],
388
+ });
389
+ const a = new TencentMapAdapter();
390
+ const raws = [];
391
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
392
+ expect(raws.length).toBe(0);
393
+ });
394
+
395
+ it("filters unknown kinds", async () => {
396
+ const now = Date.now();
397
+ const p = writeSnapshot(tmpDir, "travel-tencent-map.json", {
398
+ schemaVersion: 1,
399
+ snapshottedAt: now,
400
+ events: [
401
+ { kind: "favourite", id: "f1", capturedAt: now, name: "ok", lat: 1, lng: 2 },
402
+ { kind: "speculative-future", id: "x", capturedAt: now },
403
+ ],
404
+ });
405
+ const a = new TencentMapAdapter();
406
+ const raws = [];
407
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
408
+ expect(raws.length).toBe(1);
409
+ expect(raws[0].kind).toBe("favourite");
410
+ });
411
+
412
+ it("snapshottedAt fallback when event capturedAt missing", async () => {
413
+ const ts = 1700000000000;
414
+ const p = writeSnapshot(tmpDir, "travel-tencent-map.json", {
415
+ schemaVersion: 1,
416
+ snapshottedAt: ts,
417
+ events: [
418
+ { kind: "favourite", id: "f1", name: "no time", lat: 1, lng: 2 },
419
+ ],
420
+ });
421
+ const a = new TencentMapAdapter();
422
+ const raws = [];
423
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
424
+ expect(raws[0].capturedAt).toBe(ts);
425
+ });
426
+ });
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Unit tests for formatDriverLoadError — the pure error-translation helper
3
+ * sitting in front of `require("better-sqlite3-multiple-ciphers")`.
4
+ *
5
+ * Why this matters: bs3mc upstream only ships prebuilds for Node LTS ABIs
6
+ * (108/115/127). Running cc / PDH on Node 23/24/25 throws a cryptic
7
+ * "NODE_MODULE_VERSION X / requires NODE_MODULE_VERSION Y" stack that
8
+ * buries the real fix (use Node 22 LTS). This helper translates that into
9
+ * actionable Chinese guidance. See memory `node_23_native_dep_trap.md`.
10
+ */
11
+
12
+ "use strict";
13
+
14
+ import { describe, it, expect } from "vitest";
15
+
16
+ const {
17
+ _internal: { formatDriverLoadError },
18
+ } = require("../lib/vault");
19
+
20
+ describe("formatDriverLoadError", () => {
21
+ it("detects ABI mismatch and emits actionable Chinese guidance", () => {
22
+ const original = new Error(
23
+ "The module '\\\\?\\C:\\code\\chainlesschain\\node_modules\\better-sqlite3-multiple-ciphers\\build\\Release\\better_sqlite3.node'\n" +
24
+ "was compiled against a different Node.js version using\n" +
25
+ "NODE_MODULE_VERSION 140. This version of Node.js requires\n" +
26
+ "NODE_MODULE_VERSION 127. Please try re-compiling or re-installing\n" +
27
+ "the module (for instance, using `npm rebuild` or `npm install`).",
28
+ );
29
+ const wrapped = formatDriverLoadError(original, "v24.0.1");
30
+ expect(wrapped.code).toBe("BS3MC_ABI_MISMATCH");
31
+ expect(wrapped.cause).toBe(original);
32
+ expect(wrapped.message).toMatch(/Node v24\.0\.1 has ABI 127/);
33
+ expect(wrapped.message).toMatch(/bs3mc prebuild is ABI 140/);
34
+ expect(wrapped.message).toMatch(/切 Node 22 LTS/);
35
+ expect(wrapped.message).toMatch(/nvm install 22\.12\.0/);
36
+ expect(wrapped.message).toMatch(/npm rebuild better-sqlite3-multiple-ciphers/);
37
+ });
38
+
39
+ it("falls back to generic message when error is not ABI-related", () => {
40
+ const original = new Error("ENOENT: no such file or directory");
41
+ const wrapped = formatDriverLoadError(original, "v22.12.0");
42
+ expect(wrapped.code).toBeUndefined();
43
+ expect(wrapped.cause).toBe(original);
44
+ expect(wrapped.message).toMatch(/Failed to load better-sqlite3-multiple-ciphers/);
45
+ expect(wrapped.message).toMatch(/ENOENT: no such file or directory/);
46
+ });
47
+
48
+ it("handles non-Error throw values (string / null)", () => {
49
+ const wrapped1 = formatDriverLoadError("plain string", "v22.12.0");
50
+ expect(wrapped1.message).toMatch(/Original error: plain string/);
51
+
52
+ const wrapped2 = formatDriverLoadError(null, "v22.12.0");
53
+ expect(wrapped2.message).toMatch(/Original error: null/);
54
+ });
55
+
56
+ it("uses process.versions.node when nodeVer omitted", () => {
57
+ const original = new Error(
58
+ "NODE_MODULE_VERSION 200. requires NODE_MODULE_VERSION 127.",
59
+ );
60
+ const wrapped = formatDriverLoadError(original);
61
+ expect(wrapped.code).toBe("BS3MC_ABI_MISMATCH");
62
+ expect(wrapped.message).toContain(process.versions.node);
63
+ });
64
+
65
+ it("preserves ABI numbers from the original error message in the rewritten body", () => {
66
+ const original = new Error(
67
+ "NODE_MODULE_VERSION 137. requires NODE_MODULE_VERSION 131.",
68
+ );
69
+ const wrapped = formatDriverLoadError(original, "v23.7.0");
70
+ expect(wrapped.message).toContain("ABI 131");
71
+ expect(wrapped.message).toContain("ABI 137");
72
+ expect(wrapped.message).toContain("v23.7.0");
73
+ });
74
+ });
@@ -331,6 +331,29 @@ describe("normalizeWeChatContact", () => {
331
331
  const b = normalizeWeChatContact({});
332
332
  expect(b.persons).toHaveLength(0);
333
333
  });
334
+
335
+ // sjqz parity audit follow-up (post-Phase 12.6.10) — classify
336
+ // 公众号 / Official Accounts (gh_*) as merchant subtype so the Ask
337
+ // flow / EntityResolver can filter them out of human contacts.
338
+ it("gh_* username → subtype merchant (公众号 / Official Account)", () => {
339
+ const b = normalizeWeChatContact({
340
+ username: "gh_abc123def",
341
+ nickname: "某品牌官方",
342
+ type: 3,
343
+ });
344
+ expect(b.persons).toHaveLength(1);
345
+ expect(b.persons[0].subtype).toBe("merchant");
346
+ expect(b.persons[0].identifiers.wechatId).toBe("gh_abc123def");
347
+ });
348
+
349
+ it("regular wxid_* → subtype contact (default)", () => {
350
+ const b = normalizeWeChatContact({
351
+ username: "wxid_realfriend",
352
+ nickname: "好友",
353
+ type: 1,
354
+ });
355
+ expect(b.persons[0].subtype).toBe("contact");
356
+ });
334
357
  });
335
358
 
336
359
  // ─── WechatAdapter contract + sync flow ──────────────────────────────────
@@ -441,6 +464,101 @@ describe("WechatAdapter.sync with mocked DB reader", () => {
441
464
  }
442
465
  });
443
466
 
467
+ // sjqz parity audit follow-up — fetchContacts must exclude
468
+ // @stranger and fake_* by default (vault pollution prevention).
469
+ it("fetchContacts excludes @stranger and fake_* by default", async () => {
470
+ // Pure DI smoke — capture the SQL passed to .prepare() to verify the
471
+ // junk filter is in the query. We mock just enough of better-sqlite3's
472
+ // shape: db.prepare(sql) → { all(limit) → rows }, exec, pragma.
473
+ const seenSql = [];
474
+ const fakeDriver = function Database(_path, _opts) {
475
+ return {
476
+ pragma: () => undefined,
477
+ exec: () => undefined,
478
+ prepare(sql) {
479
+ seenSql.push(sql);
480
+ return {
481
+ all: () => {
482
+ if (sql.startsWith("PRAGMA table_info")) {
483
+ return [
484
+ { name: "username" },
485
+ { name: "alias" },
486
+ { name: "nickname" },
487
+ { name: "conRemark" },
488
+ { name: "type" },
489
+ ];
490
+ }
491
+ if (sql.startsWith("SELECT count")) return [{ n: 5 }];
492
+ if (sql.includes("FROM rcontact")) return [];
493
+ return [];
494
+ },
495
+ get: () => ({ n: 5 }),
496
+ };
497
+ },
498
+ close: () => undefined,
499
+ };
500
+ };
501
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "wechat-junkfilt-"));
502
+ const dbPath = path.join(dir, "EnMicroMsg.db");
503
+ fs.writeFileSync(dbPath, "fake");
504
+ try {
505
+ const reader = new WeChatDBReader({
506
+ dbPath,
507
+ keyProvider: { getKey: async () => "0".repeat(64) },
508
+ driver: fakeDriver,
509
+ });
510
+ await reader.open();
511
+ reader.fetchContacts({ limit: 100 });
512
+ const contactsSql = seenSql.find((s) => s.includes("FROM rcontact"));
513
+ expect(contactsSql).toBeDefined();
514
+ expect(contactsSql).toMatch(/NOT LIKE '%@stranger'/);
515
+ expect(contactsSql).toMatch(/NOT LIKE 'fake_%'/);
516
+ } finally {
517
+ fs.rmSync(dir, { recursive: true, force: true });
518
+ }
519
+ });
520
+
521
+ it("fetchContacts with includeJunk:true drops the filter (forensic mode)", async () => {
522
+ const seenSql = [];
523
+ const fakeDriver = function Database() {
524
+ return {
525
+ pragma: () => undefined,
526
+ exec: () => undefined,
527
+ prepare(sql) {
528
+ seenSql.push(sql);
529
+ return {
530
+ all: () => {
531
+ if (sql.startsWith("PRAGMA table_info")) {
532
+ return ["username", "alias", "nickname", "conRemark", "type"].map((name) => ({ name }));
533
+ }
534
+ if (sql.startsWith("SELECT count")) return [{ n: 5 }];
535
+ return [];
536
+ },
537
+ get: () => ({ n: 5 }),
538
+ };
539
+ },
540
+ close: () => undefined,
541
+ };
542
+ };
543
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "wechat-incljunk-"));
544
+ const dbPath = path.join(dir, "EnMicroMsg.db");
545
+ fs.writeFileSync(dbPath, "fake");
546
+ try {
547
+ const reader = new WeChatDBReader({
548
+ dbPath,
549
+ keyProvider: { getKey: async () => "0".repeat(64) },
550
+ driver: fakeDriver,
551
+ });
552
+ await reader.open();
553
+ reader.fetchContacts({ limit: 100, includeJunk: true });
554
+ const contactsSql = seenSql.find((s) => s.includes("FROM rcontact"));
555
+ expect(contactsSql).toBeDefined();
556
+ expect(contactsSql).not.toMatch(/NOT LIKE/);
557
+ } finally {
558
+ fs.rmSync(dir, { recursive: true, force: true });
559
+ }
560
+ });
561
+
444
562
  it("idle no-op when DB path missing", async () => {
445
563
  const a = new WechatAdapter({
446
564
  account: { uin: "self123" },