@uuaid/pillar 2.6.0 → 2.7.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/HOSTING-LIMITS.md +12 -0
- package/README.md +201 -5
- package/bin/carrier.mjs +72 -2
- package/bin/pillar-ask.mjs +4 -1
- package/bin/pillar-blob.mjs +6 -0
- package/bin/pillar-directory.mjs +280 -16
- package/bin/pillar-escrow.mjs +4 -1
- package/bin/pillar-group-v2.mjs +6 -0
- package/bin/pillar-notify.mjs +13 -0
- package/bin/pillar-responder.mjs +266 -23
- package/bin/pillar.mjs +504 -255
- package/package.json +17 -25
- package/src/cli-help.mjs +23 -0
- package/src/group-v2-cli.mjs +1 -1
- package/src/identity/trust.mjs +72 -6
- package/src/mailbox/mailbox.mjs +308 -12
- package/src/net/carrier-server.mjs +34 -2
- package/src/net/refusals.mjs +2 -0
- package/src/net/seed-registry.mjs +2 -1
- package/src/net/transport.mjs +308 -92
- package/src/node-check.mjs +29 -8
- package/src/notify-events.mjs +148 -0
- package/src/notify-log.mjs +124 -0
- package/src/notify-runner.mjs +372 -0
- package/src/notify-store.mjs +725 -0
- package/src/notify.mjs +350 -0
- package/src/pillar.mjs +382 -27
- package/src/readers.mjs +2 -2
- package/src/registry/federation.mjs +3056 -0
- package/src/registry/gossip.mjs +294 -0
- package/src/registry/heartbeats.mjs +195 -0
- package/src/registry/lineage-verifier.mjs +972 -0
- package/src/registry/lineage.mjs +984 -0
- package/src/registry/listings.mjs +549 -0
- package/src/registry/resolve.mjs +376 -0
- package/src/registry/stats.mjs +508 -0
- package/src/sqlite-loader.mjs +40 -0
- package/src/vendor/pillar-core.mjs +22 -0
- package/src/vendor/uuaid-soul.mjs +2246 -0
- package/src/vnext/a6b-common.mjs +270 -0
- package/src/vnext/b1-cli.mjs +970 -0
- package/src/vnext/card-cli.mjs +370 -0
- package/src/vnext/greeter-operator.mjs +160 -0
- package/src/vnext/greeter-suggest.mjs +318 -0
- package/src/vnext/greeter.mjs +571 -0
- package/src/vnext/homes.mjs +48 -0
- package/src/vnext/init-cli.mjs +489 -0
- package/src/vnext/intro-cli.mjs +81 -0
- package/src/vnext/json-dir-mailbox.mjs +296 -0
- package/src/vnext/jsonl-mailbox.mjs +1066 -0
- package/src/vnext/knock-answer.mjs +162 -0
- package/src/vnext/knock-cli.mjs +520 -0
- package/src/vnext/knock-lane.mjs +312 -0
- package/src/vnext/knock-responder.mjs +344 -0
- package/src/vnext/lineage-cli.mjs +653 -0
- package/src/vnext/listing-cli.mjs +323 -0
- package/src/vnext/resolve-cli.mjs +86 -0
- package/src/vnext/soul-cli.mjs +666 -0
- package/src/vnext/verify-cli.mjs +251 -0
- package/src/vnext/w4-redirect.mjs +178 -0
- package/src/vnext/wave-a.mjs +193 -0
- package/src/vnext/witness-cli.mjs +547 -0
|
@@ -0,0 +1,1066 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure-JS read-write JSONL hash-chained mailbox ledger (`<home>/mailbox/`).
|
|
3
|
+
*
|
|
4
|
+
* Used automatically by `Mailbox` when `better-sqlite3` is absent or unbuilt
|
|
5
|
+
* (`--omit=optional`, `--ignore-scripts`, no C++ toolchain, Node ABI switch)
|
|
6
|
+
* so carrier-only `pillar init`, `send`, `recv`, `inbox`, `knock`, `knocks`,
|
|
7
|
+
* and `answer` work with zero native addons.
|
|
8
|
+
*
|
|
9
|
+
* Ledger format matches `JsonDirMailboxReader` and SQLite `Mailbox`:
|
|
10
|
+
* chain[0] = sha256("uuaid-pillar-mailbox-v1|" + envelope_sha256[0])
|
|
11
|
+
* chain[n] = sha256(chain[n-1] + envelope_sha256[n])
|
|
12
|
+
*
|
|
13
|
+
* Several processes share one home (`recv` beside `inbox --mark-read`, V1 F1).
|
|
14
|
+
* Every method that writes holds `<mailbox>/mailbox.lock` for its whole
|
|
15
|
+
* read-modify-write (LOCKED_METHODS, below the class). The lock is the notify
|
|
16
|
+
* writer lock (src/notify-store.mjs): O_EXCL create, a dead holder's lock is
|
|
17
|
+
* stolen at once, a live holder's after WRITER_STALE_MS. A read takes no lock:
|
|
18
|
+
* a row is committed when its "\n" is on disk, so a reader drops an
|
|
19
|
+
* unterminated tail (an append in flight). Whole-file writes are temp + rename.
|
|
20
|
+
*/
|
|
21
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
22
|
+
import {
|
|
23
|
+
appendFileSync,
|
|
24
|
+
existsSync,
|
|
25
|
+
mkdirSync,
|
|
26
|
+
readFileSync,
|
|
27
|
+
renameSync,
|
|
28
|
+
statSync,
|
|
29
|
+
writeFileSync,
|
|
30
|
+
} from "node:fs";
|
|
31
|
+
import { basename, dirname, join } from "node:path";
|
|
32
|
+
import { jcs } from "../identity/jcs.mjs";
|
|
33
|
+
import { WRITER_STALE_MS, WRITER_WAIT_MS, acquireLockSync, releaseLock } from "../notify-store.mjs";
|
|
34
|
+
import { KNOCK_LANE_CAP, KNOCK_RATE_WINDOW_MS } from "./knock-lane.mjs";
|
|
35
|
+
|
|
36
|
+
const CHAIN_SEED = "uuaid-pillar-mailbox-v1|";
|
|
37
|
+
const EMPTY_TIP = "0".repeat(64);
|
|
38
|
+
const ERASED_ENVELOPE_JSON = '{"erased":true,"v":1}';
|
|
39
|
+
const GROUP_V2_SENDQ_MAX = 1000;
|
|
40
|
+
|
|
41
|
+
function envelopeSha(envelope) {
|
|
42
|
+
return createHash("sha256").update(jcs(envelope)).digest("hex");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function isErased(row) {
|
|
46
|
+
return !!row && row.envelope_json === ERASED_ENVELOPE_JSON;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function isKnockRow(row) {
|
|
50
|
+
if (!row || isErased(row)) return false;
|
|
51
|
+
try {
|
|
52
|
+
return JSON.parse(row.envelope_json)?.kind === "knock";
|
|
53
|
+
} catch {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function toCanonicalIso(value) {
|
|
59
|
+
const ms = typeof value === "number" ? value : Date.parse(value);
|
|
60
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : new Date().toISOString();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function hasJsonlMailboxFiles(dir) {
|
|
64
|
+
if (typeof dir !== "string" || !dir || dir === ":memory:") return false;
|
|
65
|
+
return (
|
|
66
|
+
existsSync(join(dir, "inbox.jsonl")) ||
|
|
67
|
+
existsSync(join(dir, "outbox.jsonl")) ||
|
|
68
|
+
existsSync(join(dir, "cursors.json")) ||
|
|
69
|
+
existsSync(join(dir, "knocks.jsonl")) ||
|
|
70
|
+
existsSync(join(dir, "readers.json")) ||
|
|
71
|
+
existsSync(join(dir, "groups.json"))
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function resolveWritableJsonlDir(rawPath) {
|
|
76
|
+
if (typeof rawPath !== "string" || !rawPath) return ":memory:";
|
|
77
|
+
if (rawPath === ":memory:") return ":memory:";
|
|
78
|
+
try {
|
|
79
|
+
if (statSync(rawPath).isDirectory()) {
|
|
80
|
+
return basename(rawPath) === "mailbox" ? rawPath : join(rawPath, "mailbox");
|
|
81
|
+
}
|
|
82
|
+
} catch {}
|
|
83
|
+
if (basename(rawPath) === "mailbox.db") return join(dirname(rawPath), "mailbox");
|
|
84
|
+
if (basename(rawPath) === "mailbox") return rawPath;
|
|
85
|
+
return `${rawPath}.jsonl`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** `_withLock` before the lock is taken: release is a no-op. */
|
|
89
|
+
const NOT_LOCKED = Object.freeze({ path: null });
|
|
90
|
+
|
|
91
|
+
function lockBusyError(lockPath, waitMs) {
|
|
92
|
+
const err = new Error(`mailbox-locked: another process held ${lockPath} for ${waitMs} ms; nothing was written. Retry; if it persists, check for a hung pillar process on this home`);
|
|
93
|
+
err.code = "mailbox-locked";
|
|
94
|
+
return err;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export class JsonlMailboxStore {
|
|
98
|
+
/**
|
|
99
|
+
* opts.lockWaitMs how long a write waits for another live writer (default WRITER_WAIT_MS)
|
|
100
|
+
* opts.lockStaleMs when a live holder's lock is judged stale (default WRITER_STALE_MS)
|
|
101
|
+
*/
|
|
102
|
+
constructor(mailboxDir, { lockWaitMs = WRITER_WAIT_MS, lockStaleMs = WRITER_STALE_MS } = {}) {
|
|
103
|
+
this.memory = mailboxDir === ":memory:";
|
|
104
|
+
this.dir = mailboxDir;
|
|
105
|
+
this.lockWaitMs = lockWaitMs;
|
|
106
|
+
this.lockStaleMs = lockStaleMs;
|
|
107
|
+
this._lock = null;
|
|
108
|
+
if (this.memory) {
|
|
109
|
+
this._mem = {
|
|
110
|
+
inbox: [],
|
|
111
|
+
outbox: [],
|
|
112
|
+
knocks: [],
|
|
113
|
+
cursors: {},
|
|
114
|
+
readers: {},
|
|
115
|
+
leases: [],
|
|
116
|
+
groups: {},
|
|
117
|
+
sendq: [],
|
|
118
|
+
seqFloor: 0,
|
|
119
|
+
};
|
|
120
|
+
} else {
|
|
121
|
+
this.inboxPath = join(mailboxDir, "inbox.jsonl");
|
|
122
|
+
this.outboxPath = join(mailboxDir, "outbox.jsonl");
|
|
123
|
+
this.knocksPath = join(mailboxDir, "knocks.jsonl");
|
|
124
|
+
this.cursorsPath = join(mailboxDir, "cursors.json");
|
|
125
|
+
this.readersPath = join(mailboxDir, "readers.json");
|
|
126
|
+
this.leasesPath = join(mailboxDir, "leases.json");
|
|
127
|
+
this.groupsPath = join(mailboxDir, "groups.json");
|
|
128
|
+
this.sendqPath = join(mailboxDir, "group_v2_sendq.json");
|
|
129
|
+
this.metaPath = join(mailboxDir, "meta.json");
|
|
130
|
+
this.lockPath = join(mailboxDir, "mailbox.lock");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
close() {}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Run `fn` as this home's one writer. Re-entrant: a locked method that calls
|
|
138
|
+
* another runs inside the same hold. Throws `mailbox-locked` (nothing
|
|
139
|
+
* written) when a live writer keeps the lock past lockWaitMs.
|
|
140
|
+
*/
|
|
141
|
+
_withLock(fn) {
|
|
142
|
+
if (this.memory || this._lock) return fn();
|
|
143
|
+
this._ensureDir();
|
|
144
|
+
let handle = NOT_LOCKED;
|
|
145
|
+
handle = acquireLockSync(this.lockPath, { staleMs: this.lockStaleMs, waitMs: this.lockWaitMs }); // @rule jsonl.lock-every-write
|
|
146
|
+
if (!handle) throw lockBusyError(this.lockPath, this.lockWaitMs);
|
|
147
|
+
this._lock = handle;
|
|
148
|
+
try {
|
|
149
|
+
return fn();
|
|
150
|
+
} finally {
|
|
151
|
+
this._lock = null;
|
|
152
|
+
releaseLock(handle);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** A disk write outside `_withLock` is a bug: refuse it rather than race. */
|
|
157
|
+
_assertLocked(what) {
|
|
158
|
+
if (!this.memory && !this._lock) throw new Error(`JsonlMailboxStore: ${what} outside the mailbox lock`); // @rule jsonl.write-needs-lock
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
_ensureDir() {
|
|
162
|
+
if (!this.memory) mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
_writeAtomic(filePath, content) {
|
|
166
|
+
this._assertLocked(`write ${basename(filePath)}`);
|
|
167
|
+
this._ensureDir();
|
|
168
|
+
const tmp = `${filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
169
|
+
writeFileSync(tmp, content, { mode: 0o600 });
|
|
170
|
+
renameSync(tmp, filePath);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
_readJsonlRaw(filePath) {
|
|
174
|
+
if (!existsSync(filePath)) return [];
|
|
175
|
+
let text = readFileSync(filePath, "utf8");
|
|
176
|
+
// Outside the lock an unterminated tail is an append in flight: not yet a
|
|
177
|
+
// row. Under the lock no append is in flight, so a torn tail stays visible
|
|
178
|
+
// (it fails the parse, or the audit, as before).
|
|
179
|
+
if (!this._lock) text = text.slice(0, text.lastIndexOf("\n") + 1); // @rule jsonl.read-committed-rows
|
|
180
|
+
const out = [];
|
|
181
|
+
let lineNo = 0;
|
|
182
|
+
for (const raw of text.split("\n")) {
|
|
183
|
+
lineNo++;
|
|
184
|
+
const trimmed = raw.trim();
|
|
185
|
+
if (!trimmed) continue;
|
|
186
|
+
out.push({ lineNo, raw: trimmed });
|
|
187
|
+
}
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
_readJsonl(kind, filePath) {
|
|
192
|
+
if (this.memory) return this._mem[kind].map((r) => ({ ...r }));
|
|
193
|
+
const out = [];
|
|
194
|
+
for (const { raw } of this._readJsonlRaw(filePath)) {
|
|
195
|
+
out.push(JSON.parse(raw));
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
_writeJsonl(kind, filePath, rows) {
|
|
201
|
+
if (this.memory) {
|
|
202
|
+
this._mem[kind] = rows.map((r) => ({ ...r }));
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const content = rows.length ? `${rows.map((r) => JSON.stringify(r)).join("\n")}\n` : "";
|
|
206
|
+
this._writeAtomic(filePath, content);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
_appendJsonl(kind, filePath, row) {
|
|
210
|
+
if (this.memory) {
|
|
211
|
+
this._mem[kind].push({ ...row });
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
this._assertLocked(`append ${basename(filePath)}`);
|
|
215
|
+
this._ensureDir();
|
|
216
|
+
appendFileSync(filePath, `${JSON.stringify(row)}\n`, { mode: 0o600 });
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
_readJsonObj(memKey, filePath, fallback) {
|
|
220
|
+
if (this.memory) return structuredClone(this._mem[memKey]);
|
|
221
|
+
if (!existsSync(filePath)) return fallback;
|
|
222
|
+
return JSON.parse(readFileSync(filePath, "utf8"));
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
_writeJsonObj(memKey, filePath, value) {
|
|
226
|
+
if (this.memory) {
|
|
227
|
+
this._mem[memKey] = structuredClone(value);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
this._writeAtomic(filePath, `${JSON.stringify(value, null, 2)}\n`);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
_inboxRows() {
|
|
234
|
+
return this._readJsonl("inbox", this.inboxPath).sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0));
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
_outboxRows() {
|
|
238
|
+
return this._readJsonl("outbox", this.outboxPath).sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
_knockRows() {
|
|
242
|
+
return this._readJsonl("knocks", this.knocksPath).sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0));
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
_getSeqFloor() {
|
|
246
|
+
let max = this.memory ? this._mem.seqFloor : (this._readJsonObj(null, this.metaPath, {})?.seqFloor ?? 0);
|
|
247
|
+
for (const r of this._inboxRows()) {
|
|
248
|
+
const pos = Math.max(r.seq ?? 0, r.released_seq ?? 0);
|
|
249
|
+
if (pos > max) max = pos;
|
|
250
|
+
}
|
|
251
|
+
return max;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
_bumpSeqFloor(seq) {
|
|
255
|
+
if (this.memory) {
|
|
256
|
+
this._mem.seqFloor = Math.max(this._mem.seqFloor, seq);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
const meta = existsSync(this.metaPath) ? JSON.parse(readFileSync(this.metaPath, "utf8")) : {};
|
|
260
|
+
if ((meta.seqFloor ?? 0) < seq) {
|
|
261
|
+
meta.seqFloor = seq;
|
|
262
|
+
this._writeAtomic(this.metaPath, `${JSON.stringify(meta)}\n`);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// ── Cursors ────────────────────────────────────────────────────────────────
|
|
267
|
+
|
|
268
|
+
getCarrierCursors() {
|
|
269
|
+
return this._readJsonObj("cursors", this.cursorsPath, {});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
setCarrierCursor(carrier, seq) {
|
|
273
|
+
const cursors = this.getCarrierCursors();
|
|
274
|
+
cursors[carrier] = Math.max(cursors[carrier] ?? 0, seq);
|
|
275
|
+
this._writeJsonObj("cursors", this.cursorsPath, cursors);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ── Outbox & Inbox ─────────────────────────────────────────────────────────
|
|
279
|
+
|
|
280
|
+
appendOutbound(envelope, { thread = null, groupId = null, groupMsgId = null } = {}) {
|
|
281
|
+
const rows = this._outboxRows();
|
|
282
|
+
if (rows.some((r) => r.envelope_id === envelope.id)) {
|
|
283
|
+
throw new Error(`UNIQUE constraint failed: outbox.envelope_id (${envelope.id})`);
|
|
284
|
+
}
|
|
285
|
+
const envSha = envelopeSha(envelope);
|
|
286
|
+
const prev = rows.length > 0 ? rows[rows.length - 1].chain_hash : null;
|
|
287
|
+
const chainInput = prev == null ? CHAIN_SEED + envSha : prev + envSha;
|
|
288
|
+
const chain = createHash("sha256").update(chainInput).digest("hex");
|
|
289
|
+
const seq = rows.length > 0 ? (rows[rows.length - 1].seq ?? rows.length) + 1 : 1;
|
|
290
|
+
const row = {
|
|
291
|
+
seq,
|
|
292
|
+
envelope_id: envelope.id,
|
|
293
|
+
envelope_sha256: envSha,
|
|
294
|
+
recipient: envelope.recipient,
|
|
295
|
+
created_at: envelope.createdAt,
|
|
296
|
+
envelope_json: JSON.stringify(envelope),
|
|
297
|
+
chain_hash: chain,
|
|
298
|
+
status: "pending",
|
|
299
|
+
delivered_at: null,
|
|
300
|
+
ack_sha256: null,
|
|
301
|
+
kind: envelope.kind ?? null,
|
|
302
|
+
thread: thread ?? envelope.id,
|
|
303
|
+
group_id: groupId,
|
|
304
|
+
group_msg_id: groupMsgId,
|
|
305
|
+
recipient_ack_at: null,
|
|
306
|
+
recipient_ack_id: null,
|
|
307
|
+
recipient_read_at: null,
|
|
308
|
+
};
|
|
309
|
+
this._appendJsonl("outbox", this.outboxPath, row);
|
|
310
|
+
return { envelopeId: envelope.id, envelopeSha256: envSha, chainHash: chain };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
appendInbound(envelope, { pulledBy = null, quarantined = null } = {}) {
|
|
314
|
+
const sender = envelope.sender ?? envelope.from ?? "unknown";
|
|
315
|
+
const envSha = envelopeSha(envelope);
|
|
316
|
+
const rows = this._inboxRows();
|
|
317
|
+
const existing = rows.find((r) => r.envelope_id === envelope.id && r.sender === sender);
|
|
318
|
+
if (existing) {
|
|
319
|
+
const collision = existing.envelope_sha256 !== envSha;
|
|
320
|
+
return {
|
|
321
|
+
duplicate: true,
|
|
322
|
+
...(collision ? { collision: true } : {}),
|
|
323
|
+
seq: existing.seq,
|
|
324
|
+
envelopeId: envelope.id,
|
|
325
|
+
envelopeSha256: existing.envelope_sha256,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
const prev = rows.length > 0 ? rows[rows.length - 1].chain_hash : null;
|
|
329
|
+
const chainInput = prev == null ? CHAIN_SEED + envSha : prev + envSha;
|
|
330
|
+
const chain = createHash("sha256").update(chainInput).digest("hex");
|
|
331
|
+
const nextSeq = this._getSeqFloor() + 1;
|
|
332
|
+
const row = {
|
|
333
|
+
seq: nextSeq,
|
|
334
|
+
envelope_id: envelope.id,
|
|
335
|
+
envelope_sha256: envSha,
|
|
336
|
+
sender,
|
|
337
|
+
received_at: new Date().toISOString(),
|
|
338
|
+
envelope_json: JSON.stringify(envelope),
|
|
339
|
+
chain_hash: chain,
|
|
340
|
+
read_at: null,
|
|
341
|
+
quarantined: quarantined != null ? String(quarantined).slice(0, 100) : null,
|
|
342
|
+
pulled_by: pulledBy,
|
|
343
|
+
group_id: null,
|
|
344
|
+
released_seq: null,
|
|
345
|
+
};
|
|
346
|
+
this._appendJsonl("inbox", this.inboxPath, row);
|
|
347
|
+
this._bumpSeqFloor(nextSeq);
|
|
348
|
+
return { duplicate: false, seq: nextSeq, envelopeId: envelope.id, envelopeSha256: envSha, chainHash: chain };
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
hasOutbound(envelopeId) {
|
|
352
|
+
return this._outboxRows().some((r) => r.envelope_id === envelopeId);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
getOutbound(envelopeId) {
|
|
356
|
+
return this._outboxRows().find((r) => r.envelope_id === envelopeId) ?? null;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
getInbound(envelopeId, sender) {
|
|
360
|
+
const rows = this._inboxRows();
|
|
361
|
+
if (sender === undefined) return rows.find((r) => r.envelope_id === envelopeId) ?? null;
|
|
362
|
+
return rows.find((r) => r.envelope_id === envelopeId && r.sender === sender) ?? null;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
markOutboundDelivered(envelopeId, ackSha256) {
|
|
366
|
+
const rows = this._outboxRows();
|
|
367
|
+
let changed = false;
|
|
368
|
+
const now = new Date().toISOString();
|
|
369
|
+
for (const r of rows) {
|
|
370
|
+
if (r.envelope_id === envelopeId) {
|
|
371
|
+
r.status = "delivered";
|
|
372
|
+
r.delivered_at = now;
|
|
373
|
+
r.ack_sha256 = ackSha256 ?? null;
|
|
374
|
+
changed = true;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
if (changed) this._writeJsonl("outbox", this.outboxPath, rows);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
outboxTip() {
|
|
381
|
+
const rows = this._outboxRows();
|
|
382
|
+
return rows.length > 0 ? rows[rows.length - 1].chain_hash : EMPTY_TIP;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
inboxTip() {
|
|
386
|
+
const rows = this._inboxRows();
|
|
387
|
+
return rows.length > 0 ? rows[rows.length - 1].chain_hash : EMPTY_TIP;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
outboxSince(seq = 0, limit = 100) {
|
|
391
|
+
return this._outboxRows().filter((r) => r.seq > seq && !isErased(r)).slice(0, limit);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
inboxSince(seq = 0, limit = 100) {
|
|
395
|
+
return this._inboxRows().filter((r) => r.seq > seq && !isErased(r)).slice(0, limit);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
inboxUnread(limit = 100) {
|
|
399
|
+
return this._inboxRows()
|
|
400
|
+
.filter((r) => r.read_at == null && r.quarantined == null && !isErased(r) && !isKnockRow(r))
|
|
401
|
+
.slice(0, limit);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
inboxQuarantined(limit = 100) {
|
|
405
|
+
return this._inboxRows()
|
|
406
|
+
.filter((r) => r.quarantined != null && !isErased(r))
|
|
407
|
+
.slice(0, limit);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
quarantinedSenders(envelopeId) {
|
|
411
|
+
return this._inboxRows()
|
|
412
|
+
.filter((r) => r.envelope_id === envelopeId && r.quarantined != null)
|
|
413
|
+
.map((r) => r.sender);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
oldestUnreadSeq() {
|
|
417
|
+
return this.inboxUnread(1)[0]?.seq ?? null;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
inboxTipSeq() {
|
|
421
|
+
let max = 0;
|
|
422
|
+
for (const r of this._inboxRows()) {
|
|
423
|
+
const pos = r.released_seq ?? r.seq ?? 0;
|
|
424
|
+
if (pos > max) max = pos;
|
|
425
|
+
}
|
|
426
|
+
return max;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
inboxAfter(seq = 0, limit = 500) {
|
|
430
|
+
return this._inboxRows()
|
|
431
|
+
.filter((r) => (r.released_seq ?? r.seq) > seq && r.quarantined == null && !isErased(r) && !isKnockRow(r))
|
|
432
|
+
.sort((a, b) => (a.released_seq ?? a.seq) - (b.released_seq ?? b.seq))
|
|
433
|
+
.slice(0, limit);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// ── Knocks lane ────────────────────────────────────────────────────────────
|
|
437
|
+
|
|
438
|
+
_k6Active(row) {
|
|
439
|
+
return row.answered_at == null || (row.answer_decision ?? "") !== "accept";
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
hasUnansweredRecentKnock(senderLineage, recipientLineage, { now = new Date().toISOString(), windowMs = KNOCK_RATE_WINDOW_MS } = {}) {
|
|
443
|
+
const cutoff = new Date(Date.parse(toCanonicalIso(now)) - windowMs).toISOString();
|
|
444
|
+
return this._knockRows().some(
|
|
445
|
+
(r) =>
|
|
446
|
+
r.sender_lineage === senderLineage &&
|
|
447
|
+
r.recipient_lineage === recipientLineage &&
|
|
448
|
+
this._k6Active(r) &&
|
|
449
|
+
r.received_at > cutoff,
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
hasReplayedPowStamp(senderLineage, recipientLineage, powStamp, { envelopeId = null } = {}) {
|
|
454
|
+
if (typeof powStamp !== "string" || powStamp.length === 0) return false;
|
|
455
|
+
return this._knockRows().some(
|
|
456
|
+
(r) =>
|
|
457
|
+
r.sender_lineage === senderLineage &&
|
|
458
|
+
r.recipient_lineage === recipientLineage &&
|
|
459
|
+
r.pow_stamp === powStamp &&
|
|
460
|
+
(envelopeId == null || r.envelope_id !== envelopeId),
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
admitKnock({
|
|
465
|
+
envelope,
|
|
466
|
+
senderLineage,
|
|
467
|
+
recipientLineage,
|
|
468
|
+
paymentType,
|
|
469
|
+
powStamp = null,
|
|
470
|
+
now = new Date().toISOString(),
|
|
471
|
+
cap = KNOCK_LANE_CAP,
|
|
472
|
+
windowMs = KNOCK_RATE_WINDOW_MS,
|
|
473
|
+
}) {
|
|
474
|
+
const nowIso = toCanonicalIso(now);
|
|
475
|
+
const normalizedStamp = paymentType === "pow" && typeof powStamp === "string" && powStamp.length > 0 ? powStamp : null;
|
|
476
|
+
const sender = envelope.sender ?? envelope.from ?? "unknown";
|
|
477
|
+
const rows = this._knockRows();
|
|
478
|
+
|
|
479
|
+
const existing = rows.find((r) => r.envelope_id === envelope.id && r.sender === sender);
|
|
480
|
+
if (existing) {
|
|
481
|
+
return { admitted: false, duplicate: true, rateLimited: false, stampReplayed: false, seq: existing.seq, evicted: [] };
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const cutoff = new Date(Date.parse(nowIso) - windowMs).toISOString();
|
|
485
|
+
const recent = rows.find(
|
|
486
|
+
(r) =>
|
|
487
|
+
r.sender_lineage === senderLineage &&
|
|
488
|
+
r.recipient_lineage === recipientLineage &&
|
|
489
|
+
this._k6Active(r) &&
|
|
490
|
+
r.received_at > cutoff,
|
|
491
|
+
);
|
|
492
|
+
if (recent) {
|
|
493
|
+
return { admitted: false, duplicate: false, rateLimited: true, stampReplayed: false, evicted: [] };
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
if (normalizedStamp !== null) {
|
|
497
|
+
const replayed = rows.find(
|
|
498
|
+
(r) =>
|
|
499
|
+
r.sender_lineage === senderLineage &&
|
|
500
|
+
r.recipient_lineage === recipientLineage &&
|
|
501
|
+
r.pow_stamp === normalizedStamp &&
|
|
502
|
+
r.envelope_id !== envelope.id,
|
|
503
|
+
);
|
|
504
|
+
if (replayed) {
|
|
505
|
+
return { admitted: false, duplicate: false, rateLimited: false, stampReplayed: true, evicted: [] };
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
const evicted = [];
|
|
510
|
+
const livePending = () => rows.filter((r) => r.status === "pending" && !isErased(r));
|
|
511
|
+
while (livePending().length >= cap) {
|
|
512
|
+
const pendingList = livePending();
|
|
513
|
+
const victim = pendingList.find((r) => r.payment_type !== "introduction") ?? pendingList[0];
|
|
514
|
+
if (!victim) break;
|
|
515
|
+
victim.status = "evicted";
|
|
516
|
+
victim.evicted_at = nowIso;
|
|
517
|
+
evicted.push({
|
|
518
|
+
seq: victim.seq,
|
|
519
|
+
envelope_id: victim.envelope_id,
|
|
520
|
+
sender: victim.sender,
|
|
521
|
+
payment_type: victim.payment_type,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const seq = rows.length > 0 ? (rows[rows.length - 1].seq ?? rows.length) + 1 : 1;
|
|
526
|
+
const row = {
|
|
527
|
+
seq,
|
|
528
|
+
envelope_id: envelope.id,
|
|
529
|
+
sender,
|
|
530
|
+
sender_lineage: senderLineage,
|
|
531
|
+
recipient_lineage: recipientLineage,
|
|
532
|
+
payment_type: paymentType,
|
|
533
|
+
pow_stamp: normalizedStamp,
|
|
534
|
+
received_at: nowIso,
|
|
535
|
+
status: "pending",
|
|
536
|
+
evicted_at: null,
|
|
537
|
+
answered_at: null,
|
|
538
|
+
answer_decision: null,
|
|
539
|
+
answer_envelope_id: null,
|
|
540
|
+
envelope_json: JSON.stringify(envelope),
|
|
541
|
+
};
|
|
542
|
+
rows.push(row);
|
|
543
|
+
this._writeJsonl("knocks", this.knocksPath, rows);
|
|
544
|
+
return { admitted: true, duplicate: false, rateLimited: false, stampReplayed: false, seq, evicted };
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
inboxKnocks(limit = KNOCK_LANE_CAP, { status = "pending" } = {}) {
|
|
548
|
+
const live = this._knockRows().filter((r) => !isErased(r));
|
|
549
|
+
const filtered = status === "all" ? live : live.filter((r) => r.status === status);
|
|
550
|
+
return filtered.slice(0, limit);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
getKnock(envelopeId, sender) {
|
|
554
|
+
const live = this._knockRows().filter((r) => !isErased(r));
|
|
555
|
+
if (sender === undefined) {
|
|
556
|
+
const matches = live.filter((r) => r.envelope_id === envelopeId);
|
|
557
|
+
if (matches.length > 1) {
|
|
558
|
+
throw new Error(`getKnock: multiple senders hold knock ${envelopeId} (ambiguous); name the sender`);
|
|
559
|
+
}
|
|
560
|
+
return matches[0] ?? null;
|
|
561
|
+
}
|
|
562
|
+
return live.find((r) => r.envelope_id === envelopeId && r.sender === sender) ?? null;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
knockCount(status = "pending") {
|
|
566
|
+
return this._knockRows().filter((r) => !isErased(r) && r.status === status).length;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
markKnockAnswered(envelopeId, { sender, decision = null, answerEnvelopeId = null, now = new Date().toISOString() } = {}) {
|
|
570
|
+
const nowIso = toCanonicalIso(now);
|
|
571
|
+
const rows = this._knockRows();
|
|
572
|
+
const liveMatches = rows.filter(
|
|
573
|
+
(r) => r.envelope_id === envelopeId && !isErased(r) && (sender === undefined || r.sender === sender),
|
|
574
|
+
);
|
|
575
|
+
if (sender === undefined && liveMatches.length > 1) {
|
|
576
|
+
throw new Error(`markKnockAnswered: ${liveMatches.length} senders hold knock ${envelopeId} (ambiguous); name the sender`);
|
|
577
|
+
}
|
|
578
|
+
if (liveMatches.length === 0) return false;
|
|
579
|
+
for (const r of liveMatches) {
|
|
580
|
+
r.status = "answered";
|
|
581
|
+
r.answered_at = nowIso;
|
|
582
|
+
r.answer_decision = decision;
|
|
583
|
+
if (answerEnvelopeId != null) r.answer_envelope_id = answerEnvelopeId;
|
|
584
|
+
}
|
|
585
|
+
this._writeJsonl("knocks", this.knocksPath, rows);
|
|
586
|
+
return true;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// ── Quarantine, read markers & groups ──────────────────────────────────────
|
|
590
|
+
|
|
591
|
+
markQuarantined(envelopeId, reason, sender) {
|
|
592
|
+
const rStr = String(reason).slice(0, 100);
|
|
593
|
+
const rows = this._inboxRows();
|
|
594
|
+
let changed = false;
|
|
595
|
+
for (const r of rows) {
|
|
596
|
+
if (r.envelope_id === envelopeId && !isErased(r) && (sender === undefined || r.sender === sender)) {
|
|
597
|
+
r.quarantined = rStr;
|
|
598
|
+
changed = true;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
if (changed) this._writeJsonl("inbox", this.inboxPath, rows);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
releaseQuarantined(envelopeId, sender) {
|
|
605
|
+
const rows = this._inboxRows();
|
|
606
|
+
const matches = rows.filter(
|
|
607
|
+
(r) => r.envelope_id === envelopeId && r.quarantined != null && !isErased(r) && (sender === undefined || r.sender === sender),
|
|
608
|
+
);
|
|
609
|
+
if (sender === undefined && matches.length > 1) {
|
|
610
|
+
throw new Error(`releaseQuarantined: ${matches.length} senders hold envelope ${envelopeId} quarantined; name the sender`);
|
|
611
|
+
}
|
|
612
|
+
if (matches.length === 0) return 0;
|
|
613
|
+
const nextPos = this._getSeqFloor() + 1;
|
|
614
|
+
for (const r of matches) {
|
|
615
|
+
r.quarantined = null;
|
|
616
|
+
r.released_seq = nextPos;
|
|
617
|
+
}
|
|
618
|
+
this._writeJsonl("inbox", this.inboxPath, rows);
|
|
619
|
+
this._bumpSeqFloor(nextPos);
|
|
620
|
+
return matches.length;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
markInboxRead(envelopeId, sender) {
|
|
624
|
+
const at = new Date().toISOString();
|
|
625
|
+
const rows = this._inboxRows();
|
|
626
|
+
let changed = false;
|
|
627
|
+
for (const r of rows) {
|
|
628
|
+
if (r.envelope_id === envelopeId && r.read_at == null && !isErased(r) && (sender === undefined || r.sender === sender)) {
|
|
629
|
+
r.read_at = at;
|
|
630
|
+
changed = true;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
if (changed) this._writeJsonl("inbox", this.inboxPath, rows);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
setInboundGroup(envelopeId, groupId, sender) {
|
|
637
|
+
const rows = this._inboxRows();
|
|
638
|
+
let changed = false;
|
|
639
|
+
for (const r of rows) {
|
|
640
|
+
if (r.envelope_id === envelopeId && !isErased(r) && (sender === undefined || r.sender === sender)) {
|
|
641
|
+
r.group_id = groupId;
|
|
642
|
+
changed = true;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
if (changed) this._writeJsonl("inbox", this.inboxPath, rows);
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
enqueueGroupV2Sends(groupId, sends, { now = new Date().toISOString(), newId }) {
|
|
649
|
+
const q = this._readJsonObj("sendq", this.sendqPath, []);
|
|
650
|
+
let queued = q.filter((x) => x.state === "queued").length;
|
|
651
|
+
const ids = [];
|
|
652
|
+
for (const s of sends) {
|
|
653
|
+
if (queued >= GROUP_V2_SENDQ_MAX) break;
|
|
654
|
+
const id = newId();
|
|
655
|
+
q.push({
|
|
656
|
+
id,
|
|
657
|
+
group_id: groupId,
|
|
658
|
+
recipient: s.to,
|
|
659
|
+
recipient_key: s.key ?? null,
|
|
660
|
+
op: s.op,
|
|
661
|
+
mv_version: s.mvVersion,
|
|
662
|
+
want_from: s.want?.from ?? null,
|
|
663
|
+
want_to: s.want ? s.want.to : null,
|
|
664
|
+
manifest_hash: s.manifestHash ?? null,
|
|
665
|
+
conflicts_with: s.conflictsWith ?? null,
|
|
666
|
+
queued_at: now,
|
|
667
|
+
state: "queued",
|
|
668
|
+
state_at: null,
|
|
669
|
+
envelope_id: null,
|
|
670
|
+
reason: null,
|
|
671
|
+
});
|
|
672
|
+
ids.push(id);
|
|
673
|
+
queued++;
|
|
674
|
+
}
|
|
675
|
+
if (ids.length > 0) this._writeJsonObj("sendq", this.sendqPath, q);
|
|
676
|
+
return ids;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
queuedGroupV2Sends(groupId = null) {
|
|
680
|
+
const q = this._readJsonObj("sendq", this.sendqPath, []);
|
|
681
|
+
return q
|
|
682
|
+
.filter((x) => x.state === "queued" && (groupId == null || x.group_id === groupId))
|
|
683
|
+
.sort((a, b) => (a.queued_at < b.queued_at ? -1 : a.queued_at > b.queued_at ? 1 : 0));
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
markGroupV2Send(id, state, { envelopeId = null, reason = null } = {}) {
|
|
687
|
+
const q = this._readJsonObj("sendq", this.sendqPath, []);
|
|
688
|
+
const row = q.find((x) => x.id === id);
|
|
689
|
+
if (!row) return;
|
|
690
|
+
row.state = state;
|
|
691
|
+
row.state_at = new Date().toISOString();
|
|
692
|
+
if (envelopeId != null) row.envelope_id = envelopeId;
|
|
693
|
+
row.reason = reason ? String(reason).slice(0, 200) : null;
|
|
694
|
+
this._writeJsonObj("sendq", this.sendqPath, q);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// ── Readers & Leases ───────────────────────────────────────────────────────
|
|
698
|
+
|
|
699
|
+
getReader(name) {
|
|
700
|
+
const readers = this._readJsonObj("readers", this.readersPath, {});
|
|
701
|
+
return readers[name] ?? null;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
listReaders() {
|
|
705
|
+
const readers = this._readJsonObj("readers", this.readersPath, {});
|
|
706
|
+
return Object.values(readers).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
touchReader(name, { pid = null, host = null, cwd = null, command = null, cursor = 0 } = {}) {
|
|
710
|
+
const readers = this._readJsonObj("readers", this.readersPath, {});
|
|
711
|
+
const prev = readers[name];
|
|
712
|
+
readers[name] = {
|
|
713
|
+
name,
|
|
714
|
+
cursor: prev ? prev.cursor : cursor,
|
|
715
|
+
pid,
|
|
716
|
+
host,
|
|
717
|
+
cwd,
|
|
718
|
+
command,
|
|
719
|
+
last_seen: new Date().toISOString(),
|
|
720
|
+
};
|
|
721
|
+
this._writeJsonObj("readers", this.readersPath, readers);
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
setReaderCursor(name, seq) {
|
|
725
|
+
const readers = this._readJsonObj("readers", this.readersPath, {});
|
|
726
|
+
if (!readers[name]) return;
|
|
727
|
+
readers[name].cursor = Math.max(readers[name].cursor ?? 0, seq);
|
|
728
|
+
this._writeJsonObj("readers", this.readersPath, readers);
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
holdLease(reader, { host, pid, cwd = null, command = null, ttlMs = 90_000 }) {
|
|
732
|
+
const leases = this._readJsonObj("leases", this.leasesPath, []);
|
|
733
|
+
const now = new Date();
|
|
734
|
+
const until = new Date(now.getTime() + ttlMs).toISOString();
|
|
735
|
+
const existing = leases.find((l) => l.reader === reader && l.host === host && l.pid === pid);
|
|
736
|
+
if (existing) {
|
|
737
|
+
existing.lease_until = until;
|
|
738
|
+
} else {
|
|
739
|
+
leases.push({
|
|
740
|
+
reader,
|
|
741
|
+
host,
|
|
742
|
+
pid,
|
|
743
|
+
cwd,
|
|
744
|
+
command,
|
|
745
|
+
started_at: now.toISOString(),
|
|
746
|
+
lease_until: until,
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
this._writeJsonObj("leases", this.leasesPath, leases);
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
releaseLease(reader, { host, pid }) {
|
|
753
|
+
const leases = this._readJsonObj("leases", this.leasesPath, []);
|
|
754
|
+
const next = leases.filter((l) => !(l.reader === reader && l.host === host && l.pid === pid));
|
|
755
|
+
if (next.length !== leases.length) this._writeJsonObj("leases", this.leasesPath, next);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
unexpiredLeases() {
|
|
759
|
+
const leases = this._readJsonObj("leases", this.leasesPath, []);
|
|
760
|
+
const pruneCutoff = new Date(Date.now() - 3600_000).toISOString();
|
|
761
|
+
const nowIso = new Date().toISOString();
|
|
762
|
+
const kept = leases.filter((l) => l.lease_until >= pruneCutoff);
|
|
763
|
+
if (kept.length !== leases.length) this._writeJsonObj("leases", this.leasesPath, kept);
|
|
764
|
+
return kept
|
|
765
|
+
.filter((l) => l.lease_until >= nowIso)
|
|
766
|
+
.sort((a, b) => (a.started_at < b.started_at ? -1 : a.started_at > b.started_at ? 1 : 0));
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// ── Receipts ───────────────────────────────────────────────────────────────
|
|
770
|
+
|
|
771
|
+
markOutboundAcked(envelopeId, { from, ackId = null, at = null }) {
|
|
772
|
+
const rows = this._outboxRows();
|
|
773
|
+
const ts = at ?? new Date().toISOString();
|
|
774
|
+
let changed = 0;
|
|
775
|
+
for (const r of rows) {
|
|
776
|
+
if (r.envelope_id === envelopeId && r.recipient === from && !isErased(r)) {
|
|
777
|
+
if (!r.recipient_ack_at) r.recipient_ack_at = ts;
|
|
778
|
+
if (!r.recipient_ack_id && ackId != null) r.recipient_ack_id = ackId;
|
|
779
|
+
changed++;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
if (changed > 0) this._writeJsonl("outbox", this.outboxPath, rows);
|
|
783
|
+
return changed > 0;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/** First committed ack transition only (see Mailbox#markOutboundAckedFirst). */
|
|
787
|
+
markOutboundAckedFirst(envelopeId, { from, ackId = null, at = null }) {
|
|
788
|
+
const rows = this._outboxRows();
|
|
789
|
+
let first = false;
|
|
790
|
+
for (const r of rows) {
|
|
791
|
+
if (r.envelope_id === envelopeId && r.recipient === from && !isErased(r) && !r.recipient_ack_at) {
|
|
792
|
+
r.recipient_ack_at = at ?? new Date().toISOString();
|
|
793
|
+
if (!r.recipient_ack_id && ackId != null) r.recipient_ack_id = ackId;
|
|
794
|
+
first = true;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
if (first) this._writeJsonl("outbox", this.outboxPath, rows);
|
|
798
|
+
return first;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
markOutboundRead(envelopeIds, { at = null } = {}) {
|
|
802
|
+
const ids = new Set(envelopeIds);
|
|
803
|
+
const rows = this._outboxRows();
|
|
804
|
+
const ts = at ?? new Date().toISOString();
|
|
805
|
+
let changed = 0;
|
|
806
|
+
for (const r of rows) {
|
|
807
|
+
if (ids.has(r.envelope_id) && !isErased(r)) {
|
|
808
|
+
if (!r.recipient_read_at) r.recipient_read_at = ts;
|
|
809
|
+
if (!r.recipient_ack_at) r.recipient_ack_at = ts;
|
|
810
|
+
changed++;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
if (changed > 0) this._writeJsonl("outbox", this.outboxPath, rows);
|
|
814
|
+
return changed;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
outboundTo(recipient) {
|
|
818
|
+
return this._outboxRows().filter((r) => r.recipient === recipient && !isErased(r));
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
outboxRecent(limit = 20) {
|
|
822
|
+
return this._outboxRows().filter((r) => !isErased(r)).reverse().slice(0, limit);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// ── Groups ─────────────────────────────────────────────────────────────────
|
|
826
|
+
|
|
827
|
+
_formatGroup(raw) {
|
|
828
|
+
if (!raw) return null;
|
|
829
|
+
return {
|
|
830
|
+
id: raw.id,
|
|
831
|
+
name: raw.name,
|
|
832
|
+
members: [...raw.members],
|
|
833
|
+
keys: { ...(raw.keys ?? {}) },
|
|
834
|
+
createdBy: raw.created_by ?? null,
|
|
835
|
+
createdAt: raw.created_at,
|
|
836
|
+
updatedAt: raw.updated_at,
|
|
837
|
+
pending: !!raw.pending,
|
|
838
|
+
left: !!raw.left_at,
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
getGroup(id) {
|
|
843
|
+
const groups = this._readJsonObj("groups", this.groupsPath, {});
|
|
844
|
+
return this._formatGroup(groups[id] ?? null);
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
listGroups() {
|
|
848
|
+
const groups = this._readJsonObj("groups", this.groupsPath, {});
|
|
849
|
+
return Object.values(groups)
|
|
850
|
+
.sort((a, b) => (a.updated_at > b.updated_at ? -1 : a.updated_at < b.updated_at ? 1 : 0))
|
|
851
|
+
.map((g) => this._formatGroup(g));
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
markGroupV2(id, at = new Date().toISOString()) {
|
|
855
|
+
const groups = this._readJsonObj("groups", this.groupsPath, {});
|
|
856
|
+
if (!groups[id]) return;
|
|
857
|
+
groups[id].v2_synced_at = at;
|
|
858
|
+
this._writeJsonObj("groups", this.groupsPath, groups);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
isGroupV2Marked(id) {
|
|
862
|
+
const groups = this._readJsonObj("groups", this.groupsPath, {});
|
|
863
|
+
return !!groups[id]?.v2_synced_at;
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
groupV2MarkedIds() {
|
|
867
|
+
const groups = this._readJsonObj("groups", this.groupsPath, {});
|
|
868
|
+
return Object.values(groups)
|
|
869
|
+
.filter((g) => g.v2_synced_at != null)
|
|
870
|
+
.map((g) => g.id)
|
|
871
|
+
.sort();
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
putGroup(g) {
|
|
875
|
+
const groups = this._readJsonObj("groups", this.groupsPath, {});
|
|
876
|
+
const now = new Date().toISOString();
|
|
877
|
+
const prev = groups[g.id];
|
|
878
|
+
groups[g.id] = {
|
|
879
|
+
id: g.id,
|
|
880
|
+
name: g.name,
|
|
881
|
+
members: [...g.members],
|
|
882
|
+
keys: { ...(g.keys ?? {}) },
|
|
883
|
+
created_by: prev ? prev.created_by : (g.createdBy ?? null),
|
|
884
|
+
created_at: prev ? prev.created_at : (g.createdAt ?? now),
|
|
885
|
+
updated_at: now,
|
|
886
|
+
pending: g.pending ? 1 : 0,
|
|
887
|
+
left_at: g.left ? (g.leftAt ?? now) : null,
|
|
888
|
+
v2_synced_at: prev?.v2_synced_at ?? null,
|
|
889
|
+
};
|
|
890
|
+
this._writeJsonObj("groups", this.groupsPath, groups);
|
|
891
|
+
return this.getGroup(g.id);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
groupInbound(groupId, limit = 50) {
|
|
895
|
+
return this._inboxRows()
|
|
896
|
+
.filter((r) => r.group_id === groupId && r.quarantined == null && !isErased(r))
|
|
897
|
+
.slice(-limit);
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
groupOutbound(groupId, limit = 200) {
|
|
901
|
+
return this._outboxRows()
|
|
902
|
+
.filter((r) => r.group_id === groupId && !isErased(r))
|
|
903
|
+
.slice(-limit);
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
// ── Content Erasure & Chain Audits ─────────────────────────────────────────
|
|
907
|
+
|
|
908
|
+
eraseRows(selector) {
|
|
909
|
+
const bad = () => new TypeError("eraseRows: provide exactly one non-empty selector: pairs [{sender, envelope_id}], conversation, or groupId");
|
|
910
|
+
if (!selector || typeof selector !== "object" || Array.isArray(selector)) throw bad();
|
|
911
|
+
const keys = Object.keys(selector);
|
|
912
|
+
if (keys.length !== 1 || !["pairs", "conversation", "groupId"].includes(keys[0])) throw bad();
|
|
913
|
+
const nonempty = (v) => typeof v === "string" && v.trim().length > 0;
|
|
914
|
+
const mode = keys[0];
|
|
915
|
+
let pairs = null;
|
|
916
|
+
if (mode === "pairs") {
|
|
917
|
+
if (!Array.isArray(selector.pairs) || !selector.pairs.length) throw bad();
|
|
918
|
+
pairs = Array.from(selector.pairs, (p) => {
|
|
919
|
+
if (!p || typeof p !== "object" || Array.isArray(p) || Object.keys(p).length !== 2 || !nonempty(p.sender) || !nonempty(p.envelope_id)) throw bad();
|
|
920
|
+
return { sender: p.sender, envelope_id: p.envelope_id };
|
|
921
|
+
});
|
|
922
|
+
} else if (!nonempty(selector[mode])) {
|
|
923
|
+
throw bad();
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
const matchInbox = (r) => {
|
|
927
|
+
if (isErased(r)) return false;
|
|
928
|
+
if (mode === "pairs") return pairs.some((p) => r.sender === p.sender && r.envelope_id === p.envelope_id);
|
|
929
|
+
if (mode === "conversation") return r.sender === selector.conversation && r.group_id == null;
|
|
930
|
+
return r.group_id === selector.groupId;
|
|
931
|
+
};
|
|
932
|
+
const matchOutbox = (r) => {
|
|
933
|
+
if (isErased(r)) return false;
|
|
934
|
+
if (mode === "pairs") {
|
|
935
|
+
let sender = "unknown";
|
|
936
|
+
try {
|
|
937
|
+
const parsed = JSON.parse(r.envelope_json);
|
|
938
|
+
sender = parsed?.sender ?? parsed?.from ?? "unknown";
|
|
939
|
+
} catch {}
|
|
940
|
+
return pairs.some((p) => sender === p.sender && r.envelope_id === p.envelope_id);
|
|
941
|
+
}
|
|
942
|
+
if (mode === "conversation") return r.recipient === selector.conversation && r.group_id == null;
|
|
943
|
+
return r.group_id === selector.groupId;
|
|
944
|
+
};
|
|
945
|
+
|
|
946
|
+
const counts = { inbox: 0, outbox: 0 };
|
|
947
|
+
const inRows = this._inboxRows();
|
|
948
|
+
for (const r of inRows) {
|
|
949
|
+
if (matchInbox(r)) {
|
|
950
|
+
r.envelope_json = ERASED_ENVELOPE_JSON;
|
|
951
|
+
counts.inbox++;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
if (counts.inbox > 0) this._writeJsonl("inbox", this.inboxPath, inRows);
|
|
955
|
+
|
|
956
|
+
const outRows = this._outboxRows();
|
|
957
|
+
for (const r of outRows) {
|
|
958
|
+
if (matchOutbox(r)) {
|
|
959
|
+
r.envelope_json = ERASED_ENVELOPE_JSON;
|
|
960
|
+
counts.outbox++;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
if (counts.outbox > 0) this._writeJsonl("outbox", this.outboxPath, outRows);
|
|
964
|
+
|
|
965
|
+
if (mode === "pairs" || mode === "conversation") {
|
|
966
|
+
const kRows = this._knockRows();
|
|
967
|
+
let kChanged = false;
|
|
968
|
+
for (const r of kRows) {
|
|
969
|
+
if (isErased(r)) continue;
|
|
970
|
+
const hit = mode === "pairs"
|
|
971
|
+
? pairs.some((p) => r.sender === p.sender && r.envelope_id === p.envelope_id)
|
|
972
|
+
: r.sender === selector.conversation;
|
|
973
|
+
if (hit) {
|
|
974
|
+
r.envelope_json = ERASED_ENVELOPE_JSON;
|
|
975
|
+
kChanged = true;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
if (kChanged) this._writeJsonl("knocks", this.knocksPath, kRows);
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
return counts;
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
_audit(kind, filePath) {
|
|
985
|
+
let prev = null;
|
|
986
|
+
let prevSeq = 0;
|
|
987
|
+
const entries = this.memory
|
|
988
|
+
? this._mem[kind].map((row, i) => ({ lineNo: i + 1, row }))
|
|
989
|
+
: this._readJsonlRaw(filePath).map(({ lineNo, raw }) => {
|
|
990
|
+
try { return { lineNo, row: JSON.parse(raw) }; }
|
|
991
|
+
catch { return { lineNo, row: null }; }
|
|
992
|
+
});
|
|
993
|
+
|
|
994
|
+
for (const { lineNo, row } of entries) {
|
|
995
|
+
if (!row || typeof row !== "object") return { ok: false, badSeq: lineNo };
|
|
996
|
+
if (!Number.isSafeInteger(row.seq) || row.seq <= prevSeq) return { ok: false, badSeq: lineNo };
|
|
997
|
+
prevSeq = row.seq;
|
|
998
|
+
if (!isErased(row)) {
|
|
999
|
+
let parsedEnv = null;
|
|
1000
|
+
try { parsedEnv = JSON.parse(row.envelope_json); } catch { parsedEnv = null; }
|
|
1001
|
+
if (!parsedEnv || typeof parsedEnv !== "object" || envelopeSha(parsedEnv) !== row.envelope_sha256) {
|
|
1002
|
+
return { ok: false, badSeq: row.seq };
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
const chainInput = prev === null ? CHAIN_SEED + row.envelope_sha256 : prev + row.envelope_sha256;
|
|
1006
|
+
const expected = createHash("sha256").update(chainInput).digest("hex");
|
|
1007
|
+
if (expected !== row.chain_hash) return { ok: false, badSeq: row.seq };
|
|
1008
|
+
prev = row.chain_hash;
|
|
1009
|
+
}
|
|
1010
|
+
return { ok: true };
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
auditOutbox() {
|
|
1014
|
+
return this._audit("outbox", this.outboxPath);
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
auditInbox() {
|
|
1018
|
+
return this._audit("inbox", this.inboxPath);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
/**
|
|
1023
|
+
* Every JsonlMailboxStore method that writes (or, for the audits, must see a
|
|
1024
|
+
* torn tail) runs under `_withLock`. Each is one whole read-modify-write. A
|
|
1025
|
+
* test classifies every prototype method, so a new one must be listed here or
|
|
1026
|
+
* among the lock-free reads.
|
|
1027
|
+
*/
|
|
1028
|
+
export const LOCKED_METHODS = Object.freeze([
|
|
1029
|
+
"setCarrierCursor",
|
|
1030
|
+
"appendOutbound",
|
|
1031
|
+
"appendInbound",
|
|
1032
|
+
"markOutboundDelivered",
|
|
1033
|
+
"admitKnock",
|
|
1034
|
+
"markKnockAnswered",
|
|
1035
|
+
"markQuarantined",
|
|
1036
|
+
"releaseQuarantined",
|
|
1037
|
+
"markInboxRead",
|
|
1038
|
+
"setInboundGroup",
|
|
1039
|
+
"enqueueGroupV2Sends",
|
|
1040
|
+
"markGroupV2Send",
|
|
1041
|
+
"touchReader",
|
|
1042
|
+
"setReaderCursor",
|
|
1043
|
+
"holdLease",
|
|
1044
|
+
"releaseLease",
|
|
1045
|
+
"unexpiredLeases",
|
|
1046
|
+
"markOutboundAcked",
|
|
1047
|
+
"markOutboundAckedFirst",
|
|
1048
|
+
"markOutboundRead",
|
|
1049
|
+
"markGroupV2",
|
|
1050
|
+
"putGroup",
|
|
1051
|
+
"eraseRows",
|
|
1052
|
+
"auditOutbox",
|
|
1053
|
+
"auditInbox",
|
|
1054
|
+
]);
|
|
1055
|
+
|
|
1056
|
+
for (const name of LOCKED_METHODS) {
|
|
1057
|
+
const unlocked = JsonlMailboxStore.prototype[name];
|
|
1058
|
+
if (typeof unlocked !== "function") throw new Error(`LOCKED_METHODS: JsonlMailboxStore has no method ${name}`);
|
|
1059
|
+
Object.defineProperty(JsonlMailboxStore.prototype, name, {
|
|
1060
|
+
value: function locked(...args) {
|
|
1061
|
+
return this._withLock(() => unlocked.apply(this, args));
|
|
1062
|
+
},
|
|
1063
|
+
writable: true,
|
|
1064
|
+
configurable: true,
|
|
1065
|
+
});
|
|
1066
|
+
}
|