@uuaid/pillar 2.7.3 → 2.8.1

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.
@@ -42,6 +42,7 @@ import {
42
42
  readRecoverySheetWords,
43
43
  writeFileAtomic,
44
44
  } from "./wave-a.mjs";
45
+ import { directoryCarriers, readBackCarriers, relayedCarriersIn, MAX_RELAYED_FROM_DIRECTORY } from "../net/discovery.mjs";
45
46
 
46
47
  const INIT_VALUE_FLAGS = new Set([
47
48
  "home",
@@ -173,8 +174,15 @@ function failInit(errOut, msg, exitCode = 1) {
173
174
  return { exitCode };
174
175
  }
175
176
 
176
- function carriersFromDirectory(d) {
177
- return [d.carrier, ...(Array.isArray(d.seeds) ? d.seeds.map((s) => s.url) : [])].filter(Boolean);
177
+ /**
178
+ * The carriers a directory offers, minus every relayed seed URL (2.8.0,
179
+ * src/net/discovery.mjs). A note on stderr says how many were left out, so
180
+ * --json output on stdout stays one document.
181
+ */
182
+ function carriersFromDirectory(d, errOut) {
183
+ const { carriers, skippedRelayed } = directoryCarriers(d);
184
+ if (skippedRelayed) errOut(`note: ${skippedRelayed} relayed seed URL(s) in the directory were not added (no relay named for its URL, or past the first ${MAX_RELAYED_FROM_DIRECTORY}); name one with pillar init --carriers <url>\n`);
185
+ return carriers;
178
186
  }
179
187
 
180
188
  function mergeDirectoryAgents(home, d) {
@@ -266,13 +274,21 @@ export async function runInitCli(rawArgs, io = {}) {
266
274
  if (typeof opts.directory !== "string") return failInit(errOut, "refresh: --directory <url> is required");
267
275
  const d = await fetchDirectory(opts.directory, errOut);
268
276
  if (!d) return { exitCode: 1 };
269
- const list = carriersFromDirectory(d);
270
- if (!list.length) return failInit(errOut, `refresh: directory ${opts.directory} lists no carrier and no seeds`);
277
+ const list = carriersFromDirectory(d, errOut);
271
278
  const cfgPath = join(home, "config.json");
279
+ if (!list.length) {
280
+ // Nothing is written, so a relayed URL an earlier directory added stays (2.8.0).
281
+ const left = relayedCarriersIn(cfgPath);
282
+ const still = left.length ? `; ${cfgPath} is unchanged and still lists ${left.length} relayed seed URL(s): ${left.join(", ")} (remove them by hand, or refresh from a directory that lists a carrier)` : "";
283
+ return failInit(errOut, `refresh: directory ${opts.directory} lists no carrier and no seeds${still}`);
284
+ }
272
285
  const cfg = existsSync(cfgPath) ? JSON.parse(readFileSync(cfgPath, "utf-8")) : {};
273
286
  cfg.carriers = list;
274
287
  writeFileSync(cfgPath, JSON.stringify(cfg, null, 2), { mode: 0o600 });
275
- out(`carriers refreshed from ${opts.directory}: ${list.join(", ")}\n`);
288
+ // What is on disk is the evidence (RedTeam 995f4c Q2), not what was meant.
289
+ const back = readBackCarriers(cfgPath, list);
290
+ if (!back.ok) return failInit(errOut, `refresh: ${cfgPath} ${back.reason}; the carriers were not refreshed`);
291
+ out(`carriers refreshed from ${opts.directory}: ${back.carriers.join(", ")} (read back from ${cfgPath})\n`);
276
292
  const ab = mergeDirectoryAgents(home, d);
277
293
  if (ab) out(`address book: ${ab.count} peers in ${join(home, "fleet.json")} (${ab.added} new from directory)\n`);
278
294
  out(`refresh complete at ${home} (keychain untouched)\n`);
@@ -316,7 +332,7 @@ export async function runInitCli(rawArgs, io = {}) {
316
332
  if (typeof opts.directory === "string") {
317
333
  const d = await fetchDirectory(opts.directory, errOut);
318
334
  if (!d) return { exitCode: 1 };
319
- const list = carriersFromDirectory(d);
335
+ const list = carriersFromDirectory(d, errOut);
320
336
  if (list.length) cfg.carriers = list;
321
337
  mergeDirectoryAgents(home, d);
322
338
  } else if (opts.carriers !== undefined) {
@@ -423,7 +439,7 @@ export async function runInitCli(rawArgs, io = {}) {
423
439
  if (typeof opts.directory === "string") {
424
440
  dirData = await fetchDirectory(opts.directory, errOut);
425
441
  if (!dirData) return { exitCode: 1 };
426
- const list = carriersFromDirectory(dirData);
442
+ const list = carriersFromDirectory(dirData, errOut);
427
443
  if (!list.length) return failInit(errOut, `init: directory ${opts.directory} lists no carrier and no seeds`);
428
444
  cfg.carriers = list;
429
445
  } else if (opts.carriers !== undefined) {
@@ -184,6 +184,12 @@ export class JsonDirMailboxReader {
184
184
  return this._inboxRows().filter((r) => r.seq > seq && !isErased(r)).slice(0, limit);
185
185
  }
186
186
 
187
+ inboxAtSeqs(seqs = []) {
188
+ const set = new Set(seqs.filter((n) => Number.isSafeInteger(n) && n > 0));
189
+ if (set.size === 0) return [];
190
+ return this._inboxRows().filter((r) => set.has(r.seq) && !isErased(r));
191
+ }
192
+
187
193
  inboxUnread(limit = 100) {
188
194
  return filterRegularInboxRows(
189
195
  this._inboxRows().filter((r) => r.read_at == null && r.quarantined == null && !isErased(r))
@@ -141,9 +141,14 @@ export class JsonlMailboxStore {
141
141
  this.sendqPath = join(mailboxDir, "group_v2_sendq.json");
142
142
  this.metaPath = join(mailboxDir, "meta.json");
143
143
  this.lockPath = join(mailboxDir, "mailbox.lock");
144
+ this._resetInboxIndex();
144
145
  }
145
146
  }
146
147
 
148
+ _resetInboxIndex() {
149
+ this._inboxIdx = { ino: null, size: 0, entries: [], bySeq: new Map(), byKey: new Map(), monotonic: true, maxPos: 0, maxFloor: 0, tailBuf: null };
150
+ }
151
+
147
152
  close() {}
148
153
 
149
154
  /**
@@ -209,6 +214,7 @@ export class JsonlMailboxStore {
209
214
  writeFileSync(backup, buf.subarray(cut, off), { mode: 0o600, flag: "wx" });
210
215
  this._assertStillLocked(`cut of the torn tail of ${basename(filePath)}`);
211
216
  ftruncateSync(fd, cut);
217
+ if (filePath === this.inboxPath) this._resetInboxIndex();
212
218
  return backup;
213
219
  } finally { closeSync(fd); }
214
220
  }
@@ -234,14 +240,90 @@ export class JsonlMailboxStore {
234
240
  throw e;
235
241
  }
236
242
  renameSync(tmp, filePath);
243
+ if (filePath === this.inboxPath) this._resetInboxIndex();
237
244
  }
238
245
 
239
- _readJsonlRaw(filePath) {
240
- if (!existsSync(filePath)) return [];
241
- let text = readFileSync(filePath, "utf8");
246
+ _committedBytes(buf) {
242
247
  // Outside the lock an unterminated tail is an append in flight: not yet a
243
248
  // row. Under the lock a torn tail was already moved aside (_repairTornTails).
244
- if (!this._lock) text = text.slice(0, text.lastIndexOf("\n") + 1); // @rule jsonl.read-committed-rows
249
+ if (!this._lock) buf = buf.subarray(0, buf.lastIndexOf(0x0a) + 1); // @rule jsonl.read-committed-rows
250
+ return buf;
251
+ }
252
+
253
+ _syncInboxIndex(fd) {
254
+ const st = fstatSync(fd);
255
+ let idx = this._inboxIdx;
256
+ let reset = !idx || idx.ino !== st.ino || st.size < idx.size;
257
+ if (!reset && idx.size > 0 && idx.tailBuf) {
258
+ const check = Buffer.allocUnsafe(idx.tailBuf.length);
259
+ const got = readSync(fd, check, 0, check.length, idx.size - check.length);
260
+ if (got !== check.length || !check.equals(idx.tailBuf)) reset = true;
261
+ }
262
+ if (reset) {
263
+ idx = { ino: st.ino, size: 0, entries: [], bySeq: new Map(), byKey: new Map(), monotonic: true, maxPos: 0, maxFloor: 0, tailBuf: null };
264
+ this._inboxIdx = idx;
265
+ }
266
+ if (st.size > idx.size) {
267
+ const len = st.size - idx.size;
268
+ const raw = Buffer.allocUnsafe(len);
269
+ let off = 0;
270
+ while (off < len) {
271
+ const n = readSync(fd, raw, off, len - off, idx.size + off);
272
+ if (n === 0) break;
273
+ off += n;
274
+ }
275
+ const committed = this._committedBytes(raw.subarray(0, off));
276
+ if (committed.length > 0) {
277
+ let pos = 0;
278
+ while (pos < committed.length) {
279
+ const nl = committed.indexOf(0x0a, pos);
280
+ const end = nl === -1 ? committed.length : nl;
281
+ const line = committed.subarray(pos, end).toString("utf8").trim();
282
+ if (line) {
283
+ const row = JSON.parse(line);
284
+ const seq = row.seq ?? 0;
285
+ if (idx.entries.length > 0 && seq < idx.entries[idx.entries.length - 1].seq) idx.monotonic = false;
286
+ const entry = {
287
+ seq,
288
+ offset: idx.size + pos,
289
+ length: end - pos,
290
+ erased: isErased(row),
291
+ chain_hash: row.chain_hash ?? null,
292
+ };
293
+ idx.entries.push(entry);
294
+ idx.bySeq.set(seq, entry);
295
+ idx.byKey.set(`${row.sender ?? ""}\0${row.envelope_id ?? ""}`, { seq, envelope_sha256: row.envelope_sha256 });
296
+ const tipPos = row.released_seq ?? seq;
297
+ if (tipPos > idx.maxPos) idx.maxPos = tipPos;
298
+ const floorPos = Math.max(seq, row.released_seq ?? 0);
299
+ if (floorPos > idx.maxFloor) idx.maxFloor = floorPos;
300
+ }
301
+ if (nl === -1) break;
302
+ pos = nl + 1;
303
+ }
304
+ if (!idx.monotonic) idx.entries.sort((a, b) => a.seq - b.seq);
305
+ idx.size += committed.length;
306
+ const tailLen = Math.min(64, committed.length);
307
+ idx.tailBuf = Buffer.from(committed.subarray(committed.length - tailLen));
308
+ }
309
+ }
310
+ return idx;
311
+ }
312
+
313
+ _preadInboxRow(fd, entry) {
314
+ const buf = Buffer.allocUnsafe(entry.length);
315
+ let off = 0;
316
+ while (off < entry.length) {
317
+ const n = readSync(fd, buf, off, entry.length - off, entry.offset + off);
318
+ if (n === 0) break;
319
+ off += n;
320
+ }
321
+ return JSON.parse(buf.subarray(0, off).toString("utf8").trim());
322
+ }
323
+
324
+ _readJsonlRaw(filePath) {
325
+ if (!existsSync(filePath)) return [];
326
+ const text = this._committedBytes(readFileSync(filePath)).toString("utf8");
245
327
  const out = [];
246
328
  let lineNo = 0;
247
329
  for (const raw of text.split("\n")) {
@@ -379,22 +461,47 @@ export class JsonlMailboxStore {
379
461
  appendInbound(envelope, { pulledBy = null, quarantined = null } = {}) {
380
462
  const sender = envelope.sender ?? envelope.from ?? "unknown";
381
463
  const envSha = envelopeSha(envelope);
382
- const rows = this._inboxRows();
383
- const existing = rows.find((r) => r.envelope_id === envelope.id && r.sender === sender);
384
- if (existing) {
385
- const collision = existing.envelope_sha256 !== envSha;
386
- return {
387
- duplicate: true,
388
- ...(collision ? { collision: true } : {}),
389
- seq: existing.seq,
390
- envelopeId: envelope.id,
391
- envelopeSha256: existing.envelope_sha256,
392
- };
464
+ let prev = null;
465
+ let nextSeq = 1;
466
+ if (this.memory) {
467
+ const rows = this._inboxRows();
468
+ const existing = rows.find((r) => r.envelope_id === envelope.id && r.sender === sender);
469
+ if (existing) {
470
+ const collision = existing.envelope_sha256 !== envSha;
471
+ return {
472
+ duplicate: true,
473
+ ...(collision ? { collision: true } : {}),
474
+ seq: existing.seq,
475
+ envelopeId: envelope.id,
476
+ envelopeSha256: existing.envelope_sha256,
477
+ };
478
+ }
479
+ prev = rows.length > 0 ? rows[rows.length - 1].chain_hash : null;
480
+ nextSeq = this._getSeqFloor() + 1;
481
+ } else {
482
+ let idx = null;
483
+ let fd = null;
484
+ try { fd = openSync(this.inboxPath, "r"); } catch (e) { if (e.code !== "ENOENT") throw e; }
485
+ if (fd !== null) {
486
+ try { idx = this._syncInboxIndex(fd); } finally { closeSync(fd); }
487
+ }
488
+ const existing = idx?.byKey.get(`${sender}\0${envelope.id}`);
489
+ if (existing) {
490
+ const collision = existing.envelope_sha256 !== envSha;
491
+ return {
492
+ duplicate: true,
493
+ ...(collision ? { collision: true } : {}),
494
+ seq: existing.seq,
495
+ envelopeId: envelope.id,
496
+ envelopeSha256: existing.envelope_sha256,
497
+ };
498
+ }
499
+ prev = idx && idx.entries.length > 0 ? idx.entries[idx.entries.length - 1].chain_hash : null;
500
+ const metaFloor = this._readJsonObj(null, this.metaPath, {})?.seqFloor ?? 0;
501
+ nextSeq = Math.max(metaFloor, idx ? idx.maxFloor : 0) + 1;
393
502
  }
394
- const prev = rows.length > 0 ? rows[rows.length - 1].chain_hash : null;
395
503
  const chainInput = prev == null ? CHAIN_SEED + envSha : prev + envSha;
396
504
  const chain = createHash("sha256").update(chainInput).digest("hex");
397
- const nextSeq = this._getSeqFloor() + 1;
398
505
  const row = {
399
506
  seq: nextSeq,
400
507
  envelope_id: envelope.id,
@@ -458,7 +565,47 @@ export class JsonlMailboxStore {
458
565
  }
459
566
 
460
567
  inboxSince(seq = 0, limit = 100) {
461
- return this._inboxRows().filter((r) => r.seq > seq && !isErased(r)).slice(0, limit);
568
+ if (limit <= 0) return [];
569
+ if (this.memory) return this._inboxRows().filter((r) => r.seq > seq && !isErased(r)).slice(0, limit);
570
+ let fd;
571
+ try { fd = openSync(this.inboxPath, "r"); } catch (e) { if (e.code === "ENOENT") return []; throw e; }
572
+ try {
573
+ const idx = this._syncInboxIndex(fd);
574
+ let lo = 0, hi = idx.entries.length;
575
+ while (lo < hi) {
576
+ const mid = (lo + hi) >>> 1;
577
+ if (idx.entries[mid].seq <= seq) lo = mid + 1;
578
+ else hi = mid;
579
+ }
580
+ const out = [];
581
+ for (let i = lo; i < idx.entries.length && out.length < limit; i++) {
582
+ const e = idx.entries[i];
583
+ if (e.erased) continue;
584
+ out.push(this._preadInboxRow(fd, e));
585
+ }
586
+ return out;
587
+ } finally { closeSync(fd); }
588
+ }
589
+
590
+ inboxAtSeqs(seqs = []) {
591
+ const wanted = [...new Set(seqs.filter((n) => Number.isSafeInteger(n) && n > 0))].sort((a, b) => a - b);
592
+ if (wanted.length === 0) return [];
593
+ if (this.memory) {
594
+ const set = new Set(wanted);
595
+ return this._inboxRows().filter((r) => set.has(r.seq) && !isErased(r));
596
+ }
597
+ let fd;
598
+ try { fd = openSync(this.inboxPath, "r"); } catch (e) { if (e.code === "ENOENT") return []; throw e; }
599
+ try {
600
+ const idx = this._syncInboxIndex(fd);
601
+ const out = [];
602
+ for (const s of wanted) {
603
+ const e = idx.bySeq.get(s);
604
+ if (!e || e.erased) continue;
605
+ out.push(this._preadInboxRow(fd, e));
606
+ }
607
+ return out;
608
+ } finally { closeSync(fd); }
462
609
  }
463
610
 
464
611
  inboxUnread(limit = 100) {
@@ -484,12 +631,19 @@ export class JsonlMailboxStore {
484
631
  }
485
632
 
486
633
  inboxTipSeq() {
487
- let max = 0;
488
- for (const r of this._inboxRows()) {
489
- const pos = r.released_seq ?? r.seq ?? 0;
490
- if (pos > max) max = pos;
634
+ if (this.memory) {
635
+ let max = 0;
636
+ for (const r of this._inboxRows()) {
637
+ const pos = r.released_seq ?? r.seq ?? 0;
638
+ if (pos > max) max = pos;
639
+ }
640
+ return max;
491
641
  }
492
- return max;
642
+ let fd;
643
+ try { fd = openSync(this.inboxPath, "r"); } catch (e) { if (e.code === "ENOENT") return 0; throw e; }
644
+ try {
645
+ return this._syncInboxIndex(fd).maxPos;
646
+ } finally { closeSync(fd); }
493
647
  }
494
648
 
495
649
  inboxAfter(seq = 0, limit = 500) {
@@ -44,6 +44,7 @@ import {
44
44
  resolveCarriers,
45
45
  resolveHome,
46
46
  } from "./a6b-common.mjs";
47
+ import { ContinuityRefusalError, ContinuityStore, decideFor } from "./continuity.mjs";
47
48
  import { KNOCK_ANSWER_DECISIONS } from "./knock-answer.mjs";
48
49
  import { KNOCK_LANE_CAP } from "./knock-lane.mjs";
49
50
  import { buildInertKnockRecord, quoteInertText, renderKnockDataBlock } from "./knock-responder.mjs";
@@ -161,6 +162,22 @@ export async function runKnockCli(rawArgs, io = {}) {
161
162
  let redirectedFrom;
162
163
  let redirectedTo;
163
164
 
165
+ // The continuity decision for the identity asked for comes before any registry resolution (RedTeam b5cbee P1):
166
+ // held or suspended refuses here, active knocks the destination the user confirmed.
167
+ let route;
168
+ try { route = decideFor(new ContinuityStore(home).read(), toUuaid, nowIsoSeconds()); }
169
+ catch (e) { return failCli(errOut, `knock: ${e.code ?? "continuity"}: ${e.message}${e.fix ? ` (${e.fix})` : ""}`, 1); }
170
+ if (route.state === "pending-confirm" || route.state === "suspended") {
171
+ const e = new ContinuityRefusalError(route.state === "pending-confirm" ? "continuity-held" : `redirect-blocked:${route.reason}`, `${toUuaid} is ${route.state}${route.reason ? ` (${route.reason})` : ""}; nothing was sent`, route);
172
+ return failCli(errOut, `knock: ${e.message} (${e.fix})`, 1);
173
+ }
174
+ if (route.state === "active") {
175
+ recipient = route.to;
176
+ recipientPublicKey = route.toKey;
177
+ redirectedFrom = toUuaid;
178
+ redirectedTo = route.to;
179
+ }
180
+
164
181
  if (!recipientPublicKey) {
165
182
  const registryUrl = opts.registry ?? cfg.registry ?? DEFAULT_RESOLVE_REGISTRY;
166
183
  if (!isRegistryUrl(registryUrl)) return failCli(errOut, `knock: --registry must be an https:// (or loopback http://) URL, got "${registryUrl}"`, 64); // @rule knock-cli.registry-url
@@ -237,6 +254,7 @@ export async function runKnockCli(rawArgs, io = {}) {
237
254
  sent = await p.sendKnock({
238
255
  recipient,
239
256
  recipientPublicKey,
257
+ subject: toUuaid,
240
258
  card: senderCard,
241
259
  intent,
242
260
  ...(payment ? { payment } : { bits: effectiveBits }),