@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,460 +0,0 @@
1
- "use strict";
2
-
3
- import { describe, it, expect, afterEach } from "vitest";
4
-
5
- const fs = require("node:fs");
6
- const path = require("node:path");
7
- const os = require("node:os");
8
- const crypto = require("node:crypto");
9
-
10
- const {
11
- parseKeybag,
12
- deriveBackupKey,
13
- aesUnwrap,
14
- aesWrap,
15
- unwrapClassKeys,
16
- unwrapEncryptionKey,
17
- decryptCBC,
18
- encryptCBC,
19
- } = require("../lib/mobile-extractor/ios-backup-crypto");
20
- const { parseBplist, unwrapNSKeyedArchiver, UID } = require("../lib/mobile-extractor/bplist");
21
- const { iOSBackupReader } = require("../lib/mobile-extractor");
22
-
23
- // ─── test helpers: keybag TLV + bplist00 encoder ─────────────────────────
24
-
25
- function tlv(tag, value) {
26
- const header = Buffer.alloc(8);
27
- header.write(tag, 0, "ascii");
28
- header.writeUInt32BE(value.length, 4);
29
- return Buffer.concat([header, value]);
30
- }
31
-
32
- function beInt(n, len) {
33
- const b = Buffer.alloc(len);
34
- for (let i = len - 1; i >= 0; i--) { b[i] = n & 0xff; n = Math.floor(n / 256); }
35
- return b;
36
- }
37
-
38
- // Minimal bplist00 encoder — mirrors the subset our parser reads. UID
39
- // instances encode as UID objects; Buffers as <data>; strings/ints/bools/
40
- // arrays/dicts as expected. No dedup needed for fixtures.
41
- function buildBplist(root) {
42
- const objects = [];
43
- const objIndex = new Map(); // identity for collections/buffers/UID
44
- const primIndex = new Map(); // value-key for primitives
45
-
46
- function assign(node) {
47
- if (node === null || typeof node === "boolean" || typeof node === "number" || typeof node === "string") {
48
- const k = `${typeof node}:${String(node)}`;
49
- if (primIndex.has(k)) return primIndex.get(k);
50
- const i = objects.length; objects.push(node); primIndex.set(k, i); return i;
51
- }
52
- if (objIndex.has(node)) return objIndex.get(node);
53
- const i = objects.length; objects.push(node); objIndex.set(node, i);
54
- if (Array.isArray(node)) { node.forEach(assign); }
55
- else if (node instanceof UID || Buffer.isBuffer(node)) { /* leaf */ }
56
- else if (typeof node === "object") { for (const [k, v] of Object.entries(node)) { assign(k); assign(v); } }
57
- return i;
58
- }
59
- assign(root);
60
-
61
- const refSize = objects.length < 256 ? 1 : 2;
62
- const encoded = [];
63
- for (const node of objects) encoded.push(encodeObj(node, refSize, assign));
64
-
65
- const header = Buffer.from("bplist00", "ascii");
66
- const body = Buffer.concat([header, ...encoded]);
67
- const offsets = [];
68
- let acc = header.length;
69
- for (const e of encoded) { offsets.push(acc); acc += e.length; }
70
-
71
- const offsetSize = body.length < 256 ? 1 : 2;
72
- const offsetTable = Buffer.concat(offsets.map((o) => beInt(o, offsetSize)));
73
- const offsetTableOffset = body.length;
74
-
75
- const trailer = Buffer.alloc(32);
76
- trailer.writeUInt8(offsetSize, 6);
77
- trailer.writeUInt8(refSize, 7);
78
- trailer.writeBigUInt64BE(BigInt(objects.length), 8);
79
- trailer.writeBigUInt64BE(BigInt(0), 16); // top object is index 0 (root)
80
- trailer.writeBigUInt64BE(BigInt(offsetTableOffset), 24);
81
-
82
- return Buffer.concat([body, offsetTable, trailer]);
83
- }
84
-
85
- function encodeObj(node, refSize, assign) {
86
- if (node === null) return Buffer.from([0x00]);
87
- if (node === false) return Buffer.from([0x08]);
88
- if (node === true) return Buffer.from([0x09]);
89
- if (typeof node === "number" && Number.isInteger(node)) {
90
- if (node >= 0 && node < 256) return Buffer.from([0x10, node]);
91
- if (node >= 0 && node < 65536) return Buffer.concat([Buffer.from([0x11]), beInt(node, 2)]);
92
- return Buffer.concat([Buffer.from([0x12]), beInt(node, 4)]);
93
- }
94
- if (typeof node === "string") {
95
- const buf = Buffer.from(node, "ascii");
96
- return Buffer.concat([marker(0x50, buf.length), buf]);
97
- }
98
- if (Buffer.isBuffer(node)) {
99
- return Buffer.concat([marker(0x40, node.length), node]);
100
- }
101
- if (node instanceof UID) {
102
- return Buffer.concat([Buffer.from([0x80]), beInt(node.UID, 1)]);
103
- }
104
- if (Array.isArray(node)) {
105
- const refs = Buffer.concat(node.map((c) => beInt(assign(c), refSize)));
106
- return Buffer.concat([marker(0xa0, node.length), refs]);
107
- }
108
- // dict
109
- const entries = Object.entries(node);
110
- const keyRefs = Buffer.concat(entries.map(([k]) => beInt(assign(k), refSize)));
111
- const valRefs = Buffer.concat(entries.map(([, v]) => beInt(assign(v), refSize)));
112
- return Buffer.concat([marker(0xd0, entries.length), keyRefs, valRefs]);
113
- }
114
-
115
- function marker(base, count) {
116
- if (count < 15) return Buffer.from([base | count]);
117
- return Buffer.concat([Buffer.from([base | 0x0f]), Buffer.from([0x11]), beInt(count, 2)]);
118
- }
119
-
120
- // ─── RFC 3394 AES key wrap/unwrap — official test vectors ────────────────
121
-
122
- describe("ios-backup-crypto — RFC 3394 AES key wrap", () => {
123
- const kek256 = Buffer.from("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", "hex");
124
-
125
- it("unwraps the RFC 3394 §4.5 vector (256-bit KEK, 128-bit key)", () => {
126
- const wrapped = Buffer.from("64E8C3F9CE0F5BA263E9777905818A2A93C8191E7D6E8AE7", "hex");
127
- const key = aesUnwrap(kek256, wrapped);
128
- expect(key.toString("hex").toUpperCase()).toBe("00112233445566778899AABBCCDDEEFF");
129
- });
130
-
131
- it("unwraps the RFC 3394 §4.6 vector (256-bit KEK, 256-bit key)", () => {
132
- const wrapped = Buffer.from(
133
- "28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21",
134
- "hex",
135
- );
136
- const key = aesUnwrap(kek256, wrapped);
137
- expect(key.toString("hex").toUpperCase()).toBe(
138
- "00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F",
139
- );
140
- });
141
-
142
- it("wrap is the exact inverse of unwrap (matches RFC ciphertext)", () => {
143
- const key = Buffer.from("00112233445566778899AABBCCDDEEFF", "hex");
144
- const wrapped = aesWrap(kek256, key);
145
- expect(wrapped.toString("hex").toUpperCase()).toBe("64E8C3F9CE0F5BA263E9777905818A2A93C8191E7D6E8AE7");
146
- expect(aesUnwrap(kek256, wrapped).equals(key)).toBe(true);
147
- });
148
-
149
- it("rejects a wrapped key tampered with the wrong KEK (integrity check)", () => {
150
- const wrapped = aesWrap(kek256, Buffer.alloc(32, 7));
151
- const wrongKek = Buffer.alloc(32, 9);
152
- expect(() => aesUnwrap(wrongKek, wrapped)).toThrow(/integrity check failed/);
153
- });
154
- });
155
-
156
- // ─── keybag parse + key derivation ───────────────────────────────────────
157
-
158
- describe("ios-backup-crypto — keybag + derivation", () => {
159
- function buildKeybag({ salt, iter, dpsl, dpic, classNum, wpky }) {
160
- const parts = [
161
- tlv("VERS", beInt(4, 4)),
162
- tlv("TYPE", beInt(1, 4)),
163
- tlv("UUID", crypto.randomBytes(16)), // header uuid
164
- tlv("HMCK", crypto.randomBytes(40)),
165
- tlv("WRAP", beInt(0, 4)),
166
- tlv("SALT", salt),
167
- tlv("ITER", beInt(iter, 4)),
168
- ];
169
- if (dpsl) { parts.push(tlv("DPSL", dpsl)); parts.push(tlv("DPIC", beInt(dpic, 4))); }
170
- // class-key block
171
- parts.push(tlv("UUID", crypto.randomBytes(16)));
172
- parts.push(tlv("CLAS", beInt(classNum, 4)));
173
- parts.push(tlv("WRAP", beInt(2, 4))); // WRAP_PASSCODE
174
- parts.push(tlv("WPKY", wpky));
175
- parts.push(tlv("KTYP", beInt(0, 4)));
176
- return Buffer.concat(parts);
177
- }
178
-
179
- it("parses header attrs + a passcode-wrapped class key", () => {
180
- const salt = crypto.randomBytes(20);
181
- const blob = buildKeybag({ salt, iter: 1000, classNum: 4, wpky: Buffer.alloc(40, 1) });
182
- const { attrs, classKeys } = parseKeybag(blob);
183
- expect(attrs.ITER).toBe(1000);
184
- expect(Buffer.isBuffer(attrs.SALT)).toBe(true);
185
- expect(attrs.SALT.equals(salt)).toBe(true);
186
- expect(classKeys[4]).toBeDefined();
187
- expect(classKeys[4].WRAP).toBe(2);
188
- expect(classKeys[4].WPKY.length).toBe(40);
189
- });
190
-
191
- it("single-PBKDF2 derivation + class-key unwrap round-trips", () => {
192
- const salt = crypto.randomBytes(20);
193
- const classKey = crypto.randomBytes(32);
194
- // derive with the SAME params the keybag advertises
195
- const attrsForDerive = { SALT: salt, ITER: 1000 };
196
- const backupKey = deriveBackupKey("hunter2", attrsForDerive);
197
- const wpky = aesWrap(backupKey, classKey);
198
- const blob = buildKeybag({ salt, iter: 1000, classNum: 4, wpky });
199
- const { attrs, classKeys } = parseKeybag(blob);
200
- unwrapClassKeys(classKeys, deriveBackupKey("hunter2", attrs));
201
- expect(classKeys[4].KEY.equals(classKey)).toBe(true);
202
- });
203
-
204
- it("double-PBKDF2 (iOS 10.2+ DPSL/DPIC) derivation round-trips", () => {
205
- const salt = crypto.randomBytes(20);
206
- const dpsl = crypto.randomBytes(20);
207
- const classKey = crypto.randomBytes(32);
208
- const backupKey = deriveBackupKey("pw", { SALT: salt, ITER: 1000, DPSL: dpsl, DPIC: 2000 });
209
- const wpky = aesWrap(backupKey, classKey);
210
- const blob = buildKeybag({ salt, iter: 1000, dpsl, dpic: 2000, classNum: 4, wpky });
211
- const { attrs, classKeys } = parseKeybag(blob);
212
- unwrapClassKeys(classKeys, deriveBackupKey("pw", attrs));
213
- expect(classKeys[4].KEY.equals(classKey)).toBe(true);
214
- });
215
-
216
- it("wrong password fails the class-key integrity check", () => {
217
- const salt = crypto.randomBytes(20);
218
- const classKey = crypto.randomBytes(32);
219
- const backupKey = deriveBackupKey("right", { SALT: salt, ITER: 1000 });
220
- const blob = buildKeybag({ salt, iter: 1000, classNum: 4, wpky: aesWrap(backupKey, classKey) });
221
- const { attrs, classKeys } = parseKeybag(blob);
222
- expect(() => unwrapClassKeys(classKeys, deriveBackupKey("wrong", attrs))).toThrow(/integrity check/);
223
- });
224
- });
225
-
226
- // ─── AES-CBC decrypt + size truncation ───────────────────────────────────
227
-
228
- describe("ios-backup-crypto — decryptCBC", () => {
229
- it("round-trips and truncates to the real size", () => {
230
- const key = crypto.randomBytes(32);
231
- const plaintext = Buffer.from("hello world — 你好,世界", "utf-8");
232
- const cipher = encryptCBC(key, plaintext);
233
- expect(cipher.length % 16).toBe(0);
234
- const out = decryptCBC(key, cipher, plaintext.length);
235
- expect(out.equals(plaintext)).toBe(true);
236
- });
237
-
238
- it("unwrapEncryptionKey reads a 4-byte LE class prefix + wrapped key", () => {
239
- const classKey = crypto.randomBytes(32);
240
- const inner = crypto.randomBytes(32);
241
- const classKeys = { 7: { KEY: classKey } };
242
- const blob = Buffer.concat([beIntLE(7, 4), aesWrap(classKey, inner)]);
243
- expect(unwrapEncryptionKey(classKeys, blob).equals(inner)).toBe(true);
244
- });
245
- });
246
-
247
- function beIntLE(n, len) {
248
- const b = Buffer.alloc(len);
249
- b.writeUInt32LE(n, 0);
250
- return b;
251
- }
252
-
253
- // ─── bplist parser ───────────────────────────────────────────────────────
254
-
255
- describe("bplist parser", () => {
256
- it("round-trips ints, strings, data, arrays, dicts", () => {
257
- const data = crypto.randomBytes(20);
258
- const src = { name: "secret.txt", size: 12345, flags: 1, blob: data, list: [1, 2, "three"] };
259
- const parsed = parseBplist(buildBplist(src));
260
- expect(parsed.name).toBe("secret.txt");
261
- expect(parsed.size).toBe(12345);
262
- expect(parsed.flags).toBe(1);
263
- expect(Buffer.isBuffer(parsed.blob) && parsed.blob.equals(data)).toBe(true);
264
- expect(parsed.list).toEqual([1, 2, "three"]);
265
- });
266
-
267
- it("decodes UID refs and unwraps an NSKeyedArchiver MBFile", () => {
268
- const encKey = crypto.randomBytes(44);
269
- // $objects[0]=$null, [1]=MBFile dict, [2]=relativePath, [3]=protClass,
270
- // [4]=encKey NSData, [5]=size, [6]=class marker
271
- const archive = {
272
- $version: 100000,
273
- $archiver: "NSKeyedArchiver",
274
- $top: { root: new UID(1) },
275
- $objects: [
276
- "$null",
277
- {
278
- $class: new UID(6),
279
- RelativePath: new UID(2),
280
- ProtectionClass: new UID(3),
281
- EncryptionKey: new UID(4),
282
- Size: new UID(5),
283
- },
284
- "Documents/secret.txt",
285
- 4,
286
- { $class: new UID(6), "NS.data": encKey },
287
- 9999,
288
- { $classname: "MBFile" },
289
- ],
290
- };
291
- const obj = unwrapNSKeyedArchiver(parseBplist(buildBplist(archive)));
292
- expect(obj.RelativePath).toBe("Documents/secret.txt");
293
- expect(obj.ProtectionClass).toBe(4);
294
- expect(obj.Size).toBe(9999);
295
- expect(Buffer.isBuffer(obj.EncryptionKey["NS.data"])).toBe(true);
296
- expect(obj.EncryptionKey["NS.data"].equals(encKey)).toBe(true);
297
- });
298
- });
299
-
300
- // ─── end-to-end: encrypted backup decryption via iOSBackupReader ─────────
301
-
302
- describe("iOSBackupReader — encrypted backup (Phase 7.5b)", () => {
303
- let dir;
304
- afterEach(() => {
305
- if (dir) { try { fs.rmSync(dir, { recursive: true, force: true }); } catch (_e) {} }
306
- dir = null;
307
- });
308
-
309
- function buildKeybagBlob({ salt, iter, classNum, wpky }) {
310
- return Buffer.concat([
311
- tlv("VERS", beInt(4, 4)),
312
- tlv("TYPE", beInt(1, 4)),
313
- tlv("UUID", crypto.randomBytes(16)),
314
- tlv("SALT", salt),
315
- tlv("ITER", beInt(iter, 4)),
316
- tlv("UUID", crypto.randomBytes(16)),
317
- tlv("CLAS", beInt(classNum, 4)),
318
- tlv("WRAP", beInt(2, 4)),
319
- tlv("WPKY", wpky),
320
- tlv("KTYP", beInt(0, 4)),
321
- ]);
322
- }
323
-
324
- function makeEncryptedBackup({ password = "backup-pw" } = {}) {
325
- dir = fs.mkdtempSync(path.join(os.tmpdir(), "ios-enc-"));
326
- const CLASS = 4;
327
- const salt = crypto.randomBytes(20);
328
- const classKey = crypto.randomBytes(32);
329
- const backupKey = deriveBackupKey(password, { SALT: salt, ITER: 1000 });
330
- const keybag = buildKeybagBlob({ salt, iter: 1000, classNum: CLASS, wpky: aesWrap(backupKey, classKey) });
331
-
332
- // ManifestKey: class(4 LE) + wrap(classKey, manifestKey)
333
- const manifestKey = crypto.randomBytes(32);
334
- const manifestKeyBlob = Buffer.concat([beIntLE(CLASS, 4), aesWrap(classKey, manifestKey)]);
335
-
336
- // Manifest.db (encrypted)
337
- const manifestPlain = Buffer.from("SQLite format 3\0THIS-IS-THE-DECRYPTED-MANIFEST", "utf-8");
338
- fs.writeFileSync(path.join(dir, "Manifest.db"), encryptCBC(manifestKey, manifestPlain));
339
-
340
- fs.writeFileSync(
341
- path.join(dir, "Manifest.plist"),
342
- `<?xml version="1.0"?><plist version="1.0"><dict>
343
- <key>IsEncrypted</key><true/>
344
- <key>BackupKeyBag</key><data>${keybag.toString("base64")}</data>
345
- <key>ManifestKey</key><data>${manifestKeyBlob.toString("base64")}</data>
346
- </dict></plist>`,
347
- );
348
- fs.writeFileSync(
349
- path.join(dir, "Info.plist"),
350
- `<?xml version="1.0"?><plist version="1.0"><dict>
351
- <key>Device Name</key><string>Crypto iPhone</string>
352
- </dict></plist>`,
353
- );
354
-
355
- // One encrypted data file.
356
- const fileID = "ab".padEnd(40, "f");
357
- const filePlain = Buffer.from("Hello encrypted iOS file! — 机密文件内容", "utf-8");
358
- const fileKey = crypto.randomBytes(32);
359
- const encKeyBlob = Buffer.concat([Buffer.from([0x28, 0, 0, 0]), aesWrap(classKey, fileKey)]);
360
- const shard = path.join(dir, fileID.slice(0, 2));
361
- fs.mkdirSync(shard, { recursive: true });
362
- fs.writeFileSync(path.join(shard, fileID), encryptCBC(fileKey, filePlain));
363
-
364
- const fileBplist = buildBplist({
365
- $version: 100000,
366
- $archiver: "NSKeyedArchiver",
367
- $top: { root: new UID(1) },
368
- $objects: [
369
- "$null",
370
- {
371
- $class: new UID(6),
372
- RelativePath: new UID(2),
373
- ProtectionClass: new UID(3),
374
- EncryptionKey: new UID(4),
375
- Size: new UID(5),
376
- },
377
- "Documents/secret.txt",
378
- CLASS,
379
- { $class: new UID(6), "NS.data": encKeyBlob },
380
- filePlain.length,
381
- { $classname: "MBFile" },
382
- ],
383
- });
384
-
385
- return { password, fileID, filePlain, manifestPlain, fileBplist };
386
- }
387
-
388
- // Mock SQLite driver returning the fixture rows; also lets us read the
389
- // decrypted Manifest.db temp file the reader hands it.
390
- function mockDriver(fixture, capture) {
391
- return (dbPath) => {
392
- capture.dbPath = dbPath;
393
- return {
394
- prepare: (sql) => ({
395
- all: () => [{
396
- fileID: fixture.fileID,
397
- domain: "AppDomain-com.example.app",
398
- relativePath: "Documents/secret.txt",
399
- flags: 1,
400
- }],
401
- get: (id) => (id === fixture.fileID ? { file: fixture.fileBplist } : undefined),
402
- }),
403
- close: () => {},
404
- };
405
- };
406
- }
407
-
408
- it("rejects an encrypted backup with no password", async () => {
409
- const fx = makeEncryptedBackup();
410
- const reader = new iOSBackupReader({ backupDir: dir, dbDriverFn: () => { throw new Error("nope"); } });
411
- await expect(reader.open()).rejects.toThrow(/requires opts\.password/);
412
- });
413
-
414
- it("decrypts Manifest.db with the correct password", async () => {
415
- const fx = makeEncryptedBackup({ password: "s3cret" });
416
- const capture = {};
417
- const reader = new iOSBackupReader({ backupDir: dir, password: "s3cret", dbDriverFn: mockDriver(fx, capture) });
418
- const r = await reader.open();
419
- expect(r.encrypted).toBe(true);
420
- expect(r.info["Device Name"]).toBe("Crypto iPhone");
421
- // The temp file handed to the driver holds the decrypted SQLite bytes.
422
- // (Manifest.db isn't size-truncated — real ones are page-aligned and
423
- // SQLite ignores any trailing zero pad; compare the meaningful prefix.)
424
- const decrypted = fs.readFileSync(capture.dbPath);
425
- expect(decrypted.subarray(0, fx.manifestPlain.length).equals(fx.manifestPlain)).toBe(true);
426
- reader.close();
427
- // Temp file cleaned up on close.
428
- expect(fs.existsSync(capture.dbPath)).toBe(false);
429
- });
430
-
431
- it("fails to decrypt Manifest.db with the wrong password", async () => {
432
- makeEncryptedBackup({ password: "right-pw" });
433
- const reader = new iOSBackupReader({ backupDir: dir, password: "WRONG", dbDriverFn: () => ({ prepare: () => ({}), close: () => {} }) });
434
- await expect(reader.open()).rejects.toThrow(/integrity check/);
435
- });
436
-
437
- it("copyOut transparently decrypts a per-file-encrypted file", async () => {
438
- const fx = makeEncryptedBackup({ password: "pw" });
439
- const capture = {};
440
- const reader = new iOSBackupReader({ backupDir: dir, password: "pw", dbDriverFn: mockDriver(fx, capture) });
441
- await reader.open();
442
- const out = path.join(dir, "out", "secret.txt");
443
- reader.copyOut(fx.fileID, out);
444
- expect(fs.readFileSync(out).equals(fx.filePlain)).toBe(true);
445
- reader.close();
446
- });
447
-
448
- it("pullDomain decrypts every file under the domain", async () => {
449
- const fx = makeEncryptedBackup({ password: "pw" });
450
- const capture = {};
451
- const reader = new iOSBackupReader({ backupDir: dir, password: "pw", dbDriverFn: mockDriver(fx, capture) });
452
- await reader.open();
453
- const outDir = path.join(dir, "pulled");
454
- const summary = reader.pullDomain("AppDomain-com.example.app", outDir);
455
- expect(summary.copied).toBe(1);
456
- expect(summary.errors).toEqual([]);
457
- expect(fs.readFileSync(path.join(outDir, "Documents/secret.txt")).equals(fx.filePlain)).toBe(true);
458
- reader.close();
459
- });
460
- });