@chainlesschain/personal-data-hub 0.2.0 → 0.2.1

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 (50) hide show
  1. package/__tests__/adapters/ai-chat-cookie-capture-spec.test.js +211 -0
  2. package/__tests__/adapters/ai-chat-health-checker.test.js +262 -0
  3. package/__tests__/adapters/ai-chat-history.test.js +8 -7
  4. package/__tests__/adapters/ai-chat-vendors.test.js +149 -8
  5. package/__tests__/adapters/social-toutiao-kuaishou-scaffold.test.js +269 -0
  6. package/__tests__/adapters/system-data-android-ingest.test.js +144 -0
  7. package/__tests__/adapters/system-data-android.test.js +387 -0
  8. package/__tests__/adapters/wechat-bootstrap.test.js +240 -0
  9. package/__tests__/adapters/wechat-env-probe.test.js +162 -0
  10. package/__tests__/adapters/wechat-frida-agent.test.js +191 -0
  11. package/__tests__/adapters/wechat-frida-integration.test.js +149 -0
  12. package/__tests__/adapters/wechat-frida-key-provider.test.js +188 -0
  13. package/__tests__/adapters/wechat-md5-key-provider.test.js +101 -0
  14. package/__tests__/analysis-skills.test.js +147 -0
  15. package/__tests__/analysis.test.js +329 -1
  16. package/__tests__/e2e/ai-chat-cross-source-journey.test.js +213 -0
  17. package/__tests__/e2e/full-user-journey.test.js +188 -0
  18. package/__tests__/integration/ai-chat-history-registry.test.js +228 -0
  19. package/__tests__/integration/aichat-wizard-end-to-end.test.js +282 -0
  20. package/__tests__/integration/cross-adapter-pipelines.test.js +396 -0
  21. package/__tests__/integration/wechat-bootstrap-end-to-end.test.js +390 -0
  22. package/__tests__/registry.test.js +4 -2
  23. package/lib/adapters/ai-chat-history/ai-chat-adapter.js +55 -16
  24. package/lib/adapters/ai-chat-history/cookie-capture-spec.js +331 -0
  25. package/lib/adapters/ai-chat-history/health-checker.js +210 -0
  26. package/lib/adapters/ai-chat-history/schema-map.js +42 -5
  27. package/lib/adapters/ai-chat-history/vendor-spec.js +1 -0
  28. package/lib/adapters/ai-chat-history/vendors/doubao.js +255 -0
  29. package/lib/adapters/ai-chat-history/wizard-controller.js +473 -0
  30. package/lib/adapters/alipay-bill/alipay-bill-adapter.js +4 -0
  31. package/lib/adapters/social-kuaishou/index.js +237 -0
  32. package/lib/adapters/social-toutiao/index.js +236 -0
  33. package/lib/adapters/system-data-android/adapter.js +348 -0
  34. package/lib/adapters/system-data-android/index.js +76 -0
  35. package/lib/adapters/wechat/bootstrap.js +146 -0
  36. package/lib/adapters/wechat/env-probe.js +218 -0
  37. package/lib/adapters/wechat/frida-agent/loader.js +67 -0
  38. package/lib/adapters/wechat/frida-agent/wechat-key-hook.js +126 -0
  39. package/lib/adapters/wechat/index.js +9 -0
  40. package/lib/adapters/wechat/key-providers/frida-key-provider.js +244 -0
  41. package/lib/adapters/wechat/key-providers/index.js +22 -0
  42. package/lib/adapters/wechat/key-providers/key-provider-base.js +44 -0
  43. package/lib/adapters/wechat/key-providers/md5-key-provider.js +81 -0
  44. package/lib/analysis-skills/spending.js +4 -1
  45. package/lib/analysis.js +191 -2
  46. package/lib/index.js +16 -0
  47. package/lib/prompt-builder.js +11 -1
  48. package/lib/query-parser.js +7 -1
  49. package/lib/vault.js +77 -0
  50. package/package.json +8 -1
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect } from "vitest";
4
+
5
+ const { probe, decide } = require("../../lib/adapters/wechat/env-probe");
6
+
7
+ /**
8
+ * Build a scripted exec that returns a canned response per matching
9
+ * substring. Falls back to `{ code: 1, stdout: "", stderr: "" }`.
10
+ */
11
+ function makeExec(table) {
12
+ return async (cmd) => {
13
+ for (const [needle, response] of table) {
14
+ if (cmd.includes(needle)) return { code: 0, stdout: response, stderr: "" };
15
+ }
16
+ return { code: 1, stdout: "", stderr: "" };
17
+ };
18
+ }
19
+
20
+ const ADB_DEVICES_OK = "List of devices attached\nABC123XYZ\tdevice\n\n";
21
+ const WECHAT_7 = " versionName=7.0.22\n";
22
+ const WECHAT_8 = " versionName=8.0.50\n";
23
+ const NETSTAT_FRIDA = "tcp 0 0 0.0.0.0:27042 0.0.0.0:* LISTEN\n";
24
+
25
+ describe("decide() — pure decision logic", () => {
26
+ it("device unreachable → unsupported", () => {
27
+ const r = decide({
28
+ device: { reachable: false }, root: {}, frida: {}, wechat: {},
29
+ });
30
+ expect(r.suggestedKeyProvider).toBe("unsupported");
31
+ });
32
+
33
+ it("WeChat 7.x → md5 regardless of root/frida", () => {
34
+ const r = decide({
35
+ device: { reachable: true },
36
+ root: { detected: false },
37
+ frida: { serverRunning: false },
38
+ wechat: { installed: true, versionName: "7.0.22", majorVersion: 7 },
39
+ });
40
+ expect(r.suggestedKeyProvider).toBe("md5");
41
+ });
42
+
43
+ it("WeChat 8.x + root + frida → frida", () => {
44
+ const r = decide({
45
+ device: { reachable: true },
46
+ root: { detected: true, magiskInstalled: true },
47
+ frida: { serverRunning: true, port: 27042 },
48
+ wechat: { installed: true, versionName: "8.0.50", majorVersion: 8 },
49
+ });
50
+ expect(r.suggestedKeyProvider).toBe("frida");
51
+ });
52
+
53
+ it("WeChat 8.x + no root → unsupported", () => {
54
+ const r = decide({
55
+ device: { reachable: true },
56
+ root: { detected: false },
57
+ frida: { serverRunning: true },
58
+ wechat: { installed: true, versionName: "8.0.50", majorVersion: 8 },
59
+ });
60
+ expect(r.suggestedKeyProvider).toBe("unsupported");
61
+ expect(r.reasons.join(" ")).toMatch(/root/);
62
+ });
63
+
64
+ it("WeChat 8.x + root + no frida-server → unsupported", () => {
65
+ const r = decide({
66
+ device: { reachable: true },
67
+ root: { detected: true },
68
+ frida: { serverRunning: false },
69
+ wechat: { installed: true, versionName: "8.0.50", majorVersion: 8 },
70
+ });
71
+ expect(r.suggestedKeyProvider).toBe("unsupported");
72
+ expect(r.reasons.join(" ")).toMatch(/frida-server/i);
73
+ });
74
+
75
+ it("WeChat not installed → unsupported", () => {
76
+ const r = decide({
77
+ device: { reachable: true },
78
+ root: { detected: true },
79
+ frida: { serverRunning: true },
80
+ wechat: { installed: false },
81
+ });
82
+ expect(r.suggestedKeyProvider).toBe("unsupported");
83
+ expect(r.reasons.join(" ")).toMatch(/not installed/);
84
+ });
85
+
86
+ it("WeChat 8.x + root + frida + no Magisk → frida (warn reason)", () => {
87
+ const r = decide({
88
+ device: { reachable: true },
89
+ root: { detected: true, magiskInstalled: false },
90
+ frida: { serverRunning: true, port: 27042 },
91
+ wechat: { installed: true, versionName: "8.0.50", majorVersion: 8 },
92
+ });
93
+ expect(r.suggestedKeyProvider).toBe("frida");
94
+ expect(r.reasons.join(" ")).toMatch(/Magisk not detected/);
95
+ });
96
+ });
97
+
98
+ describe("probe() — end-to-end with mock exec", () => {
99
+ it("returns unsupported when no device", async () => {
100
+ const exec = makeExec([["adb devices", "List of devices attached\n\n"]]);
101
+ const r = await probe({ exec });
102
+ expect(r.ok).toBe(false);
103
+ expect(r.suggestedKeyProvider).toBe("unsupported");
104
+ expect(r.device.reachable).toBe(false);
105
+ });
106
+
107
+ it("WeChat 7.x device → md5 path", async () => {
108
+ const exec = makeExec([
109
+ ["adb devices", ADB_DEVICES_OK],
110
+ ["getprop ro.product.cpu.abi", "arm64-v8a\n"],
111
+ ["com.tencent.mm", WECHAT_7],
112
+ ]);
113
+ const r = await probe({ exec });
114
+ expect(r.ok).toBe(true);
115
+ expect(r.suggestedKeyProvider).toBe("md5");
116
+ expect(r.device.serial).toBe("ABC123XYZ");
117
+ expect(r.device.abi).toBe("arm64-v8a");
118
+ expect(r.wechat.majorVersion).toBe(7);
119
+ });
120
+
121
+ it("WeChat 8.x + rooted + frida → frida path", async () => {
122
+ const exec = makeExec([
123
+ ["adb devices", ADB_DEVICES_OK],
124
+ ["getprop ro.product.cpu.abi", "arm64-v8a\n"],
125
+ ['su -c id', "uid=0(root) gid=0(root) groups=0(root)\n"],
126
+ ["command -v magisk", "/system/bin/magisk\n"],
127
+ ["pgrep -f frida-server", "12345\n"],
128
+ ["netstat -tln", NETSTAT_FRIDA],
129
+ ["com.tencent.mm", WECHAT_8],
130
+ ]);
131
+ const r = await probe({ exec });
132
+ expect(r.ok).toBe(true);
133
+ expect(r.suggestedKeyProvider).toBe("frida");
134
+ expect(r.root.detected).toBe(true);
135
+ expect(r.root.magiskInstalled).toBe(true);
136
+ expect(r.frida.serverRunning).toBe(true);
137
+ expect(r.frida.port).toBe(27042);
138
+ expect(r.wechat.majorVersion).toBe(8);
139
+ });
140
+
141
+ it("WeChat 8.x but no root → unsupported with reason", async () => {
142
+ const exec = makeExec([
143
+ ["adb devices", ADB_DEVICES_OK],
144
+ ["getprop ro.product.cpu.abi", "arm64-v8a\n"],
145
+ ["com.tencent.mm", WECHAT_8],
146
+ ]);
147
+ const r = await probe({ exec });
148
+ expect(r.ok).toBe(false);
149
+ expect(r.suggestedKeyProvider).toBe("unsupported");
150
+ expect(r.reasons.join(" ")).toMatch(/root not detected/);
151
+ });
152
+
153
+ it("non-ARM ABI gets warning", async () => {
154
+ const exec = makeExec([
155
+ ["adb devices", ADB_DEVICES_OK],
156
+ ["getprop ro.product.cpu.abi", "x86_64\n"],
157
+ ["com.tencent.mm", WECHAT_7],
158
+ ]);
159
+ const r = await probe({ exec });
160
+ expect(r.warnings.join(" ")).toMatch(/x86_64/);
161
+ });
162
+ });
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect, vi } from "vitest";
4
+
5
+ const { loadAgentScript, runAgentUnderMock } = require("../../lib/adapters/wechat/frida-agent/loader");
6
+
7
+ function hexToBuffer(hex) {
8
+ const out = new Uint8Array(hex.length / 2);
9
+ for (let i = 0; i < out.length; i++) {
10
+ out[i] = parseInt(hex.substr(i * 2, 2), 16);
11
+ }
12
+ return out.buffer;
13
+ }
14
+
15
+ /** Fake NativePointer — supports toInt32() (length) and readByteArray(len) (key bytes). */
16
+ function fakePtr(value) {
17
+ return {
18
+ _v: value,
19
+ toInt32() { return typeof value === "number" ? value : 0; },
20
+ readByteArray(len) {
21
+ // value is a hex string for key bytes; len ignored beyond bounds
22
+ if (typeof value !== "string") return new Uint8Array(0).buffer;
23
+ const buf = hexToBuffer(value);
24
+ // truncate to requested len if needed
25
+ return new Uint8Array(buf, 0, Math.min(len, buf.byteLength)).buffer;
26
+ },
27
+ };
28
+ }
29
+
30
+ describe("frida-agent loader — script loading", () => {
31
+ it("loadAgentScript returns non-empty JS text", () => {
32
+ const src = loadAgentScript();
33
+ expect(src.length).toBeGreaterThan(100);
34
+ expect(src).toContain("libwcdb.so");
35
+ expect(src).toContain("sqlite3_key");
36
+ });
37
+ });
38
+
39
+ describe("frida-agent — sqlite3_key hook on module already loaded", () => {
40
+ it("emits hooked + key on sqlite3_key onEnter", () => {
41
+ const send = vi.fn();
42
+ const attached = {};
43
+ const Interceptor = {
44
+ attach(addr, handlers) {
45
+ attached[addr.symbol] = handlers;
46
+ },
47
+ };
48
+ const Module = {
49
+ findExportByName(mod, sym) {
50
+ if (mod !== "libwcdb.so") return null;
51
+ if (sym === "sqlite3_key") return { symbol: sym };
52
+ return null; // only sqlite3_key resolves; others null
53
+ },
54
+ };
55
+ const Process = {
56
+ findModuleByName(mod) { return mod === "libwcdb.so" ? { name: mod } : null; },
57
+ };
58
+
59
+ runAgentUnderMock({ Module, Process, Interceptor, send });
60
+
61
+ // After load, "hooked" event already sent
62
+ const hooked = send.mock.calls.find((c) => c[0].kind === "hooked");
63
+ expect(hooked).toBeDefined();
64
+ expect(hooked[0].symbol).toBe("sqlite3_key");
65
+ expect(hooked[0].module).toBe("libwcdb.so");
66
+
67
+ // Fire the hook: args = [sqlite3*, keyBytes, len]
68
+ const keyHex = "11223344556677889900aabbccddeeff" +
69
+ "00112233445566778899aabbccddeeff"; // 64 hex = 32 bytes (SQLCipher 256-bit)
70
+ const args = [fakePtr(0), fakePtr(keyHex), fakePtr(32)];
71
+ attached.sqlite3_key.onEnter(args);
72
+
73
+ const key = send.mock.calls.find((c) => c[0].kind === "key");
74
+ expect(key).toBeDefined();
75
+ expect(key[0].hex).toBe(keyHex);
76
+ expect(key[0].source).toBe("sqlite3_key");
77
+ });
78
+
79
+ it("only emits the first key event (anti-detection: hook fires once)", () => {
80
+ const send = vi.fn();
81
+ const attached = {};
82
+ const Interceptor = {
83
+ attach(addr, handlers) { attached[addr.symbol] = handlers; },
84
+ };
85
+ const Module = {
86
+ findExportByName(mod, sym) {
87
+ if (sym === "sqlite3_key") return { symbol: sym };
88
+ return null;
89
+ },
90
+ };
91
+ const Process = { findModuleByName() { return { name: "libwcdb.so" }; } };
92
+
93
+ runAgentUnderMock({ Module, Process, Interceptor, send });
94
+
95
+ const args = [fakePtr(0), fakePtr("aabb" + "00".repeat(30)), fakePtr(32)];
96
+ attached.sqlite3_key.onEnter(args);
97
+ attached.sqlite3_key.onEnter(args);
98
+ attached.sqlite3_key.onEnter(args);
99
+
100
+ const keyEvents = send.mock.calls.filter((c) => c[0].kind === "key");
101
+ expect(keyEvents).toHaveLength(1);
102
+ });
103
+
104
+ it("rejects implausible key length with error event", () => {
105
+ const send = vi.fn();
106
+ const attached = {};
107
+ const Interceptor = {
108
+ attach(addr, handlers) { attached[addr.symbol] = handlers; },
109
+ };
110
+ const Module = {
111
+ findExportByName(mod, sym) { return sym === "sqlite3_key" ? { symbol: sym } : null; },
112
+ };
113
+ const Process = { findModuleByName() { return { name: "libwcdb.so" }; } };
114
+
115
+ runAgentUnderMock({ Module, Process, Interceptor, send });
116
+
117
+ attached.sqlite3_key.onEnter([fakePtr(0), fakePtr("aa"), fakePtr(9999)]);
118
+
119
+ const errs = send.mock.calls.filter((c) => c[0].kind === "error");
120
+ expect(errs.length).toBeGreaterThan(0);
121
+ expect(errs[0][0].message).toMatch(/implausible key length 9999/);
122
+ });
123
+ });
124
+
125
+ describe("frida-agent — fallback symbol resolution", () => {
126
+ it("attaches to wcdb_setkey when sqlite3_key absent", () => {
127
+ const send = vi.fn();
128
+ const attached = {};
129
+ const Interceptor = {
130
+ attach(addr, handlers) { attached[addr.symbol] = handlers; },
131
+ };
132
+ const Module = {
133
+ findExportByName(mod, sym) {
134
+ // WeChat 8.x renamed primary symbol
135
+ if (sym === "wcdb_setkey") return { symbol: sym };
136
+ return null;
137
+ },
138
+ };
139
+ const Process = { findModuleByName() { return { name: "libwcdb.so" }; } };
140
+
141
+ runAgentUnderMock({ Module, Process, Interceptor, send });
142
+
143
+ const hooked = send.mock.calls.find((c) => c[0].kind === "hooked");
144
+ expect(hooked[0].symbol).toBe("wcdb_setkey");
145
+ expect(attached.wcdb_setkey).toBeDefined();
146
+ });
147
+
148
+ it("emits source = matched symbol when fallback fires", () => {
149
+ const send = vi.fn();
150
+ const attached = {};
151
+ const Interceptor = {
152
+ attach(addr, handlers) { attached[addr.symbol] = handlers; },
153
+ };
154
+ const Module = {
155
+ findExportByName(mod, sym) {
156
+ return sym === "WCDBKeyDerive" ? { symbol: sym } : null;
157
+ },
158
+ };
159
+ const Process = { findModuleByName() { return { name: "libwcdb.so" }; } };
160
+
161
+ runAgentUnderMock({ Module, Process, Interceptor, send });
162
+
163
+ attached.WCDBKeyDerive.onEnter([
164
+ fakePtr(0),
165
+ fakePtr("deadbeef" + "00".repeat(28)),
166
+ fakePtr(32),
167
+ ]);
168
+
169
+ const key = send.mock.calls.find((c) => c[0].kind === "key");
170
+ expect(key[0].source).toBe("WCDBKeyDerive");
171
+ });
172
+ });
173
+
174
+ describe("frida-agent — module not yet loaded path", () => {
175
+ it("emits module-waiting and schedules retry", () => {
176
+ const send = vi.fn();
177
+ const Interceptor = { attach: vi.fn() };
178
+ const Module = { findExportByName: vi.fn().mockReturnValue(null) };
179
+ const Process = { findModuleByName: vi.fn().mockReturnValue(null) };
180
+ const setTimeoutMock = vi.fn();
181
+
182
+ runAgentUnderMock({ Module, Process, Interceptor, send, setTimeout: setTimeoutMock });
183
+
184
+ const waiting = send.mock.calls.find((c) => c[0].kind === "module-waiting");
185
+ expect(waiting).toBeDefined();
186
+ expect(waiting[0].module).toBe("libwcdb.so");
187
+ expect(setTimeoutMock).toHaveBeenCalled();
188
+ // First retry delay 500ms
189
+ expect(setTimeoutMock.mock.calls[0][1]).toBe(500);
190
+ });
191
+ });
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect, vi } from "vitest";
4
+
5
+ const {
6
+ WechatAdapter,
7
+ WeChatFridaKeyProvider,
8
+ } = require("../../lib/adapters/wechat");
9
+
10
+ /**
11
+ * Phase 12.6.5 — integration: WechatAdapter.authenticate flow against
12
+ * a mock FridaKeyProvider. We don't open a real SQLCipher DB here —
13
+ * that requires a fixture + better-sqlite3-multiple-ciphers compiled
14
+ * against the host's Node ABI, and is covered separately in the v0.5
15
+ * suite. Goal of this slice: prove the adapter's KeyProvider DI seam
16
+ * works identically for the Frida path.
17
+ */
18
+
19
+ function mockFrida({ keyHex, throwOnAttach, delayMs = 0 } = {}) {
20
+ const script = {
21
+ message: { connect: (h) => { script._handler = h; } },
22
+ load: async () => {
23
+ setTimeout(() => {
24
+ if (!script._handler) return;
25
+ script._handler({ type: "send", payload: {
26
+ kind: "hooked", symbol: "sqlite3_key", module: "libwcdb.so",
27
+ } });
28
+ script._handler({ type: "send", payload: {
29
+ kind: "key", hex: keyHex, source: "sqlite3_key",
30
+ } });
31
+ }, delayMs);
32
+ },
33
+ unload: async () => {},
34
+ };
35
+ const session = {
36
+ createScript: async () => script,
37
+ detach: async () => {},
38
+ };
39
+ const device = {
40
+ attach: async () => {
41
+ if (throwOnAttach) throw new Error(throwOnAttach);
42
+ return session;
43
+ },
44
+ };
45
+ return {
46
+ getDevice: async () => device,
47
+ getUsbDevice: async () => device,
48
+ };
49
+ }
50
+
51
+ describe("WechatAdapter + FridaKeyProvider — DI integration", () => {
52
+ it("authenticate succeeds when frida provides a key", async () => {
53
+ // dbPath needs to point to a real file for the existsSync gate
54
+ const fs = require("node:fs");
55
+ const path = require("node:path");
56
+ const os = require("node:os");
57
+ const tmpDb = path.join(os.tmpdir(), `wechat-mock-${Date.now()}.db`);
58
+ fs.writeFileSync(tmpDb, "fake sqlite header");
59
+
60
+ const frida = mockFrida({ keyHex: "ab".repeat(32) /* 64 hex */ });
61
+ const keyProvider = new WeChatFridaKeyProvider({
62
+ frida,
63
+ deviceId: "TEST",
64
+ agentLoader: () => "/* test agent */",
65
+ });
66
+
67
+ const adapter = new WechatAdapter({
68
+ account: { uin: "1234567890" },
69
+ dbPath: tmpDb,
70
+ keyProvider,
71
+ });
72
+
73
+ const r = await adapter.authenticate();
74
+ expect(r.ok).toBe(true);
75
+ expect(r.account).toBe("1234567890");
76
+
77
+ try { fs.unlinkSync(tmpDb); } catch (_e) { /* test cleanup */ }
78
+ });
79
+
80
+ it("authenticate reports NO_KEY_PROVIDER when keyProvider absent", async () => {
81
+ const fs = require("node:fs");
82
+ const path = require("node:path");
83
+ const os = require("node:os");
84
+ const tmpDb = path.join(os.tmpdir(), `wechat-mock-${Date.now()}.db`);
85
+ fs.writeFileSync(tmpDb, "fake");
86
+
87
+ const adapter = new WechatAdapter({
88
+ account: { uin: "1234567890" },
89
+ dbPath: tmpDb,
90
+ // keyProvider omitted on purpose
91
+ });
92
+ const r = await adapter.authenticate();
93
+ expect(r.ok).toBe(false);
94
+ expect(r.reason).toBe("NO_KEY_PROVIDER");
95
+
96
+ try { fs.unlinkSync(tmpDb); } catch (_e) { /* test cleanup */ }
97
+ });
98
+
99
+ it("authenticate reports KEY_PROVIDER_THREW when Frida times out", async () => {
100
+ const fs = require("node:fs");
101
+ const path = require("node:path");
102
+ const os = require("node:os");
103
+ const tmpDb = path.join(os.tmpdir(), `wechat-mock-${Date.now()}.db`);
104
+ fs.writeFileSync(tmpDb, "fake");
105
+
106
+ // Mock with no messages → will timeout
107
+ const session = {
108
+ createScript: async () => ({
109
+ message: { connect: () => {} },
110
+ load: async () => {},
111
+ unload: async () => {},
112
+ }),
113
+ detach: async () => {},
114
+ };
115
+ const frida = {
116
+ getDevice: async () => ({ attach: async () => session }),
117
+ getUsbDevice: async () => ({ attach: async () => session }),
118
+ };
119
+ const keyProvider = new WeChatFridaKeyProvider({
120
+ frida,
121
+ deviceId: "TEST",
122
+ agentLoader: () => "",
123
+ timeoutMs: 30,
124
+ });
125
+
126
+ const adapter = new WechatAdapter({
127
+ account: { uin: "1234567890" },
128
+ dbPath: tmpDb,
129
+ keyProvider,
130
+ });
131
+
132
+ const r = await adapter.authenticate();
133
+ expect(r.ok).toBe(false);
134
+ expect(r.reason).toBe("KEY_PROVIDER_THREW");
135
+ expect(r.error).toMatch(/30ms/);
136
+
137
+ try { fs.unlinkSync(tmpDb); } catch (_e) { /* test cleanup */ }
138
+ });
139
+
140
+ it("DB_NOT_PULLED takes precedence over keyProvider absence", async () => {
141
+ const adapter = new WechatAdapter({
142
+ account: { uin: "1234567890" },
143
+ dbPath: "/definitely/not/a/real/path/wechat.db",
144
+ });
145
+ const r = await adapter.authenticate();
146
+ expect(r.ok).toBe(false);
147
+ expect(r.reason).toBe("DB_NOT_PULLED");
148
+ });
149
+ });
@@ -0,0 +1,188 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect, vi } from "vitest";
4
+
5
+ const { FridaKeyProvider } = require("../../lib/adapters/wechat/key-providers/frida-key-provider");
6
+
7
+ /** Helper that builds a mock frida binding with a scripted message timeline. */
8
+ function makeMockFrida({ onAttachThrow, onCreateScriptThrow, onLoadThrow, messages = [], deviceId = "device" }) {
9
+ const ops = {
10
+ unloadCalled: 0,
11
+ detachCalled: 0,
12
+ loadCalled: 0,
13
+ messageHandler: null,
14
+ };
15
+ const script = {
16
+ message: {
17
+ connect: (handler) => { ops.messageHandler = handler; },
18
+ },
19
+ load: vi.fn(async () => {
20
+ ops.loadCalled++;
21
+ if (onLoadThrow) throw onLoadThrow;
22
+ // Replay the scripted messages on next tick so .connect handler is
23
+ // wired before the first send fires.
24
+ setTimeout(() => {
25
+ for (const m of messages) {
26
+ if (ops.messageHandler) ops.messageHandler({ type: "send", payload: m });
27
+ }
28
+ }, 0);
29
+ }),
30
+ unload: vi.fn(async () => { ops.unloadCalled++; }),
31
+ };
32
+ const session = {
33
+ createScript: vi.fn(async () => {
34
+ if (onCreateScriptThrow) throw onCreateScriptThrow;
35
+ return script;
36
+ }),
37
+ detach: vi.fn(async () => { ops.detachCalled++; }),
38
+ };
39
+ const device = {
40
+ attach: vi.fn(async (pkg) => {
41
+ if (onAttachThrow) throw onAttachThrow;
42
+ device._attachedTo = pkg;
43
+ return session;
44
+ }),
45
+ };
46
+ const frida = {
47
+ getDevice: vi.fn(async (id) => {
48
+ device._id = id;
49
+ return device;
50
+ }),
51
+ getUsbDevice: vi.fn(async () => device),
52
+ };
53
+ return { frida, device, session, script, ops };
54
+ }
55
+
56
+ describe("FridaKeyProvider — construction", () => {
57
+ it("defaults packageName to com.tencent.mm", () => {
58
+ const p = new FridaKeyProvider({});
59
+ expect(p._packageName).toBe("com.tencent.mm");
60
+ });
61
+
62
+ it("name is frida", () => {
63
+ const p = new FridaKeyProvider({});
64
+ expect(p.name).toBe("frida");
65
+ });
66
+
67
+ it("getKey throws FRIDA_BINDING_MISSING when frida not available", async () => {
68
+ const p = new FridaKeyProvider({});
69
+ try {
70
+ await p.getKey();
71
+ throw new Error("should have thrown");
72
+ } catch (err) {
73
+ expect(err.code).toBe("FRIDA_BINDING_MISSING");
74
+ }
75
+ });
76
+ });
77
+
78
+ describe("FridaKeyProvider — happy path", () => {
79
+ it("captures key hex and detaches", async () => {
80
+ const keyHex = "00112233445566778899aabbccddeeff" +
81
+ "ffeeddccbbaa99887766554433221100";
82
+ const { frida, ops } = makeMockFrida({
83
+ messages: [
84
+ { kind: "hooked", symbol: "sqlite3_key", module: "libwcdb.so" },
85
+ { kind: "key", hex: keyHex.toUpperCase(), source: "sqlite3_key" },
86
+ ],
87
+ });
88
+ const p = new FridaKeyProvider({ frida, deviceId: "Z1", agentLoader: () => "/* mock agent */" });
89
+ const k = await p.getKey();
90
+ expect(k).toBe(keyHex); // lowercased
91
+ expect(ops.unloadCalled).toBe(1);
92
+ expect(ops.detachCalled).toBe(1);
93
+ const tel = p.getLastTelemetry();
94
+ expect(tel.keySource).toBe("sqlite3_key");
95
+ expect(tel.hooked).toHaveLength(1);
96
+ expect(tel.durationMs).toBeGreaterThanOrEqual(0);
97
+ });
98
+
99
+ it("uses USB device when no deviceId provided", async () => {
100
+ const { frida } = makeMockFrida({
101
+ messages: [{ kind: "key", hex: "aa" + "00".repeat(31), source: "sqlite3_key" }],
102
+ });
103
+ const p = new FridaKeyProvider({ frida, agentLoader: () => "/* mock */" });
104
+ await p.getKey();
105
+ expect(frida.getUsbDevice).toHaveBeenCalled();
106
+ expect(frida.getDevice).not.toHaveBeenCalled();
107
+ });
108
+ });
109
+
110
+ describe("FridaKeyProvider — error paths", () => {
111
+ it("WECHAT_NOT_RUNNING when attach reports process not found", async () => {
112
+ const { frida } = makeMockFrida({
113
+ onAttachThrow: new Error("unable to find process with name 'com.tencent.mm'"),
114
+ });
115
+ const p = new FridaKeyProvider({ frida, deviceId: "Z1", agentLoader: () => "" });
116
+ await expect(p.getKey()).rejects.toMatchObject({ code: "WECHAT_NOT_RUNNING" });
117
+ });
118
+
119
+ it("FRIDA_ATTACH_FAILED on generic attach error", async () => {
120
+ const { frida } = makeMockFrida({
121
+ onAttachThrow: new Error("permission denied"),
122
+ });
123
+ const p = new FridaKeyProvider({ frida, deviceId: "Z1", agentLoader: () => "" });
124
+ await expect(p.getKey()).rejects.toMatchObject({ code: "FRIDA_ATTACH_FAILED" });
125
+ });
126
+
127
+ it("FRIDA_ATTACH_FAILED + session cleanup when createScript throws", async () => {
128
+ const { frida, ops } = makeMockFrida({
129
+ onCreateScriptThrow: new Error("syntax error in agent"),
130
+ });
131
+ const p = new FridaKeyProvider({ frida, deviceId: "Z1", agentLoader: () => "BAD" });
132
+ await expect(p.getKey()).rejects.toMatchObject({ code: "FRIDA_ATTACH_FAILED" });
133
+ // Even though createScript threw, the session was already attached;
134
+ // implementation cleans it up in the catch path.
135
+ expect(ops.detachCalled).toBe(1);
136
+ });
137
+
138
+ it("WCDB_KEY_TIMEOUT when no key event in time", async () => {
139
+ const { frida, ops } = makeMockFrida({
140
+ messages: [{ kind: "hooked", symbol: "sqlite3_key", module: "libwcdb.so" }],
141
+ });
142
+ const p = new FridaKeyProvider({
143
+ frida,
144
+ deviceId: "Z1",
145
+ timeoutMs: 50,
146
+ agentLoader: () => "",
147
+ });
148
+ await expect(p.getKey()).rejects.toMatchObject({ code: "WCDB_KEY_TIMEOUT" });
149
+ expect(ops.unloadCalled).toBe(1);
150
+ expect(ops.detachCalled).toBe(1);
151
+ });
152
+
153
+ it("non-fatal hook errors are recorded but don't reject", async () => {
154
+ const keyHex = "ee" + "00".repeat(31);
155
+ const { frida } = makeMockFrida({
156
+ messages: [
157
+ { kind: "error", message: "Interceptor.attach failed for WCDBKeyDerive: not found" },
158
+ { kind: "hooked", symbol: "sqlite3_key", module: "libwcdb.so" },
159
+ { kind: "key", hex: keyHex, source: "sqlite3_key" },
160
+ ],
161
+ });
162
+ const p = new FridaKeyProvider({ frida, deviceId: "Z1", agentLoader: () => "" });
163
+ const k = await p.getKey();
164
+ expect(k).toBe(keyHex);
165
+ expect(p.getLastTelemetry().errors).toContain("Interceptor.attach failed for WCDBKeyDerive: not found");
166
+ });
167
+ });
168
+
169
+ describe("FridaKeyProvider — logger DI", () => {
170
+ it("logger receives frida-message events", async () => {
171
+ const events = [];
172
+ const { frida } = makeMockFrida({
173
+ messages: [
174
+ { kind: "hooked", symbol: "sqlite3_key", module: "libwcdb.so" },
175
+ { kind: "key", hex: "ff" + "00".repeat(31), source: "sqlite3_key" },
176
+ ],
177
+ });
178
+ const p = new FridaKeyProvider({
179
+ frida,
180
+ deviceId: "Z1",
181
+ agentLoader: () => "",
182
+ logger: (e) => events.push(e),
183
+ });
184
+ await p.getKey();
185
+ expect(events.some((e) => e.kind === "frida-message" && e.evt.kind === "hooked")).toBe(true);
186
+ expect(events.some((e) => e.kind === "frida-message" && e.evt.kind === "key")).toBe(true);
187
+ });
188
+ });