@chainlesschain/personal-data-hub 0.4.29 → 0.4.31

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 (199) hide show
  1. package/lib/forensics/qq-nt-collect.js +190 -0
  2. package/lib/prompt-builder.js +15 -1
  3. package/package.json +8 -3
  4. package/__tests__/adapter-guide.test.js +0 -47
  5. package/__tests__/adapter-spec.test.js +0 -78
  6. package/__tests__/adapters/ai-chat-cookie-capture-spec.test.js +0 -211
  7. package/__tests__/adapters/ai-chat-health-checker.test.js +0 -262
  8. package/__tests__/adapters/ai-chat-history.test.js +0 -396
  9. package/__tests__/adapters/ai-chat-http-client.test.js +0 -242
  10. package/__tests__/adapters/ai-chat-vendors.test.js +0 -874
  11. package/__tests__/adapters/alipay-bill-adapter.test.js +0 -538
  12. package/__tests__/adapters/apple-health.test.js +0 -95
  13. package/__tests__/adapters/bank-family.test.js +0 -125
  14. package/__tests__/adapters/biz-tianyancha.test.js +0 -159
  15. package/__tests__/adapters/browser-history-chrome.test.js +0 -377
  16. package/__tests__/adapters/browser-history-edge.test.js +0 -159
  17. package/__tests__/adapters/car-mercedesme.test.js +0 -74
  18. package/__tests__/adapters/doc-baidu-netdisk.test.js +0 -102
  19. package/__tests__/adapters/doc-camscanner.test.js +0 -147
  20. package/__tests__/adapters/doc-platforms.test.js +0 -177
  21. package/__tests__/adapters/edu-huawei-learning-live.test.js +0 -198
  22. package/__tests__/adapters/edu-zuoyebang-live.test.js +0 -226
  23. package/__tests__/adapters/email-adapter-snapshot.test.js +0 -237
  24. package/__tests__/adapters/email-adapter.test.js +0 -742
  25. package/__tests__/adapters/email-classifier.test.js +0 -347
  26. package/__tests__/adapters/email-imap-session.test.js +0 -334
  27. package/__tests__/adapters/email-parser.test.js +0 -244
  28. package/__tests__/adapters/email-pdf-extractor.test.js +0 -529
  29. package/__tests__/adapters/email-providers.test.js +0 -84
  30. package/__tests__/adapters/email-retry-progress.test.js +0 -294
  31. package/__tests__/adapters/email-templates.test.js +0 -822
  32. package/__tests__/adapters/family-23-collectors-scaffold.test.js +0 -182
  33. package/__tests__/adapters/finance-alipay-live.test.js +0 -258
  34. package/__tests__/adapters/finance-dcep.test.js +0 -74
  35. package/__tests__/adapters/fitness-joyrun.test.js +0 -82
  36. package/__tests__/adapters/game-genshin-live.test.js +0 -238
  37. package/__tests__/adapters/game-genshin-scaffold.test.js +0 -108
  38. package/__tests__/adapters/game-honor-of-kings-live.test.js +0 -230
  39. package/__tests__/adapters/git-activity.test.js +0 -222
  40. package/__tests__/adapters/gov-12123.test.js +0 -103
  41. package/__tests__/adapters/gov-ixiamen.test.js +0 -150
  42. package/__tests__/adapters/gov-tax.test.js +0 -135
  43. package/__tests__/adapters/health-meiyou.test.js +0 -125
  44. package/__tests__/adapters/local-files.test.js +0 -264
  45. package/__tests__/adapters/local-im-pc.test.js +0 -154
  46. package/__tests__/adapters/messaging-whatsapp.test.js +0 -289
  47. package/__tests__/adapters/music-kugou.test.js +0 -187
  48. package/__tests__/adapters/music-qq.test.js +0 -112
  49. package/__tests__/adapters/netease-music-live.test.js +0 -244
  50. package/__tests__/adapters/netease-music.test.js +0 -74
  51. package/__tests__/adapters/pc-local-discovery.test.js +0 -141
  52. package/__tests__/adapters/qq-pc-direct-read.test.js +0 -227
  53. package/__tests__/adapters/reading-family.test.js +0 -108
  54. package/__tests__/adapters/recruit-boss.test.js +0 -180
  55. package/__tests__/adapters/shell-history.test.js +0 -180
  56. package/__tests__/adapters/shopping-base.test.js +0 -179
  57. package/__tests__/adapters/shopping-dianping.test.js +0 -239
  58. package/__tests__/adapters/social-bilibili-adb-api-client.test.js +0 -721
  59. package/__tests__/adapters/social-bilibili-adb-chromium-cookies-reader.test.js +0 -346
  60. package/__tests__/adapters/social-bilibili-adb-collector.test.js +0 -284
  61. package/__tests__/adapters/social-bilibili-adb-cookies-extension.test.js +0 -343
  62. package/__tests__/adapters/social-bilibili-adb-snapshot-builder.test.js +0 -296
  63. package/__tests__/adapters/social-csdn.test.js +0 -175
  64. package/__tests__/adapters/social-dongchedi.test.js +0 -165
  65. package/__tests__/adapters/social-douyin-adb-aweme-detail.test.js +0 -165
  66. package/__tests__/adapters/social-douyin-adb-collector.test.js +0 -254
  67. package/__tests__/adapters/social-douyin-adb-db-extension.test.js +0 -114
  68. package/__tests__/adapters/social-douyin-adb-im-db-parser.test.js +0 -304
  69. package/__tests__/adapters/social-douyin-adb-snapshot-builder.test.js +0 -216
  70. package/__tests__/adapters/social-douyin-adb-usage-profile.test.js +0 -229
  71. package/__tests__/adapters/social-douyin-adb-watch-history.test.js +0 -269
  72. package/__tests__/adapters/social-kuaishou-adb-api-client.test.js +0 -496
  73. package/__tests__/adapters/social-kuaishou-adb-collector.test.js +0 -276
  74. package/__tests__/adapters/social-kuaishou-adb-cookies-extension.test.js +0 -152
  75. package/__tests__/adapters/social-kuaishou-adb-snapshot-builder.test.js +0 -178
  76. package/__tests__/adapters/social-toutiao-adb-account-reader.test.js +0 -135
  77. package/__tests__/adapters/social-toutiao-adb-api-client.test.js +0 -626
  78. package/__tests__/adapters/social-toutiao-adb-article.test.js +0 -155
  79. package/__tests__/adapters/social-toutiao-adb-collector.test.js +0 -378
  80. package/__tests__/adapters/social-toutiao-adb-cookies-extension.test.js +0 -193
  81. package/__tests__/adapters/social-toutiao-adb-snapshot-builder.test.js +0 -196
  82. package/__tests__/adapters/social-toutiao-kuaishou-scaffold.test.js +0 -311
  83. package/__tests__/adapters/social-weibo-adb-api-client.test.js +0 -362
  84. package/__tests__/adapters/social-weibo-adb-collector.test.js +0 -201
  85. package/__tests__/adapters/social-weibo-adb-cookies-extension.test.js +0 -167
  86. package/__tests__/adapters/social-weibo-adb-snapshot-builder.test.js +0 -189
  87. package/__tests__/adapters/social-xiaohongshu-adb-api-client.test.js +0 -431
  88. package/__tests__/adapters/social-xiaohongshu-adb-collector.test.js +0 -207
  89. package/__tests__/adapters/social-xiaohongshu-adb-cookies-extension.test.js +0 -0
  90. package/__tests__/adapters/social-xiaohongshu-adb-sign-provider-injection.test.js +0 -351
  91. package/__tests__/adapters/social-xiaohongshu-adb-sign.test.js +0 -130
  92. package/__tests__/adapters/social-xiaohongshu-adb-snapshot-builder.test.js +0 -200
  93. package/__tests__/adapters/social-zhihu.test.js +0 -246
  94. package/__tests__/adapters/system-data-adapter.test.js +0 -443
  95. package/__tests__/adapters/system-data-android-ingest.test.js +0 -144
  96. package/__tests__/adapters/system-data-android.test.js +0 -519
  97. package/__tests__/adapters/system-data-disclosure.test.js +0 -153
  98. package/__tests__/adapters/travel-12306.test.js +0 -512
  99. package/__tests__/adapters/travel-amap.test.js +0 -219
  100. package/__tests__/adapters/travel-baidu-map.test.js +0 -305
  101. package/__tests__/adapters/travel-base.test.js +0 -205
  102. package/__tests__/adapters/travel-ctrip.test.js +0 -377
  103. package/__tests__/adapters/travel-didi-consumer.test.js +0 -66
  104. package/__tests__/adapters/travel-didi.test.js +0 -204
  105. package/__tests__/adapters/travel-tencent-map.test.js +0 -207
  106. package/__tests__/adapters/travel-tongcheng.test.js +0 -289
  107. package/__tests__/adapters/video-platforms.test.js +0 -152
  108. package/__tests__/adapters/video-xigua.test.js +0 -106
  109. package/__tests__/adapters/vscode.test.js +0 -299
  110. package/__tests__/adapters/wechat-bootstrap.test.js +0 -240
  111. package/__tests__/adapters/wechat-env-probe.test.js +0 -162
  112. package/__tests__/adapters/wechat-frida-agent.test.js +0 -322
  113. package/__tests__/adapters/wechat-frida-integration.test.js +0 -149
  114. package/__tests__/adapters/wechat-frida-key-provider.test.js +0 -188
  115. package/__tests__/adapters/wechat-md5-key-provider.test.js +0 -101
  116. package/__tests__/adapters/wechat-pc-direct-read.test.js +0 -365
  117. package/__tests__/adapters/wechat-pc-group-topic.test.js +0 -63
  118. package/__tests__/adapters/wechat-pc-v4-sidecar.test.js +0 -72
  119. package/__tests__/adapters/weread.test.js +0 -123
  120. package/__tests__/adapters/wework-pc.test.js +0 -124
  121. package/__tests__/adapters/win-recent.test.js +0 -192
  122. package/__tests__/analysis-skills.test.js +0 -754
  123. package/__tests__/analysis.test.js +0 -1845
  124. package/__tests__/audio-ximalaya-snapshot.test.js +0 -279
  125. package/__tests__/batch.test.js +0 -133
  126. package/__tests__/bridges-cc-kg.test.js +0 -231
  127. package/__tests__/bridges-cc-llm.test.js +0 -191
  128. package/__tests__/bridges-cc-rag.test.js +0 -162
  129. package/__tests__/categories.test.js +0 -92
  130. package/__tests__/e2e/ai-chat-cross-source-journey.test.js +0 -213
  131. package/__tests__/e2e/full-user-journey.test.js +0 -188
  132. package/__tests__/e2e/local-data-adapters-cli.e2e.test.js +0 -146
  133. package/__tests__/entity-resolver-ingest-hook.test.js +0 -177
  134. package/__tests__/entity-resolver-stages.test.js +0 -411
  135. package/__tests__/entity-resolver-vault.test.js +0 -249
  136. package/__tests__/entity-resolver.test.js +0 -526
  137. package/__tests__/fitness-keep-snapshot.test.js +0 -224
  138. package/__tests__/fixtures/entity-resolver-200-mock.json +0 -96
  139. package/__tests__/ids.test.js +0 -45
  140. package/__tests__/integration/ai-chat-history-registry.test.js +0 -228
  141. package/__tests__/integration/aichat-wizard-end-to-end.test.js +0 -282
  142. package/__tests__/integration/cross-adapter-pipelines.test.js +0 -396
  143. package/__tests__/integration/local-data-adapters-pipeline.test.js +0 -373
  144. package/__tests__/integration/social-bilibili-pipeline.test.js +0 -261
  145. package/__tests__/integration/wechat-bootstrap-end-to-end.test.js +0 -390
  146. package/__tests__/key-providers.test.js +0 -126
  147. package/__tests__/kg-derive.test.js +0 -219
  148. package/__tests__/llm-client.test.js +0 -122
  149. package/__tests__/longtail-adapters.test.js +0 -281
  150. package/__tests__/messaging-qq-snapshot.test.js +0 -294
  151. package/__tests__/mobile-extractor-encrypted.test.js +0 -460
  152. package/__tests__/mobile-extractor.test.js +0 -288
  153. package/__tests__/mock-adapter.test.js +0 -93
  154. package/__tests__/prompt-builder.test.js +0 -249
  155. package/__tests__/query-parser.test.js +0 -365
  156. package/__tests__/rag-derive.test.js +0 -169
  157. package/__tests__/registry-readiness.test.js +0 -292
  158. package/__tests__/registry.test.js +0 -420
  159. package/__tests__/salvage-ingest.test.js +0 -97
  160. package/__tests__/schemas.test.js +0 -331
  161. package/__tests__/shopping-adapters.test.js +0 -392
  162. package/__tests__/shopping-eleme-snapshot.test.js +0 -454
  163. package/__tests__/shopping-pinduoduo-snapshot.test.js +0 -484
  164. package/__tests__/shopping-snapshot.test.js +0 -438
  165. package/__tests__/shopping-vipshop-snapshot.test.js +0 -425
  166. package/__tests__/shopping-xianyu-snapshot.test.js +0 -451
  167. package/__tests__/sidecar-contacts-cross-validate.test.js +0 -186
  168. package/__tests__/sidecar-supervisor.test.js +0 -128
  169. package/__tests__/sign-providers.test.js +0 -62
  170. package/__tests__/social-adapters.test.js +0 -280
  171. package/__tests__/social-bilibili-snapshot.test.js +0 -278
  172. package/__tests__/social-douban-snapshot.test.js +0 -351
  173. package/__tests__/social-douyin-im-direct-read.test.js +0 -377
  174. package/__tests__/social-douyin-salvage-collector.test.js +0 -98
  175. package/__tests__/social-douyin-salvage-mapper.test.js +0 -90
  176. package/__tests__/social-douyin-snapshot.test.js +0 -256
  177. package/__tests__/social-kuaishou-snapshot.test.js +0 -362
  178. package/__tests__/social-toutiao-snapshot.test.js +0 -366
  179. package/__tests__/social-weibo-snapshot.test.js +0 -234
  180. package/__tests__/social-weibo-sqlite-device.test.js +0 -174
  181. package/__tests__/social-xiaohongshu-snapshot.test.js +0 -232
  182. package/__tests__/sqlite-leaf-salvage.test.js +0 -97
  183. package/__tests__/travel-adapters.test.js +0 -483
  184. package/__tests__/travel-maps-snapshot.test.js +0 -426
  185. package/__tests__/vault-driver-error.test.js +0 -74
  186. package/__tests__/vault-search-helpers.test.js +0 -104
  187. package/__tests__/vault-search.test.js +0 -423
  188. package/__tests__/vault.test.js +0 -767
  189. package/__tests__/wechat-adapter.test.js +0 -594
  190. package/__tests__/whatsapp-adapter.test.js +0 -138
  191. package/scripts/_make-fixture-all.js +0 -126
  192. package/scripts/_make-fixture-contacts.js +0 -84
  193. package/scripts/evaluate-entity-resolver.js +0 -213
  194. package/scripts/run-native-tests-sandbox.sh +0 -55
  195. package/scripts/smoke-phase-5-5.js +0 -196
  196. package/scripts/smoke-phase-5-7.js +0 -181
  197. package/scripts/smoke-system-data-contacts.js +0 -309
  198. package/scripts/smoke-system-data.js +0 -312
  199. package/vitest.config.js +0 -88
@@ -1,346 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * Phase 1a (Bilibili C 路径) — unit cover for the chromium-cookies-reader.
5
- *
6
- * Builds a real chromium-shape Cookies sqlite via better-sqlite3 (the
7
- * test path that browser-history-chrome.test.js uses — root Node ABI
8
- * 127 matches plain better-sqlite3, no FTS5 / encryption needed). All
9
- * tests run in <1s on CI.
10
- *
11
- * Covered:
12
- * - hostKeyMatches across .domain / domain / subdomain / non-match
13
- * - readChromiumCookies filtering by domain
14
- * - Cookie schema column tolerance (encrypted_value / is_secure /
15
- * is_persistent missing — old or aggressively-pruned WebView builds)
16
- * - assembleBilibiliCookieHeader: complete / missing-required / dup-name
17
- * - encrypted_value rows skipped + diagnostic counter
18
- * - corrupted DB / wrong-schema DB → clear error
19
- */
20
-
21
- import { describe, it, expect, beforeEach, afterEach } from "vitest";
22
- import { mkdtempSync, rmSync } from "node:fs";
23
- import { join } from "node:path";
24
- import { tmpdir } from "node:os";
25
- import Database from "better-sqlite3";
26
-
27
- const {
28
- readChromiumCookies,
29
- assembleBilibiliCookieHeader,
30
- BILIBILI_COOKIE_NAMES,
31
- _internals,
32
- } = require("../../lib/adapters/social-bilibili-adb/chromium-cookies-reader");
33
-
34
- let tmpDir;
35
- let dbPath;
36
-
37
- beforeEach(() => {
38
- tmpDir = mkdtempSync(join(tmpdir(), "cc-cookies-test-"));
39
- dbPath = join(tmpDir, "Cookies");
40
- });
41
-
42
- afterEach(() => {
43
- try {
44
- rmSync(tmpDir, { recursive: true, force: true });
45
- } catch (_e) {
46
- // ignore — temp cleanup is best-effort
47
- }
48
- });
49
-
50
- /**
51
- * Build a chromium-shape Cookies sqlite at [dbPath]. Optionally omit
52
- * encrypted_value column (`{omitEncrypted: true}`) to simulate older
53
- * Android WebView schemas that didn't have it.
54
- */
55
- function buildCookiesFixture(rows, { omitEncrypted = false, omitSecure = false } = {}) {
56
- const db = new Database(dbPath);
57
- const cols = [
58
- "creation_utc INTEGER",
59
- "host_key TEXT",
60
- "name TEXT",
61
- "value TEXT",
62
- omitEncrypted ? null : "encrypted_value BLOB",
63
- "path TEXT",
64
- "expires_utc INTEGER",
65
- omitSecure ? null : "is_secure INTEGER",
66
- "is_httponly INTEGER",
67
- "is_persistent INTEGER",
68
- ].filter(Boolean).join(", ");
69
- db.exec(`CREATE TABLE cookies(${cols});`);
70
- const params = [
71
- "creation_utc",
72
- "host_key",
73
- "name",
74
- "value",
75
- omitEncrypted ? null : "encrypted_value",
76
- "path",
77
- "expires_utc",
78
- omitSecure ? null : "is_secure",
79
- "is_httponly",
80
- "is_persistent",
81
- ].filter(Boolean);
82
- const placeholders = params.map(() => "?").join(", ");
83
- const insert = db.prepare(
84
- `INSERT INTO cookies(${params.join(", ")}) VALUES(${placeholders})`,
85
- );
86
- for (const r of rows) {
87
- const values = [
88
- r.creationUtc || 0,
89
- r.hostKey,
90
- r.name,
91
- r.value || "",
92
- ...(omitEncrypted ? [] : [r.encryptedValue || null]),
93
- r.path || "/",
94
- r.expiresUtc || 0,
95
- ...(omitSecure ? [] : [r.isSecure ? 1 : 0]),
96
- r.isHttpOnly ? 1 : 0,
97
- r.isPersistent ? 1 : 0,
98
- ];
99
- insert.run(...values);
100
- }
101
- db.close();
102
- }
103
-
104
- // ─── hostKeyMatches ─────────────────────────────────────────────────────
105
-
106
- describe("hostKeyMatches", () => {
107
- it("matches exact host_key against domain", () => {
108
- expect(_internals.hostKeyMatches("bilibili.com", "bilibili.com")).toBe(true);
109
- });
110
-
111
- it("matches leading-dot host_key (most common)", () => {
112
- expect(_internals.hostKeyMatches(".bilibili.com", "bilibili.com")).toBe(true);
113
- });
114
-
115
- it("matches subdomain host_key", () => {
116
- expect(_internals.hostKeyMatches(".api.bilibili.com", "bilibili.com")).toBe(true);
117
- expect(_internals.hostKeyMatches("api.bilibili.com", "bilibili.com")).toBe(true);
118
- });
119
-
120
- it("matches when both have leading dot", () => {
121
- expect(_internals.hostKeyMatches(".bilibili.com", ".bilibili.com")).toBe(true);
122
- });
123
-
124
- it("rejects unrelated domain", () => {
125
- expect(_internals.hostKeyMatches(".weibo.com", "bilibili.com")).toBe(false);
126
- });
127
-
128
- it("rejects partial-name collisions (bilibili.com.evil.cn)", () => {
129
- // The domain check uses dot-anchored suffix, so foo.com matching
130
- // foo.com.evil.cn is impossible.
131
- expect(_internals.hostKeyMatches(".bilibili.com.evil.cn", "bilibili.com")).toBe(false);
132
- });
133
-
134
- it("rejects null / undefined / empty", () => {
135
- expect(_internals.hostKeyMatches(null, "bilibili.com")).toBe(false);
136
- expect(_internals.hostKeyMatches(".bilibili.com", null)).toBe(false);
137
- expect(_internals.hostKeyMatches("", "bilibili.com")).toBe(false);
138
- });
139
- });
140
-
141
- // ─── readChromiumCookies ────────────────────────────────────────────────
142
-
143
- describe("readChromiumCookies", () => {
144
- it("returns only cookies matching the domain filter", () => {
145
- buildCookiesFixture([
146
- { hostKey: ".bilibili.com", name: "SESSDATA", value: "abc123" },
147
- { hostKey: ".weibo.com", name: "SUB", value: "wbxx" },
148
- { hostKey: ".bilibili.com", name: "bili_jct", value: "csrf456" },
149
- ]);
150
- const out = readChromiumCookies(dbPath, "bilibili.com");
151
- expect(out).toHaveLength(2);
152
- expect(out.map((r) => r.name).sort()).toEqual(["SESSDATA", "bili_jct"]);
153
- });
154
-
155
- it("handles subdomain-pinned cookies", () => {
156
- buildCookiesFixture([
157
- { hostKey: "api.bilibili.com", name: "PinnedCookie", value: "x" },
158
- { hostKey: ".bilibili.com", name: "SESSDATA", value: "y" },
159
- ]);
160
- const out = readChromiumCookies(dbPath, "bilibili.com");
161
- expect(out).toHaveLength(2);
162
- });
163
-
164
- it("skips encrypted_value rows + reports count", () => {
165
- buildCookiesFixture([
166
- { hostKey: ".bilibili.com", name: "SESSDATA", value: "plain" },
167
- {
168
- hostKey: ".bilibili.com",
169
- name: "EncryptedThing",
170
- value: "", // empty plaintext
171
- encryptedValue: Buffer.from("garbled-bytes"),
172
- },
173
- ]);
174
- const out = readChromiumCookies(dbPath, "bilibili.com");
175
- expect(out).toHaveLength(1);
176
- expect(out[0].name).toBe("SESSDATA");
177
- expect(out._skippedEncryptedCount).toBe(1);
178
- });
179
-
180
- it("works on schema without encrypted_value column", () => {
181
- buildCookiesFixture(
182
- [{ hostKey: ".bilibili.com", name: "SESSDATA", value: "x" }],
183
- { omitEncrypted: true },
184
- );
185
- const out = readChromiumCookies(dbPath, "bilibili.com");
186
- expect(out).toHaveLength(1);
187
- expect(out[0].hasEncryptedValue).toBe(false);
188
- });
189
-
190
- it("works on schema without is_secure column", () => {
191
- buildCookiesFixture(
192
- [{ hostKey: ".bilibili.com", name: "SESSDATA", value: "x" }],
193
- { omitSecure: true },
194
- );
195
- const out = readChromiumCookies(dbPath, "bilibili.com");
196
- expect(out[0].isSecure).toBe(false); // defaulted to 0 by COALESCE
197
- });
198
-
199
- it("converts WebKit expires_utc to epoch ms", () => {
200
- // 2026-05-25 00:00:00 UTC = 1779999600000 ms epoch
201
- // = 13422518400000000 µs WebKit (epoch + 11644473600 * 1e6)
202
- const expiresMs = 1779999600000;
203
- const expiresWk = (BigInt(expiresMs) * 1000n + 11_644_473_600_000_000n).toString();
204
- buildCookiesFixture([
205
- {
206
- hostKey: ".bilibili.com",
207
- name: "SESSDATA",
208
- value: "x",
209
- expiresUtc: expiresWk,
210
- },
211
- ]);
212
- const out = readChromiumCookies(dbPath, "bilibili.com");
213
- expect(out[0].expiresMs).toBe(expiresMs);
214
- });
215
-
216
- it("throws clear error when cookies table missing (not a Cookies DB)", () => {
217
- const db = new Database(dbPath);
218
- db.exec("CREATE TABLE not_cookies(x INTEGER);");
219
- db.close();
220
- // PRAGMA table_info(<nonexistent>) returns empty rather than throwing
221
- // on SQLite, so we hit the "empty / unreadable" branch. Either message
222
- // is fine for the caller's purpose — both mean "not a Cookies DB".
223
- expect(() => readChromiumCookies(dbPath, "bilibili.com")).toThrow(
224
- /cookies.*(table not found|table empty.*unreadable)/,
225
- );
226
- });
227
-
228
- it("throws clear error when required column missing", () => {
229
- const db = new Database(dbPath);
230
- db.exec("CREATE TABLE cookies(creation_utc INTEGER, host_key TEXT);");
231
- db.close();
232
- expect(() => readChromiumCookies(dbPath, "bilibili.com")).toThrow(
233
- /required column.*missing/,
234
- );
235
- });
236
-
237
- it("rejects empty dbPath", () => {
238
- expect(() => readChromiumCookies("", "bilibili.com")).toThrow(TypeError);
239
- });
240
-
241
- it("rejects empty domain", () => {
242
- buildCookiesFixture([{ hostKey: ".bilibili.com", name: "SESSDATA", value: "x" }]);
243
- expect(() => readChromiumCookies(dbPath, "")).toThrow(TypeError);
244
- });
245
- });
246
-
247
- // ─── assembleBilibiliCookieHeader ───────────────────────────────────────
248
-
249
- describe("assembleBilibiliCookieHeader", () => {
250
- function cookieRow(name, value, hostKey = ".bilibili.com") {
251
- return {
252
- name,
253
- value,
254
- hostKey,
255
- expiresMs: null,
256
- isSecure: false,
257
- isHttponly: true,
258
- isPersistent: true,
259
- hasEncryptedValue: false,
260
- };
261
- }
262
-
263
- it("assembles complete header when all 5 cookies present", () => {
264
- const cookies = [
265
- cookieRow("SESSDATA", "abc"),
266
- cookieRow("bili_jct", "csrf"),
267
- cookieRow("DedeUserID", "1234"),
268
- cookieRow("DedeUserID__ckMd5", "deadbeef"),
269
- cookieRow("buvid3", "buvid-x"),
270
- ];
271
- const { header, missing, present } = assembleBilibiliCookieHeader(cookies);
272
- expect(missing).toEqual([]);
273
- expect(header).toBe(
274
- "SESSDATA=abc; bili_jct=csrf; DedeUserID=1234; DedeUserID__ckMd5=deadbeef; buvid3=buvid-x",
275
- );
276
- expect(present).toEqual(new Set(BILIBILI_COOKIE_NAMES));
277
- });
278
-
279
- it("returns null header + missing list when any required cookie absent", () => {
280
- const cookies = [
281
- cookieRow("SESSDATA", "abc"),
282
- cookieRow("bili_jct", "csrf"),
283
- // missing DedeUserID, DedeUserID__ckMd5, buvid3
284
- ];
285
- const { header, missing } = assembleBilibiliCookieHeader(cookies);
286
- expect(header).toBe(null);
287
- expect(missing.sort()).toEqual(["DedeUserID", "DedeUserID__ckMd5", "buvid3"].sort());
288
- });
289
-
290
- it("ignores non-bilibili cookies if accidentally passed in", () => {
291
- const cookies = [
292
- cookieRow("SESSDATA", "abc"),
293
- cookieRow("bili_jct", "csrf"),
294
- cookieRow("DedeUserID", "1234"),
295
- cookieRow("DedeUserID__ckMd5", "deadbeef"),
296
- cookieRow("buvid3", "buvid-x"),
297
- cookieRow("randomNoise", "ignored", ".weibo.com"),
298
- ];
299
- const { header } = assembleBilibiliCookieHeader(cookies);
300
- expect(header).not.toContain("randomNoise");
301
- expect(header).not.toContain("ignored");
302
- });
303
-
304
- it("prefers more-specific host_key on duplicate names", () => {
305
- const cookies = [
306
- cookieRow("SESSDATA", "shorter", ".bilibili.com"),
307
- cookieRow("SESSDATA", "longer", "api.bilibili.com"), // longer host wins
308
- cookieRow("bili_jct", "csrf"),
309
- cookieRow("DedeUserID", "1234"),
310
- cookieRow("DedeUserID__ckMd5", "deadbeef"),
311
- cookieRow("buvid3", "buvid-x"),
312
- ];
313
- const { header } = assembleBilibiliCookieHeader(cookies);
314
- expect(header).toContain("SESSDATA=longer");
315
- expect(header).not.toContain("SESSDATA=shorter");
316
- });
317
-
318
- it("throws TypeError when given non-array", () => {
319
- expect(() => assembleBilibiliCookieHeader(null)).toThrow(TypeError);
320
- expect(() => assembleBilibiliCookieHeader({})).toThrow(TypeError);
321
- });
322
-
323
- it("returns null header for empty cookie list (all 5 missing)", () => {
324
- const { header, missing } = assembleBilibiliCookieHeader([]);
325
- expect(header).toBe(null);
326
- expect(missing.length).toBe(BILIBILI_COOKIE_NAMES.length);
327
- });
328
- });
329
-
330
- // ─── BILIBILI_COOKIE_NAMES contract ─────────────────────────────────────
331
-
332
- describe("BILIBILI_COOKIE_NAMES", () => {
333
- it("is frozen", () => {
334
- expect(Object.isFrozen(BILIBILI_COOKIE_NAMES)).toBe(true);
335
- });
336
-
337
- it("contains the 5 expected names", () => {
338
- expect(BILIBILI_COOKIE_NAMES).toEqual([
339
- "SESSDATA",
340
- "bili_jct",
341
- "DedeUserID",
342
- "DedeUserID__ckMd5",
343
- "buvid3",
344
- ]);
345
- });
346
- });
@@ -1,284 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * Phase 1b — unit cover for the BilibiliAdbCollector orchestrator.
5
- *
6
- * Strategy: mock bridge + ApiClient + registry as plain objects so we
7
- * verify the orchestration logic (call order, error propagation,
8
- * partial-result tolerance, cleanup) without spawning real ADB or
9
- * hitting api.bilibili.com.
10
- *
11
- * What we cover:
12
- * - collect() — bridge.invoke → 4 fetches → snapshot file written
13
- * - collect() returns counts + diagnostic
14
- * - collect() rejects malformed bridge payload
15
- * - collect() propagates bridge.invoke errors
16
- * - collect() tolerates any-of-4 endpoint failure (partial)
17
- * - collect() tolerates ALL 4 endpoints empty (0-event snapshot)
18
- * - collectAndSync() — pipes snapshot to registry + always cleans up
19
- * - collectAndSync() cleanup happens even on syncAdapter throw
20
- */
21
-
22
- import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
23
- import { existsSync, readFileSync, mkdtempSync, rmSync } from "node:fs";
24
- import { join } from "node:path";
25
- import { tmpdir } from "node:os";
26
-
27
- const {
28
- collect,
29
- collectAndSync,
30
- } = require("../../lib/adapters/social-bilibili-adb/collector");
31
-
32
- let stagingDir;
33
-
34
- beforeEach(() => {
35
- stagingDir = mkdtempSync(join(tmpdir(), "cc-collector-test-"));
36
- });
37
-
38
- afterEach(() => {
39
- try {
40
- rmSync(stagingDir, { recursive: true, force: true });
41
- } catch (_e) {
42
- // ignore
43
- }
44
- });
45
-
46
- function makeFakeBridge(invokeResult) {
47
- return {
48
- invoke: vi.fn(async () => {
49
- if (invokeResult instanceof Error) throw invokeResult;
50
- return invokeResult;
51
- }),
52
- };
53
- }
54
-
55
- function makeFakeApiClient({
56
- history = [],
57
- favourites = [],
58
- dynamics = [],
59
- follows = [],
60
- lastErrorCode = 0,
61
- lastErrorMessage = null,
62
- } = {}) {
63
- return {
64
- fetchHistory: vi.fn(async () => history),
65
- fetchFavourites: vi.fn(async () => favourites),
66
- fetchDynamics: vi.fn(async () => dynamics),
67
- fetchFollows: vi.fn(async () => follows),
68
- lastErrorCode,
69
- lastErrorMessage,
70
- };
71
- }
72
-
73
- // ─── collect() ──────────────────────────────────────────────────────────
74
-
75
- describe("collect — happy path", () => {
76
- it("invokes bridge, fetches 4 endpoints, writes snapshot, returns counts", async () => {
77
- const bridge = makeFakeBridge({
78
- cookie: "SESSDATA=x; DedeUserID=1234567890; ...",
79
- uid: 1234567890,
80
- diagnostic: { cookieCount: 5 },
81
- });
82
- const apiClient = makeFakeApiClient({
83
- history: [{ bvid: "BV1", title: "h", viewAt: 1 }],
84
- favourites: [{ bvid: "BVf", title: "f", savedAt: 2 }],
85
- dynamics: [{ rid: "r1", summary: "d", dynamicType: "av", publishedAt: 3 }],
86
- follows: [{ mid: 1, uname: "u", followedAt: 4 }],
87
- });
88
- const result = await collect(bridge, { apiClient, stagingDir });
89
-
90
- expect(bridge.invoke).toHaveBeenCalledWith("bilibili.cookies");
91
- expect(apiClient.fetchHistory).toHaveBeenCalled();
92
- expect(apiClient.fetchFavourites).toHaveBeenCalledWith(
93
- "SESSDATA=x; DedeUserID=1234567890; ...",
94
- 1234567890,
95
- expect.any(Object),
96
- );
97
- expect(apiClient.fetchDynamics).toHaveBeenCalled();
98
- expect(apiClient.fetchFollows).toHaveBeenCalled();
99
-
100
- expect(result.uid).toBe(1234567890);
101
- expect(result.eventCounts).toEqual({
102
- history: 1,
103
- favourite: 1,
104
- dynamic: 1,
105
- follow: 1,
106
- total: 4,
107
- });
108
- expect(existsSync(result.snapshotPath)).toBe(true);
109
- const snap = JSON.parse(readFileSync(result.snapshotPath, "utf-8"));
110
- expect(snap.schemaVersion).toBe(1);
111
- expect(snap.events).toHaveLength(4);
112
- expect(result.cookieDiagnostic).toEqual({ cookieCount: 5 });
113
- });
114
-
115
- it("forwards lastErrorCode + lastErrorMessage from api client", async () => {
116
- const bridge = makeFakeBridge({ cookie: "x", uid: 1 });
117
- const apiClient = makeFakeApiClient({
118
- lastErrorCode: -412,
119
- lastErrorMessage: "anti-spider",
120
- });
121
- const result = await collect(bridge, { apiClient, stagingDir });
122
- expect(result.lastErrorCode).toBe(-412);
123
- expect(result.lastErrorMessage).toBe("anti-spider");
124
- });
125
-
126
- it("calls 4 endpoints in parallel (Promise.all)", async () => {
127
- const order = [];
128
- const apiClient = {
129
- fetchHistory: async () => {
130
- order.push("history-start");
131
- await new Promise((r) => setTimeout(r, 10));
132
- order.push("history-end");
133
- return [];
134
- },
135
- fetchFavourites: async () => {
136
- order.push("favourites-start");
137
- await new Promise((r) => setTimeout(r, 10));
138
- order.push("favourites-end");
139
- return [];
140
- },
141
- fetchDynamics: async () => {
142
- order.push("dynamics-start");
143
- await new Promise((r) => setTimeout(r, 10));
144
- order.push("dynamics-end");
145
- return [];
146
- },
147
- fetchFollows: async () => {
148
- order.push("follows-start");
149
- await new Promise((r) => setTimeout(r, 10));
150
- order.push("follows-end");
151
- return [];
152
- },
153
- lastErrorCode: 0,
154
- lastErrorMessage: null,
155
- };
156
- const bridge = makeFakeBridge({ cookie: "x", uid: 1 });
157
- await collect(bridge, { apiClient, stagingDir });
158
- // All 4 "start" events should fire before any "end" event (parallel)
159
- const firstEnd = order.findIndex((e) => e.endsWith("-end"));
160
- const startsBeforeFirstEnd = order.slice(0, firstEnd).filter((e) => e.endsWith("-start"));
161
- expect(startsBeforeFirstEnd).toHaveLength(4);
162
- });
163
- });
164
-
165
- describe("collect — failure modes", () => {
166
- it("propagates bridge.invoke error", async () => {
167
- const bridge = makeFakeBridge(new Error("BILIBILI_NO_ROOT: ..."));
168
- await expect(collect(bridge, { stagingDir })).rejects.toThrow(
169
- /BILIBILI_NO_ROOT/,
170
- );
171
- });
172
-
173
- it("throws TypeError when bridge missing invoke fn", async () => {
174
- await expect(collect(null, { stagingDir })).rejects.toThrow(TypeError);
175
- await expect(collect({}, { stagingDir })).rejects.toThrow(TypeError);
176
- });
177
-
178
- it("throws when bridge returns malformed payload", async () => {
179
- const bridge = makeFakeBridge({ cookie: null, uid: null });
180
- await expect(collect(bridge, { stagingDir })).rejects.toThrow(
181
- /malformed payload/,
182
- );
183
- });
184
-
185
- it("throws when uid is not positive", async () => {
186
- const bridge = makeFakeBridge({ cookie: "x", uid: 0 });
187
- await expect(collect(bridge, { stagingDir })).rejects.toThrow();
188
- });
189
- });
190
-
191
- describe("collect — partial result tolerance", () => {
192
- it("succeeds with 0 events when ALL 4 endpoints empty", async () => {
193
- const bridge = makeFakeBridge({ cookie: "x", uid: 1 });
194
- const apiClient = makeFakeApiClient(); // all empty
195
- const result = await collect(bridge, { apiClient, stagingDir });
196
- expect(result.eventCounts.total).toBe(0);
197
- expect(existsSync(result.snapshotPath)).toBe(true);
198
- });
199
-
200
- it("succeeds with partial event set when one endpoint fails (returns [])", async () => {
201
- const bridge = makeFakeBridge({ cookie: "x", uid: 1 });
202
- const apiClient = makeFakeApiClient({
203
- history: [{ bvid: "BV1", title: "h", viewAt: 1 }],
204
- favourites: [], // simulated failure
205
- dynamics: [],
206
- follows: [{ mid: 1, uname: "u", followedAt: 1 }],
207
- });
208
- const result = await collect(bridge, { apiClient, stagingDir });
209
- expect(result.eventCounts).toEqual({
210
- history: 1,
211
- favourite: 0,
212
- dynamic: 0,
213
- follow: 1,
214
- total: 2,
215
- });
216
- });
217
- });
218
-
219
- // ─── collectAndSync() ───────────────────────────────────────────────────
220
-
221
- describe("collectAndSync — pipes to registry + cleans up", () => {
222
- it("calls registry.syncAdapter with snapshot path + returns merged report", async () => {
223
- const bridge = makeFakeBridge({ cookie: "x", uid: 42 });
224
- const apiClient = makeFakeApiClient({
225
- history: [{ bvid: "BV1", title: "h", viewAt: 1 }],
226
- });
227
- let syncedPath = null;
228
- const registry = {
229
- syncAdapter: vi.fn(async (name, opts) => {
230
- if (name !== "social-bilibili") throw new Error("wrong name");
231
- syncedPath = opts.inputPath;
232
- return {
233
- adapter: name,
234
- status: "ok",
235
- rawCount: 1,
236
- entityCounts: { events: 1, persons: 0, places: 0, items: 0, topics: 0 },
237
- };
238
- }),
239
- };
240
-
241
- const report = await collectAndSync(bridge, registry, {
242
- apiClient,
243
- stagingDir,
244
- });
245
-
246
- expect(registry.syncAdapter).toHaveBeenCalledWith("social-bilibili", {
247
- inputPath: expect.any(String),
248
- });
249
- expect(syncedPath).toBeTruthy();
250
- expect(report.status).toBe("ok");
251
- expect(report.rawCount).toBe(1);
252
- expect(report.bilibili.uid).toBe(42);
253
- expect(report.bilibili.eventCounts.history).toBe(1);
254
- // Cleanup happened: the snapshot file should be gone
255
- expect(existsSync(syncedPath)).toBe(false);
256
- });
257
-
258
- it("cleans up snapshot file even when syncAdapter throws", async () => {
259
- const bridge = makeFakeBridge({ cookie: "x", uid: 42 });
260
- const apiClient = makeFakeApiClient();
261
- let syncedPath = null;
262
- const registry = {
263
- syncAdapter: vi.fn(async (_name, opts) => {
264
- syncedPath = opts.inputPath;
265
- throw new Error("simulated registry failure");
266
- }),
267
- };
268
- await expect(
269
- collectAndSync(bridge, registry, { apiClient, stagingDir }),
270
- ).rejects.toThrow("simulated registry failure");
271
- expect(syncedPath).toBeTruthy();
272
- expect(existsSync(syncedPath)).toBe(false); // cleanup ran
273
- });
274
-
275
- it("throws TypeError when registry missing syncAdapter fn", async () => {
276
- const bridge = makeFakeBridge({ cookie: "x", uid: 1 });
277
- await expect(
278
- collectAndSync(bridge, null, { apiClient: makeFakeApiClient() }),
279
- ).rejects.toThrow(TypeError);
280
- await expect(
281
- collectAndSync(bridge, {}, { apiClient: makeFakeApiClient() }),
282
- ).rejects.toThrow(TypeError);
283
- });
284
- });