@chainlesschain/personal-data-hub 0.1.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 (154) 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 +396 -0
  4. package/__tests__/adapters/ai-chat-http-client.test.js +242 -0
  5. package/__tests__/adapters/ai-chat-vendors.test.js +874 -0
  6. package/__tests__/adapters/alipay-bill-adapter.test.js +538 -0
  7. package/__tests__/adapters/email-adapter.test.js +138 -1
  8. package/__tests__/adapters/email-classifier.test.js +347 -0
  9. package/__tests__/adapters/email-pdf-extractor.test.js +529 -0
  10. package/__tests__/adapters/email-retry-progress.test.js +294 -0
  11. package/__tests__/adapters/email-templates.test.js +699 -0
  12. package/__tests__/adapters/social-toutiao-kuaishou-scaffold.test.js +269 -0
  13. package/__tests__/adapters/system-data-adapter.test.js +440 -0
  14. package/__tests__/adapters/system-data-android-ingest.test.js +144 -0
  15. package/__tests__/adapters/system-data-android.test.js +387 -0
  16. package/__tests__/adapters/system-data-disclosure.test.js +153 -0
  17. package/__tests__/adapters/wechat-bootstrap.test.js +240 -0
  18. package/__tests__/adapters/wechat-env-probe.test.js +162 -0
  19. package/__tests__/adapters/wechat-frida-agent.test.js +191 -0
  20. package/__tests__/adapters/wechat-frida-integration.test.js +149 -0
  21. package/__tests__/adapters/wechat-frida-key-provider.test.js +188 -0
  22. package/__tests__/adapters/wechat-md5-key-provider.test.js +101 -0
  23. package/__tests__/analysis-skills.test.js +556 -0
  24. package/__tests__/analysis.test.js +329 -1
  25. package/__tests__/e2e/ai-chat-cross-source-journey.test.js +213 -0
  26. package/__tests__/e2e/full-user-journey.test.js +188 -0
  27. package/__tests__/entity-resolver-ingest-hook.test.js +177 -0
  28. package/__tests__/entity-resolver-stages.test.js +411 -0
  29. package/__tests__/entity-resolver-vault.test.js +246 -0
  30. package/__tests__/entity-resolver.test.js +526 -0
  31. package/__tests__/fixtures/entity-resolver-200-mock.json +96 -0
  32. package/__tests__/integration/ai-chat-history-registry.test.js +228 -0
  33. package/__tests__/integration/aichat-wizard-end-to-end.test.js +282 -0
  34. package/__tests__/integration/cross-adapter-pipelines.test.js +396 -0
  35. package/__tests__/integration/wechat-bootstrap-end-to-end.test.js +390 -0
  36. package/__tests__/longtail-adapters.test.js +217 -0
  37. package/__tests__/mobile-extractor.test.js +288 -0
  38. package/__tests__/registry.test.js +4 -2
  39. package/__tests__/shopping-adapters.test.js +296 -0
  40. package/__tests__/sidecar-contacts-cross-validate.test.js +163 -0
  41. package/__tests__/sidecar-supervisor.test.js +120 -0
  42. package/__tests__/social-adapters.test.js +206 -0
  43. package/__tests__/travel-adapters.test.js +325 -0
  44. package/__tests__/vault.test.js +3 -3
  45. package/__tests__/wechat-adapter.test.js +476 -0
  46. package/__tests__/whatsapp-adapter.test.js +135 -0
  47. package/lib/adapter-spec.js +12 -0
  48. package/lib/adapters/_python-sidecar-base.js +207 -0
  49. package/lib/adapters/ai-chat-history/ai-chat-adapter.js +374 -0
  50. package/lib/adapters/ai-chat-history/cookie-auth.js +109 -0
  51. package/lib/adapters/ai-chat-history/cookie-capture-spec.js +331 -0
  52. package/lib/adapters/ai-chat-history/health-checker.js +210 -0
  53. package/lib/adapters/ai-chat-history/http-client.js +211 -0
  54. package/lib/adapters/ai-chat-history/index.js +28 -0
  55. package/lib/adapters/ai-chat-history/schema-map.js +258 -0
  56. package/lib/adapters/ai-chat-history/vendor-spec.js +86 -0
  57. package/lib/adapters/ai-chat-history/vendors/coze.js +179 -0
  58. package/lib/adapters/ai-chat-history/vendors/deepseek.js +199 -0
  59. package/lib/adapters/ai-chat-history/vendors/doubao.js +255 -0
  60. package/lib/adapters/ai-chat-history/vendors/dreamina.js +174 -0
  61. package/lib/adapters/ai-chat-history/vendors/hunyuan.js +176 -0
  62. package/lib/adapters/ai-chat-history/vendors/kimi.js +182 -0
  63. package/lib/adapters/ai-chat-history/vendors/qianfan.js +160 -0
  64. package/lib/adapters/ai-chat-history/vendors/tongyi.js +193 -0
  65. package/lib/adapters/ai-chat-history/vendors/zhipu.js +202 -0
  66. package/lib/adapters/ai-chat-history/wizard-controller.js +473 -0
  67. package/lib/adapters/alipay-bill/alipay-bill-adapter.js +311 -0
  68. package/lib/adapters/alipay-bill/counterparty.js +129 -0
  69. package/lib/adapters/alipay-bill/csv-parser.js +217 -0
  70. package/lib/adapters/alipay-bill/index.js +41 -0
  71. package/lib/adapters/alipay-bill/zip-decryptor.js +111 -0
  72. package/lib/adapters/email-imap/classifier.js +495 -0
  73. package/lib/adapters/email-imap/email-adapter.js +419 -8
  74. package/lib/adapters/email-imap/index.js +42 -0
  75. package/lib/adapters/email-imap/pdf-extractor.js +192 -0
  76. package/lib/adapters/email-imap/templates/bill.js +232 -0
  77. package/lib/adapters/email-imap/templates/government.js +120 -0
  78. package/lib/adapters/email-imap/templates/index.js +78 -0
  79. package/lib/adapters/email-imap/templates/order.js +186 -0
  80. package/lib/adapters/email-imap/templates/other.js +114 -0
  81. package/lib/adapters/email-imap/templates/register.js +113 -0
  82. package/lib/adapters/email-imap/templates/travel.js +157 -0
  83. package/lib/adapters/email-imap/templates/utils.js +275 -0
  84. package/lib/adapters/email-imap/transactions.js +234 -0
  85. package/lib/adapters/messaging-qq/index.js +158 -0
  86. package/lib/adapters/messaging-telegram/index.js +142 -0
  87. package/lib/adapters/messaging-whatsapp/index.js +189 -0
  88. package/lib/adapters/shopping-base/index.js +208 -0
  89. package/lib/adapters/shopping-jd/index.js +150 -0
  90. package/lib/adapters/shopping-meituan/index.js +154 -0
  91. package/lib/adapters/shopping-taobao/index.js +176 -0
  92. package/lib/adapters/social-bilibili/index.js +171 -0
  93. package/lib/adapters/social-douyin/index.js +116 -0
  94. package/lib/adapters/social-kuaishou/index.js +237 -0
  95. package/lib/adapters/social-toutiao/index.js +236 -0
  96. package/lib/adapters/social-weibo/index.js +164 -0
  97. package/lib/adapters/social-xiaohongshu/index.js +96 -0
  98. package/lib/adapters/system-data/disclosure.js +166 -0
  99. package/lib/adapters/system-data/index.js +34 -0
  100. package/lib/adapters/system-data/system-data-adapter.js +344 -0
  101. package/lib/adapters/system-data-android/adapter.js +348 -0
  102. package/lib/adapters/system-data-android/index.js +76 -0
  103. package/lib/adapters/travel-12306/index.js +151 -0
  104. package/lib/adapters/travel-amap/index.js +164 -0
  105. package/lib/adapters/travel-baidu-map/index.js +162 -0
  106. package/lib/adapters/travel-base/index.js +240 -0
  107. package/lib/adapters/travel-ctrip/index.js +151 -0
  108. package/lib/adapters/wechat/bootstrap.js +146 -0
  109. package/lib/adapters/wechat/content-parser.js +326 -0
  110. package/lib/adapters/wechat/db-reader.js +209 -0
  111. package/lib/adapters/wechat/env-probe.js +218 -0
  112. package/lib/adapters/wechat/frida-agent/loader.js +67 -0
  113. package/lib/adapters/wechat/frida-agent/wechat-key-hook.js +126 -0
  114. package/lib/adapters/wechat/index.js +37 -0
  115. package/lib/adapters/wechat/key-extractor.js +158 -0
  116. package/lib/adapters/wechat/key-providers/frida-key-provider.js +244 -0
  117. package/lib/adapters/wechat/key-providers/index.js +22 -0
  118. package/lib/adapters/wechat/key-providers/key-provider-base.js +44 -0
  119. package/lib/adapters/wechat/key-providers/md5-key-provider.js +81 -0
  120. package/lib/adapters/wechat/normalize.js +220 -0
  121. package/lib/adapters/wechat/wechat-adapter.js +205 -0
  122. package/lib/analysis-skills/base.js +113 -0
  123. package/lib/analysis-skills/footprint.js +167 -0
  124. package/lib/analysis-skills/index.js +58 -0
  125. package/lib/analysis-skills/interests.js +161 -0
  126. package/lib/analysis-skills/relations.js +226 -0
  127. package/lib/analysis-skills/spending.js +219 -0
  128. package/lib/analysis-skills/timeline.js +167 -0
  129. package/lib/analysis.js +191 -2
  130. package/lib/entity-resolver/embedding-stage.js +198 -0
  131. package/lib/entity-resolver/entity-resolver.js +384 -0
  132. package/lib/entity-resolver/index.js +42 -0
  133. package/lib/entity-resolver/llm-stage.js +191 -0
  134. package/lib/entity-resolver/rule-stage.js +208 -0
  135. package/lib/entity-resolver/worker.js +149 -0
  136. package/lib/index.js +131 -0
  137. package/lib/migrations.js +73 -0
  138. package/lib/mobile-extractor/android.js +193 -0
  139. package/lib/mobile-extractor/index.js +9 -0
  140. package/lib/mobile-extractor/ios.js +223 -0
  141. package/lib/prompt-builder.js +11 -1
  142. package/lib/query-parser.js +7 -1
  143. package/lib/registry.js +42 -0
  144. package/lib/sidecar/index.js +15 -0
  145. package/lib/sidecar/supervisor.js +359 -0
  146. package/lib/vault.js +343 -0
  147. package/package.json +36 -3
  148. package/scripts/_make-fixture-all.js +126 -0
  149. package/scripts/_make-fixture-contacts.js +84 -0
  150. package/scripts/evaluate-entity-resolver.js +213 -0
  151. package/scripts/smoke-phase-5-5.js +196 -0
  152. package/scripts/smoke-phase-5-7.js +181 -0
  153. package/scripts/smoke-system-data-contacts.js +309 -0
  154. package/scripts/smoke-system-data.js +312 -0
@@ -0,0 +1,387 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
4
+ import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { tmpdir } from "node:os";
7
+
8
+ const {
9
+ SystemDataAndroidAdapter,
10
+ SYSTEM_DATA_ANDROID_NAME,
11
+ SYSTEM_DATA_ANDROID_VERSION,
12
+ SNAPSHOT_SCHEMA_VERSION,
13
+ } = require("../../lib/adapters/system-data-android");
14
+ const { assertAdapter } = require("../../lib/adapter-spec");
15
+ const {
16
+ ENTITY_TYPES,
17
+ PERSON_SUBTYPES,
18
+ ITEM_SUBTYPES,
19
+ CAPTURED_BY,
20
+ } = require("../../lib/constants");
21
+ const { validatePerson, validateItem } = require("../../lib/schemas");
22
+
23
+ let tmpDir;
24
+ let snapshotPath;
25
+
26
+ function writeSnapshot(obj) {
27
+ writeFileSync(snapshotPath, JSON.stringify(obj), "utf-8");
28
+ }
29
+
30
+ beforeEach(() => {
31
+ tmpDir = mkdtempSync(join(tmpdir(), "sda-test-"));
32
+ snapshotPath = join(tmpDir, "snapshot.json");
33
+ });
34
+
35
+ afterEach(() => {
36
+ rmSync(tmpDir, { recursive: true, force: true });
37
+ });
38
+
39
+ describe("SystemDataAndroidAdapter — contract", () => {
40
+ it("conforms to PersonalDataAdapter contract", () => {
41
+ const adapter = new SystemDataAndroidAdapter();
42
+ const r = assertAdapter(adapter);
43
+ expect(r).toEqual({ ok: true });
44
+ });
45
+
46
+ it("exposes stable name + version + capabilities", () => {
47
+ const adapter = new SystemDataAndroidAdapter();
48
+ expect(adapter.name).toBe(SYSTEM_DATA_ANDROID_NAME);
49
+ expect(adapter.version).toBe(SYSTEM_DATA_ANDROID_VERSION);
50
+ expect(adapter.extractMode).toBe("device-pull");
51
+ expect(adapter.dataDisclosure.sensitivity).toBe("medium");
52
+ expect(adapter.dataDisclosure.legalGate).toBe(false);
53
+ });
54
+ });
55
+
56
+ describe("SystemDataAndroidAdapter.authenticate", () => {
57
+ it("fails when inputPath missing", async () => {
58
+ const adapter = new SystemDataAndroidAdapter();
59
+ const r = await adapter.authenticate({});
60
+ expect(r.ok).toBe(false);
61
+ expect(r.reason).toBe("INPUT_PATH_REQUIRED");
62
+ });
63
+
64
+ it("fails when inputPath does not exist", async () => {
65
+ const adapter = new SystemDataAndroidAdapter();
66
+ const r = await adapter.authenticate({ inputPath: join(tmpDir, "does-not-exist.json") });
67
+ expect(r.ok).toBe(false);
68
+ expect(r.reason).toBe("INPUT_PATH_UNREADABLE");
69
+ });
70
+
71
+ it("succeeds when inputPath is readable", async () => {
72
+ writeSnapshot({ schemaVersion: SNAPSHOT_SCHEMA_VERSION, contacts: [], apps: [] });
73
+ const adapter = new SystemDataAndroidAdapter();
74
+ const r = await adapter.authenticate({ inputPath: snapshotPath });
75
+ expect(r).toEqual({ ok: true, mode: "snapshot-file" });
76
+ });
77
+ });
78
+
79
+ describe("SystemDataAndroidAdapter.sync + normalize", () => {
80
+ it("rejects mismatched snapshot schemaVersion", async () => {
81
+ writeSnapshot({ schemaVersion: 99, contacts: [], apps: [] });
82
+ const adapter = new SystemDataAndroidAdapter();
83
+ await expect(async () => {
84
+ // eslint-disable-next-line no-unused-vars
85
+ for await (const _ of adapter.sync({ inputPath: snapshotPath })) {
86
+ // drain
87
+ }
88
+ }).rejects.toThrow(/schemaVersion mismatch/);
89
+ });
90
+
91
+ it("yields contact + app raws and normalizes each into a valid entity", async () => {
92
+ writeSnapshot({
93
+ schemaVersion: SNAPSHOT_SCHEMA_VERSION,
94
+ snapshottedAt: 1_700_000_000_000,
95
+ contacts: [
96
+ {
97
+ lookupKey: "0r1-3A2B",
98
+ displayName: "妈妈",
99
+ phones: ["+8613800138000"],
100
+ emails: [],
101
+ starred: true,
102
+ organization: "家庭",
103
+ },
104
+ ],
105
+ apps: [
106
+ {
107
+ packageName: "com.tencent.mm",
108
+ label: "微信",
109
+ versionName: "8.0.45",
110
+ versionCode: 2200,
111
+ firstInstallTime: 1_650_000_000_000,
112
+ lastUpdateTime: 1_700_000_000_000,
113
+ isSystem: false,
114
+ },
115
+ ],
116
+ });
117
+ const adapter = new SystemDataAndroidAdapter();
118
+
119
+ // Every yielded raw must carry originalId so registry.putRawEvent's NOT
120
+ // NULL constraint doesn't surface as invalidCount=rawCount (real-device
121
+ // bug 2026-05-21). Capture all raws to assert structure first.
122
+ const rawsSeen = [];
123
+ for await (const r of adapter.sync({ inputPath: snapshotPath })) {
124
+ rawsSeen.push(r);
125
+ }
126
+ expect(rawsSeen[0].originalId).toBe("android-contact:0r1-3A2B");
127
+ expect(rawsSeen[1].originalId).toBe("android-app:com.tencent.mm");
128
+
129
+ const persons = [];
130
+ const items = [];
131
+ for await (const raw of adapter.sync({ inputPath: snapshotPath })) {
132
+ const batch = adapter.normalize(raw);
133
+ persons.push(...batch.persons);
134
+ items.push(...batch.items);
135
+ }
136
+
137
+ expect(persons).toHaveLength(1);
138
+ const p = persons[0];
139
+ expect(p.id).toBe("person-android-0r1-3A2B");
140
+ expect(p.type).toBe(ENTITY_TYPES.PERSON);
141
+ expect(p.subtype).toBe(PERSON_SUBTYPES.CONTACT);
142
+ expect(p.names).toEqual(["妈妈"]);
143
+ expect(p.identifiers).toEqual({ phone: ["+8613800138000"] });
144
+ expect(p.extra).toEqual({ starred: true });
145
+ expect(p.relation).toBe("家庭");
146
+ expect(p.source.adapter).toBe(SYSTEM_DATA_ANDROID_NAME);
147
+ expect(p.source.capturedBy).toBe(CAPTURED_BY.API);
148
+ expect(p.source.capturedAt).toBe(1_700_000_000_000);
149
+ const pv = validatePerson(p);
150
+ expect(pv).toEqual({ valid: true, errors: [] });
151
+
152
+ expect(items).toHaveLength(1);
153
+ const i = items[0];
154
+ expect(i.id).toBe("item-android-app-com.tencent.mm");
155
+ expect(i.type).toBe(ENTITY_TYPES.ITEM);
156
+ expect(i.subtype).toBe(ITEM_SUBTYPES.OTHER);
157
+ expect(i.name).toBe("微信");
158
+ expect(i.category).toBe("user-app");
159
+ expect(i.extra.kind).toBe("installed_app");
160
+ expect(i.extra.packageName).toBe("com.tencent.mm");
161
+ expect(i.extra.versionCode).toBe(2200);
162
+ expect(i.extra.firstInstallTime).toBe(1_650_000_000_000);
163
+ expect(i.extra.isSystem).toBe(false);
164
+ const iv = validateItem(i);
165
+ expect(iv).toEqual({ valid: true, errors: [] });
166
+ });
167
+
168
+ it("dedupes by stable lookupKey — same key across syncs returns same id", async () => {
169
+ writeSnapshot({
170
+ schemaVersion: SNAPSHOT_SCHEMA_VERSION,
171
+ contacts: [{ lookupKey: "abc", displayName: "Alice", phones: [], emails: [] }],
172
+ apps: [],
173
+ });
174
+ const adapter = new SystemDataAndroidAdapter();
175
+ const ids = [];
176
+ for (let pass = 0; pass < 2; pass++) {
177
+ for await (const raw of adapter.sync({ inputPath: snapshotPath })) {
178
+ const batch = adapter.normalize(raw);
179
+ if (batch.persons[0]) ids.push(batch.persons[0].id);
180
+ }
181
+ }
182
+ expect(ids).toEqual(["person-android-abc", "person-android-abc"]);
183
+ });
184
+
185
+ it("falls back to displayName when lookupKey missing", async () => {
186
+ writeSnapshot({
187
+ schemaVersion: SNAPSHOT_SCHEMA_VERSION,
188
+ contacts: [{ displayName: "Bob", phones: [], emails: [] }],
189
+ apps: [],
190
+ });
191
+ const adapter = new SystemDataAndroidAdapter();
192
+ let id;
193
+ for await (const raw of adapter.sync({ inputPath: snapshotPath })) {
194
+ id = adapter.normalize(raw).persons[0]?.id;
195
+ }
196
+ expect(id).toBe("person-android-Bob");
197
+ });
198
+
199
+ it("honors include filter — apps only", async () => {
200
+ writeSnapshot({
201
+ schemaVersion: SNAPSHOT_SCHEMA_VERSION,
202
+ contacts: [{ lookupKey: "k", displayName: "X", phones: [], emails: [] }],
203
+ apps: [
204
+ { packageName: "com.x", label: "X", versionName: "1", versionCode: 1, isSystem: false },
205
+ ],
206
+ });
207
+ const adapter = new SystemDataAndroidAdapter();
208
+ const kinds = [];
209
+ for await (const raw of adapter.sync({
210
+ inputPath: snapshotPath,
211
+ include: { contacts: false, apps: true },
212
+ })) {
213
+ kinds.push(raw.kind);
214
+ }
215
+ expect(kinds).toEqual(["app"]);
216
+ });
217
+
218
+ it("honors limit option", async () => {
219
+ writeSnapshot({
220
+ schemaVersion: SNAPSHOT_SCHEMA_VERSION,
221
+ contacts: [
222
+ { lookupKey: "a", displayName: "A", phones: [], emails: [] },
223
+ { lookupKey: "b", displayName: "B", phones: [], emails: [] },
224
+ { lookupKey: "c", displayName: "C", phones: [], emails: [] },
225
+ ],
226
+ apps: [],
227
+ });
228
+ const adapter = new SystemDataAndroidAdapter();
229
+ let count = 0;
230
+ for await (const _raw of adapter.sync({ inputPath: snapshotPath, limit: 2 })) {
231
+ count += 1;
232
+ }
233
+ expect(count).toBe(2);
234
+ });
235
+ });
236
+
237
+ describe("SystemDataAndroidAdapter — degenerate snapshots", () => {
238
+ it("anonymous contact gets placeholder name", () => {
239
+ const adapter = new SystemDataAndroidAdapter();
240
+ const batch = adapter.normalize({
241
+ kind: "contact",
242
+ capturedAt: 1_700_000_000_000,
243
+ payload: { lookupKey: "x" },
244
+ });
245
+ expect(batch.persons[0].names).toEqual(["(无名联系人)"]);
246
+ });
247
+
248
+ it("system app gets category 'system-app'", () => {
249
+ const adapter = new SystemDataAndroidAdapter();
250
+ const batch = adapter.normalize({
251
+ kind: "app",
252
+ capturedAt: 1_700_000_000_000,
253
+ payload: { packageName: "com.android.settings", label: "Settings", isSystem: true },
254
+ });
255
+ expect(batch.items[0].category).toBe("system-app");
256
+ expect(batch.items[0].extra.isSystem).toBe(true);
257
+ });
258
+
259
+ it("throws on unknown raw.kind", () => {
260
+ const adapter = new SystemDataAndroidAdapter();
261
+ expect(() =>
262
+ adapter.normalize({ kind: "mystery", capturedAt: 1, payload: {} })
263
+ ).toThrow(/unknown raw.kind/);
264
+ });
265
+ });
266
+
267
+ // ─── Bridge-direct mode (A8 follow-up) ────────────────────────────────
268
+ //
269
+ // When `cc-android-bridge` is loaded inside in-APK cc, the adapter can pull
270
+ // directly from ContentResolver / PackageManager instead of waiting for the
271
+ // UI to write a snapshot file. These tests inject a mock bridge to exercise
272
+ // the new path without a real device.
273
+
274
+ describe("SystemDataAndroidAdapter — bridge-direct sync", () => {
275
+ function makeBridge({ contacts = [], apps = [], throws = null } = {}) {
276
+ return {
277
+ caps: () => ({ available: true, reason: "test" }),
278
+ invoke: async (method) => {
279
+ if (throws) throw throws;
280
+ if (method === "contacts.query") return { contacts };
281
+ if (method === "app.list") return { apps };
282
+ throw new Error("unexpected method " + method);
283
+ },
284
+ };
285
+ }
286
+
287
+ it("useBridge=true pulls contacts and apps via bridge.invoke", async () => {
288
+ const adapter = new SystemDataAndroidAdapter();
289
+ const bridge = makeBridge({
290
+ contacts: [
291
+ { lookupKey: "ck-1", displayName: "妈妈", phones: ["13800000001"] },
292
+ { lookupKey: "ck-2", displayName: "同事" },
293
+ ],
294
+ apps: [
295
+ { packageName: "com.tencent.mm", label: "微信", versionName: "8.0", isSystem: false },
296
+ ],
297
+ });
298
+ adapter._deps.bridgeProvider = () => bridge;
299
+
300
+ const out = [];
301
+ for await (const r of adapter.sync({ useBridge: true })) out.push(r);
302
+ expect(out).toHaveLength(3);
303
+ expect(out[0].kind).toBe("contact");
304
+ expect(out[0].payload.displayName).toBe("妈妈");
305
+ expect(out[2].kind).toBe("app");
306
+ expect(out[2].payload.packageName).toBe("com.tencent.mm");
307
+ });
308
+
309
+ it("auto-engages bridge when inputPath omitted AND bridge.available", async () => {
310
+ const adapter = new SystemDataAndroidAdapter();
311
+ adapter._deps.bridgeProvider = () => makeBridge({
312
+ contacts: [{ lookupKey: "auto", displayName: "Auto" }],
313
+ });
314
+ const out = [];
315
+ for await (const r of adapter.sync({})) out.push(r);
316
+ expect(out).toHaveLength(1);
317
+ expect(out[0].payload.displayName).toBe("Auto");
318
+ });
319
+
320
+ it("respects include.contacts=false in bridge mode", async () => {
321
+ const adapter = new SystemDataAndroidAdapter();
322
+ adapter._deps.bridgeProvider = () => makeBridge({
323
+ contacts: [{ displayName: "should be skipped" }],
324
+ apps: [{ packageName: "com.kept" }],
325
+ });
326
+ const out = [];
327
+ for await (const r of adapter.sync({ useBridge: true, include: { contacts: false } })) {
328
+ out.push(r);
329
+ }
330
+ expect(out).toHaveLength(1);
331
+ expect(out[0].kind).toBe("app");
332
+ });
333
+
334
+ it("limit caps bridge yields", async () => {
335
+ const adapter = new SystemDataAndroidAdapter();
336
+ const many = Array.from({ length: 10 }, (_, i) => ({ displayName: `c${i}` }));
337
+ adapter._deps.bridgeProvider = () => makeBridge({ contacts: many });
338
+ const out = [];
339
+ for await (const r of adapter.sync({ useBridge: true, limit: 3 })) out.push(r);
340
+ expect(out).toHaveLength(3);
341
+ });
342
+
343
+ it("throws when useBridge=true but bridge missing", async () => {
344
+ const adapter = new SystemDataAndroidAdapter();
345
+ adapter._deps.bridgeProvider = () => null;
346
+ const it = adapter.sync({ useBridge: true });
347
+ await expect(it.next()).rejects.toThrow(/cc-android-bridge is not loaded/);
348
+ });
349
+
350
+ it("propagates bridge.invoke errors", async () => {
351
+ const adapter = new SystemDataAndroidAdapter();
352
+ adapter._deps.bridgeProvider = () =>
353
+ makeBridge({ throws: new Error("ANDROID_BRIDGE_NOT_AVAILABLE: not-on-android") });
354
+ const it = adapter.sync({ useBridge: true });
355
+ await expect(it.next()).rejects.toThrow(/ANDROID_BRIDGE_NOT_AVAILABLE/);
356
+ });
357
+
358
+ it("accepts bare array response from bridge (contacts as Array)", async () => {
359
+ const adapter = new SystemDataAndroidAdapter();
360
+ adapter._deps.bridgeProvider = () => ({
361
+ caps: () => ({ available: true }),
362
+ invoke: async (method) => {
363
+ if (method === "contacts.query") return [{ displayName: "Bare" }];
364
+ if (method === "app.list") return [];
365
+ return [];
366
+ },
367
+ });
368
+ const out = [];
369
+ for await (const r of adapter.sync({ useBridge: true })) out.push(r);
370
+ expect(out).toHaveLength(1);
371
+ expect(out[0].payload.displayName).toBe("Bare");
372
+ });
373
+
374
+ it("inputPath snapshot mode still works when bridgeProvider returns null", async () => {
375
+ writeSnapshot({
376
+ schemaVersion: SNAPSHOT_SCHEMA_VERSION,
377
+ snapshottedAt: 1_700_000_000_000,
378
+ contacts: [{ lookupKey: "snap", displayName: "From Snapshot" }],
379
+ apps: [],
380
+ });
381
+ const adapter = new SystemDataAndroidAdapter();
382
+ const out = [];
383
+ for await (const r of adapter.sync({ inputPath: snapshotPath })) out.push(r);
384
+ expect(out).toHaveLength(1);
385
+ expect(out[0].payload.displayName).toBe("From Snapshot");
386
+ });
387
+ });
@@ -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
+ });