@chainlesschain/personal-data-hub 0.1.0 → 0.2.0

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 (116) hide show
  1. package/__tests__/adapters/ai-chat-history.test.js +395 -0
  2. package/__tests__/adapters/ai-chat-http-client.test.js +242 -0
  3. package/__tests__/adapters/ai-chat-vendors.test.js +733 -0
  4. package/__tests__/adapters/alipay-bill-adapter.test.js +538 -0
  5. package/__tests__/adapters/email-adapter.test.js +138 -1
  6. package/__tests__/adapters/email-classifier.test.js +347 -0
  7. package/__tests__/adapters/email-pdf-extractor.test.js +529 -0
  8. package/__tests__/adapters/email-retry-progress.test.js +294 -0
  9. package/__tests__/adapters/email-templates.test.js +699 -0
  10. package/__tests__/adapters/system-data-adapter.test.js +440 -0
  11. package/__tests__/adapters/system-data-disclosure.test.js +153 -0
  12. package/__tests__/analysis-skills.test.js +409 -0
  13. package/__tests__/entity-resolver-ingest-hook.test.js +177 -0
  14. package/__tests__/entity-resolver-stages.test.js +411 -0
  15. package/__tests__/entity-resolver-vault.test.js +246 -0
  16. package/__tests__/entity-resolver.test.js +526 -0
  17. package/__tests__/fixtures/entity-resolver-200-mock.json +96 -0
  18. package/__tests__/longtail-adapters.test.js +217 -0
  19. package/__tests__/mobile-extractor.test.js +288 -0
  20. package/__tests__/shopping-adapters.test.js +296 -0
  21. package/__tests__/sidecar-contacts-cross-validate.test.js +163 -0
  22. package/__tests__/sidecar-supervisor.test.js +120 -0
  23. package/__tests__/social-adapters.test.js +206 -0
  24. package/__tests__/travel-adapters.test.js +325 -0
  25. package/__tests__/vault.test.js +3 -3
  26. package/__tests__/wechat-adapter.test.js +476 -0
  27. package/__tests__/whatsapp-adapter.test.js +135 -0
  28. package/lib/adapter-spec.js +12 -0
  29. package/lib/adapters/_python-sidecar-base.js +207 -0
  30. package/lib/adapters/ai-chat-history/ai-chat-adapter.js +335 -0
  31. package/lib/adapters/ai-chat-history/cookie-auth.js +109 -0
  32. package/lib/adapters/ai-chat-history/http-client.js +211 -0
  33. package/lib/adapters/ai-chat-history/index.js +28 -0
  34. package/lib/adapters/ai-chat-history/schema-map.js +221 -0
  35. package/lib/adapters/ai-chat-history/vendor-spec.js +85 -0
  36. package/lib/adapters/ai-chat-history/vendors/coze.js +179 -0
  37. package/lib/adapters/ai-chat-history/vendors/deepseek.js +199 -0
  38. package/lib/adapters/ai-chat-history/vendors/dreamina.js +174 -0
  39. package/lib/adapters/ai-chat-history/vendors/hunyuan.js +176 -0
  40. package/lib/adapters/ai-chat-history/vendors/kimi.js +182 -0
  41. package/lib/adapters/ai-chat-history/vendors/qianfan.js +160 -0
  42. package/lib/adapters/ai-chat-history/vendors/tongyi.js +193 -0
  43. package/lib/adapters/ai-chat-history/vendors/zhipu.js +202 -0
  44. package/lib/adapters/alipay-bill/alipay-bill-adapter.js +307 -0
  45. package/lib/adapters/alipay-bill/counterparty.js +129 -0
  46. package/lib/adapters/alipay-bill/csv-parser.js +217 -0
  47. package/lib/adapters/alipay-bill/index.js +41 -0
  48. package/lib/adapters/alipay-bill/zip-decryptor.js +111 -0
  49. package/lib/adapters/email-imap/classifier.js +495 -0
  50. package/lib/adapters/email-imap/email-adapter.js +419 -8
  51. package/lib/adapters/email-imap/index.js +42 -0
  52. package/lib/adapters/email-imap/pdf-extractor.js +192 -0
  53. package/lib/adapters/email-imap/templates/bill.js +232 -0
  54. package/lib/adapters/email-imap/templates/government.js +120 -0
  55. package/lib/adapters/email-imap/templates/index.js +78 -0
  56. package/lib/adapters/email-imap/templates/order.js +186 -0
  57. package/lib/adapters/email-imap/templates/other.js +114 -0
  58. package/lib/adapters/email-imap/templates/register.js +113 -0
  59. package/lib/adapters/email-imap/templates/travel.js +157 -0
  60. package/lib/adapters/email-imap/templates/utils.js +275 -0
  61. package/lib/adapters/email-imap/transactions.js +234 -0
  62. package/lib/adapters/messaging-qq/index.js +158 -0
  63. package/lib/adapters/messaging-telegram/index.js +142 -0
  64. package/lib/adapters/messaging-whatsapp/index.js +189 -0
  65. package/lib/adapters/shopping-base/index.js +208 -0
  66. package/lib/adapters/shopping-jd/index.js +150 -0
  67. package/lib/adapters/shopping-meituan/index.js +154 -0
  68. package/lib/adapters/shopping-taobao/index.js +176 -0
  69. package/lib/adapters/social-bilibili/index.js +171 -0
  70. package/lib/adapters/social-douyin/index.js +116 -0
  71. package/lib/adapters/social-weibo/index.js +164 -0
  72. package/lib/adapters/social-xiaohongshu/index.js +96 -0
  73. package/lib/adapters/system-data/disclosure.js +166 -0
  74. package/lib/adapters/system-data/index.js +34 -0
  75. package/lib/adapters/system-data/system-data-adapter.js +344 -0
  76. package/lib/adapters/travel-12306/index.js +151 -0
  77. package/lib/adapters/travel-amap/index.js +164 -0
  78. package/lib/adapters/travel-baidu-map/index.js +162 -0
  79. package/lib/adapters/travel-base/index.js +240 -0
  80. package/lib/adapters/travel-ctrip/index.js +151 -0
  81. package/lib/adapters/wechat/content-parser.js +326 -0
  82. package/lib/adapters/wechat/db-reader.js +209 -0
  83. package/lib/adapters/wechat/index.js +28 -0
  84. package/lib/adapters/wechat/key-extractor.js +158 -0
  85. package/lib/adapters/wechat/normalize.js +220 -0
  86. package/lib/adapters/wechat/wechat-adapter.js +205 -0
  87. package/lib/analysis-skills/base.js +113 -0
  88. package/lib/analysis-skills/footprint.js +167 -0
  89. package/lib/analysis-skills/index.js +58 -0
  90. package/lib/analysis-skills/interests.js +161 -0
  91. package/lib/analysis-skills/relations.js +226 -0
  92. package/lib/analysis-skills/spending.js +216 -0
  93. package/lib/analysis-skills/timeline.js +167 -0
  94. package/lib/entity-resolver/embedding-stage.js +198 -0
  95. package/lib/entity-resolver/entity-resolver.js +384 -0
  96. package/lib/entity-resolver/index.js +42 -0
  97. package/lib/entity-resolver/llm-stage.js +191 -0
  98. package/lib/entity-resolver/rule-stage.js +208 -0
  99. package/lib/entity-resolver/worker.js +149 -0
  100. package/lib/index.js +115 -0
  101. package/lib/migrations.js +73 -0
  102. package/lib/mobile-extractor/android.js +193 -0
  103. package/lib/mobile-extractor/index.js +9 -0
  104. package/lib/mobile-extractor/ios.js +223 -0
  105. package/lib/registry.js +42 -0
  106. package/lib/sidecar/index.js +15 -0
  107. package/lib/sidecar/supervisor.js +359 -0
  108. package/lib/vault.js +266 -0
  109. package/package.json +29 -3
  110. package/scripts/_make-fixture-all.js +126 -0
  111. package/scripts/_make-fixture-contacts.js +84 -0
  112. package/scripts/evaluate-entity-resolver.js +213 -0
  113. package/scripts/smoke-phase-5-5.js +196 -0
  114. package/scripts/smoke-phase-5-7.js +181 -0
  115. package/scripts/smoke-system-data-contacts.js +309 -0
  116. package/scripts/smoke-system-data.js +312 -0
@@ -0,0 +1,440 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Unit tests for SystemDataAdapter (Phase 4.5.5).
5
+ *
6
+ * Uses a hand-rolled FakeSupervisor — we don't spawn Python here. The supervisor
7
+ * boundary is verified separately by the integration tests in
8
+ * `sidecar-supervisor.test.js` + `sidecar-contacts-cross-validate.test.js`.
9
+ * Here we want fast, deterministic, full-coverage exercise of the adapter's
10
+ * orchestration logic (include flags / dataPaths fallback / progress events /
11
+ * authenticate gating / etc).
12
+ */
13
+
14
+ import { describe, it, expect, beforeEach } from "vitest";
15
+
16
+ const {
17
+ SystemDataAdapter,
18
+ SYSTEM_DATA_ADAPTER_NAME,
19
+ SYSTEM_DATA_ADAPTER_VERSION,
20
+ DEFAULT_INCLUDE,
21
+ } = require("../../lib/adapters/system-data");
22
+ const { assertAdapter } = require("../../lib/adapter-spec");
23
+
24
+ /**
25
+ * Minimal supervisor stub: pluggable per-method handlers + recorded calls.
26
+ */
27
+ class FakeSupervisor {
28
+ constructor(handlers = {}) {
29
+ this.handlers = handlers;
30
+ this.calls = [];
31
+ }
32
+
33
+ async invoke(method, params = {}, opts = {}) {
34
+ this.calls.push({ method, params, opts });
35
+ const handler = this.handlers[method];
36
+ if (!handler) throw Object.assign(new Error(`unhandled method: ${method}`), { code: "TEST_NO_HANDLER" });
37
+ return await handler(params, opts);
38
+ }
39
+ }
40
+
41
+ /** Make a chunk-emitting handler whose `onChunk` is fed by `chunks`. */
42
+ function chunkingHandler(chunks, result) {
43
+ return async (_params, opts) => {
44
+ for (const c of chunks) {
45
+ if (opts && typeof opts.onChunk === "function") opts.onChunk(c);
46
+ }
47
+ return result;
48
+ };
49
+ }
50
+
51
+ function personPayload(rawContactId, name, phones = []) {
52
+ return {
53
+ id: `person:system:android:${rawContactId}`,
54
+ type: "person",
55
+ subtype: "contact",
56
+ names: [name],
57
+ identifiers: phones.length ? { phone: phones } : undefined,
58
+ ingestedAt: 1_700_000_000_000,
59
+ confidence: 1.0,
60
+ source: {
61
+ adapter: "system-data",
62
+ adapterVersion: "0.1.0",
63
+ originalId: String(rawContactId),
64
+ capturedAt: 1_700_000_000_000,
65
+ capturedBy: "sqlite",
66
+ },
67
+ extra: { starred: false },
68
+ };
69
+ }
70
+
71
+ function callEventPayload(callId, occurredAt = 1_700_000_000_000) {
72
+ return {
73
+ id: `event:system:call:${callId}`,
74
+ type: "event",
75
+ subtype: "call",
76
+ occurredAt,
77
+ actor: "person:self",
78
+ participants: ["person:system:android:1"],
79
+ content: {},
80
+ ingestedAt: occurredAt,
81
+ confidence: 1.0,
82
+ source: {
83
+ adapter: "system-data",
84
+ adapterVersion: "0.1.0",
85
+ originalId: String(callId),
86
+ capturedAt: occurredAt,
87
+ capturedBy: "sqlite",
88
+ },
89
+ extra: { callType: "outgoing", callTypeCode: 2, isRead: true, rawNumber: "13800001111" },
90
+ };
91
+ }
92
+
93
+ function placePayload(name) {
94
+ return {
95
+ id: `place:wifi:${name.toLowerCase()}`,
96
+ type: "place",
97
+ name,
98
+ category: "wifi",
99
+ aliases: [],
100
+ ingestedAt: 1_700_000_000_000,
101
+ confidence: 0.95,
102
+ source: {
103
+ adapter: "system-data",
104
+ adapterVersion: "0.1.0",
105
+ originalId: name,
106
+ capturedAt: 1_700_000_000_000,
107
+ capturedBy: "manual",
108
+ },
109
+ extra: { securityType: "WPA/WPA2", hidden: false, passwordStored: true },
110
+ };
111
+ }
112
+
113
+ // ---------------------------------------------------------------------------
114
+ // Suite
115
+ // ---------------------------------------------------------------------------
116
+
117
+ describe("SystemDataAdapter contract", () => {
118
+ it("conforms to PersonalDataAdapter contract", () => {
119
+ const adapter = new SystemDataAdapter({ supervisor: new FakeSupervisor() });
120
+ const result = assertAdapter(adapter);
121
+ expect(result).toEqual({ ok: true });
122
+ });
123
+
124
+ it("exposes constants and version", () => {
125
+ expect(SYSTEM_DATA_ADAPTER_NAME).toBe("system-data");
126
+ expect(SYSTEM_DATA_ADAPTER_VERSION).toMatch(/^\d+\.\d+\.\d+/);
127
+ });
128
+
129
+ it("declares correct default include flags (SMS opt-out)", () => {
130
+ expect(DEFAULT_INCLUDE).toEqual({
131
+ contacts: true,
132
+ calllog: true,
133
+ sms: false,
134
+ wifi: true,
135
+ });
136
+ });
137
+
138
+ it("dataDisclosure is high-sensitivity + legalGate ON", () => {
139
+ const adapter = new SystemDataAdapter({ supervisor: new FakeSupervisor() });
140
+ expect(adapter.dataDisclosure.sensitivity).toBe("high");
141
+ expect(adapter.dataDisclosure.legalGate).toBe(true);
142
+ expect(adapter.dataDisclosure.notice).toMatch(/不向任何服务器上传/);
143
+ expect(adapter.dataDisclosure.fields.some((f) => f.startsWith("sms:"))).toBe(true);
144
+ });
145
+ });
146
+
147
+ describe("SystemDataAdapter.authenticate", () => {
148
+ it("returns offline mode when dataPaths are provided", async () => {
149
+ const sup = new FakeSupervisor({
150
+ "sidecar.ping": async () => ({ version: "0.1.0", pythonVersion: "3.12" }),
151
+ });
152
+ const adapter = new SystemDataAdapter({ supervisor: sup });
153
+
154
+ const out = await adapter.authenticate({ dataPaths: { contacts: "/tmp/c.db" } });
155
+ expect(out).toEqual({ ok: true, mode: "offline", sidecarVersion: "0.1.0" });
156
+ expect(sup.calls.map((c) => c.method)).toEqual(["sidecar.ping"]);
157
+ });
158
+
159
+ it("fails when sidecar is down", async () => {
160
+ const sup = new FakeSupervisor({
161
+ "sidecar.ping": async () => {
162
+ throw Object.assign(new Error("sidecar gone"), {
163
+ code: "SIDECAR_NOT_RUNNING",
164
+ });
165
+ },
166
+ });
167
+ const adapter = new SystemDataAdapter({ supervisor: sup });
168
+ await expect(adapter.authenticate({ dataPaths: { contacts: "/x" } })).rejects.toThrow();
169
+ });
170
+
171
+ it("device mode lists devices and accepts any authorized one", async () => {
172
+ const sup = new FakeSupervisor({
173
+ "sidecar.ping": async () => ({ version: "0.1.0", pythonVersion: "3.12" }),
174
+ "android.list_devices": async () => ({
175
+ devices: [
176
+ { serial: "abc", state: "device", model: "Redmi" },
177
+ { serial: "xyz", state: "unauthorized" },
178
+ ],
179
+ }),
180
+ });
181
+ const adapter = new SystemDataAdapter({ supervisor: sup });
182
+
183
+ const out = await adapter.authenticate({});
184
+ expect(out.ok).toBe(true);
185
+ expect(out.mode).toBe("device");
186
+ expect(out.devices).toHaveLength(1);
187
+ expect(out.devices[0].serial).toBe("abc");
188
+ });
189
+
190
+ it("device mode fails when no authorized device matches", async () => {
191
+ const sup = new FakeSupervisor({
192
+ "sidecar.ping": async () => ({ version: "0.1.0", pythonVersion: "3.12" }),
193
+ "android.list_devices": async () => ({
194
+ devices: [{ serial: "xyz", state: "unauthorized" }],
195
+ }),
196
+ });
197
+ const adapter = new SystemDataAdapter({ supervisor: sup });
198
+ const out = await adapter.authenticate({});
199
+ expect(out.ok).toBe(false);
200
+ expect(out.reason).toMatch(/no authorized/i);
201
+ });
202
+
203
+ it("device mode targets a specific serial when provided", async () => {
204
+ const sup = new FakeSupervisor({
205
+ "sidecar.ping": async () => ({ version: "0.1.0", pythonVersion: "3.12" }),
206
+ "android.list_devices": async () => ({
207
+ devices: [
208
+ { serial: "abc", state: "device" },
209
+ { serial: "xyz", state: "device" },
210
+ ],
211
+ }),
212
+ });
213
+ const adapter = new SystemDataAdapter({ supervisor: sup });
214
+ const out = await adapter.authenticate({ serial: "xyz" });
215
+ expect(out.ok).toBe(true);
216
+ expect(out.devices).toEqual([{ serial: "xyz", state: "device" }]);
217
+ });
218
+ });
219
+
220
+ describe("SystemDataAdapter.sync via dataPaths (no ADB)", () => {
221
+ let sup;
222
+ let adapter;
223
+
224
+ beforeEach(() => {
225
+ sup = new FakeSupervisor({
226
+ "system.parse_contacts": chunkingHandler(
227
+ [{ events: [], persons: [personPayload(1, "妈妈", ["138"])], places: [], items: [] }],
228
+ { status: "ok", totalPersons: 1, watermark: null, stats: { with_phone: 1, with_email: 0, starred: 0 } },
229
+ ),
230
+ "system.parse_calllog": chunkingHandler(
231
+ [{
232
+ events: [callEventPayload(101)],
233
+ persons: [personPayload("unknown:139", "139")],
234
+ places: [],
235
+ items: [],
236
+ }],
237
+ { status: "ok", totalEvents: 1, totalPersonsCreated: 1, watermark: null, stats: {} },
238
+ ),
239
+ "system.parse_wifi": chunkingHandler(
240
+ [{ events: [], persons: [], places: [placePayload("HomeWiFi")], items: [] }],
241
+ { status: "ok", totalPlaces: 1, watermark: null, stats: {} },
242
+ ),
243
+ });
244
+ adapter = new SystemDataAdapter({ supervisor: sup });
245
+ });
246
+
247
+ it("yields raws in entityType-tagged envelope shape", async () => {
248
+ const raws = [];
249
+ for await (const raw of adapter.sync({
250
+ dataPaths: {
251
+ contacts: "/tmp/contacts2.db",
252
+ calllog: "/tmp/calls.db",
253
+ wifi: "/tmp/wifi-dir",
254
+ },
255
+ })) {
256
+ raws.push(raw);
257
+ }
258
+
259
+ // 1 person (contacts) + 1 event + 1 unknown person (calllog) + 1 place
260
+ expect(raws).toHaveLength(4);
261
+ const types = raws.map((r) => r.entityType);
262
+ expect(types.sort()).toEqual(["event", "person", "person", "place"]);
263
+
264
+ // Envelope shape
265
+ for (const r of raws) {
266
+ expect(typeof r.originalId).toBe("string");
267
+ expect(typeof r.capturedAt).toBe("number");
268
+ expect(r.payload && r.payload.type).toBe(r.entityType);
269
+ }
270
+ });
271
+
272
+ it("normalize() places one entity into its correct bucket", () => {
273
+ const raw = {
274
+ entityType: "person",
275
+ originalId: "1",
276
+ capturedAt: 1,
277
+ payload: personPayload(1, "X"),
278
+ };
279
+ const batch = adapter.normalize(raw);
280
+ expect(batch).toEqual({
281
+ events: [],
282
+ persons: [raw.payload],
283
+ places: [],
284
+ items: [],
285
+ topics: [],
286
+ });
287
+ });
288
+
289
+ it("normalize() returns empty buckets for unknown entityType", () => {
290
+ const batch = adapter.normalize({ entityType: "???", payload: {} });
291
+ expect(batch.events).toEqual([]);
292
+ expect(batch.persons).toEqual([]);
293
+ });
294
+
295
+ it("respects include flag — disabling SMS skips parse_sms entirely", async () => {
296
+ // sms enabled in this run; we have no parse_sms handler, so enabling
297
+ // it would crash. Default has it off — sync should succeed.
298
+ const raws = [];
299
+ for await (const raw of adapter.sync({
300
+ dataPaths: {
301
+ contacts: "/tmp/c.db",
302
+ calllog: "/tmp/cl.db",
303
+ wifi: "/tmp/wifi",
304
+ },
305
+ })) {
306
+ raws.push(raw);
307
+ }
308
+ expect(sup.calls.find((c) => c.method === "system.parse_sms")).toBeUndefined();
309
+ expect(raws.length).toBeGreaterThan(0);
310
+ });
311
+
312
+ it("explicitly disabling every source yields zero raws and zero sidecar calls", async () => {
313
+ const raws = [];
314
+ for await (const raw of adapter.sync({
315
+ include: { contacts: false, calllog: false, sms: false, wifi: false },
316
+ dataPaths: {},
317
+ })) {
318
+ raws.push(raw);
319
+ }
320
+ expect(raws).toEqual([]);
321
+ expect(sup.calls).toEqual([]);
322
+ });
323
+
324
+ it("forwards onProgress events from adapter scope", async () => {
325
+ const events = [];
326
+ const iter = adapter.sync({
327
+ dataPaths: { contacts: "/c", calllog: "/cl", wifi: "/w" },
328
+ onProgress: (msg) => events.push(msg),
329
+ });
330
+ for await (const _ of iter) { /* drain */ }
331
+
332
+ const phases = events.map((e) => `${e.source}:${e.phase}`);
333
+ expect(phases).toContain("contacts:parsing");
334
+ expect(phases).toContain("calllog:parsing");
335
+ expect(phases).toContain("wifi:parsing");
336
+ });
337
+ });
338
+
339
+ describe("SystemDataAdapter.sync ADB pull flow", () => {
340
+ it("invokes android.pull_file per enabled source when no dataPaths given", async () => {
341
+ const pullCalls = [];
342
+ const sup = new FakeSupervisor({
343
+ "android.pull_file": async (params) => {
344
+ pullCalls.push(params.remote_path);
345
+ return { remote: params.remote_path, local: `/scratch/${pullCalls.length}.db`, bytes: 100 };
346
+ },
347
+ "system.parse_contacts": chunkingHandler([], { status: "ok", totalPersons: 0, watermark: null, stats: {} }),
348
+ "system.parse_calllog": chunkingHandler([], { status: "ok", totalEvents: 0, totalPersonsCreated: 0, watermark: null, stats: {} }),
349
+ "system.parse_wifi": chunkingHandler([], { status: "ok", totalPlaces: 0, watermark: null, stats: {} }),
350
+ });
351
+ const adapter = new SystemDataAdapter({ supervisor: sup });
352
+
353
+ const iter = adapter.sync({ serial: "redmi", scratchDir: "/scratch" });
354
+ for await (const _ of iter) { /* drain */ }
355
+
356
+ expect(pullCalls).toEqual([
357
+ "/data/data/com.android.providers.contacts/databases/contacts2.db",
358
+ "/data/data/com.android.providers.contacts/databases/calllog.db",
359
+ "/data/misc/wifi/",
360
+ ]);
361
+ });
362
+
363
+ it("sdcard mode uses /sdcard/Download/ paths", async () => {
364
+ const pullCalls = [];
365
+ const sup = new FakeSupervisor({
366
+ "android.pull_file": async (params) => {
367
+ pullCalls.push(params.remote_path);
368
+ return { remote: params.remote_path, local: `/scratch/${pullCalls.length}`, bytes: 100 };
369
+ },
370
+ "system.parse_contacts": chunkingHandler([], { status: "ok", totalPersons: 0, watermark: null, stats: {} }),
371
+ "system.parse_calllog": chunkingHandler([], { status: "ok", totalEvents: 0, totalPersonsCreated: 0, watermark: null, stats: {} }),
372
+ "system.parse_wifi": chunkingHandler([], { status: "ok", totalPlaces: 0, watermark: null, stats: {} }),
373
+ });
374
+ const adapter = new SystemDataAdapter({ supervisor: sup });
375
+
376
+ const iter = adapter.sync({ serial: "redmi", extractMode: "sdcard" });
377
+ for await (const _ of iter) { /* drain */ }
378
+
379
+ for (const p of pullCalls) expect(p).toMatch(/^\/sdcard\/Download\//);
380
+ });
381
+
382
+ it("throws when a source is enabled but neither serial nor dataPaths present", async () => {
383
+ const sup = new FakeSupervisor();
384
+ const adapter = new SystemDataAdapter({ supervisor: sup });
385
+ const iter = adapter.sync({ include: { contacts: true, calllog: false, sms: false, wifi: false } });
386
+ await expect((async () => {
387
+ for await (const _ of iter) { /* */ }
388
+ })()).rejects.toThrow(/no serial.*dataPaths/i);
389
+ });
390
+
391
+ it("skips wifi gracefully when pull_file fails with EXTRACT_PERMISSION_DENIED", async () => {
392
+ const sup = new FakeSupervisor({
393
+ "android.pull_file": async (params) => {
394
+ if (params.remote_path.startsWith("/data/misc/wifi")) {
395
+ throw Object.assign(new Error("denied"), {
396
+ code: "EXTRACT_PERMISSION_DENIED",
397
+ });
398
+ }
399
+ return { remote: params.remote_path, local: `/scratch/x`, bytes: 1 };
400
+ },
401
+ "system.parse_contacts": chunkingHandler([], { status: "ok", totalPersons: 0, watermark: null, stats: {} }),
402
+ "system.parse_calllog": chunkingHandler([], { status: "ok", totalEvents: 0, totalPersonsCreated: 0, watermark: null, stats: {} }),
403
+ });
404
+ const adapter = new SystemDataAdapter({ supervisor: sup });
405
+ const events = [];
406
+ const iter = adapter.sync({
407
+ serial: "redmi",
408
+ include: { contacts: true, calllog: true, sms: false, wifi: true },
409
+ onProgress: (msg) => events.push(msg),
410
+ });
411
+ for await (const _ of iter) { /* drain */ }
412
+
413
+ const wifiSkipped = events.find((e) => e.source === "wifi" && e.phase === "skipped");
414
+ expect(wifiSkipped).toBeDefined();
415
+ expect(wifiSkipped.reason).toBe("EXTRACT_PERMISSION_DENIED");
416
+ });
417
+ });
418
+
419
+ describe("SystemDataAdapter.healthCheck", () => {
420
+ it("returns ok when sidecar pings", async () => {
421
+ const sup = new FakeSupervisor({
422
+ "sidecar.ping": async () => ({ version: "0.1.0" }),
423
+ });
424
+ const adapter = new SystemDataAdapter({ supervisor: sup });
425
+ const r = await adapter.healthCheck();
426
+ expect(r).toEqual({ ok: true, version: "0.1.0" });
427
+ });
428
+
429
+ it("returns not-ok with reason when ping fails", async () => {
430
+ const sup = new FakeSupervisor({
431
+ "sidecar.ping": async () => {
432
+ throw Object.assign(new Error("dead"), { code: "TIMEOUT" });
433
+ },
434
+ });
435
+ const adapter = new SystemDataAdapter({ supervisor: sup });
436
+ const r = await adapter.healthCheck();
437
+ expect(r.ok).toBe(false);
438
+ expect(r.reason).toMatch(/TIMEOUT/);
439
+ });
440
+ });
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect } from "vitest";
4
+
5
+ const {
6
+ SystemDataAdapter,
7
+ SOURCE_DESCRIPTORS,
8
+ SOURCE_KEYS,
9
+ sanitizeInclude,
10
+ resolveRetentionMs,
11
+ checkDisclosureCoverage,
12
+ buildDisclosurePayload,
13
+ } = require("../../lib/adapters/system-data");
14
+
15
+ class StubSupervisor {
16
+ invoke() { return Promise.resolve({}); }
17
+ }
18
+
19
+ // ---------------------------------------------------------------------------
20
+
21
+ describe("SOURCE_DESCRIPTORS", () => {
22
+ it("declares all four sources with required metadata", () => {
23
+ expect(SOURCE_KEYS).toEqual(["contacts", "calllog", "sms", "wifi"]);
24
+ for (const key of SOURCE_KEYS) {
25
+ const d = SOURCE_DESCRIPTORS[key];
26
+ expect(d.label).toBeTruthy();
27
+ expect(Array.isArray(d.fields)).toBe(true);
28
+ expect(d.fields.length).toBeGreaterThan(0);
29
+ expect(["low", "medium", "high"]).toContain(d.sensitivity);
30
+ expect(typeof d.defaultEnabled).toBe("boolean");
31
+ }
32
+ });
33
+
34
+ it("SMS is the only opt-out source", () => {
35
+ const optOut = SOURCE_KEYS.filter((k) => !SOURCE_DESCRIPTORS[k].defaultEnabled);
36
+ expect(optOut).toEqual(["sms"]);
37
+ });
38
+
39
+ it("SMS carries a third-party-content warning", () => {
40
+ expect(SOURCE_DESCRIPTORS.sms.warning).toMatch(/他人/);
41
+ });
42
+
43
+ it("WiFi excludes password from collected fields", () => {
44
+ expect(SOURCE_DESCRIPTORS.wifi.excludedFields).toContain("password");
45
+ expect(SOURCE_DESCRIPTORS.wifi.fields).not.toContain("password");
46
+ });
47
+ });
48
+
49
+ // ---------------------------------------------------------------------------
50
+
51
+ describe("sanitizeInclude", () => {
52
+ it("returns descriptor defaults when input is empty", () => {
53
+ expect(sanitizeInclude({})).toEqual({
54
+ contacts: true, calllog: true, sms: false, wifi: true,
55
+ });
56
+ });
57
+
58
+ it("returns descriptor defaults when input is null", () => {
59
+ expect(sanitizeInclude(null)).toEqual({
60
+ contacts: true, calllog: true, sms: false, wifi: true,
61
+ });
62
+ });
63
+
64
+ it("coerces truthy non-boolean values to true", () => {
65
+ const out = sanitizeInclude({ sms: 1, contacts: "yes", wifi: 0 });
66
+ expect(out.sms).toBe(true);
67
+ expect(out.contacts).toBe(true);
68
+ expect(out.wifi).toBe(false);
69
+ });
70
+
71
+ it("drops unknown keys silently", () => {
72
+ const out = sanitizeInclude({ contacts: true, MALICIOUS_KEY: true });
73
+ expect(out).not.toHaveProperty("MALICIOUS_KEY");
74
+ expect(Object.keys(out).sort()).toEqual(["calllog", "contacts", "sms", "wifi"]);
75
+ });
76
+
77
+ it("missing keys fall back to source defaults — sms stays false", () => {
78
+ const out = sanitizeInclude({ contacts: true });
79
+ expect(out.sms).toBe(false);
80
+ });
81
+ });
82
+
83
+ // ---------------------------------------------------------------------------
84
+
85
+ describe("resolveRetentionMs", () => {
86
+ it("returns null when policy is missing", () => {
87
+ expect(resolveRetentionMs(null)).toBeNull();
88
+ expect(resolveRetentionMs({})).toBeNull();
89
+ });
90
+
91
+ it("returns null when retentionDays is not positive", () => {
92
+ expect(resolveRetentionMs({ retentionDays: 0 })).toBeNull();
93
+ expect(resolveRetentionMs({ retentionDays: -10 })).toBeNull();
94
+ expect(resolveRetentionMs({ retentionDays: "abc" })).toBeNull();
95
+ });
96
+
97
+ it("converts days to milliseconds", () => {
98
+ expect(resolveRetentionMs({ retentionDays: 1 })).toBe(24 * 60 * 60 * 1000);
99
+ expect(resolveRetentionMs({ retentionDays: 30 })).toBe(30 * 24 * 60 * 60 * 1000);
100
+ });
101
+ });
102
+
103
+ // ---------------------------------------------------------------------------
104
+
105
+ describe("checkDisclosureCoverage", () => {
106
+ it("ok when adapter declares every descriptor field", () => {
107
+ const adapter = new SystemDataAdapter({ supervisor: new StubSupervisor() });
108
+ const result = checkDisclosureCoverage(adapter.dataDisclosure.fields);
109
+ if (!result.ok) {
110
+ console.error("missing fields:", result.missing);
111
+ }
112
+ expect(result.ok).toBe(true);
113
+ expect(result.missing).toEqual([]);
114
+ });
115
+
116
+ it("flags missing source", () => {
117
+ const result = checkDisclosureCoverage(["contacts:name", "calllog:number", "wifi:ssid"]);
118
+ // Missing sms entirely + missing fields under contacts/calllog/wifi
119
+ expect(result.ok).toBe(false);
120
+ expect(result.missing.some((m) => m.startsWith("sms:"))).toBe(true);
121
+ });
122
+
123
+ it("flags missing per-source fields", () => {
124
+ const result = checkDisclosureCoverage([
125
+ "contacts:name", // missing phone/email/...
126
+ "calllog:number,duration,timestamp,type,name",
127
+ "sms:address,body,timestamp,type,threadId,isRead",
128
+ "wifi:ssid,securityType,hidden",
129
+ ]);
130
+ expect(result.ok).toBe(false);
131
+ expect(result.missing).toContain("contacts:phone");
132
+ });
133
+ });
134
+
135
+ // ---------------------------------------------------------------------------
136
+
137
+ describe("buildDisclosurePayload", () => {
138
+ it("returns a payload that the UI can render directly", () => {
139
+ const payload = buildDisclosurePayload();
140
+ expect(payload.adapter).toBe("system-data");
141
+ expect(payload.sensitivity).toBe("high");
142
+ expect(payload.legalGate).toBe(true);
143
+ expect(payload.sources).toHaveLength(4);
144
+ expect(payload.sources.map((s) => s.key)).toEqual(["contacts", "calllog", "sms", "wifi"]);
145
+ expect(payload.legalDeclaration).toMatch(/合法使用者/);
146
+ expect(payload.legalDeclaration).toMatch(/不向任何第三方分发/);
147
+ });
148
+
149
+ it("notice mentions the no-upload promise", () => {
150
+ const payload = buildDisclosurePayload();
151
+ expect(payload.notice).toMatch(/不向任何服务器上传/);
152
+ });
153
+ });