@chainlesschain/personal-data-hub 0.4.28 → 0.4.30

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 (204) hide show
  1. package/README.md +13 -5
  2. package/lib/adapters/social-douyin-adb/usage-profile-reader.js +253 -0
  3. package/lib/adapters/social-douyin-adb/watch-history-reader.js +104 -31
  4. package/lib/adapters/social-toutiao-adb/article-reader.js +202 -0
  5. package/lib/analysis-skills/overview.js +24 -4
  6. package/lib/analysis-skills/spending.js +63 -2
  7. package/lib/analysis-skills/timeline.js +11 -6
  8. package/lib/prompt-builder.js +15 -1
  9. package/lib/query-parser.js +38 -8
  10. package/package.json +4 -1
  11. package/__tests__/adapter-guide.test.js +0 -47
  12. package/__tests__/adapter-spec.test.js +0 -78
  13. package/__tests__/adapters/ai-chat-cookie-capture-spec.test.js +0 -211
  14. package/__tests__/adapters/ai-chat-health-checker.test.js +0 -262
  15. package/__tests__/adapters/ai-chat-history.test.js +0 -396
  16. package/__tests__/adapters/ai-chat-http-client.test.js +0 -242
  17. package/__tests__/adapters/ai-chat-vendors.test.js +0 -874
  18. package/__tests__/adapters/alipay-bill-adapter.test.js +0 -538
  19. package/__tests__/adapters/apple-health.test.js +0 -95
  20. package/__tests__/adapters/bank-family.test.js +0 -125
  21. package/__tests__/adapters/biz-tianyancha.test.js +0 -159
  22. package/__tests__/adapters/browser-history-chrome.test.js +0 -377
  23. package/__tests__/adapters/browser-history-edge.test.js +0 -159
  24. package/__tests__/adapters/car-mercedesme.test.js +0 -74
  25. package/__tests__/adapters/doc-baidu-netdisk.test.js +0 -102
  26. package/__tests__/adapters/doc-camscanner.test.js +0 -147
  27. package/__tests__/adapters/doc-platforms.test.js +0 -177
  28. package/__tests__/adapters/edu-huawei-learning-live.test.js +0 -198
  29. package/__tests__/adapters/edu-zuoyebang-live.test.js +0 -226
  30. package/__tests__/adapters/email-adapter-snapshot.test.js +0 -237
  31. package/__tests__/adapters/email-adapter.test.js +0 -742
  32. package/__tests__/adapters/email-classifier.test.js +0 -347
  33. package/__tests__/adapters/email-imap-session.test.js +0 -334
  34. package/__tests__/adapters/email-parser.test.js +0 -244
  35. package/__tests__/adapters/email-pdf-extractor.test.js +0 -529
  36. package/__tests__/adapters/email-providers.test.js +0 -84
  37. package/__tests__/adapters/email-retry-progress.test.js +0 -294
  38. package/__tests__/adapters/email-templates.test.js +0 -822
  39. package/__tests__/adapters/family-23-collectors-scaffold.test.js +0 -182
  40. package/__tests__/adapters/finance-alipay-live.test.js +0 -258
  41. package/__tests__/adapters/finance-dcep.test.js +0 -74
  42. package/__tests__/adapters/fitness-joyrun.test.js +0 -82
  43. package/__tests__/adapters/game-genshin-live.test.js +0 -238
  44. package/__tests__/adapters/game-genshin-scaffold.test.js +0 -108
  45. package/__tests__/adapters/game-honor-of-kings-live.test.js +0 -230
  46. package/__tests__/adapters/git-activity.test.js +0 -222
  47. package/__tests__/adapters/gov-12123.test.js +0 -103
  48. package/__tests__/adapters/gov-ixiamen.test.js +0 -150
  49. package/__tests__/adapters/gov-tax.test.js +0 -135
  50. package/__tests__/adapters/health-meiyou.test.js +0 -125
  51. package/__tests__/adapters/local-files.test.js +0 -264
  52. package/__tests__/adapters/local-im-pc.test.js +0 -154
  53. package/__tests__/adapters/messaging-whatsapp.test.js +0 -289
  54. package/__tests__/adapters/music-kugou.test.js +0 -187
  55. package/__tests__/adapters/music-qq.test.js +0 -112
  56. package/__tests__/adapters/netease-music-live.test.js +0 -244
  57. package/__tests__/adapters/netease-music.test.js +0 -74
  58. package/__tests__/adapters/pc-local-discovery.test.js +0 -141
  59. package/__tests__/adapters/qq-pc-direct-read.test.js +0 -227
  60. package/__tests__/adapters/reading-family.test.js +0 -108
  61. package/__tests__/adapters/recruit-boss.test.js +0 -180
  62. package/__tests__/adapters/shell-history.test.js +0 -180
  63. package/__tests__/adapters/shopping-base.test.js +0 -179
  64. package/__tests__/adapters/shopping-dianping.test.js +0 -239
  65. package/__tests__/adapters/social-bilibili-adb-api-client.test.js +0 -721
  66. package/__tests__/adapters/social-bilibili-adb-chromium-cookies-reader.test.js +0 -346
  67. package/__tests__/adapters/social-bilibili-adb-collector.test.js +0 -284
  68. package/__tests__/adapters/social-bilibili-adb-cookies-extension.test.js +0 -343
  69. package/__tests__/adapters/social-bilibili-adb-snapshot-builder.test.js +0 -296
  70. package/__tests__/adapters/social-csdn.test.js +0 -175
  71. package/__tests__/adapters/social-dongchedi.test.js +0 -165
  72. package/__tests__/adapters/social-douyin-adb-aweme-detail.test.js +0 -165
  73. package/__tests__/adapters/social-douyin-adb-collector.test.js +0 -254
  74. package/__tests__/adapters/social-douyin-adb-db-extension.test.js +0 -114
  75. package/__tests__/adapters/social-douyin-adb-im-db-parser.test.js +0 -304
  76. package/__tests__/adapters/social-douyin-adb-snapshot-builder.test.js +0 -216
  77. package/__tests__/adapters/social-douyin-adb-watch-history.test.js +0 -192
  78. package/__tests__/adapters/social-kuaishou-adb-api-client.test.js +0 -496
  79. package/__tests__/adapters/social-kuaishou-adb-collector.test.js +0 -276
  80. package/__tests__/adapters/social-kuaishou-adb-cookies-extension.test.js +0 -152
  81. package/__tests__/adapters/social-kuaishou-adb-snapshot-builder.test.js +0 -178
  82. package/__tests__/adapters/social-toutiao-adb-account-reader.test.js +0 -135
  83. package/__tests__/adapters/social-toutiao-adb-api-client.test.js +0 -626
  84. package/__tests__/adapters/social-toutiao-adb-collector.test.js +0 -378
  85. package/__tests__/adapters/social-toutiao-adb-cookies-extension.test.js +0 -193
  86. package/__tests__/adapters/social-toutiao-adb-snapshot-builder.test.js +0 -196
  87. package/__tests__/adapters/social-toutiao-kuaishou-scaffold.test.js +0 -311
  88. package/__tests__/adapters/social-weibo-adb-api-client.test.js +0 -362
  89. package/__tests__/adapters/social-weibo-adb-collector.test.js +0 -201
  90. package/__tests__/adapters/social-weibo-adb-cookies-extension.test.js +0 -167
  91. package/__tests__/adapters/social-weibo-adb-snapshot-builder.test.js +0 -189
  92. package/__tests__/adapters/social-xiaohongshu-adb-api-client.test.js +0 -431
  93. package/__tests__/adapters/social-xiaohongshu-adb-collector.test.js +0 -207
  94. package/__tests__/adapters/social-xiaohongshu-adb-cookies-extension.test.js +0 -0
  95. package/__tests__/adapters/social-xiaohongshu-adb-sign-provider-injection.test.js +0 -351
  96. package/__tests__/adapters/social-xiaohongshu-adb-sign.test.js +0 -130
  97. package/__tests__/adapters/social-xiaohongshu-adb-snapshot-builder.test.js +0 -200
  98. package/__tests__/adapters/social-zhihu.test.js +0 -246
  99. package/__tests__/adapters/system-data-adapter.test.js +0 -443
  100. package/__tests__/adapters/system-data-android-ingest.test.js +0 -144
  101. package/__tests__/adapters/system-data-android.test.js +0 -519
  102. package/__tests__/adapters/system-data-disclosure.test.js +0 -153
  103. package/__tests__/adapters/travel-12306.test.js +0 -512
  104. package/__tests__/adapters/travel-amap.test.js +0 -219
  105. package/__tests__/adapters/travel-baidu-map.test.js +0 -305
  106. package/__tests__/adapters/travel-base.test.js +0 -205
  107. package/__tests__/adapters/travel-ctrip.test.js +0 -377
  108. package/__tests__/adapters/travel-didi-consumer.test.js +0 -66
  109. package/__tests__/adapters/travel-didi.test.js +0 -204
  110. package/__tests__/adapters/travel-tencent-map.test.js +0 -207
  111. package/__tests__/adapters/travel-tongcheng.test.js +0 -289
  112. package/__tests__/adapters/video-platforms.test.js +0 -152
  113. package/__tests__/adapters/video-xigua.test.js +0 -106
  114. package/__tests__/adapters/vscode.test.js +0 -299
  115. package/__tests__/adapters/wechat-bootstrap.test.js +0 -240
  116. package/__tests__/adapters/wechat-env-probe.test.js +0 -162
  117. package/__tests__/adapters/wechat-frida-agent.test.js +0 -322
  118. package/__tests__/adapters/wechat-frida-integration.test.js +0 -149
  119. package/__tests__/adapters/wechat-frida-key-provider.test.js +0 -188
  120. package/__tests__/adapters/wechat-md5-key-provider.test.js +0 -101
  121. package/__tests__/adapters/wechat-pc-direct-read.test.js +0 -365
  122. package/__tests__/adapters/wechat-pc-group-topic.test.js +0 -63
  123. package/__tests__/adapters/wechat-pc-v4-sidecar.test.js +0 -72
  124. package/__tests__/adapters/weread.test.js +0 -123
  125. package/__tests__/adapters/wework-pc.test.js +0 -124
  126. package/__tests__/adapters/win-recent.test.js +0 -192
  127. package/__tests__/analysis-skills.test.js +0 -679
  128. package/__tests__/analysis.test.js +0 -1845
  129. package/__tests__/audio-ximalaya-snapshot.test.js +0 -279
  130. package/__tests__/batch.test.js +0 -133
  131. package/__tests__/bridges-cc-kg.test.js +0 -231
  132. package/__tests__/bridges-cc-llm.test.js +0 -191
  133. package/__tests__/bridges-cc-rag.test.js +0 -162
  134. package/__tests__/categories.test.js +0 -92
  135. package/__tests__/e2e/ai-chat-cross-source-journey.test.js +0 -213
  136. package/__tests__/e2e/full-user-journey.test.js +0 -188
  137. package/__tests__/e2e/local-data-adapters-cli.e2e.test.js +0 -146
  138. package/__tests__/entity-resolver-ingest-hook.test.js +0 -177
  139. package/__tests__/entity-resolver-stages.test.js +0 -411
  140. package/__tests__/entity-resolver-vault.test.js +0 -249
  141. package/__tests__/entity-resolver.test.js +0 -526
  142. package/__tests__/fitness-keep-snapshot.test.js +0 -224
  143. package/__tests__/fixtures/entity-resolver-200-mock.json +0 -96
  144. package/__tests__/ids.test.js +0 -45
  145. package/__tests__/integration/ai-chat-history-registry.test.js +0 -228
  146. package/__tests__/integration/aichat-wizard-end-to-end.test.js +0 -282
  147. package/__tests__/integration/cross-adapter-pipelines.test.js +0 -396
  148. package/__tests__/integration/local-data-adapters-pipeline.test.js +0 -373
  149. package/__tests__/integration/social-bilibili-pipeline.test.js +0 -261
  150. package/__tests__/integration/wechat-bootstrap-end-to-end.test.js +0 -390
  151. package/__tests__/key-providers.test.js +0 -126
  152. package/__tests__/kg-derive.test.js +0 -219
  153. package/__tests__/llm-client.test.js +0 -122
  154. package/__tests__/longtail-adapters.test.js +0 -281
  155. package/__tests__/messaging-qq-snapshot.test.js +0 -294
  156. package/__tests__/mobile-extractor-encrypted.test.js +0 -460
  157. package/__tests__/mobile-extractor.test.js +0 -288
  158. package/__tests__/mock-adapter.test.js +0 -93
  159. package/__tests__/prompt-builder.test.js +0 -249
  160. package/__tests__/query-parser.test.js +0 -302
  161. package/__tests__/rag-derive.test.js +0 -169
  162. package/__tests__/registry-readiness.test.js +0 -292
  163. package/__tests__/registry.test.js +0 -420
  164. package/__tests__/salvage-ingest.test.js +0 -97
  165. package/__tests__/schemas.test.js +0 -331
  166. package/__tests__/shopping-adapters.test.js +0 -392
  167. package/__tests__/shopping-eleme-snapshot.test.js +0 -454
  168. package/__tests__/shopping-pinduoduo-snapshot.test.js +0 -484
  169. package/__tests__/shopping-snapshot.test.js +0 -438
  170. package/__tests__/shopping-vipshop-snapshot.test.js +0 -425
  171. package/__tests__/shopping-xianyu-snapshot.test.js +0 -451
  172. package/__tests__/sidecar-contacts-cross-validate.test.js +0 -186
  173. package/__tests__/sidecar-supervisor.test.js +0 -128
  174. package/__tests__/sign-providers.test.js +0 -62
  175. package/__tests__/social-adapters.test.js +0 -280
  176. package/__tests__/social-bilibili-snapshot.test.js +0 -278
  177. package/__tests__/social-douban-snapshot.test.js +0 -351
  178. package/__tests__/social-douyin-im-direct-read.test.js +0 -377
  179. package/__tests__/social-douyin-salvage-collector.test.js +0 -98
  180. package/__tests__/social-douyin-salvage-mapper.test.js +0 -90
  181. package/__tests__/social-douyin-snapshot.test.js +0 -256
  182. package/__tests__/social-kuaishou-snapshot.test.js +0 -362
  183. package/__tests__/social-toutiao-snapshot.test.js +0 -366
  184. package/__tests__/social-weibo-snapshot.test.js +0 -234
  185. package/__tests__/social-weibo-sqlite-device.test.js +0 -174
  186. package/__tests__/social-xiaohongshu-snapshot.test.js +0 -232
  187. package/__tests__/sqlite-leaf-salvage.test.js +0 -97
  188. package/__tests__/travel-adapters.test.js +0 -483
  189. package/__tests__/travel-maps-snapshot.test.js +0 -426
  190. package/__tests__/vault-driver-error.test.js +0 -74
  191. package/__tests__/vault-search-helpers.test.js +0 -104
  192. package/__tests__/vault-search.test.js +0 -423
  193. package/__tests__/vault.test.js +0 -767
  194. package/__tests__/wechat-adapter.test.js +0 -594
  195. package/__tests__/whatsapp-adapter.test.js +0 -138
  196. package/scripts/_make-fixture-all.js +0 -126
  197. package/scripts/_make-fixture-contacts.js +0 -84
  198. package/scripts/evaluate-entity-resolver.js +0 -213
  199. package/scripts/run-native-tests-sandbox.sh +0 -55
  200. package/scripts/smoke-phase-5-5.js +0 -196
  201. package/scripts/smoke-phase-5-7.js +0 -181
  202. package/scripts/smoke-system-data-contacts.js +0 -309
  203. package/scripts/smoke-system-data.js +0 -312
  204. package/vitest.config.js +0 -88
@@ -1,343 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * Phase 1a (Bilibili C 路径) — unit cover for the bilibili.cookies ADB
5
- * extension factory.
6
- *
7
- * Strategy: build a real chromium-shape Cookies sqlite via better-sqlite3,
8
- * read it back as bytes, base64-encode, and feed the encoded string back
9
- * to the extension via a fake `ctx.adb` that returns canned ADB stdout
10
- * per-command. This exercises the full pipeline (probe → su id-u check →
11
- * base64 stream → decode → sqlite magic check → parse → header assemble →
12
- * temp-file cleanup) without any real ADB / device.
13
- *
14
- * Covered:
15
- * - Happy path: pulls + parses + returns {cookie, uid, ...}
16
- * - File not found on phone → BILIBILI_NOT_INSTALLED_OR_NEVER_LOGGED_IN
17
- * - Phone not rooted (id -u returns non-zero/non-root) → BILIBILI_NO_ROOT
18
- * - Empty base64 stream → BILIBILI_COOKIES_EMPTY
19
- * - Truncated stream (decoded <1KB) → BILIBILI_COOKIES_TRUNCATED
20
- * - Wrong magic header (not sqlite) → BILIBILI_NOT_SQLITE
21
- * - Cookies DB present but missing required cookies → BILIBILI_COOKIES_INCOMPLETE
22
- * - Invalid DedeUserID (non-integer / negative) → BILIBILI_INVALID_UID
23
- * - Cleanup: temp file deleted on both success and failure
24
- * - Bridge integration via createHostAdbBridge({ extensions: {...} })
25
- */
26
-
27
- import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
28
- import {
29
- mkdtempSync,
30
- rmSync,
31
- readFileSync,
32
- writeFileSync,
33
- existsSync,
34
- readdirSync,
35
- } from "node:fs";
36
- import { join } from "node:path";
37
- import { tmpdir } from "node:os";
38
- import Database from "better-sqlite3";
39
-
40
- const {
41
- createBilibiliCookiesExtension,
42
- BILIBILI_COOKIES_REMOTE_PATH,
43
- } = require("../../lib/adapters/social-bilibili-adb/cookies-extension");
44
-
45
- let tmpDir;
46
-
47
- beforeEach(() => {
48
- tmpDir = mkdtempSync(join(tmpdir(), "cc-bilibili-ext-test-"));
49
- });
50
-
51
- afterEach(() => {
52
- try {
53
- rmSync(tmpDir, { recursive: true, force: true });
54
- } catch (_e) {
55
- // ignore
56
- }
57
- });
58
-
59
- /**
60
- * Build a chromium-shape Cookies sqlite + return its raw bytes + base64.
61
- * cookies = array of {name, value, hostKey?}.
62
- */
63
- function buildCookiesAsBase64(cookies) {
64
- const dbPath = join(tmpDir, "fixture-cookies");
65
- const db = new Database(dbPath);
66
- db.exec(`
67
- CREATE TABLE cookies(
68
- creation_utc INTEGER,
69
- host_key TEXT,
70
- name TEXT,
71
- value TEXT,
72
- encrypted_value BLOB,
73
- path TEXT,
74
- expires_utc INTEGER,
75
- is_secure INTEGER,
76
- is_httponly INTEGER,
77
- is_persistent INTEGER
78
- );
79
- `);
80
- const insert = db.prepare(
81
- "INSERT INTO cookies(host_key, name, value, path, expires_utc, is_secure, is_httponly, is_persistent) VALUES(?, ?, ?, '/', 0, 0, 1, 1)",
82
- );
83
- for (const c of cookies) {
84
- insert.run(c.hostKey || ".bilibili.com", c.name, c.value);
85
- }
86
- db.close();
87
- const buf = readFileSync(dbPath);
88
- rmSync(dbPath);
89
- return buf.toString("base64");
90
- }
91
-
92
- /**
93
- * Build a fake ctx with a scripted adb response. `responses` is a Map
94
- * keyed by the joined args (whitespace-stripped) → string stdout.
95
- *
96
- * `pickDevice` returns a fixed serial. `parseContentQueryRows` isn't
97
- * used by the bilibili extension but is part of the ctx contract.
98
- */
99
- function fakeCtx(responses) {
100
- return {
101
- adb: vi.fn(async (args, _opts) => {
102
- const key = args.join(" ");
103
- // Allow exact key OR keyword-contains match (the extension only
104
- // checks substrings; the test can opt into "first arg matching ..."
105
- // by registering with a unique substring).
106
- for (const [pattern, body] of responses) {
107
- if (key === pattern || key.includes(pattern)) {
108
- return typeof body === "function" ? body(args) : body;
109
- }
110
- }
111
- throw new Error(`fake adb: no scripted response for: ${key}`);
112
- }),
113
- pickDevice: vi.fn(async () => "FAKE_SERIAL"),
114
- parseContentQueryRows: () => [],
115
- };
116
- }
117
-
118
- const FULL_BILIBILI_COOKIES = [
119
- { name: "SESSDATA", value: "abcSESSDATA123" },
120
- { name: "bili_jct", value: "csrfTokenXYZ" },
121
- { name: "DedeUserID", value: "1234567890" },
122
- { name: "DedeUserID__ckMd5", value: "deadbeef0000" },
123
- { name: "buvid3", value: "buvid-uniq-id" },
124
- ];
125
-
126
- describe("bilibili.cookies extension — happy path", () => {
127
- it("pulls + parses + returns {cookie, uid, ...}", async () => {
128
- const b64 = buildCookiesAsBase64(FULL_BILIBILI_COOKIES);
129
- const ctx = fakeCtx([
130
- [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH + "\n"],
131
- ["id -u", "0\n"],
132
- [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
133
- ]);
134
- const ext = createBilibiliCookiesExtension();
135
- const result = await ext({}, ctx);
136
-
137
- expect(result.cookie).toContain("SESSDATA=abcSESSDATA123");
138
- expect(result.cookie).toContain("bili_jct=csrfTokenXYZ");
139
- expect(result.cookie).toContain("DedeUserID=1234567890");
140
- expect(result.cookie).toContain("buvid3=buvid-uniq-id");
141
- expect(result.uid).toBe(1234567890);
142
- expect(result.extractedAt).toBeGreaterThan(0);
143
- expect(result.diagnostic.cookieCount).toBe(5);
144
- expect(result.diagnostic.hadEncrypted).toBe(false);
145
- });
146
-
147
- it("uid is parsed as positive integer", async () => {
148
- const b64 = buildCookiesAsBase64(FULL_BILIBILI_COOKIES);
149
- const ctx = fakeCtx([
150
- [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
151
- ["id -u", "uid=0(root) gid=0(root)\n"], // alternate id -u format
152
- [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
153
- ]);
154
- const ext = createBilibiliCookiesExtension();
155
- const result = await ext({}, ctx);
156
- expect(Number.isInteger(result.uid)).toBe(true);
157
- expect(result.uid).toBeGreaterThan(0);
158
- });
159
- });
160
-
161
- describe("bilibili.cookies extension — failure modes", () => {
162
- it("BILIBILI_NOT_INSTALLED_OR_NEVER_LOGGED_IN when ls returns NOT_FOUND", async () => {
163
- const ctx = fakeCtx([[`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, "NOT_FOUND\n"]]);
164
- const ext = createBilibiliCookiesExtension();
165
- await expect(ext({}, ctx)).rejects.toThrow(
166
- /BILIBILI_NOT_INSTALLED_OR_NEVER_LOGGED_IN/,
167
- );
168
- });
169
-
170
- it("BILIBILI_NO_ROOT when id -u not 0", async () => {
171
- const ctx = fakeCtx([
172
- [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
173
- ["id -u", "2000\n"], // shell user, not root
174
- ]);
175
- const ext = createBilibiliCookiesExtension();
176
- await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_NO_ROOT/);
177
- });
178
-
179
- it("BILIBILI_COOKIES_EMPTY when base64 stream is empty", async () => {
180
- const ctx = fakeCtx([
181
- [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
182
- ["id -u", "0\n"],
183
- [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, " \r\n"],
184
- ]);
185
- const ext = createBilibiliCookiesExtension();
186
- await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_COOKIES_EMPTY/);
187
- });
188
-
189
- it("BILIBILI_COOKIES_TRUNCATED when decoded file too small", async () => {
190
- // 50 bytes of base64 → ~37 bytes decoded, way below 1KB threshold
191
- const tinyB64 = Buffer.from("a".repeat(100)).toString("base64");
192
- const ctx = fakeCtx([
193
- [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
194
- ["id -u", "0\n"],
195
- [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, tinyB64],
196
- ]);
197
- const ext = createBilibiliCookiesExtension();
198
- await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_COOKIES_TRUNCATED/);
199
- });
200
-
201
- it("BILIBILI_NOT_SQLITE when magic header missing", async () => {
202
- // 2KB of non-sqlite garbage
203
- const garbage = Buffer.alloc(2048, "X").toString("base64");
204
- const ctx = fakeCtx([
205
- [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
206
- ["id -u", "0\n"],
207
- [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, garbage],
208
- ]);
209
- const ext = createBilibiliCookiesExtension();
210
- await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_NOT_SQLITE/);
211
- });
212
-
213
- it("BILIBILI_COOKIES_INCOMPLETE when required cookies missing", async () => {
214
- const b64 = buildCookiesAsBase64([
215
- { name: "SESSDATA", value: "abc" },
216
- { name: "bili_jct", value: "csrf" },
217
- // missing DedeUserID + DedeUserID__ckMd5 + buvid3
218
- ]);
219
- const ctx = fakeCtx([
220
- [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
221
- ["id -u", "0\n"],
222
- [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
223
- ]);
224
- const ext = createBilibiliCookiesExtension();
225
- await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_COOKIES_INCOMPLETE/);
226
- });
227
-
228
- it("BILIBILI_INVALID_UID when DedeUserID is non-numeric", async () => {
229
- const b64 = buildCookiesAsBase64([
230
- { name: "SESSDATA", value: "abc" },
231
- { name: "bili_jct", value: "csrf" },
232
- { name: "DedeUserID", value: "not-a-number" },
233
- { name: "DedeUserID__ckMd5", value: "deadbeef" },
234
- { name: "buvid3", value: "x" },
235
- ]);
236
- const ctx = fakeCtx([
237
- [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
238
- ["id -u", "0\n"],
239
- [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
240
- ]);
241
- const ext = createBilibiliCookiesExtension();
242
- await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_INVALID_UID/);
243
- });
244
- });
245
-
246
- describe("bilibili.cookies extension — temp file cleanup", () => {
247
- function countTempFiles() {
248
- // Count cc-bilibili-cookies-*.db files in os.tmpdir() at the time
249
- // of inspection. We snapshot before/after to compare delta.
250
- try {
251
- return readdirSync(tmpdir()).filter((n) =>
252
- n.startsWith("cc-bilibili-cookies-"),
253
- ).length;
254
- } catch (_e) {
255
- return 0;
256
- }
257
- }
258
-
259
- it("removes temp file on success", async () => {
260
- const before = countTempFiles();
261
- const b64 = buildCookiesAsBase64(FULL_BILIBILI_COOKIES);
262
- const ctx = fakeCtx([
263
- [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
264
- ["id -u", "0\n"],
265
- [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
266
- ]);
267
- const ext = createBilibiliCookiesExtension();
268
- await ext({}, ctx);
269
- const after = countTempFiles();
270
- expect(after).toBe(before);
271
- });
272
-
273
- it("removes temp file on parse failure", async () => {
274
- const before = countTempFiles();
275
- const b64 = buildCookiesAsBase64([
276
- { name: "SESSDATA", value: "abc" }, // incomplete → throws
277
- ]);
278
- const ctx = fakeCtx([
279
- [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
280
- ["id -u", "0\n"],
281
- [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
282
- ]);
283
- const ext = createBilibiliCookiesExtension();
284
- await expect(ext({}, ctx)).rejects.toThrow();
285
- const after = countTempFiles();
286
- expect(after).toBe(before); // cleanup still ran via try/finally
287
- });
288
- });
289
-
290
- describe("bilibili.cookies extension — ctx contract", () => {
291
- it("throws TypeError when ctx missing adb fn", async () => {
292
- const ext = createBilibiliCookiesExtension();
293
- await expect(
294
- ext({}, { pickDevice: async () => "x" }),
295
- ).rejects.toThrow(TypeError);
296
- });
297
-
298
- it("throws TypeError when ctx missing pickDevice fn", async () => {
299
- const ext = createBilibiliCookiesExtension();
300
- await expect(
301
- ext({}, { adb: async () => "" }),
302
- ).rejects.toThrow(TypeError);
303
- });
304
- });
305
-
306
- describe("bilibili.cookies extension — bridge integration", () => {
307
- it("works through createHostAdbBridge plugin point", async () => {
308
- // Use createHostAdbBridge to verify the extension actually dispatches
309
- // via the host-adb-bridge plugin pipeline (Phase B0 contract).
310
- const { createHostAdbBridge } = await import(
311
- "../../../cli/src/lib/host-adb-bridge.js"
312
- );
313
- const b64 = buildCookiesAsBase64(FULL_BILIBILI_COOKIES);
314
-
315
- // The real createHostAdbBridge uses its own internal adb fn (calls
316
- // real `execFile`), which would fail on CI without a device. To
317
- // smoke-test the dispatch wiring we construct an extension that
318
- // ignores ctx and returns the same shape directly — that proves
319
- // the bridge invokes our handler.
320
- const ext = createBilibiliCookiesExtension();
321
-
322
- // Replace the ctx that the real bridge would build by giving the
323
- // extension a wrapper that swaps in our fake ctx.
324
- const wrappedExt = (params, _realCtx) => ext(params, fakeCtxClosure());
325
-
326
- function fakeCtxClosure() {
327
- return fakeCtx([
328
- [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
329
- ["id -u", "0\n"],
330
- [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
331
- ]);
332
- }
333
-
334
- const bridge = createHostAdbBridge({
335
- extensions: { "bilibili.cookies": wrappedExt },
336
- });
337
-
338
- expect(bridge.extensionMethods()).toContain("bilibili.cookies");
339
- const result = await bridge.invoke("bilibili.cookies");
340
- expect(result.uid).toBe(1234567890);
341
- expect(result.cookie).toContain("SESSDATA=");
342
- });
343
- });
@@ -1,296 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * Phase 1b — unit cover for snapshot-builder (API responses → snapshot JSON).
5
- *
6
- * What we cover:
7
- * - schemaVersion + snapshottedAt + account shape match adapter.js
8
- * snapshot mode contract
9
- * - 4 kinds (history/favourite/dynamic/follow) all populate correct fields
10
- * - capturedAt comes from the kind-specific field (viewAt / savedAt /
11
- * publishedAt / followedAt)
12
- * - id derivation: stable for items with bvid/rid/mid, fallback to index
13
- * - displayName defaults to empty string when omitted
14
- * - Edge cases: empty arrays / null items / missing fields don't crash
15
- * - writeSnapshotJson / cleanupSnapshotJson disk lifecycle
16
- */
17
-
18
- import { describe, it, expect, beforeEach, afterEach } from "vitest";
19
- import { existsSync, readFileSync, mkdtempSync, rmSync } from "node:fs";
20
- import { join } from "node:path";
21
- import { tmpdir } from "node:os";
22
-
23
- const {
24
- buildSnapshot,
25
- writeSnapshotJson,
26
- cleanupSnapshotJson,
27
- SNAPSHOT_SCHEMA_VERSION,
28
- } = require("../../lib/adapters/social-bilibili-adb/snapshot-builder");
29
-
30
- let tmpDir;
31
-
32
- beforeEach(() => {
33
- tmpDir = mkdtempSync(join(tmpdir(), "cc-snapshot-test-"));
34
- });
35
-
36
- afterEach(() => {
37
- try {
38
- rmSync(tmpDir, { recursive: true, force: true });
39
- } catch (_e) {
40
- // ignore
41
- }
42
- });
43
-
44
- // ─── buildSnapshot ──────────────────────────────────────────────────────
45
-
46
- describe("buildSnapshot — schema contract", () => {
47
- it("returns the documented schema shape", () => {
48
- const snap = buildSnapshot({
49
- uid: 12345,
50
- displayName: "alice",
51
- history: [],
52
- favourites: [],
53
- dynamics: [],
54
- follows: [],
55
- snapshottedAt: 1716383021000,
56
- });
57
- expect(snap.schemaVersion).toBe(SNAPSHOT_SCHEMA_VERSION);
58
- expect(snap.schemaVersion).toBe(1);
59
- expect(snap.snapshottedAt).toBe(1716383021000);
60
- expect(snap.account).toEqual({ uid: "12345", displayName: "alice" });
61
- expect(Array.isArray(snap.events)).toBe(true);
62
- });
63
-
64
- it("converts uid to string in account", () => {
65
- const snap = buildSnapshot({ uid: 42 });
66
- expect(snap.account.uid).toBe("42");
67
- expect(typeof snap.account.uid).toBe("string");
68
- });
69
-
70
- it("defaults displayName to empty string", () => {
71
- const snap = buildSnapshot({ uid: 1 });
72
- expect(snap.account.displayName).toBe("");
73
- });
74
-
75
- it("defaults snapshottedAt to Date.now() when omitted", () => {
76
- const before = Date.now();
77
- const snap = buildSnapshot({ uid: 1 });
78
- const after = Date.now();
79
- expect(snap.snapshottedAt).toBeGreaterThanOrEqual(before);
80
- expect(snap.snapshottedAt).toBeLessThanOrEqual(after);
81
- });
82
-
83
- it("rejects non-positive uid", () => {
84
- expect(() => buildSnapshot({ uid: 0 })).toThrow(TypeError);
85
- expect(() => buildSnapshot({ uid: -1 })).toThrow(TypeError);
86
- expect(() => buildSnapshot({ uid: "string" })).toThrow(TypeError);
87
- });
88
-
89
- it("rejects null / non-object input", () => {
90
- expect(() => buildSnapshot(null)).toThrow(TypeError);
91
- expect(() => buildSnapshot("string")).toThrow(TypeError);
92
- });
93
- });
94
-
95
- describe("buildSnapshot — events", () => {
96
- it("maps history items → kind=history events", () => {
97
- const snap = buildSnapshot({
98
- uid: 1,
99
- history: [
100
- {
101
- bvid: "BV1xx",
102
- avid: 100,
103
- title: "Test",
104
- viewAt: 1716383021,
105
- duration: 300,
106
- uploader: "u1",
107
- uploaderMid: 999,
108
- part: "Part1",
109
- },
110
- ],
111
- });
112
- expect(snap.events).toHaveLength(1);
113
- expect(snap.events[0]).toMatchObject({
114
- kind: "history",
115
- id: "BV1xx",
116
- capturedAt: 1716383021,
117
- title: "Test",
118
- bvid: "BV1xx",
119
- avid: 100,
120
- duration: 300,
121
- uploader: "u1",
122
- uploaderMid: 999,
123
- part: "Part1",
124
- });
125
- });
126
-
127
- it("maps favourite items → kind=favourite + id prefix", () => {
128
- const snap = buildSnapshot({
129
- uid: 1,
130
- favourites: [
131
- {
132
- bvid: "BVfav1",
133
- title: "F1",
134
- savedAt: 1716383021000,
135
- folderName: "MyFolder",
136
- uploader: "u1",
137
- },
138
- ],
139
- });
140
- expect(snap.events[0].kind).toBe("favourite");
141
- expect(snap.events[0].id).toBe("fav-BVfav1");
142
- expect(snap.events[0].capturedAt).toBe(1716383021000);
143
- expect(snap.events[0].folderName).toBe("MyFolder");
144
- });
145
-
146
- it("maps dynamic items → kind=dynamic + id prefix", () => {
147
- const snap = buildSnapshot({
148
- uid: 1,
149
- dynamics: [
150
- {
151
- rid: "dyn-rid-1",
152
- summary: "hi",
153
- dynamicType: "av",
154
- publishedAt: 1716383021000,
155
- authorMid: 999,
156
- authorName: "x",
157
- },
158
- ],
159
- });
160
- expect(snap.events[0].kind).toBe("dynamic");
161
- expect(snap.events[0].id).toBe("dyn-dyn-rid-1");
162
- expect(snap.events[0].capturedAt).toBe(1716383021000);
163
- expect(snap.events[0].dynamicType).toBe("av");
164
- });
165
-
166
- it("maps follow items → kind=follow + id prefix + mid as string", () => {
167
- const snap = buildSnapshot({
168
- uid: 1,
169
- follows: [
170
- {
171
- mid: 42,
172
- uname: "Friend",
173
- face: "https://x.png",
174
- sign: "hi",
175
- followedAt: 1716383021000,
176
- },
177
- ],
178
- });
179
- expect(snap.events[0].kind).toBe("follow");
180
- expect(snap.events[0].id).toBe("follow-42");
181
- expect(snap.events[0].mid).toBe("42");
182
- expect(typeof snap.events[0].mid).toBe("string");
183
- });
184
-
185
- it("preserves event order: history → favourite → dynamic → follow", () => {
186
- const snap = buildSnapshot({
187
- uid: 1,
188
- history: [{ bvid: "BV1", title: "h", viewAt: 1 }],
189
- favourites: [{ bvid: "BV2", title: "f", savedAt: 2 }],
190
- dynamics: [{ rid: "r1", summary: "d", dynamicType: "av", publishedAt: 3 }],
191
- follows: [{ mid: 1, uname: "x", followedAt: 4 }],
192
- });
193
- const kinds = snap.events.map((e) => e.kind);
194
- expect(kinds).toEqual(["history", "favourite", "dynamic", "follow"]);
195
- });
196
-
197
- it("uses snapshottedAt as fallback when capturedAt source is missing", () => {
198
- const snap = buildSnapshot({
199
- uid: 1,
200
- snapshottedAt: 999,
201
- history: [{ bvid: "BV1", title: "h" /* no viewAt */ }],
202
- });
203
- expect(snap.events[0].capturedAt).toBe(999);
204
- });
205
-
206
- it("uses index-based fallback id when key field missing", () => {
207
- const snap = buildSnapshot({
208
- uid: 1,
209
- history: [{ title: "no bvid", viewAt: 1 }],
210
- favourites: [{ title: "no bvid", savedAt: 1 }],
211
- dynamics: [{ summary: "no rid", dynamicType: "av", publishedAt: 1 }],
212
- follows: [{ uname: "no mid", followedAt: 1 }],
213
- });
214
- const ids = snap.events.map((e) => e.id);
215
- expect(ids).toEqual(["history-0", "fav-0", "dyn-0", "follow-0"]);
216
- });
217
-
218
- it("skips null / non-object items", () => {
219
- const snap = buildSnapshot({
220
- uid: 1,
221
- history: [null, { bvid: "BV1", title: "ok", viewAt: 1 }, undefined, "not an object"],
222
- });
223
- expect(snap.events).toHaveLength(1);
224
- expect(snap.events[0].id).toBe("BV1");
225
- });
226
-
227
- it("handles empty / missing arrays", () => {
228
- const snap = buildSnapshot({ uid: 1 });
229
- expect(snap.events).toEqual([]);
230
- });
231
-
232
- it("handles non-array input fields gracefully", () => {
233
- const snap = buildSnapshot({
234
- uid: 1,
235
- history: "not an array",
236
- favourites: null,
237
- dynamics: 42,
238
- follows: { x: 1 },
239
- });
240
- expect(snap.events).toEqual([]);
241
- });
242
- });
243
-
244
- // ─── writeSnapshotJson / cleanupSnapshotJson ────────────────────────────
245
-
246
- describe("writeSnapshotJson + cleanupSnapshotJson", () => {
247
- it("writes JSON to default tmpdir path", () => {
248
- const snap = buildSnapshot({ uid: 1 });
249
- const filePath = writeSnapshotJson(snap);
250
- expect(existsSync(filePath)).toBe(true);
251
- expect(filePath).toContain("cc-bilibili-snapshot-");
252
- expect(filePath).toMatch(/\.json$/);
253
- const parsed = JSON.parse(readFileSync(filePath, "utf-8"));
254
- expect(parsed.schemaVersion).toBe(1);
255
- cleanupSnapshotJson(filePath);
256
- expect(existsSync(filePath)).toBe(false);
257
- });
258
-
259
- it("respects custom dir", () => {
260
- const snap = buildSnapshot({ uid: 1 });
261
- const filePath = writeSnapshotJson(snap, { dir: tmpDir });
262
- expect(filePath.startsWith(tmpDir)).toBe(true);
263
- expect(existsSync(filePath)).toBe(true);
264
- });
265
-
266
- it("respects custom fileName", () => {
267
- const snap = buildSnapshot({ uid: 1 });
268
- const filePath = writeSnapshotJson(snap, {
269
- dir: tmpDir,
270
- fileName: "custom.json",
271
- });
272
- expect(filePath).toBe(join(tmpDir, "custom.json"));
273
- });
274
-
275
- it("rejects fileName with path separators", () => {
276
- const snap = buildSnapshot({ uid: 1 });
277
- expect(() =>
278
- writeSnapshotJson(snap, { dir: tmpDir, fileName: "../escape.json" }),
279
- ).toThrow(/must be a basename/);
280
- expect(() =>
281
- writeSnapshotJson(snap, { dir: tmpDir, fileName: "sub/path.json" }),
282
- ).toThrow(/must be a basename/);
283
- });
284
-
285
- it("cleanupSnapshotJson is no-op on missing file", () => {
286
- cleanupSnapshotJson(join(tmpDir, "nonexistent.json"));
287
- // Should not throw
288
- });
289
-
290
- it("cleanupSnapshotJson tolerates null / empty", () => {
291
- cleanupSnapshotJson(null);
292
- cleanupSnapshotJson("");
293
- cleanupSnapshotJson(undefined);
294
- // Should not throw
295
- });
296
- });