@peer2peer/cli 0.0.0-stage → 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.
Files changed (105) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +366 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +363 -0
  6. package/dist/app.js +1177 -0
  7. package/dist/bin.d.ts +2 -0
  8. package/dist/bin.js +56 -0
  9. package/dist/circle-ops.d.ts +402 -0
  10. package/dist/circle-ops.js +1725 -0
  11. package/dist/cli.d.ts +611 -0
  12. package/dist/cli.js +1650 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +112 -0
  16. package/dist/config.js +243 -0
  17. package/dist/doctor.d.ts +99 -0
  18. package/dist/doctor.js +817 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +32 -0
  22. package/dist/ext-host.js +259 -0
  23. package/dist/extensions.d.ts +386 -0
  24. package/dist/extensions.js +395 -0
  25. package/dist/features.d.ts +91 -0
  26. package/dist/features.js +164 -0
  27. package/dist/format.d.ts +57 -0
  28. package/dist/format.js +248 -0
  29. package/dist/identity.d.ts +236 -0
  30. package/dist/identity.js +751 -0
  31. package/dist/inbound.d.ts +32 -0
  32. package/dist/inbound.js +258 -0
  33. package/dist/index.d.ts +8 -0
  34. package/dist/index.js +14 -0
  35. package/dist/join-answers.d.ts +49 -0
  36. package/dist/join-answers.js +149 -0
  37. package/dist/outbox.d.ts +109 -0
  38. package/dist/outbox.js +337 -0
  39. package/dist/pretty.d.ts +100 -0
  40. package/dist/pretty.js +256 -0
  41. package/dist/procstart.d.ts +1 -0
  42. package/dist/procstart.js +66 -0
  43. package/dist/progress.d.ts +30 -0
  44. package/dist/progress.js +78 -0
  45. package/dist/projects.d.ts +240 -0
  46. package/dist/projects.js +699 -0
  47. package/dist/prompt/picker.d.ts +64 -0
  48. package/dist/prompt/picker.js +152 -0
  49. package/dist/prompt/tty.d.ts +29 -0
  50. package/dist/prompt/tty.js +122 -0
  51. package/dist/readonly.d.ts +20 -0
  52. package/dist/readonly.js +50 -0
  53. package/dist/receipts.d.ts +99 -0
  54. package/dist/receipts.js +180 -0
  55. package/dist/relay-client.d.ts +277 -0
  56. package/dist/relay-client.js +873 -0
  57. package/dist/relay-info.d.ts +24 -0
  58. package/dist/relay-info.js +53 -0
  59. package/dist/rotation.d.ts +402 -0
  60. package/dist/rotation.js +2054 -0
  61. package/dist/running.d.ts +5 -0
  62. package/dist/running.js +74 -0
  63. package/dist/sessions.d.ts +340 -0
  64. package/dist/sessions.js +1152 -0
  65. package/dist/shortcode.d.ts +149 -0
  66. package/dist/shortcode.js +465 -0
  67. package/dist/social.d.ts +139 -0
  68. package/dist/social.js +485 -0
  69. package/dist/state.d.ts +483 -0
  70. package/dist/state.js +217 -0
  71. package/dist/stdin.d.ts +17 -0
  72. package/dist/stdin.js +46 -0
  73. package/dist/sync.d.ts +77 -0
  74. package/dist/sync.js +375 -0
  75. package/dist/transient.d.ts +1 -0
  76. package/dist/transient.js +28 -0
  77. package/dist/trust.d.ts +37 -0
  78. package/dist/trust.js +134 -0
  79. package/dist/tty-confirm.d.ts +2 -0
  80. package/dist/tty-confirm.js +53 -0
  81. package/dist/tui/command.d.ts +20 -0
  82. package/dist/tui/command.js +70 -0
  83. package/dist/tui/frame.d.ts +43 -0
  84. package/dist/tui/frame.js +111 -0
  85. package/dist/tui/model.d.ts +215 -0
  86. package/dist/tui/model.js +255 -0
  87. package/dist/tui/sanitize.d.ts +13 -0
  88. package/dist/tui/sanitize.js +151 -0
  89. package/dist/tui/terminal.d.ts +88 -0
  90. package/dist/tui/terminal.js +354 -0
  91. package/dist/tui/tui.d.ts +71 -0
  92. package/dist/tui/tui.js +571 -0
  93. package/dist/tui/view.d.ts +4 -0
  94. package/dist/tui/view.js +356 -0
  95. package/dist/unknown-kinds.d.ts +12 -0
  96. package/dist/unknown-kinds.js +66 -0
  97. package/dist/version.d.ts +1 -0
  98. package/dist/version.js +5 -0
  99. package/dist/want-pow.d.ts +12 -0
  100. package/dist/want-pow.js +46 -0
  101. package/dist/watch.d.ts +35 -0
  102. package/dist/watch.js +325 -0
  103. package/dist/xstate.d.ts +125 -0
  104. package/dist/xstate.js +422 -0
  105. package/package.json +60 -4
package/dist/sync.js ADDED
@@ -0,0 +1,375 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // `sync` envelopes (§4.3, from == to only): how a user's devices share
4
+ // state. Each object is re-verified on arrival where it can be (friendships,
5
+ // unfriends, caps held, circle chains and statements); local preferences
6
+ // (blocks, petnames, the default circle) are taken as the user's own.
7
+ //
8
+ // Reading: joining a circle is the user's explicit action (review C1); it is
9
+ // carried to the user's own devices by sync, with `myN` kept in step (§3.3).
10
+ import { applyCircleBundle, CircleChain, loadCircle, P2PError, recordFriendshipV3, storeOfferedCircle, verifyCap, peekIdentityDoc, reverifyFriendshipForApproval, verifyUnfriendV3, parseCircleVersion, } from "@peer2peer/core/v3";
11
+ import { FileDocBackend } from "@peer2peer/core/v3/node";
12
+ import { App } from "./app.js";
13
+ import { importCodes } from "./codes.js";
14
+ import { importWantAnswered } from "./circle-ops.js";
15
+ import { importRotationApprovals, importRotationDispute, importRotationResolved, noteOwnRotation, untrustedImportSigner } from "./rotation.js";
16
+ /**
17
+ * Keeps each sync (and circle bundle) plaintext under the 64 KiB envelope cap (§1). Sealing and the
18
+ * two layers of base64 (the ciphertext, then the JWS payload) make an envelope about 16/9 of its
19
+ * plaintext, plus ~3 KiB of certificate and fields: 36 KiB came out at ~66 KB, and a long circle
20
+ * chain could no longer be sent at all (found by the soak harness). 30 KiB leaves ~9 KiB spare.
21
+ */
22
+ export const SYNC_CHUNK_BYTES = 30 * 1024;
23
+ const bytes = (v) => Buffer.byteLength(JSON.stringify(v ?? null), "utf8");
24
+ /** Sync fields that are maps merged key by key on import, so a large one can be split (review M2). */
25
+ const MAP_FIELDS = new Set(["petnames"]);
26
+ /**
27
+ * A circle export cut into items that each fit a chunk (review M2): its versions in order, then its
28
+ * statements, each item carrying the circle's metadata. importCircle puts them back together.
29
+ */
30
+ export function splitCircle(c, max = SYNC_CHUNK_BYTES - 1024) {
31
+ if (bytes(c) <= max)
32
+ return [c];
33
+ const { versions, statements, ...meta } = c;
34
+ const out = [];
35
+ let cur = { ...meta, versions: [], statements: [] };
36
+ let size = bytes(cur);
37
+ const add = (field, v) => {
38
+ const s = bytes(v) + 1;
39
+ if (size + s > max && (cur.versions.length > 0 || cur.statements.length > 0)) {
40
+ out.push(cur);
41
+ cur = { ...meta, versions: [], statements: [] };
42
+ size = bytes(cur);
43
+ }
44
+ cur[field].push(v);
45
+ size += s;
46
+ };
47
+ for (const v of versions)
48
+ add("versions", v);
49
+ for (const s of statements)
50
+ add("statements", s);
51
+ out.push(cur);
52
+ return out;
53
+ }
54
+ /** Splits a body of arrays into several bodies, each at most `max` bytes of UTF-8 JSON (single items may exceed it). */
55
+ export function chunkBody(body, max = SYNC_CHUNK_BYTES) {
56
+ const out = [];
57
+ let cur = {};
58
+ let size = 2;
59
+ const flush = () => {
60
+ if (Object.keys(cur).length > 0)
61
+ out.push(cur);
62
+ cur = {};
63
+ size = 2;
64
+ };
65
+ for (const [k, v] of Object.entries(body)) {
66
+ if (!Array.isArray(v)) {
67
+ const s = bytes(v) + Buffer.byteLength(k, "utf8") + 4;
68
+ // A map (petnames) too big for one chunk goes in parts: the receiver merges it key by key.
69
+ if (MAP_FIELDS.has(k) && v !== null && typeof v === "object" && s > max / 2) {
70
+ for (const [mk, mv] of Object.entries(v)) {
71
+ const es = bytes(mk) + bytes(mv) + 2;
72
+ if (size + es + k.length + 8 > max)
73
+ flush();
74
+ const m = (cur[k] ??= {});
75
+ m[mk] = mv;
76
+ size += es + (Object.keys(m).length === 1 ? Buffer.byteLength(k, "utf8") + 6 : 0);
77
+ }
78
+ continue;
79
+ }
80
+ if (size + s > max)
81
+ flush();
82
+ cur[k] = v;
83
+ size += s;
84
+ continue;
85
+ }
86
+ for (const item of v) {
87
+ const s = bytes(item) + Buffer.byteLength(k, "utf8") + 4;
88
+ if (size + s > max)
89
+ flush();
90
+ (cur[k] = cur[k] ?? []);
91
+ cur[k].push(item);
92
+ size += s;
93
+ }
94
+ }
95
+ flush();
96
+ return out;
97
+ }
98
+ export async function exportCircle(app, cid) {
99
+ const c = await loadCircle(app.store, cid);
100
+ if (!c)
101
+ return undefined;
102
+ return {
103
+ cid,
104
+ versions: c.chain.versionsFrom(1),
105
+ statements: Object.values(c.book).map((s) => s.jws),
106
+ joinedByMe: c.record.joinedByMe,
107
+ ...(c.record.myN !== undefined ? { myN: c.record.myN } : {}),
108
+ ...(c.record.removed?.length ? { removed: c.record.removed } : {}),
109
+ };
110
+ }
111
+ /**
112
+ * Takes over another store of ours' removal record (a device of ours by sync, or our old identity
113
+ * on rotation): the union of the removed members still off the head. It can only add holds: every
114
+ * former member's open re-join is held anyway (review H1, as on main).
115
+ */
116
+ export async function mergeRemovals(app, cid, removed) {
117
+ if (!removed?.length)
118
+ return;
119
+ await app.store.updateCircle(cid, (cur) => {
120
+ if (!cur)
121
+ return { result: undefined };
122
+ const head = CircleChain.fromStored(cur.chain).head;
123
+ const all = [...new Set([...(cur.removed ?? []), ...(removed ?? [])])].filter((m) => !head.members.includes(m));
124
+ const next = { ...cur, ...(all.length ? { removed: all } : {}) };
125
+ if (!all.length)
126
+ delete next.removed;
127
+ return { next, result: undefined };
128
+ });
129
+ }
130
+ /** Everything a newly linked device needs (§2.4 is followed by a sync). */
131
+ export async function exportAll(app) {
132
+ const circles = [];
133
+ for (const r of await app.store.listCircles()) {
134
+ const c = await exportCircle(app, r.cid);
135
+ if (c)
136
+ circles.push(c);
137
+ }
138
+ const contacts = [];
139
+ for (const u of await app.store.listIdentities()) {
140
+ if (u === app.userId)
141
+ continue;
142
+ const v = await app.view(u);
143
+ if (v)
144
+ contacts.push(v.head.jws);
145
+ }
146
+ return {
147
+ friendships: (await app.store.listFriendships()).map((f) => f.proof),
148
+ unfriends: (await app.store.listUnfriends()).map((u) => u.jws),
149
+ blocks: (await app.store.listBlocks()).map((b) => b.userId),
150
+ petnames: await app.store.listPetnames(),
151
+ capsHeld: (await app.store.listCapsHeld()).map((c) => c.jws),
152
+ capsIssued: await app.store.listCapsIssued(),
153
+ outgoing: await listOutgoing(app),
154
+ circles,
155
+ contacts,
156
+ defaultCircle: app.self?.defaultCircle ?? null,
157
+ codes: Object.values((await app.state.get("codes")) ?? {}),
158
+ };
159
+ }
160
+ /** The store keeps outgoing invites by `inv` without a list API; read its document directly (read-only). */
161
+ export async function listOutgoing(app) {
162
+ const doc = (await new FileDocBackend(app.store.dir).read("v3-outgoing"));
163
+ return Object.values(doc ?? {});
164
+ }
165
+ /** Sends `body` to our other devices (all of them, or `only`), chunked. */
166
+ export async function sendSync(app, body, only) {
167
+ const view = await app.view(app.userId);
168
+ if (!view || view.devices.filter((d) => d !== app.did).length === 0)
169
+ return 0;
170
+ let n = 0;
171
+ // A circle with a long chain is more than one envelope: its export goes in slices (review M2).
172
+ const split = body.circles ? { ...body, circles: body.circles.flatMap((c) => splitCircle(c)) } : body;
173
+ for (const part of chunkBody(split)) {
174
+ try {
175
+ const d = await app.deliver(app.userId, "sync", { own: app.userId, sid: "~sync" }, part, only ? { onlyDevices: only } : {});
176
+ if (d.relays.length > 0)
177
+ n++;
178
+ }
179
+ catch (e) {
180
+ app.io.err(`sync to your other devices failed: ${e.message}`);
181
+ }
182
+ }
183
+ return n;
184
+ }
185
+ /** One bad item never aborts the rest of a sync: each is applied on its own, failures logged. */
186
+ let syncLog;
187
+ const ignore = (e) => {
188
+ if (!(e instanceof P2PError))
189
+ syncLog?.(`sync: skipped an item: ${e?.message ?? String(e)}`);
190
+ };
191
+ export async function importSync(app, raw, meta = {}) {
192
+ syncLog = (m) => app.io.err(m);
193
+ const body = raw;
194
+ const ctx = app.signerCtx();
195
+ // Contacts' documents: refreshed from the relays they list, never taken as sent.
196
+ for (const c of body.contacts ?? []) {
197
+ let iss;
198
+ try {
199
+ iss = peekIdentityDoc(c).iss;
200
+ }
201
+ catch {
202
+ continue;
203
+ }
204
+ await app.refreshIdentity(iss, App.relaysOf(c), { force: true, quiet: true }).catch(ignore);
205
+ }
206
+ for (const proof of body.friendships ?? []) {
207
+ try {
208
+ // Re-verified against refreshed identities (the friend may be new to this device).
209
+ const f = await reverifyFriendshipForApproval(app.store, proof, app.fetcher(), { self: app.userId });
210
+ // pre-release re-review L1: while our identity is rotating (or was rotated by someone), a friendship
211
+ // our side of which a device we can't vouch for signed isn't taken: a thief's device could
212
+ // plant accomplices that way for the rotation to carry over.
213
+ const why = await untrustedImportSigner(app, f.inviter === app.userId ? f.invite.did : f.accept.did);
214
+ if (why) {
215
+ syncLog?.(`sync: not taking a friendship made by another device while your identity is rotating (${why})`);
216
+ continue;
217
+ }
218
+ await recordFriendshipV3(app.store, f);
219
+ }
220
+ catch (e) {
221
+ ignore(e);
222
+ }
223
+ }
224
+ for (const j of body.unfriends ?? []) {
225
+ try {
226
+ const u = await verifyUnfriendV3(j, ctx);
227
+ await app.store.addUnfriend({ iss: u.iss, peer: u.peer, inv: u.inv, iat: u.iat, jws: u.jws });
228
+ }
229
+ catch (e) {
230
+ ignore(e);
231
+ }
232
+ }
233
+ for (const u of body.blocks ?? [])
234
+ await app.store.addBlock({ userId: u, at: Math.floor(Date.now() / 1000) }).catch(ignore);
235
+ for (const u of body.unblocks ?? [])
236
+ await app.store.removeBlock(u).catch(ignore);
237
+ for (const [u, p] of Object.entries(body.petnames ?? {}))
238
+ await app.store.setPetname(u, p ?? undefined).catch(ignore);
239
+ for (const j of body.capsHeld ?? []) {
240
+ try {
241
+ const c = verifyCap(j);
242
+ await app.store.addCapHeld({ capid: c.capid, iss: c.iss, sub: c.sub, relays: c.relays, kinds: c.kinds, exp: c.exp, jws: c.jws });
243
+ }
244
+ catch (e) {
245
+ ignore(e);
246
+ }
247
+ }
248
+ // review M5: a record is rebuilt from its verified JWS (our own signature), never trusted field by field.
249
+ for (const c of body.capsIssued ?? []) {
250
+ const v = verifiedIssuedCap(app, c.jws);
251
+ if (v)
252
+ await app.store.addCapIssued(v).catch(ignore);
253
+ }
254
+ for (const o of body.outgoing ?? [])
255
+ await app.store.addOutgoingInvite(o).catch(ignore);
256
+ for (const c of body.circles ?? [])
257
+ await importCircle(app, c).catch(ignore);
258
+ if (Array.isArray(body.codes))
259
+ await importCodes(app, body.codes).catch(ignore);
260
+ if (body.wantAnswered !== undefined)
261
+ await importWantAnswered(app, body.wantAnswered).catch(ignore);
262
+ if (body.rotation !== undefined)
263
+ await noteOwnRotation(app, body.rotation, meta.fdid).catch(ignore);
264
+ if (body.rotationApprovals !== undefined)
265
+ await importRotationApprovals(app, body.rotationApprovals).catch(ignore);
266
+ if (body.rotationDispute !== undefined)
267
+ await importRotationDispute(app, body.rotationDispute).catch(ignore);
268
+ if (body.rotationResolved !== undefined)
269
+ await importRotationResolved(app, body.rotationResolved, meta.fdid).catch(ignore);
270
+ if (body.defaultCircle !== undefined) {
271
+ const byJoin = typeof body.defaultFromJoin === "string" && body.defaultFromJoin === body.defaultCircle ? body.defaultFromJoin : undefined;
272
+ await app.updateSelf((s) => {
273
+ const { defaultFromJoin: _was, ...rest } = s;
274
+ return { ...rest, defaultCircle: body.defaultCircle ?? undefined, ...(byJoin ? { defaultFromJoin: byJoin } : {}) };
275
+ });
276
+ }
277
+ }
278
+ /** A cap this user issued, from its JWS: signature and cert checked, every field taken from the payload. */
279
+ export function verifiedIssuedCap(app, jws) {
280
+ if (typeof jws !== "string")
281
+ return undefined;
282
+ try {
283
+ const c = verifyCap(jws);
284
+ if (c.iss !== app.userId)
285
+ return undefined;
286
+ return { capid: c.capid, iss: c.iss, sub: c.sub, relays: c.relays, kinds: c.kinds, exp: c.exp, jws };
287
+ }
288
+ catch (e) {
289
+ ignore(e);
290
+ return undefined;
291
+ }
292
+ }
293
+ function verOf(v) {
294
+ try {
295
+ return parseCircleVersion(v).ver;
296
+ }
297
+ catch {
298
+ return 0;
299
+ }
300
+ }
301
+ function sortVersions(vs) {
302
+ return [...vs].sort((a, b) => verOf(a) - verOf(b));
303
+ }
304
+ /** Slices waiting for the rest of their circle are dropped this long after the circle's first one. */
305
+ const SYNC_SLICE_TTL_MS = 24 * 3600_000;
306
+ /** At most this much waiting for one circle (beyond it the slice is dropped), and for all. */
307
+ const SYNC_SLICE_MAX_BYTES = 4 * 1024 * 1024;
308
+ const SYNC_SLICES_TOTAL_BYTES = 16 * 1024 * 1024;
309
+ async function importCircle(app, c) {
310
+ try {
311
+ // A slice of a split export (splitCircle), together with what earlier slices left waiting. The
312
+ // buffer is bounded per circle and in all, and its 24 h starts with a circle's first slice.
313
+ const now = Date.now();
314
+ const held = await app.store.getCircle(c.cid);
315
+ const headVer = held ? CircleChain.fromStored(held.chain).head.ver : 0;
316
+ // A version that doesn't parse is dropped, not kept: it would stall the circle's slices for good.
317
+ const fresh = c.versions.filter((v) => verOf(v) > headVer);
318
+ const waiting = await app.state.update("syncCircles", (cur = {}) => {
319
+ const keep = Object.fromEntries(Object.entries(cur).filter(([, w]) => now - w.at < SYNC_SLICE_TTL_MS));
320
+ const w = keep[c.cid] ?? { versions: [], statements: [], at: now };
321
+ // `held` is re-read here, under the state lock, from what the buffer says was applied: a slice
322
+ // another process applied meanwhile is not kept again.
323
+ const merged = { versions: [...new Set([...w.versions.filter((v) => verOf(v) > headVer), ...fresh])], statements: [...new Set([...w.statements, ...c.statements])], at: w.at };
324
+ if (bytes(merged) > SYNC_SLICE_MAX_BYTES)
325
+ return { result: undefined };
326
+ const others = Object.entries(keep).filter(([cid]) => cid !== c.cid);
327
+ // Over the overall cap, the oldest other circles' slices go first.
328
+ others.sort((x, y) => x[1].at - y[1].at);
329
+ let total = bytes(merged) + others.reduce((n, [, x]) => n + bytes(x), 0);
330
+ while (total > SYNC_SLICES_TOTAL_BYTES && others.length > 0)
331
+ total -= bytes(others.shift()[1]);
332
+ return { next: { ...Object.fromEntries(others), [c.cid]: merged }, result: merged };
333
+ });
334
+ if (!waiting)
335
+ return;
336
+ // Applied only once the versions line up (from 1, or from the held head): each slice is
337
+ // verified once, not again with every later slice.
338
+ const versions = sortVersions(waiting.versions);
339
+ const vers = versions.map(verOf);
340
+ const contiguous = vers.every((v, i) => v === (i === 0 ? headVer + 1 : vers[i - 1] + 1) || (i > 0 && v === vers[i - 1]));
341
+ if (versions.length > 0 && !contiguous)
342
+ return;
343
+ if (!held) {
344
+ if (versions.length === 0)
345
+ return;
346
+ await storeOfferedCircle(app.store, versions);
347
+ }
348
+ await applyCircleBundle(app.store, { circles: held ? versions : [], joins: waiting.statements, ops: [] }, { ...app.signerCtx(), self: app.userId });
349
+ // Under the lock, from the head now held: only what was applied leaves the buffer; slices that
350
+ // arrived meanwhile (another process) stay for their turn.
351
+ const newHead = CircleChain.fromStored((await app.store.getCircle(c.cid)).chain).head.ver;
352
+ await app.state.update("syncCircles", (cur = {}) => {
353
+ const w = cur[c.cid];
354
+ if (!w)
355
+ return { result: undefined };
356
+ const versionsLeft = w.versions.filter((v) => verOf(v) > newHead);
357
+ const statementsLeft = w.statements.filter((x) => !waiting.statements.includes(x));
358
+ const { [c.cid]: _done, ...others } = cur;
359
+ return { next: versionsLeft.length || statementsLeft.length ? { ...others, [c.cid]: { versions: versionsLeft, statements: statementsLeft, at: w.at } } : others, result: undefined };
360
+ });
361
+ await app.store.updateCircle(c.cid, (cur) => {
362
+ if (!cur)
363
+ return { result: undefined };
364
+ const myN = Math.max(cur.myN ?? -1, c.myN ?? -1);
365
+ // A leave synced from another device ends the join here too; a join is carried over.
366
+ const mine = cur.statements[app.userId];
367
+ const joinedByMe = mine ? mine.op === "join" && (c.joinedByMe || cur.joinedByMe) && CircleChain.fromStored(cur.chain).hasAncestor(mine.at ?? "") : false;
368
+ return { next: { ...cur, joinedByMe, ...(myN >= 0 ? { myN } : {}) }, result: undefined };
369
+ });
370
+ await mergeRemovals(app, c.cid, c.removed);
371
+ }
372
+ catch (e) {
373
+ ignore(e);
374
+ }
375
+ }
@@ -0,0 +1 @@
1
+ export declare function isTransient(e: unknown): boolean;
@@ -0,0 +1,28 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Which failures while handling an envelope are worth another attempt (inbound.ts, review M-A).
4
+ import { CliError } from "./errors.js";
5
+ /**
6
+ * Failures worth another attempt (review M-A), still bounded by the attempt limit and the
7
+ * per-envelope timeout: clearly local and transient (this command closing, a lock timeout, a full
8
+ * disk), or a transient network failure (a dropped connection, an unreachable relay, a timeout),
9
+ * so a short Wi-Fi drop doesn't lose a friend's accept. Everything else (a bug, a validation
10
+ * failure, any other CliError) is final at once.
11
+ */
12
+ const TRANSIENT_ERRNO = new Set([
13
+ "ENOSPC", "EBUSY", "EAGAIN", "EMFILE", "ENFILE", "EDQUOT",
14
+ "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "EAI_AGAIN", "EPIPE", "ECONNABORTED",
15
+ ]);
16
+ const TRANSIENT_CLI = new Set(["closing", "network", "timeout", "unreachable", "no_relay"]);
17
+ export function isTransient(e) {
18
+ if (e instanceof CliError)
19
+ return TRANSIENT_CLI.has(e.code);
20
+ if (!(e instanceof Error))
21
+ return false;
22
+ if (/ is locked$/.test(e.message))
23
+ return true; // a state or trust store lock timeout (FileDocBackend)
24
+ if (/socket hang up|socket (has been )?closed|other side closed|fetch failed/i.test(e.message))
25
+ return true;
26
+ const code = e.code ?? (e.cause?.code);
27
+ return typeof code === "string" && TRANSIENT_ERRNO.has(code);
28
+ }
@@ -0,0 +1,37 @@
1
+ import type { App } from "./app.js";
2
+ /** At most this many trusted users and circles each. */
3
+ export declare const TRUST_MAX = 256;
4
+ export interface TrustList {
5
+ users: {
6
+ userId: string;
7
+ address: string;
8
+ blocked: boolean;
9
+ }[];
10
+ /** `open`: the circle is open now, so it trusts nobody until it is invite-only again. */
11
+ circles: {
12
+ cid: string;
13
+ name: string | null;
14
+ joined: boolean;
15
+ open: boolean;
16
+ members: string[];
17
+ }[];
18
+ /** Everyone trusted right now: the users (unblocked) and the standing members of trusted circles. */
19
+ trusted: string[];
20
+ }
21
+ export declare function trustAdd(app: App, target: string): Promise<{
22
+ added: string;
23
+ kind: "user" | "circle";
24
+ address?: string;
25
+ name?: string;
26
+ }>;
27
+ export declare function trustRemove(app: App, target: string): Promise<{
28
+ removed: string | null;
29
+ kind: "user" | "circle";
30
+ }>;
31
+ export declare function trustList(app: App): Promise<TrustList>;
32
+ /** Whether `userId` is trusted right now, and why (the user itself, or a trusted circle). */
33
+ export declare function trustCheck(app: App, userId: string): Promise<{
34
+ userId: string;
35
+ trusted: boolean;
36
+ via: string | null;
37
+ }>;
package/dist/trust.js ADDED
@@ -0,0 +1,134 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Per-person trust for message delivery (`p2p trust`). A front end that holds peers' messages
4
+ // for a session approving its own tool calls (the Claude mod) delivers a trusted sender's
5
+ // messages without the hold. Trust only skips that hold: a trusted sender's messages are still
6
+ // peer data, never the user's instructions.
7
+ //
8
+ // - Stored in <home>/config.json (`trust: {users, circles}`, 0600), by full userId and circle id
9
+ // only. A `name@fingerprint` is resolved by its fingerprint among known identities; a bare
10
+ // name or petname is refused (names are self-chosen).
11
+ // - A trusted circle covers its members as the verified circle state has them when asked
12
+ // (`trust check`, `trust ls`): a member removed from it, or who no longer stands in it, stops
13
+ // being trusted, as does everyone once this user leaves the circle.
14
+ // - A blocked user is never trusted (refused when added, left out when checked).
15
+ import { isCircleId, isUserId } from "@peer2peer/core/v3";
16
+ import { circleMembers, resolveCircle } from "./circle-ops.js";
17
+ import { readFileConfig, updateFileConfigField } from "./config.js";
18
+ import { CliError } from "./errors.js";
19
+ const FP_ADDRESS = /^[^\s@]+@[a-z2-7]{4}-[a-z2-7]{4}-[a-z2-7]{4}-[a-z2-7]{4}$/;
20
+ /** At most this many trusted users and circles each. */
21
+ export const TRUST_MAX = 256;
22
+ function parseStored(t) {
23
+ const o = (typeof t === "object" && t !== null ? t : {});
24
+ const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
25
+ return { users: strs(o.users).filter(isUserId), circles: strs(o.circles).filter((c) => isCircleId(c)) };
26
+ }
27
+ function stored(app) {
28
+ return parseStored(readFileConfig(app.home).trust);
29
+ }
30
+ /**
31
+ * Changes the stored trust under the state lock, against what is stored at that moment (pre-release review
32
+ * N3): a concurrent `p2p trust` or `p2p receipts` can't make this one lose its update, or lose theirs.
33
+ */
34
+ function change(app, fn) {
35
+ return updateFileConfigField(app, "trust", (raw) => {
36
+ const cur = parseStored(raw);
37
+ const r = fn(cur);
38
+ const next = r.next ?? cur;
39
+ return { next: { users: [...new Set(next.users)].slice(0, TRUST_MAX), circles: [...new Set(next.circles)].slice(0, TRUST_MAX) }, result: r.result };
40
+ });
41
+ }
42
+ /** `circle:<cid|name>` names a circle; anything else a user. */
43
+ function parseTarget(target) {
44
+ const s = target.trim();
45
+ return s.startsWith("circle:") ? { circle: s.slice("circle:".length).trim() } : { user: s };
46
+ }
47
+ /** A full userId, or name@fingerprint resolved by its fingerprint; never a bare name or petname. */
48
+ async function userOf(app, input) {
49
+ if (isUserId(input))
50
+ return input;
51
+ if (!FP_ADDRESS.test(input))
52
+ throw new CliError("usage", `trust takes a full userId (p2p:…) or name@fingerprint, never a bare name: names are self-chosen (${input})`);
53
+ return app.resolveUser(input);
54
+ }
55
+ export async function trustAdd(app, target) {
56
+ const t = parseTarget(target);
57
+ if ("circle" in t) {
58
+ const c = await resolveCircle(app, t.circle);
59
+ if (!c.record.joinedByMe)
60
+ throw new CliError("usage", "you can only trust a circle you are in");
61
+ // An open circle admits anyone who asks (P2: no owner decision): trusting it would trust strangers.
62
+ if ((await circleMembers(app, c.record.cid)).circle.policy === "open")
63
+ throw new CliError("open_circle", "an open circle admits anyone who asks, so it can't be trusted: trust its members one by one");
64
+ const cid = c.record.cid;
65
+ await change(app, (cur) => {
66
+ if (cur.circles.length >= TRUST_MAX && !cur.circles.includes(cid))
67
+ throw new CliError("too_many", `at most ${TRUST_MAX} trusted circles`);
68
+ return { next: { ...cur, circles: [...cur.circles, cid] }, result: undefined };
69
+ });
70
+ return { added: cid, kind: "circle", name: c.chain.head.name };
71
+ }
72
+ const userId = await userOf(app, t.user);
73
+ if (userId === app.userId)
74
+ throw new CliError("usage", "your own devices are always delivered");
75
+ if (await app.store.isBlocked(userId))
76
+ throw new CliError("blocked", "you blocked that user: unblock them first");
77
+ await change(app, (cur) => {
78
+ if (cur.users.length >= TRUST_MAX && !cur.users.includes(userId))
79
+ throw new CliError("too_many", `at most ${TRUST_MAX} trusted users`);
80
+ return { next: { ...cur, users: [...cur.users, userId] }, result: undefined };
81
+ });
82
+ return { added: userId, kind: "user", address: await app.addressOf(userId) };
83
+ }
84
+ export async function trustRemove(app, target) {
85
+ const t = parseTarget(target);
86
+ if ("circle" in t) {
87
+ // By cid even when the circle is gone from this device; else by name.
88
+ const cid = isCircleId(t.circle) ? t.circle : await resolveCircle(app, t.circle).then((c) => c.record.cid).catch(() => null);
89
+ if (cid === null)
90
+ return { removed: null, kind: "circle" };
91
+ return change(app, (cur) => (cur.circles.includes(cid) ? { next: { ...cur, circles: cur.circles.filter((c) => c !== cid) }, result: { removed: cid, kind: "circle" } } : { result: { removed: null, kind: "circle" } }));
92
+ }
93
+ const userId = isUserId(t.user) ? t.user : await userOf(app, t.user).catch(() => null);
94
+ if (userId === null)
95
+ return { removed: null, kind: "user" };
96
+ return change(app, (cur) => (cur.users.includes(userId) ? { next: { ...cur, users: cur.users.filter((u) => u !== userId) }, result: { removed: userId, kind: "user" } } : { result: { removed: null, kind: "user" } }));
97
+ }
98
+ /** The standing, unblocked members (not this user) of a trusted circle this user is in, from its verified state. */
99
+ async function circleTrusted(app, cid) {
100
+ try {
101
+ const r = await circleMembers(app, cid);
102
+ if (!r.circle.joined)
103
+ return { name: r.circle.name, joined: false, open: false, members: [] };
104
+ // Open now, per its verified current version: anyone who asks gets in, so it trusts nobody (review N1).
105
+ if (r.circle.policy === "open")
106
+ return { name: r.circle.name, joined: true, open: true, members: [] };
107
+ const blocked = new Set((await app.store.listBlocks()).map((b) => b.userId));
108
+ return { name: r.circle.name, joined: true, open: false, members: r.members.filter((m) => m.stands && !m.self && !blocked.has(m.userId)).map((m) => m.userId) };
109
+ }
110
+ catch {
111
+ return { name: null, joined: false, open: false, members: [] };
112
+ }
113
+ }
114
+ export async function trustList(app) {
115
+ const cur = stored(app);
116
+ const users = await Promise.all(cur.users.map(async (u) => ({ userId: u, address: await app.addressOf(u), blocked: await app.store.isBlocked(u) })));
117
+ const circles = await Promise.all(cur.circles.map(async (cid) => ({ cid, ...(await circleTrusted(app, cid)) })));
118
+ const trusted = new Set([...users.filter((u) => !u.blocked).map((u) => u.userId), ...circles.flatMap((c) => c.members)]);
119
+ return { users, circles, trusted: [...trusted] };
120
+ }
121
+ /** Whether `userId` is trusted right now, and why (the user itself, or a trusted circle). */
122
+ export async function trustCheck(app, userId) {
123
+ if (!isUserId(userId))
124
+ throw new CliError("usage", "trust check takes a full userId");
125
+ if (await app.store.isBlocked(userId))
126
+ return { userId, trusted: false, via: null };
127
+ const cur = stored(app);
128
+ if (cur.users.includes(userId))
129
+ return { userId, trusted: true, via: "user" };
130
+ for (const cid of cur.circles)
131
+ if ((await circleTrusted(app, cid)).members.includes(userId))
132
+ return { userId, trusted: true, via: `circle:${cid}` };
133
+ return { userId, trusted: false, via: null };
134
+ }
@@ -0,0 +1,2 @@
1
+ /** Asks `question` on the controlling terminal; true only for "yes". No terminal: false. */
2
+ export declare function confirmOnTty(question: string): Promise<boolean>;
@@ -0,0 +1,53 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // The person's own confirmation, read from the controlling terminal (`/dev/tty`, `CONIN$` on
4
+ // Windows), never from stdin or a flag: a process an agent detached from any terminal (`setsid`,
5
+ // `(sh x.sh &)`, a daemon) can't answer it, whatever its environment says. Not airtight: an agent
6
+ // that spawns a pseudo-terminal from a script can (docs/security/threat-model.md).
7
+ import { closeSync, openSync, readSync, writeSync } from "node:fs";
8
+ /** Asks `question` on the controlling terminal; true only for "yes". No terminal: false. */
9
+ export async function confirmOnTty(question) {
10
+ let inFd;
11
+ let outFd;
12
+ try {
13
+ if (process.platform === "win32") {
14
+ inFd = openSync("CONIN$", "r");
15
+ outFd = openSync("CONOUT$", "w");
16
+ }
17
+ else {
18
+ inFd = openSync("/dev/tty", "r+");
19
+ outFd = inFd;
20
+ }
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ try {
26
+ writeSync(outFd, `${question} Type yes to go on: `);
27
+ const buf = Buffer.alloc(1);
28
+ let answer = "";
29
+ for (let i = 0; i < 64; i++) {
30
+ const n = readSync(inFd, buf, 0, 1, null);
31
+ if (n <= 0)
32
+ break;
33
+ const c = buf.toString("utf8");
34
+ if (c === "\n" || c === "\r")
35
+ break;
36
+ answer += c;
37
+ }
38
+ return answer.trim().toLowerCase() === "yes";
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ finally {
44
+ try {
45
+ closeSync(inFd);
46
+ if (outFd !== inFd)
47
+ closeSync(outFd);
48
+ }
49
+ catch {
50
+ // closed
51
+ }
52
+ }
53
+ }
@@ -0,0 +1,20 @@
1
+ import type { App, Io } from "../app.js";
2
+ import type { Env } from "../config.js";
3
+ import { type Terminal } from "./terminal.js";
4
+ export interface TuiCommandDeps {
5
+ env: Env;
6
+ io: Io;
7
+ version: string;
8
+ makeApp: (env: Env, io: Io) => App;
9
+ isTTY?: boolean;
10
+ /** Tests: a fake terminal. */
11
+ terminal?: Terminal;
12
+ signal?: AbortSignal;
13
+ /** The person token was valid (cli.ts main). */
14
+ front?: boolean;
15
+ }
16
+ /** Why `p2p tui` won't start here, or undefined. */
17
+ export declare function tuiRefusal(env: Env, isTTY: boolean, front?: boolean): string | undefined;
18
+ export declare function tuiCommand(d: TuiCommandDeps, o: {
19
+ session?: string;
20
+ }): Promise<number>;