@chainlesschain/personal-data-hub 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +241 -0
- package/__tests__/adapter-spec.test.js +78 -0
- package/__tests__/adapters/email-adapter.test.js +605 -0
- package/__tests__/adapters/email-imap-session.test.js +334 -0
- package/__tests__/adapters/email-parser.test.js +244 -0
- package/__tests__/adapters/email-providers.test.js +84 -0
- package/__tests__/analysis.test.js +302 -0
- package/__tests__/batch.test.js +133 -0
- package/__tests__/bridges-cc-kg.test.js +231 -0
- package/__tests__/bridges-cc-llm.test.js +191 -0
- package/__tests__/bridges-cc-rag.test.js +162 -0
- package/__tests__/ids.test.js +45 -0
- package/__tests__/key-providers.test.js +126 -0
- package/__tests__/kg-derive.test.js +219 -0
- package/__tests__/llm-client.test.js +122 -0
- package/__tests__/mock-adapter.test.js +93 -0
- package/__tests__/prompt-builder.test.js +204 -0
- package/__tests__/query-parser.test.js +150 -0
- package/__tests__/rag-derive.test.js +169 -0
- package/__tests__/registry.test.js +304 -0
- package/__tests__/schemas.test.js +331 -0
- package/__tests__/vault.test.js +506 -0
- package/lib/adapter-spec.js +155 -0
- package/lib/adapters/email-imap/email-adapter.js +398 -0
- package/lib/adapters/email-imap/email-parser.js +177 -0
- package/lib/adapters/email-imap/imap-session.js +294 -0
- package/lib/adapters/email-imap/index.js +26 -0
- package/lib/adapters/email-imap/providers.js +111 -0
- package/lib/analysis.js +226 -0
- package/lib/batch.js +123 -0
- package/lib/bridges/cc-kg-sink.js +264 -0
- package/lib/bridges/cc-llm-adapter.js +169 -0
- package/lib/bridges/cc-rag-sink.js +118 -0
- package/lib/bridges/index.js +44 -0
- package/lib/constants.js +92 -0
- package/lib/ids.js +103 -0
- package/lib/index.js +141 -0
- package/lib/key-providers.js +146 -0
- package/lib/kg-derive.js +214 -0
- package/lib/llm-client.js +171 -0
- package/lib/migrations.js +246 -0
- package/lib/mock-adapter.js +199 -0
- package/lib/prompt-builder.js +205 -0
- package/lib/query-parser.js +250 -0
- package/lib/rag-derive.js +186 -0
- package/lib/registry.js +398 -0
- package/lib/schemas.js +379 -0
- package/lib/vault.js +883 -0
- package/package.json +63 -0
- package/vitest.config.js +10 -0
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
|
4
|
+
|
|
5
|
+
const fs = require("node:fs");
|
|
6
|
+
const os = require("node:os");
|
|
7
|
+
const path = require("node:path");
|
|
8
|
+
|
|
9
|
+
const { newId } = require("../lib/ids");
|
|
10
|
+
const { generateKeyHex } = require("../lib/key-providers");
|
|
11
|
+
const { LocalVault } = require("../lib/vault");
|
|
12
|
+
|
|
13
|
+
// ─── Fixtures ─────────────────────────────────────────────────────────────
|
|
14
|
+
|
|
15
|
+
const ts = () => Date.now();
|
|
16
|
+
|
|
17
|
+
const source = (overrides = {}) => ({
|
|
18
|
+
adapter: "test",
|
|
19
|
+
adapterVersion: "0.1.0",
|
|
20
|
+
capturedAt: ts(),
|
|
21
|
+
capturedBy: "manual",
|
|
22
|
+
...overrides,
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const eventOk = (overrides = {}) => ({
|
|
26
|
+
id: newId(),
|
|
27
|
+
type: "event",
|
|
28
|
+
subtype: "message",
|
|
29
|
+
occurredAt: ts(),
|
|
30
|
+
ingestedAt: ts(),
|
|
31
|
+
content: { text: "Hello" },
|
|
32
|
+
source: source(),
|
|
33
|
+
...overrides,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const personOk = (overrides = {}) => ({
|
|
37
|
+
id: newId(),
|
|
38
|
+
type: "person",
|
|
39
|
+
subtype: "contact",
|
|
40
|
+
names: ["妈妈"],
|
|
41
|
+
ingestedAt: ts(),
|
|
42
|
+
source: source(),
|
|
43
|
+
...overrides,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const placeOk = (overrides = {}) => ({
|
|
47
|
+
id: newId(),
|
|
48
|
+
type: "place",
|
|
49
|
+
name: "妈妈家",
|
|
50
|
+
aliases: ["home", "妈家"],
|
|
51
|
+
ingestedAt: ts(),
|
|
52
|
+
source: source(),
|
|
53
|
+
...overrides,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const itemOk = (overrides = {}) => ({
|
|
57
|
+
id: newId(),
|
|
58
|
+
type: "item",
|
|
59
|
+
subtype: "product",
|
|
60
|
+
name: "蛋白粉",
|
|
61
|
+
ingestedAt: ts(),
|
|
62
|
+
source: source(),
|
|
63
|
+
...overrides,
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const topicOk = (overrides = {}) => ({
|
|
67
|
+
id: newId(),
|
|
68
|
+
type: "topic",
|
|
69
|
+
name: "母亲健康",
|
|
70
|
+
ingestedAt: ts(),
|
|
71
|
+
source: source(),
|
|
72
|
+
...overrides,
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// ─── Test scaffolding ─────────────────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
let tmpDir;
|
|
78
|
+
let vaultPath;
|
|
79
|
+
let vault;
|
|
80
|
+
let key;
|
|
81
|
+
|
|
82
|
+
function freshVault() {
|
|
83
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pdh-vault-"));
|
|
84
|
+
vaultPath = path.join(tmpDir, "vault.db");
|
|
85
|
+
key = generateKeyHex();
|
|
86
|
+
vault = new LocalVault({ path: vaultPath, key, skipAudit: true });
|
|
87
|
+
vault.open();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
afterEach(() => {
|
|
91
|
+
if (vault) {
|
|
92
|
+
try {
|
|
93
|
+
vault.close();
|
|
94
|
+
} catch (_e) {}
|
|
95
|
+
vault = null;
|
|
96
|
+
}
|
|
97
|
+
if (tmpDir && fs.existsSync(tmpDir)) {
|
|
98
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
// ─── open / migrations ────────────────────────────────────────────────────
|
|
103
|
+
|
|
104
|
+
describe("LocalVault open + migrations", () => {
|
|
105
|
+
it("opens a fresh vault and runs initial migrations", () => {
|
|
106
|
+
freshVault();
|
|
107
|
+
expect(vault.schemaVersion()).toBe(1);
|
|
108
|
+
expect(fs.existsSync(vaultPath)).toBe(true);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it("is idempotent: re-open same vault with same key works", () => {
|
|
112
|
+
freshVault();
|
|
113
|
+
const p = vault.putPerson(personOk());
|
|
114
|
+
expect(p.changes).toBe(1);
|
|
115
|
+
vault.close();
|
|
116
|
+
|
|
117
|
+
const reopen = new LocalVault({ path: vaultPath, key, skipAudit: true });
|
|
118
|
+
reopen.open();
|
|
119
|
+
expect(reopen.schemaVersion()).toBe(1);
|
|
120
|
+
expect(reopen.stats().persons).toBe(1);
|
|
121
|
+
reopen.close();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("rejects open with wrong key", () => {
|
|
125
|
+
freshVault();
|
|
126
|
+
vault.close();
|
|
127
|
+
|
|
128
|
+
const wrongKey = generateKeyHex();
|
|
129
|
+
const bad = new LocalVault({ path: vaultPath, key: wrongKey, skipAudit: true });
|
|
130
|
+
expect(() => bad.open()).toThrow(/decryption failed/);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it("rejects construction with invalid key", () => {
|
|
134
|
+
expect(() => new LocalVault({ path: "/tmp/x.db", key: "tooshort" })).toThrow(/hex/);
|
|
135
|
+
expect(() => new LocalVault({ path: "/tmp/x.db" })).toThrow(/key/);
|
|
136
|
+
expect(() => new LocalVault({})).toThrow(/path/);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("opens unencrypted-rejection: file without key cannot be read with wrong key", () => {
|
|
140
|
+
freshVault();
|
|
141
|
+
vault.putEvent(eventOk());
|
|
142
|
+
vault.close();
|
|
143
|
+
|
|
144
|
+
const wrong = new LocalVault({ path: vaultPath, key: generateKeyHex(), skipAudit: true });
|
|
145
|
+
expect(() => wrong.open()).toThrow();
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
// ─── Entity put/get ───────────────────────────────────────────────────────
|
|
150
|
+
|
|
151
|
+
describe("LocalVault entity put/get round-trip", () => {
|
|
152
|
+
it("event round-trips with content + extra preserved", () => {
|
|
153
|
+
freshVault();
|
|
154
|
+
const e = eventOk({
|
|
155
|
+
content: { text: "买妈妈生日礼物", title: "淘宝订单", amount: { value: 288.5, currency: "CNY", direction: "out" } },
|
|
156
|
+
extra: { vendor: "taobao", orderId: "T-12345" },
|
|
157
|
+
});
|
|
158
|
+
vault.putEvent(e);
|
|
159
|
+
const got = vault.getEvent(e.id);
|
|
160
|
+
expect(got).not.toBeNull();
|
|
161
|
+
expect(got.id).toBe(e.id);
|
|
162
|
+
expect(got.content.text).toBe("买妈妈生日礼物");
|
|
163
|
+
expect(got.content.amount.value).toBe(288.5);
|
|
164
|
+
expect(got.extra.vendor).toBe("taobao");
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it("person round-trips with identifiers + names array", () => {
|
|
168
|
+
freshVault();
|
|
169
|
+
const p = personOk({
|
|
170
|
+
names: ["妈妈", "陈某某"],
|
|
171
|
+
identifiers: { phone: ["13800001111"], wechatId: "wxid_xyz" },
|
|
172
|
+
});
|
|
173
|
+
vault.putPerson(p);
|
|
174
|
+
const got = vault.getPerson(p.id);
|
|
175
|
+
expect(got.names).toEqual(["妈妈", "陈某某"]);
|
|
176
|
+
expect(got.identifiers.phone).toEqual(["13800001111"]);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it("place round-trips with coordinates + aliases", () => {
|
|
180
|
+
freshVault();
|
|
181
|
+
const pl = placeOk({
|
|
182
|
+
coordinates: { lat: 24.4798, lng: 118.0894 },
|
|
183
|
+
address: "厦门思明区 XX 路 88 号",
|
|
184
|
+
aliases: ["home", "妈家"],
|
|
185
|
+
});
|
|
186
|
+
vault.putPlace(pl);
|
|
187
|
+
const got = vault.getPlace(pl.id);
|
|
188
|
+
expect(got.coordinates).toEqual({ lat: 24.4798, lng: 118.0894 });
|
|
189
|
+
expect(got.aliases).toEqual(["home", "妈家"]);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("item round-trips with price object", () => {
|
|
193
|
+
freshVault();
|
|
194
|
+
const it = itemOk({ price: { value: 288.5, currency: "CNY" }, merchant: "person-taobao" });
|
|
195
|
+
vault.putItem(it);
|
|
196
|
+
const got = vault.getItem(it.id);
|
|
197
|
+
expect(got.price).toEqual({ value: 288.5, currency: "CNY" });
|
|
198
|
+
expect(got.merchant).toBe("person-taobao");
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it("topic round-trips with parent + derivedFromEvents", () => {
|
|
202
|
+
freshVault();
|
|
203
|
+
const eId = newId();
|
|
204
|
+
const t = topicOk({ parentTopic: "topic-family", derivedFromEvents: [eId] });
|
|
205
|
+
vault.putTopic(t);
|
|
206
|
+
const got = vault.getTopic(t.id);
|
|
207
|
+
expect(got.parentTopic).toBe("topic-family");
|
|
208
|
+
expect(got.derivedFromEvents).toEqual([eId]);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it("put with invalid entity throws (validators gate the vault)", () => {
|
|
212
|
+
freshVault();
|
|
213
|
+
expect(() => vault.putEvent({ id: "x", type: "event" })).toThrow(/invalid event/);
|
|
214
|
+
expect(() => vault.putPerson({ id: "x", type: "person", subtype: "alien", names: [] })).toThrow(
|
|
215
|
+
/invalid person/
|
|
216
|
+
);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it("get returns null for unknown id", () => {
|
|
220
|
+
freshVault();
|
|
221
|
+
expect(vault.getEvent(newId())).toBeNull();
|
|
222
|
+
expect(vault.getPerson(newId())).toBeNull();
|
|
223
|
+
expect(vault.getPlace(newId())).toBeNull();
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it("upsert: re-putting same id overwrites", () => {
|
|
227
|
+
freshVault();
|
|
228
|
+
const id = newId();
|
|
229
|
+
vault.putEvent(eventOk({ id, content: { text: "v1" } }));
|
|
230
|
+
vault.putEvent(eventOk({ id, content: { text: "v2" } }));
|
|
231
|
+
expect(vault.getEvent(id).content.text).toBe("v2");
|
|
232
|
+
expect(vault.stats().events).toBe(1);
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// ─── putBatch (transactional) ─────────────────────────────────────────────
|
|
237
|
+
|
|
238
|
+
describe("LocalVault.putBatch", () => {
|
|
239
|
+
it("commits all entities in a single transaction", () => {
|
|
240
|
+
freshVault();
|
|
241
|
+
const batch = {
|
|
242
|
+
events: [eventOk(), eventOk()],
|
|
243
|
+
persons: [personOk(), personOk(), personOk()],
|
|
244
|
+
places: [placeOk()],
|
|
245
|
+
items: [],
|
|
246
|
+
topics: [topicOk()],
|
|
247
|
+
};
|
|
248
|
+
const counts = vault.putBatch(batch);
|
|
249
|
+
expect(counts).toEqual({ events: 2, persons: 3, places: 1, items: 0, topics: 1 });
|
|
250
|
+
expect(vault.stats().events).toBe(2);
|
|
251
|
+
expect(vault.stats().persons).toBe(3);
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it("rolls back on any invalid entity (atomicity)", () => {
|
|
255
|
+
freshVault();
|
|
256
|
+
const before = vault.stats();
|
|
257
|
+
expect(() =>
|
|
258
|
+
vault.putBatch({
|
|
259
|
+
events: [eventOk(), { id: "bad", type: "event" /* invalid */ }],
|
|
260
|
+
persons: [],
|
|
261
|
+
})
|
|
262
|
+
).toThrow(/invalid event/);
|
|
263
|
+
const after = vault.stats();
|
|
264
|
+
expect(after.events).toBe(before.events); // no partial commit
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it("findBySource locates a row by (adapter, originalId)", () => {
|
|
268
|
+
freshVault();
|
|
269
|
+
const e = eventOk({ source: source({ originalId: "msg-42" }) });
|
|
270
|
+
vault.putEvent(e);
|
|
271
|
+
const found = vault.findBySource("events", "test", "msg-42");
|
|
272
|
+
expect(found).not.toBeNull();
|
|
273
|
+
expect(found.id).toBe(e.id);
|
|
274
|
+
expect(vault.findBySource("events", "test", "no-such")).toBeNull();
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
// ─── raw_events ──────────────────────────────────────────────────────────
|
|
279
|
+
|
|
280
|
+
describe("LocalVault.putRawEvent", () => {
|
|
281
|
+
it("stores and replaces by (adapter, originalId)", () => {
|
|
282
|
+
freshVault();
|
|
283
|
+
vault.putRawEvent({
|
|
284
|
+
adapter: "email-imap",
|
|
285
|
+
originalId: "<msg-1@example.com>",
|
|
286
|
+
capturedAt: ts(),
|
|
287
|
+
payload: { from: "a@b.c", subject: "v1" },
|
|
288
|
+
});
|
|
289
|
+
vault.putRawEvent({
|
|
290
|
+
adapter: "email-imap",
|
|
291
|
+
originalId: "<msg-1@example.com>",
|
|
292
|
+
capturedAt: ts(),
|
|
293
|
+
payload: { from: "a@b.c", subject: "v2" },
|
|
294
|
+
});
|
|
295
|
+
expect(vault.stats().rawEvents).toBe(1); // dedup, not duplicate
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
it("validates required fields", () => {
|
|
299
|
+
freshVault();
|
|
300
|
+
expect(() =>
|
|
301
|
+
vault.putRawEvent({ adapter: "", originalId: "x", capturedAt: ts(), payload: {} })
|
|
302
|
+
).toThrow(/adapter/);
|
|
303
|
+
expect(() =>
|
|
304
|
+
vault.putRawEvent({ adapter: "a", originalId: "", capturedAt: ts(), payload: {} })
|
|
305
|
+
).toThrow(/originalId/);
|
|
306
|
+
expect(() =>
|
|
307
|
+
vault.putRawEvent({ adapter: "a", originalId: "x", capturedAt: 0, payload: {} })
|
|
308
|
+
).toThrow(/capturedAt/);
|
|
309
|
+
});
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
// ─── queryEvents / countEvents ───────────────────────────────────────────
|
|
313
|
+
|
|
314
|
+
describe("LocalVault.queryEvents + countEvents", () => {
|
|
315
|
+
it("filters by subtype + time window, ordered by occurred_at DESC", () => {
|
|
316
|
+
freshVault();
|
|
317
|
+
const t0 = ts() - 1_000_000;
|
|
318
|
+
vault.putEvent(eventOk({ subtype: "order", occurredAt: t0 + 1000 }));
|
|
319
|
+
vault.putEvent(eventOk({ subtype: "order", occurredAt: t0 + 5000 }));
|
|
320
|
+
vault.putEvent(eventOk({ subtype: "message", occurredAt: t0 + 3000 }));
|
|
321
|
+
|
|
322
|
+
const orders = vault.queryEvents({ subtype: "order", since: t0 });
|
|
323
|
+
expect(orders.length).toBe(2);
|
|
324
|
+
expect(orders[0].occurredAt).toBe(t0 + 5000); // newest first
|
|
325
|
+
expect(orders[1].occurredAt).toBe(t0 + 1000);
|
|
326
|
+
|
|
327
|
+
expect(vault.countEvents({ subtype: "order" })).toBe(2);
|
|
328
|
+
expect(vault.countEvents({ subtype: "message" })).toBe(1);
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
it("filters by adapter", () => {
|
|
332
|
+
freshVault();
|
|
333
|
+
vault.putEvent(eventOk({ source: source({ adapter: "alipay" }) }));
|
|
334
|
+
vault.putEvent(eventOk({ source: source({ adapter: "alipay" }) }));
|
|
335
|
+
vault.putEvent(eventOk({ source: source({ adapter: "wechat" }) }));
|
|
336
|
+
expect(vault.queryEvents({ adapter: "alipay" }).length).toBe(2);
|
|
337
|
+
expect(vault.queryEvents({ adapter: "wechat" }).length).toBe(1);
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
it("limit + offset paginate correctly", () => {
|
|
341
|
+
freshVault();
|
|
342
|
+
const t0 = ts() - 1_000_000;
|
|
343
|
+
for (let i = 0; i < 5; i++) {
|
|
344
|
+
vault.putEvent(eventOk({ subtype: "message", occurredAt: t0 + i * 1000 }));
|
|
345
|
+
}
|
|
346
|
+
const page1 = vault.queryEvents({ limit: 2, offset: 0 });
|
|
347
|
+
const page2 = vault.queryEvents({ limit: 2, offset: 2 });
|
|
348
|
+
expect(page1.length).toBe(2);
|
|
349
|
+
expect(page2.length).toBe(2);
|
|
350
|
+
expect(page1[0].occurredAt).toBeGreaterThan(page2[0].occurredAt);
|
|
351
|
+
});
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
// ─── sync watermarks ──────────────────────────────────────────────────────
|
|
355
|
+
|
|
356
|
+
describe("LocalVault sync watermarks", () => {
|
|
357
|
+
it("get returns null for missing adapter", () => {
|
|
358
|
+
freshVault();
|
|
359
|
+
expect(vault.getWatermark("never-synced")).toBeNull();
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
it("set then get round-trips", () => {
|
|
363
|
+
freshVault();
|
|
364
|
+
vault.setWatermark("email-imap", "INBOX", {
|
|
365
|
+
watermark: "12345",
|
|
366
|
+
lastSyncedAt: 1700000000000,
|
|
367
|
+
lastStatus: "ok",
|
|
368
|
+
});
|
|
369
|
+
const got = vault.getWatermark("email-imap", "INBOX");
|
|
370
|
+
expect(got.adapter).toBe("email-imap");
|
|
371
|
+
expect(got.scope).toBe("INBOX");
|
|
372
|
+
expect(got.watermark).toBe("12345");
|
|
373
|
+
expect(got.last_synced_at).toBe(1700000000000);
|
|
374
|
+
expect(got.last_status).toBe("ok");
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
it("scope defaults to empty string", () => {
|
|
378
|
+
freshVault();
|
|
379
|
+
vault.setWatermark("alipay", "", { watermark: "2026-04" });
|
|
380
|
+
expect(vault.getWatermark("alipay").watermark).toBe("2026-04");
|
|
381
|
+
expect(vault.getWatermark("alipay", "").watermark).toBe("2026-04");
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
it("overwrites on duplicate (adapter, scope)", () => {
|
|
385
|
+
freshVault();
|
|
386
|
+
vault.setWatermark("a", "s", { watermark: "v1" });
|
|
387
|
+
vault.setWatermark("a", "s", { watermark: "v2", lastStatus: "ok" });
|
|
388
|
+
expect(vault.getWatermark("a", "s").watermark).toBe("v2");
|
|
389
|
+
});
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
// ─── audit log ────────────────────────────────────────────────────────────
|
|
393
|
+
|
|
394
|
+
describe("LocalVault audit_log", () => {
|
|
395
|
+
it("appends audit rows", () => {
|
|
396
|
+
freshVault();
|
|
397
|
+
vault.audit("test.event", "target-1", { foo: "bar" });
|
|
398
|
+
vault.audit("test.event", "target-2");
|
|
399
|
+
const rows = vault.queryAudit({ action: "test.event" });
|
|
400
|
+
expect(rows.length).toBe(2);
|
|
401
|
+
expect(JSON.parse(rows.find((r) => r.target === "target-1").details).foo).toBe("bar");
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
it("filters by since + sorts DESC", () => {
|
|
405
|
+
freshVault();
|
|
406
|
+
vault.audit("a"); // older
|
|
407
|
+
const middle = Date.now();
|
|
408
|
+
vault.audit("b"); // newer
|
|
409
|
+
const rows = vault.queryAudit({ since: middle });
|
|
410
|
+
expect(rows.length).toBeGreaterThanOrEqual(1);
|
|
411
|
+
expect(rows[0].action).toBe("b");
|
|
412
|
+
});
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
// ─── key rotation ─────────────────────────────────────────────────────────
|
|
416
|
+
|
|
417
|
+
describe("LocalVault.rotateKey", () => {
|
|
418
|
+
it("rotates to a new key and old key can no longer decrypt", () => {
|
|
419
|
+
freshVault();
|
|
420
|
+
vault.putEvent(eventOk());
|
|
421
|
+
vault.putPerson(personOk());
|
|
422
|
+
|
|
423
|
+
const newKey = generateKeyHex();
|
|
424
|
+
vault.rotateKey(newKey);
|
|
425
|
+
vault.close();
|
|
426
|
+
|
|
427
|
+
// Old key should fail.
|
|
428
|
+
const withOldKey = new LocalVault({ path: vaultPath, key, skipAudit: true });
|
|
429
|
+
expect(() => withOldKey.open()).toThrow();
|
|
430
|
+
|
|
431
|
+
// New key opens fine and data is intact.
|
|
432
|
+
const withNewKey = new LocalVault({ path: vaultPath, key: newKey, skipAudit: true });
|
|
433
|
+
withNewKey.open();
|
|
434
|
+
expect(withNewKey.stats().events).toBe(1);
|
|
435
|
+
expect(withNewKey.stats().persons).toBe(1);
|
|
436
|
+
withNewKey.close();
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
it("refuses to rotate to the same key", () => {
|
|
440
|
+
freshVault();
|
|
441
|
+
expect(() => vault.rotateKey(key)).toThrow(/refusing/);
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
it("validates new key shape", () => {
|
|
445
|
+
freshVault();
|
|
446
|
+
expect(() => vault.rotateKey("nope")).toThrow(/hex/);
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
it("records vault.key_rotated audit row", () => {
|
|
450
|
+
freshVault();
|
|
451
|
+
vault.rotateKey(generateKeyHex());
|
|
452
|
+
const rows = vault.queryAudit({ action: "vault.key_rotated" });
|
|
453
|
+
expect(rows.length).toBe(1);
|
|
454
|
+
});
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
// ─── destroy ──────────────────────────────────────────────────────────────
|
|
458
|
+
|
|
459
|
+
describe("LocalVault.destroy", () => {
|
|
460
|
+
it("removes vault file + wal/shm sidecars", () => {
|
|
461
|
+
freshVault();
|
|
462
|
+
vault.putEvent(eventOk()); // forces WAL creation
|
|
463
|
+
vault.destroy();
|
|
464
|
+
expect(fs.existsSync(vaultPath)).toBe(false);
|
|
465
|
+
expect(fs.existsSync(vaultPath + "-wal")).toBe(false);
|
|
466
|
+
expect(fs.existsSync(vaultPath + "-shm")).toBe(false);
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
it("is safe to call on an already-closed vault", () => {
|
|
470
|
+
freshVault();
|
|
471
|
+
vault.close();
|
|
472
|
+
expect(() => vault.destroy()).not.toThrow();
|
|
473
|
+
});
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
// ─── stats ────────────────────────────────────────────────────────────────
|
|
477
|
+
|
|
478
|
+
describe("LocalVault.stats", () => {
|
|
479
|
+
it("reports per-table counts + schema version", () => {
|
|
480
|
+
freshVault();
|
|
481
|
+
vault.putBatch({
|
|
482
|
+
events: [eventOk(), eventOk(), eventOk()],
|
|
483
|
+
persons: [personOk()],
|
|
484
|
+
places: [placeOk(), placeOk()],
|
|
485
|
+
items: [],
|
|
486
|
+
topics: [],
|
|
487
|
+
});
|
|
488
|
+
vault.putRawEvent({
|
|
489
|
+
adapter: "x",
|
|
490
|
+
originalId: "y",
|
|
491
|
+
capturedAt: ts(),
|
|
492
|
+
payload: {},
|
|
493
|
+
});
|
|
494
|
+
vault.audit("hello");
|
|
495
|
+
|
|
496
|
+
const s = vault.stats();
|
|
497
|
+
expect(s.schemaVersion).toBe(1);
|
|
498
|
+
expect(s.events).toBe(3);
|
|
499
|
+
expect(s.persons).toBe(1);
|
|
500
|
+
expect(s.places).toBe(2);
|
|
501
|
+
expect(s.items).toBe(0);
|
|
502
|
+
expect(s.topics).toBe(0);
|
|
503
|
+
expect(s.rawEvents).toBe(1);
|
|
504
|
+
expect(s.auditLog).toBeGreaterThanOrEqual(1);
|
|
505
|
+
});
|
|
506
|
+
});
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PersonalDataAdapter contract — what every adapter (Email / Alipay / WeChat /
|
|
3
|
+
* AI Chat / ...) must implement so the AdapterRegistry can orchestrate sync.
|
|
4
|
+
*
|
|
5
|
+
* Mirrors §9.1 of docs/design/Personal_Data_Hub_Architecture.md.
|
|
6
|
+
*
|
|
7
|
+
* class MyAdapter {
|
|
8
|
+
* name = "my-adapter";
|
|
9
|
+
* version = "0.1.0";
|
|
10
|
+
* capabilities = ["sync:imap", "parse:bill"];
|
|
11
|
+
* rateLimits = { perMinute: 60 };
|
|
12
|
+
* dataDisclosure = {
|
|
13
|
+
* fields: ["email:from,subject,body"],
|
|
14
|
+
* sensitivity: "high",
|
|
15
|
+
* legalGate: false,
|
|
16
|
+
* };
|
|
17
|
+
*
|
|
18
|
+
* async authenticate(ctx) { ... return { ok: true } }
|
|
19
|
+
* async *sync(opts) { yield rawEvent1; yield rawEvent2; ... }
|
|
20
|
+
* normalize(raw) { return { events, persons, places, items, topics } }
|
|
21
|
+
* async healthCheck() { return { ok: true } }
|
|
22
|
+
* }
|
|
23
|
+
*
|
|
24
|
+
* Design rationale:
|
|
25
|
+
* - `sync` is an AsyncIterable so adapters can stream large windows without
|
|
26
|
+
* buffering everything in memory. The registry batches yielded raws
|
|
27
|
+
* before validating + writing.
|
|
28
|
+
* - `normalize` is sync and takes ONE raw at a time. Heavy IO belongs in
|
|
29
|
+
* `sync`; `normalize` is pure transform → testable in isolation.
|
|
30
|
+
* - `dataDisclosure.legalGate` flips the UI from "one-tap enable" to
|
|
31
|
+
* "checkbox-gated user agreement" (WeChat needs this; Alipay doesn't).
|
|
32
|
+
*
|
|
33
|
+
* This module's runtime checks are NOT defensive against adversarial
|
|
34
|
+
* adapters — they only catch the common "I forgot a field" mistakes during
|
|
35
|
+
* development. Adapters run in the same trust boundary as the hub itself.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
"use strict";
|
|
39
|
+
|
|
40
|
+
const SENSITIVITY_LEVELS = Object.freeze(["low", "medium", "high"]);
|
|
41
|
+
|
|
42
|
+
function isString(v) {
|
|
43
|
+
return typeof v === "string";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function isNonEmptyString(v) {
|
|
47
|
+
return typeof v === "string" && v.length > 0;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isFunction(v) {
|
|
51
|
+
return typeof v === "function";
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function isAsyncIterableProducer(fn) {
|
|
55
|
+
// AsyncGeneratorFunction's constructor name in V8 is "AsyncGeneratorFunction".
|
|
56
|
+
// We can also accept a regular function that returns an AsyncIterable, so
|
|
57
|
+
// accept either ctor name OR a function (we'll call it and check at runtime).
|
|
58
|
+
if (!isFunction(fn)) return false;
|
|
59
|
+
const ctor = fn.constructor && fn.constructor.name;
|
|
60
|
+
return ctor === "AsyncGeneratorFunction" || ctor === "Function" || ctor === "AsyncFunction";
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Verify an object conforms to the PersonalDataAdapter contract. Returns
|
|
65
|
+
* { ok: true } on success or { ok: false, errors: [...] } on the first
|
|
66
|
+
* spec violation found in each field (collected, not throw-on-first).
|
|
67
|
+
*
|
|
68
|
+
* Use in tests and as a sanity check in AdapterRegistry.register so a
|
|
69
|
+
* malformed adapter is rejected at registration time rather than failing
|
|
70
|
+
* mysteriously mid-sync.
|
|
71
|
+
*/
|
|
72
|
+
function assertAdapter(a) {
|
|
73
|
+
const errors = [];
|
|
74
|
+
|
|
75
|
+
if (a == null || typeof a !== "object") {
|
|
76
|
+
return { ok: false, errors: ["adapter must be an object instance"] };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Identity
|
|
80
|
+
if (!isNonEmptyString(a.name)) errors.push("name must be a non-empty string");
|
|
81
|
+
if (!isNonEmptyString(a.version)) errors.push("version must be a non-empty string");
|
|
82
|
+
|
|
83
|
+
// Capabilities (array of strings, may be empty)
|
|
84
|
+
if (!Array.isArray(a.capabilities) || !a.capabilities.every(isString)) {
|
|
85
|
+
errors.push("capabilities must be a (possibly empty) array of strings");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Rate limits (optional, but if present must be an object with numeric fields)
|
|
89
|
+
if (a.rateLimits !== undefined) {
|
|
90
|
+
const rl = a.rateLimits;
|
|
91
|
+
if (rl == null || typeof rl !== "object") {
|
|
92
|
+
errors.push("rateLimits must be an object when present");
|
|
93
|
+
} else {
|
|
94
|
+
for (const field of ["perMinute", "perDay", "minIntervalMs"]) {
|
|
95
|
+
if (rl[field] !== undefined && (typeof rl[field] !== "number" || !Number.isFinite(rl[field]) || rl[field] < 0)) {
|
|
96
|
+
errors.push(`rateLimits.${field} must be a non-negative finite number when present`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Data disclosure (required — adapter must declare what it touches)
|
|
103
|
+
if (a.dataDisclosure == null || typeof a.dataDisclosure !== "object") {
|
|
104
|
+
errors.push("dataDisclosure must be a plain object");
|
|
105
|
+
} else {
|
|
106
|
+
const dd = a.dataDisclosure;
|
|
107
|
+
if (!Array.isArray(dd.fields) || !dd.fields.every(isString)) {
|
|
108
|
+
errors.push("dataDisclosure.fields must be an array of strings");
|
|
109
|
+
}
|
|
110
|
+
if (!SENSITIVITY_LEVELS.includes(dd.sensitivity)) {
|
|
111
|
+
errors.push(
|
|
112
|
+
`dataDisclosure.sensitivity must be one of ${SENSITIVITY_LEVELS.join("|")}`
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
if (dd.legalGate !== undefined && typeof dd.legalGate !== "boolean") {
|
|
116
|
+
errors.push("dataDisclosure.legalGate must be a boolean when present");
|
|
117
|
+
}
|
|
118
|
+
if (dd.retentionDays !== undefined && (typeof dd.retentionDays !== "number" || dd.retentionDays <= 0)) {
|
|
119
|
+
errors.push("dataDisclosure.retentionDays must be a positive number when present");
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Required methods
|
|
124
|
+
if (!isFunction(a.authenticate)) errors.push("authenticate must be a function");
|
|
125
|
+
if (!isFunction(a.healthCheck)) errors.push("healthCheck must be a function");
|
|
126
|
+
if (!isFunction(a.normalize)) errors.push("normalize must be a function");
|
|
127
|
+
if (!isAsyncIterableProducer(a.sync)) {
|
|
128
|
+
errors.push("sync must be a function (async generator or async fn returning AsyncIterable)");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return errors.length === 0 ? { ok: true } : { ok: false, errors };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Coerce arbitrary thrown values into Error instances with the original
|
|
136
|
+
* preserved as .cause. Used by registry sync paths so the caller always
|
|
137
|
+
* gets a real Error to log/await-throw against.
|
|
138
|
+
*/
|
|
139
|
+
function toError(thrown, context) {
|
|
140
|
+
if (thrown instanceof Error) {
|
|
141
|
+
if (context && !thrown.context) thrown.context = context;
|
|
142
|
+
return thrown;
|
|
143
|
+
}
|
|
144
|
+
const e = new Error(
|
|
145
|
+
`${context ? context + ": " : ""}${typeof thrown === "string" ? thrown : JSON.stringify(thrown)}`
|
|
146
|
+
);
|
|
147
|
+
e.cause = thrown;
|
|
148
|
+
return e;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
module.exports = {
|
|
152
|
+
SENSITIVITY_LEVELS,
|
|
153
|
+
assertAdapter,
|
|
154
|
+
toError,
|
|
155
|
+
};
|