@peer2peer/cli 0.0.0-stage → 0.1.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.
Files changed (111) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +370 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +368 -0
  6. package/dist/app.js +1181 -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 +660 -0
  12. package/dist/cli.js +1787 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +159 -0
  16. package/dist/config.js +294 -0
  17. package/dist/doctor.d.ts +113 -0
  18. package/dist/doctor.js +930 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +38 -0
  22. package/dist/ext-host.js +293 -0
  23. package/dist/extensions.d.ts +487 -0
  24. package/dist/extensions.js +406 -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/graph-memory.d.ts +107 -0
  30. package/dist/graph-memory.js +393 -0
  31. package/dist/history.d.ts +155 -0
  32. package/dist/history.js +697 -0
  33. package/dist/identity.d.ts +239 -0
  34. package/dist/identity.js +759 -0
  35. package/dist/inbound.d.ts +32 -0
  36. package/dist/inbound.js +261 -0
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.js +14 -0
  39. package/dist/ix-local.d.ts +76 -0
  40. package/dist/ix-local.js +203 -0
  41. package/dist/join-answers.d.ts +49 -0
  42. package/dist/join-answers.js +149 -0
  43. package/dist/outbox.d.ts +109 -0
  44. package/dist/outbox.js +337 -0
  45. package/dist/pretty.d.ts +100 -0
  46. package/dist/pretty.js +256 -0
  47. package/dist/procstart.d.ts +1 -0
  48. package/dist/procstart.js +66 -0
  49. package/dist/progress.d.ts +30 -0
  50. package/dist/progress.js +78 -0
  51. package/dist/projects.d.ts +491 -0
  52. package/dist/projects.js +1383 -0
  53. package/dist/prompt/picker.d.ts +64 -0
  54. package/dist/prompt/picker.js +152 -0
  55. package/dist/prompt/tty.d.ts +29 -0
  56. package/dist/prompt/tty.js +122 -0
  57. package/dist/readonly.d.ts +20 -0
  58. package/dist/readonly.js +50 -0
  59. package/dist/receipts.d.ts +99 -0
  60. package/dist/receipts.js +182 -0
  61. package/dist/relay-client.d.ts +277 -0
  62. package/dist/relay-client.js +873 -0
  63. package/dist/relay-info.d.ts +24 -0
  64. package/dist/relay-info.js +53 -0
  65. package/dist/rotation.d.ts +402 -0
  66. package/dist/rotation.js +2054 -0
  67. package/dist/running.d.ts +5 -0
  68. package/dist/running.js +74 -0
  69. package/dist/sessions.d.ts +355 -0
  70. package/dist/sessions.js +1247 -0
  71. package/dist/shortcode.d.ts +149 -0
  72. package/dist/shortcode.js +465 -0
  73. package/dist/social.d.ts +139 -0
  74. package/dist/social.js +485 -0
  75. package/dist/state.d.ts +509 -0
  76. package/dist/state.js +220 -0
  77. package/dist/stdin.d.ts +17 -0
  78. package/dist/stdin.js +46 -0
  79. package/dist/sync.d.ts +77 -0
  80. package/dist/sync.js +375 -0
  81. package/dist/transient.d.ts +1 -0
  82. package/dist/transient.js +28 -0
  83. package/dist/trust.d.ts +37 -0
  84. package/dist/trust.js +134 -0
  85. package/dist/tty-confirm.d.ts +2 -0
  86. package/dist/tty-confirm.js +53 -0
  87. package/dist/tui/command.d.ts +20 -0
  88. package/dist/tui/command.js +70 -0
  89. package/dist/tui/frame.d.ts +43 -0
  90. package/dist/tui/frame.js +111 -0
  91. package/dist/tui/model.d.ts +221 -0
  92. package/dist/tui/model.js +259 -0
  93. package/dist/tui/sanitize.d.ts +13 -0
  94. package/dist/tui/sanitize.js +151 -0
  95. package/dist/tui/terminal.d.ts +88 -0
  96. package/dist/tui/terminal.js +354 -0
  97. package/dist/tui/tui.d.ts +78 -0
  98. package/dist/tui/tui.js +612 -0
  99. package/dist/tui/view.d.ts +4 -0
  100. package/dist/tui/view.js +358 -0
  101. package/dist/unknown-kinds.d.ts +12 -0
  102. package/dist/unknown-kinds.js +66 -0
  103. package/dist/version.d.ts +1 -0
  104. package/dist/version.js +5 -0
  105. package/dist/want-pow.d.ts +12 -0
  106. package/dist/want-pow.js +46 -0
  107. package/dist/watch.d.ts +35 -0
  108. package/dist/watch.js +331 -0
  109. package/dist/xstate.d.ts +125 -0
  110. package/dist/xstate.js +422 -0
  111. package/package.json +60 -4
package/dist/app.js ADDED
@@ -0,0 +1,1181 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // The CLI's working context. Daemon-free: every command builds an App, opens
4
+ // the stores, connects to the relays only if it needs to, does its work and
5
+ // closes. Only `watch` stays connected.
6
+ //
7
+ // What lives here: loading this device's keys, identity-document handling
8
+ // (fetch from relays and fill gaps, §2.5/§5.6; build, sign and publish the
9
+ // next version of our own), sealing and delivering envelopes (§4.1, §5.4,
10
+ // §5.8), finding caps, resolving addresses and petnames, and syncing state to
11
+ // the user's other devices.
12
+ import { personTokenOk } from "./projects.js";
13
+ import { confirmOnTty } from "./tty-confirm.js";
14
+ import { hostname, userInfo } from "node:os";
15
+ import { addIdentityVersion, b64uDecode, b64uEncode, capAllowsKind, CircleChain, createCap, createDeviceCert, createIdentityDoc, decodeTyped, deviceKeysV3FromSecrets, displayAddress, displayFingerprint, getIdentityView, MAX_DEVICES, mergeFields, mergePrevTip, scheduledWriter, refreshIdentity as coreRefreshIdentity, IdentityChain, identityKeyFromSeed, isUserId, isValidName, nowSec, P2PError, peekIdentityDoc, canonicalRelayUrl, sealEnvelopeV3, storeCertResolver, storeSignerContext, TYP3, verifyDeviceCertV3, verifyRotationSignatures, } from "@peer2peer/core/v3";
16
+ import { FileDocBackend, FileTrustStoreV3 } from "@peer2peer/core/v3/node";
17
+ import { OverlayDocBackend, ReadOnlyTrustStoreV3 } from "./readonly.js";
18
+ import { basename, join } from "node:path";
19
+ import { deviceInfoEnabled, readFileConfig, resolveHome, transportResolver, tunables, } from "./config.js";
20
+ import { CliError } from "./errors.js";
21
+ import { fetchChain, fetchTips, handlerPool, RelayPool } from "./relay-client.js";
22
+ import { isOwnRelay, privateGuardLookup } from "./shortcode.js";
23
+ import { RELAY_FEATURE_LENIENT_IDENTITY, relaysSupport } from "./relay-info.js";
24
+ import { CLI_CAPS } from "./features.js";
25
+ import { VERSION } from "./version.js";
26
+ import { CliState } from "./state.js";
27
+ import { debug, makeProgress, step } from "./progress.js";
28
+ /** refreshDeviceInfo: at most one publish an hour to bring `dinfo` current, and a minute after one that failed. */
29
+ const DEVICE_INFO_EVERY_MS = 3600_000;
30
+ const DEVICE_INFO_RETRY_MS = 60_000;
31
+ /** A redeemed code's admission key is kept this long (codes live at most 7 days). */
32
+ const ADMIT_KEEP_MS = 8 * 86_400_000;
33
+ /** One `circle-put` frame: at most this many versions and about this many bytes (relay frames are 96 KiB). */
34
+ const CIRCLE_PUSH_MAX_VERSIONS = 64;
35
+ const CIRCLE_PUSH_MAX_BYTES = 80 * 1024;
36
+ /** Days before a certificate's or document's expiry at which it is renewed. */
37
+ export const RENEW_CERT_WITHIN_SEC = 30 * 86_400;
38
+ /** How long closing waits for envelope handlers still running. */
39
+ export const CLOSE_GRACE_MS = 3000;
40
+ /** refreshIdentity: a `fetched` time this recent is left as it is (see there). */
41
+ const FETCHED_SLACK_MS = 5000;
42
+ export const REPUBLISH_DOC_WITHIN_SEC = 7 * 86_400;
43
+ const CAP_PRIORITY = (c) => (c.kinds[0] === "*" ? 0 : 1);
44
+ export class App {
45
+ /** The person's front end vouched for this command (P2P_PERSON_TOKEN, checked once and removed: projects.ts). */
46
+ front = false;
47
+ /** The person's "yes" on their controlling terminal (tty-confirm.ts); cli.ts may stand another in (tests). */
48
+ confirmTty = confirmOnTty;
49
+ env;
50
+ io;
51
+ home;
52
+ state;
53
+ store;
54
+ readOnly;
55
+ file;
56
+ transport;
57
+ tun;
58
+ keys;
59
+ self;
60
+ device;
61
+ ik;
62
+ pool;
63
+ /** Slow-step notices and P2P_DEBUG step logs (stderr). */
64
+ progress;
65
+ /** Aborted by the command deadline (cli.ts): stops new network steps (progress.step). */
66
+ abort = new AbortController();
67
+ /**
68
+ * Set once an identity publish may have been stored by a relay: one accepted, or one went out
69
+ * and its answer never came (timeout, dropped connection). A restore must not wipe after that
70
+ * (review L1). Definite refusals (a relay's error code) and relays never reached don't set it.
71
+ */
72
+ publishMaybeStored = false;
73
+ /** Handles envelopes delivered while connected (set by inbound.ts). */
74
+ onEnvelope;
75
+ /** Runs after connectAndDrain (set by inbound.ts: finishes short-code circle joins). */
76
+ afterDrain;
77
+ /** Runs when every relay refused this device and our own document turned out rotated (set by inbound.ts: the alert). */
78
+ onIdentityRotated;
79
+ /** The session this process is the `p2p watch` of (running.ts). */
80
+ watching;
81
+ /** close() is giving up on envelope handlers still running (set by inbound.ts: abandonInFlight). */
82
+ onAbandon;
83
+ /** close() is waiting for the pool's handlers. */
84
+ closing = false;
85
+ discovered = new Map();
86
+ refusedVerdicts = new Map();
87
+ /** The relays as of the last connect (for `ls --json`). */
88
+ relayStatus;
89
+ warnings = [];
90
+ /** Accept restricted relay connections (only `backup restore`, before its new device is listed). */
91
+ allowRestricted = false;
92
+ /** Installed extensions (extensions.ts): render inbound `x:<ns>.*` kinds. Absent: fallbacks only. */
93
+ extensions;
94
+ constructor(opts) {
95
+ this.env = opts.env;
96
+ this.io = opts.io;
97
+ this.home = resolveHome(opts.env);
98
+ // An embedder holding the person token is a front end (the CLI's main() checks and removes it first,
99
+ // then sets this from its own check).
100
+ this.front = personTokenOk(this.env, this.home);
101
+ // Progress and P2P_DEBUG lines go to stderr (never secrets: see progress.ts).
102
+ this.progress = { ...makeProgress(opts.env, (m) => opts.io.err(`p2p: ${m}`)), signal: this.abort.signal };
103
+ this.readOnly = opts.readOnly === true;
104
+ // P2P_DEBUG: lock waits and hold times of both stores, for tail-latency work (bench/README.md).
105
+ const lockOpts = this.progress.debug
106
+ ? { onLock: lockLogger(this.progress), onLockWait: ({ dir, waitedMs, holderPid }) => debug(this.progress, `lock ${basename(dir)}: still waiting after ${waitedMs}ms (held by pid ${holderPid ?? "?"})`) }
107
+ : {};
108
+ this.state = new CliState(this.home, this.progress, this.readOnly ? new OverlayDocBackend(new FileDocBackend(join(this.home, "cli"))) : undefined, lockOpts);
109
+ this.store = this.readOnly ? new ReadOnlyTrustStoreV3(join(this.home, "v3")) : new FileTrustStoreV3(join(this.home, "v3"), lockOpts);
110
+ this.file = readFileConfig(this.home);
111
+ this.transport = transportResolver(opts.env, this.file);
112
+ this.tun = tunables(opts.env);
113
+ }
114
+ /** Loads this device's keys. With `require`, a missing identity is an error. */
115
+ async load(require = true) {
116
+ const keys = await this.state.get("keys");
117
+ const self = await this.state.get("self");
118
+ if (!keys || !self) {
119
+ if (require)
120
+ throw new CliError("no_identity", "no identity here yet: run `p2p init` (or `p2p link join` / `p2p backup restore`)");
121
+ return false;
122
+ }
123
+ this.setKeys(keys, self);
124
+ return true;
125
+ }
126
+ setKeys(keys, self) {
127
+ this.keys = keys;
128
+ this.self = self;
129
+ this.device = deviceKeysV3FromSecrets(keys.userId, b64uDecode(keys.spk, 32), b64uDecode(keys.kpk, 32));
130
+ this.ik = keys.ik ? identityKeyFromSeed(b64uDecode(keys.ik, 32)) : undefined;
131
+ }
132
+ get userId() {
133
+ return this.keys.userId;
134
+ }
135
+ get did() {
136
+ return this.keys.did;
137
+ }
138
+ get relays() {
139
+ return this.self.relays;
140
+ }
141
+ get isKeyholder() {
142
+ return this.ik !== undefined;
143
+ }
144
+ requireKeyholder(what) {
145
+ if (!this.ik)
146
+ throw new CliError("not_keyholder", `${what} needs a key-holding device (§2.2); this device doesn't hold the identity key`);
147
+ return this.ik;
148
+ }
149
+ signer() {
150
+ return { userId: this.userId, did: this.did, signingSecretKey: this.device.signingSecretKey };
151
+ }
152
+ warn(msg) {
153
+ this.warnings.push(msg);
154
+ this.io.err(`warning: ${msg}`);
155
+ }
156
+ // -------------------------------------------------------------------------
157
+ // Relays
158
+ /** Connects to every own relay (receiving whatever is queued). At least one must answer. */
159
+ async connect(opts = {}) {
160
+ if (this.pool)
161
+ return this.pool;
162
+ // An envelope handler of a pool already closed (one that outlived close's grace) must not
163
+ // open a new pool that nobody closes: it would take deliveries meant for the next command and
164
+ // spend them in a process on its way out (pre-release review M1).
165
+ const from = handlerPool.getStore();
166
+ if (from !== undefined && from !== this.pool)
167
+ throw new CliError("closing", "this command closed its relay connections");
168
+ const pool = new RelayPool({
169
+ relays: this.relays,
170
+ transport: this.transport,
171
+ lookupFor: (r) => this.guardedLookup(r),
172
+ // Re-read on every reconnect: a long-running watch picks up a certificate renewed by another
173
+ // process (keys on disk) or published in our own document (R4-L1).
174
+ auth: async () => {
175
+ await this.reloadCert().catch(() => { });
176
+ const admits = await this.pendingAdmits();
177
+ return {
178
+ cert: this.keys.cert,
179
+ signingSecretKey: this.device.signingSecretKey,
180
+ ...(admits ? { admits, onAdmitted: (relay) => void this.forgetAdmit(relay).catch(() => { }) } : {}),
181
+ };
182
+ },
183
+ onAuthed: (conn) => {
184
+ if (!conn.circle)
185
+ return;
186
+ const p = this.syncRelayCircle(conn).catch((e) => debug(this.progress, `circle push to ${conn.relay}: ${e.message}`));
187
+ this.circlePushes.add(p);
188
+ void p.finally(() => this.circlePushes.delete(p));
189
+ },
190
+ onAuthRefused: (relay) => this.authRefusedVerdict(relay),
191
+ timeoutMs: this.tun.connectTimeoutMs,
192
+ requestTimeoutMs: this.tun.requestTimeoutMs,
193
+ progress: this.progress,
194
+ onEnvelope: (env, relay) => (this.onEnvelope ? this.onEnvelope(env, relay) : Promise.resolve("keep")),
195
+ reconnect: opts.reconnect,
196
+ keepRetryMs: Number(this.env.P2P_KEEP_RETRY_MS ?? "") || undefined,
197
+ log: (m) => this.io.err(m),
198
+ onFatal: opts.onFatal,
199
+ allowRestricted: this.allowRestricted,
200
+ });
201
+ this.pool = pool;
202
+ const r = await pool.connect();
203
+ this.relayStatus = { listed: [...this.relays], connected: r.connected, failed: r.failed.map((f) => ({ url: f.relay, reason: f.error })) };
204
+ for (const f of r.failed)
205
+ this.io.err(f.error.startsWith("can't reach") ? `p2p: ${f.error}` : `relay ${f.relay}: ${f.error}`);
206
+ if (r.connected.length === 0 && !opts.allowNone && !opts.reconnect) {
207
+ if (r.failed.length > 0 && r.failed.every((f) => /is members-only/.test(f.error))) {
208
+ throw new CliError("not_member", "every relay of yours is members-only and doesn't admit this identity: ask a member for an invite code, or the operator to add your userId");
209
+ }
210
+ const revoked = r.failed.some((f) => /refused this device/.test(f.error));
211
+ if (revoked)
212
+ await this.throwIfRotated();
213
+ throw new CliError(revoked ? "device_revoked" : "no_relay", revoked ? "every relay refused this device: it may have been revoked" : "could not reach any of your relays");
214
+ }
215
+ if (this.self && (this.self.unpublished?.length || Object.keys(this.self.refusedPublish ?? {}).length))
216
+ await this.retryUnpublished();
217
+ // Best effort, quietly: a document just created isn't on the relays yet (the next command retries).
218
+ await this.refreshDeviceInfo().catch(() => undefined);
219
+ return pool;
220
+ }
221
+ // -------------------------------------------------------------------------
222
+ // Members-only relays
223
+ /** circle-puts started when a members-only relay connection authenticated: close waits for them (bounded). */
224
+ circlePushes = new Set();
225
+ /** Admission keys from redeemed codes not used yet (by relay), or undefined when there are none. */
226
+ async pendingAdmits() {
227
+ const cur = (await this.state.get("admits")) ?? {};
228
+ const live = Object.entries(cur).filter(([, a]) => Date.now() - a.at < ADMIT_KEEP_MS);
229
+ return live.length > 0 ? Object.fromEntries(live.map(([r, a]) => [r, a.key])) : undefined;
230
+ }
231
+ /** Keeps a redeemed code's admission key for `relay` until that relay admits us with it. */
232
+ async saveAdmit(relay, key) {
233
+ await this.state.update("admits", (cur = {}) => {
234
+ const keep = Object.fromEntries(Object.entries(cur).filter(([, a]) => Date.now() - a.at < ADMIT_KEEP_MS));
235
+ return { next: { ...keep, [relay]: { key, at: Date.now() } }, result: undefined };
236
+ });
237
+ }
238
+ async forgetAdmit(relay) {
239
+ await this.state.update("admits", (cur = {}) => {
240
+ if (!cur[relay])
241
+ return { result: undefined };
242
+ const { [relay]: _used, ...rest } = cur;
243
+ return { next: rest, result: undefined };
244
+ });
245
+ }
246
+ /**
247
+ * A members-only relay that follows a circle said which version it holds: when we hold that
248
+ * circle further along, push the rest (`circle-put`), so additions and removals take effect
249
+ * there at once. The relay verifies every version itself; its refusals change nothing here.
250
+ *
251
+ * A chain names every member: it goes only to one of our OWN relays (listed in our identity
252
+ * document), and only for a circle we are a member of. Any other relay (a recipient's, or one
253
+ * that names a circle id it shouldn't know) gets nothing, whatever cid it asks for.
254
+ */
255
+ async syncRelayCircle(conn) {
256
+ const rc = conn.circle;
257
+ if (!rc || !conn.authed || conn.restricted)
258
+ return;
259
+ if (!this.relays.includes(conn.relay))
260
+ return;
261
+ const rec = await this.store.getCircle(rc.cid);
262
+ if (!rec || !rec.joinedByMe)
263
+ return;
264
+ const chain = CircleChain.fromStored(rec.chain);
265
+ if (!chain.head.members.includes(this.userId))
266
+ return;
267
+ if (chain.head.ver <= rc.ver)
268
+ return;
269
+ // From version 1 when the relay holds none (only an allowlisted member may seed it).
270
+ const versions = chain.versionsFrom(rc.ver === 0 ? 1 : rc.ver + 1);
271
+ let batch = [];
272
+ let bytes = 0;
273
+ const flush = async () => {
274
+ if (batch.length === 0)
275
+ return;
276
+ const r = await conn.request({ t: "circle-put", versions: batch });
277
+ batch = [];
278
+ bytes = 0;
279
+ if (r.t !== "ok")
280
+ throw new CliError("circle_push", `refused (${typeof r.code === "string" ? r.code : r.t})`);
281
+ if (typeof r.ver === "number")
282
+ conn.circle = { cid: rc.cid, ver: r.ver };
283
+ };
284
+ for (const v of versions) {
285
+ if (batch.length >= CIRCLE_PUSH_MAX_VERSIONS || (batch.length > 0 && bytes + v.length > CIRCLE_PUSH_MAX_BYTES))
286
+ await flush();
287
+ batch.push(v);
288
+ bytes += v.length;
289
+ }
290
+ await flush();
291
+ }
292
+ /** After this owner published a version of `cid`: every open members-only relay connection that follows it. */
293
+ async pushCircleToRelays(cid) {
294
+ for (const conn of this.pool?.authedConnections() ?? []) {
295
+ if (conn.circle?.cid !== cid)
296
+ continue;
297
+ await this.syncRelayCircle(conn).catch((e) => debug(this.progress, `circle push to ${conn.relay}: ${e.message}`));
298
+ }
299
+ }
300
+ refreshingDeviceInfo = false;
301
+ /** Set while `init` publishes the first document: nothing to bring current until it is on the relays. */
302
+ deviceInfoDeferred = false;
303
+ /**
304
+ * docs/compatibility.md: keeps this device's entry in the identity document (`dinfo`) current
305
+ * after an upgrade, or removes it when the user opted out: a key holder publishes the next version
306
+ * when the entry differs from what this client is. At most once an hour, and not when every relay
307
+ * wouldn't store it anyway (an entry is only ever published to relays that list identity.lenient).
308
+ */
309
+ async refreshDeviceInfo() {
310
+ if (this.readOnly || this.refreshingDeviceInfo || this.deviceInfoDeferred || !this.keys || !this.isKeyholder || !this.self)
311
+ return false;
312
+ const view = await this.view(this.userId);
313
+ if (!view || view.head.rotation)
314
+ return false;
315
+ const want = deviceInfoEnabled(this.env, this.home) ? { caps: [...CLI_CAPS], client: VERSION } : undefined;
316
+ const have = view.head.dinfo?.[this.did];
317
+ if (JSON.stringify(have ?? null) === JSON.stringify(want ?? null))
318
+ return false;
319
+ if (Date.now() - (this.self.deviceInfoAt ?? 0) < DEVICE_INFO_EVERY_MS)
320
+ return false;
321
+ if (want && !have && !(await relaysSupport(this, view.relays, RELAY_FEATURE_LENIENT_IDENTITY)))
322
+ return false;
323
+ this.refreshingDeviceInfo = true;
324
+ try {
325
+ await this.publishNext(() => undefined);
326
+ await this.updateSelf((s) => ({ ...s, deviceInfoAt: Date.now() }));
327
+ return true;
328
+ }
329
+ catch (e) {
330
+ // Tried: again in a minute, not on every command.
331
+ await this.updateSelf((s) => ({ ...s, deviceInfoAt: Date.now() - DEVICE_INFO_EVERY_MS + DEVICE_INFO_RETRY_MS }));
332
+ throw e;
333
+ }
334
+ finally {
335
+ this.refreshingDeviceInfo = false;
336
+ }
337
+ }
338
+ /**
339
+ * §2.8: every relay refused this device. When our own document's final
340
+ * version carries a rotation (relays serve documents publicly), the
341
+ * identity moved without this device: say so, and how to re-link.
342
+ */
343
+ async throwIfRotated() {
344
+ await this.refreshIdentity(this.userId, this.relays, { force: true, quiet: true }).catch(() => undefined);
345
+ const to = [];
346
+ for (const s of (await this.view(this.userId))?.rotations ?? []) {
347
+ try {
348
+ const r = verifyRotationSignatures(s);
349
+ if (r.from === this.userId)
350
+ to.push(r.to);
351
+ }
352
+ catch {
353
+ // not a valid statement
354
+ }
355
+ }
356
+ if (to.length === 0)
357
+ return;
358
+ // A rotation this device didn't publish is raised (§2.8) even though nothing can be drained now.
359
+ await this.onIdentityRotated?.().catch(() => undefined);
360
+ throw new CliError("identity_rotated", `your identity moved to a new key (${to.join(" and ")}${to.length > 1 ? ": more than one rotation, someone else holds your old key" : ""}) and this device didn't follow.${this.isKeyholder ? " If you didn't start that, someone holds your identity key: contest it with `p2p identity rotate --contest` (your friends then see a conflict). If you did:" : ""} Re-link it: run \`p2p link start\` on a device of the new identity, then here \`p2p link join <code> --rotated\``, { to });
361
+ }
362
+ /** Connects and handles everything queued for this device. */
363
+ async connectAndDrain() {
364
+ const pool = await this.connect();
365
+ await pool.drain(this.tun.drainQuietMs, this.tun.drainMaxMs, { backlog: true });
366
+ if (this.afterDrain)
367
+ await this.afterDrain().catch((e) => this.io.err(`p2p: ${e.message}`));
368
+ // afterDrain may have moved this device to its identity's new key (§2.8): connect as that one.
369
+ return this.pool ?? (await this.connect());
370
+ }
371
+ async close() {
372
+ if (this.pool && !this.closing) {
373
+ const pool = this.pool;
374
+ // The pool stays this app's while handlers still running finish: what they send goes out
375
+ // on it, and nothing opens a second one (connect refuses while closing).
376
+ this.closing = true;
377
+ try {
378
+ // Bounded: a command never hangs on its way out.
379
+ if (this.circlePushes.size > 0)
380
+ await Promise.race([Promise.allSettled([...this.circlePushes]), new Promise((r) => setTimeout(r, CLOSE_GRACE_MS).unref())]);
381
+ await Promise.race([pool.drain(0, 0).catch(() => { }), new Promise((r) => setTimeout(r, CLOSE_GRACE_MS).unref())]);
382
+ // Handlers still running past the grace: the process exits under them. Their claims go
383
+ // back uncounted, so the next command or the watch applies those envelopes in full.
384
+ if (pool.busy) {
385
+ pool.stopHandling();
386
+ // Bounded too: giving claims back waits on the store's lock, and an exit never hangs on it.
387
+ if (this.onAbandon)
388
+ await Promise.race([this.onAbandon().catch(() => undefined), new Promise((r) => setTimeout(r, CLOSE_GRACE_MS).unref())]);
389
+ }
390
+ }
391
+ finally {
392
+ this.pool = undefined;
393
+ this.closing = false;
394
+ pool.close();
395
+ }
396
+ }
397
+ }
398
+ // -------------------------------------------------------------------------
399
+ // Identity documents (§2.5, §5.6)
400
+ ownView() {
401
+ return getIdentityView(this.store, this.userId).then((v) => {
402
+ if (!v)
403
+ throw new CliError("no_identity", "this device holds no identity document for its user");
404
+ return v;
405
+ });
406
+ }
407
+ async view(userId) {
408
+ return getIdentityView(this.store, userId);
409
+ }
410
+ /**
411
+ * Network I/O for core's refreshIdentity (§5.6), per relay so core can cap
412
+ * each relay's answer on its own: `tips` and the `chain` walk
413
+ * (`/v3/identity/<id>/chain?to=&n=`) on every listed relay (at most 5).
414
+ */
415
+ fetcher() {
416
+ const t = this.tun.connectTimeoutMs;
417
+ const perRelay = async (relays, get) => {
418
+ const list = [...new Set(relays)].slice(0, 5);
419
+ const answers = await Promise.all(list.map((r) => get(r).catch(() => [])));
420
+ return Object.fromEntries(list.map((r, i) => [r, answers[i]]));
421
+ };
422
+ return {
423
+ tips: (userId, relays) => perRelay(relays, (r) => fetchTips(this.transport(r), userId, t, this.progress, this.guardedLookup(r))),
424
+ chain: (userId, relays, to, n) => perRelay(relays, (r) => fetchChain(this.transport(r), userId, to, n, t, this.progress, this.guardedLookup(r))),
425
+ };
426
+ }
427
+ /**
428
+ * Refreshes `userId` from the relays (core refreshIdentity: chain rules,
429
+ * gap filling, automatic jumps only over unanchored history). This is the
430
+ * only way an identity enters the store: bundled documents never do.
431
+ * Failures leave the held view (or none) and are reported as a warning.
432
+ */
433
+ async refreshIdentity(userId, relays, opts = {}) {
434
+ const fetched = (await this.state.get("fetched"))?.[userId];
435
+ const fresh = fetched !== undefined && Date.now() - fetched < this.tun.docRefreshSec * 1000;
436
+ if (fresh && !opts.force && !opts.strict)
437
+ return this.view(userId);
438
+ const held = await this.view(userId);
439
+ const list = [...new Set([...(held?.relays ?? []), ...relays])];
440
+ if (list.length === 0) {
441
+ if (opts.strict)
442
+ throw new CliError("refresh_failed", `no relays to refresh ${userId} from`);
443
+ return held;
444
+ }
445
+ try {
446
+ const v = await step(this.progress, `refreshing ${userId}'s identity document from ${list.join(", ")}`, () => coreRefreshIdentity(this.store, userId, this.fetcher(), { relays: list }));
447
+ if (v.incomplete) {
448
+ if (opts.strict)
449
+ throw new CliError("refresh_failed", "refreshing the identity document was cut short; try again");
450
+ // Cut short by core's work bound: the head may be stale. Not refreshed; don't act on it as fresh.
451
+ if (!opts.quiet)
452
+ this.warn(`refreshing ${await this.addressOf(userId)}'s identity document was cut short; using what was held before (try again)`);
453
+ return held;
454
+ }
455
+ // Recorded moments ago by another p2p process of this home (a watch and a command refresh
456
+ // the same people in a burst): no write. Only ever leaves the time a little older, so the
457
+ // next refresh comes no later.
458
+ const now = Date.now();
459
+ const last = (await this.state.get("fetched"))?.[userId];
460
+ if (last === undefined || last < now - FETCHED_SLACK_MS)
461
+ await this.state.update("fetched", (cur = {}) => ({ next: { ...cur, [userId]: Math.max(cur[userId] ?? 0, now) }, result: undefined }));
462
+ return v;
463
+ }
464
+ catch (e) {
465
+ if (!(e instanceof P2PError))
466
+ throw e;
467
+ // Strict callers (publishing our own next version) must not build on a head they couldn't confirm.
468
+ if (opts.strict)
469
+ throw new CliError("refresh_failed", `couldn't confirm the current identity document on the relays (${e.reason}): not publishing on a possibly stale head`);
470
+ if (e.reason === "chain-broken" && held && !opts.quiet) {
471
+ this.warn(`${await this.addressOf(userId)}'s newest identity document doesn't connect to the history held here (§2.5 history gap); keeping the held one`);
472
+ }
473
+ return held;
474
+ }
475
+ }
476
+ /** Relays a (bundled, unverified) identity document lists: only a hint for where to refresh from. */
477
+ static relaysOf(docJws) {
478
+ if (!docJws)
479
+ return [];
480
+ try {
481
+ return peekIdentityDoc(docJws).relays;
482
+ }
483
+ catch {
484
+ return [];
485
+ }
486
+ }
487
+ /** The view of `userId`, refreshed from the relays its document lists (or `hint`, then ours, when unknown). */
488
+ async viewFor(userId, opts = {}) {
489
+ const held = await this.view(userId);
490
+ if (held && opts.refresh === false)
491
+ return held;
492
+ const relays = held ? held.relays : [...(opts.hint ?? []), ...this.relays];
493
+ return (await this.refreshIdentity(userId, relays)) ?? held;
494
+ }
495
+ /** Relays someone else named (a code's, a pasted link's): their names are checked where they resolve, on every WebSocket and HTTP connection. */
496
+ guarded = new Set();
497
+ /** From now on in this process, connections to these relays (documents over HTTP, the pool's WebSockets) go through privateGuardLookup. */
498
+ guardRelays(relays) {
499
+ for (const r of relays) {
500
+ // Decided now: the user's own relays are left out, and a relay guarded now stays guarded for the
501
+ // rest of the command even if it becomes theirs meanwhile (a code join's new identity on the code's relay).
502
+ if (isOwnRelay(r, this.self?.relays ?? []))
503
+ continue;
504
+ try {
505
+ this.guarded.add(canonicalRelayUrl(r));
506
+ }
507
+ catch {
508
+ // not a relay URL: nothing is fetched from it
509
+ }
510
+ }
511
+ }
512
+ guardedLookup(relay) {
513
+ if (this.guarded.size === 0)
514
+ return undefined;
515
+ try {
516
+ return this.guarded.has(canonicalRelayUrl(relay)) ? privateGuardLookup() : undefined;
517
+ }
518
+ catch {
519
+ return undefined;
520
+ }
521
+ }
522
+ /** Signer resolution for core verifiers, finding unknown identities on the relays (once per process). */
523
+ signerCtx(hint = []) {
524
+ return storeSignerContext(this.store, {
525
+ resolveIdentity: (u) => this.discover(u, hint),
526
+ });
527
+ }
528
+ discover(userId, hint = []) {
529
+ if (!isUserId(userId))
530
+ return Promise.resolve(undefined);
531
+ // Found identities are cached for the process; misses only for P2P_DISCOVER_RETRY_SEC.
532
+ const hit = this.discovered.get(userId);
533
+ if (hit && (hit.found !== false || Date.now() - hit.at < this.tun.discoverRetrySec * 1000))
534
+ return hit.p;
535
+ const entry = { at: Date.now(), p: Promise.resolve(undefined) };
536
+ entry.p = (async () => {
537
+ const v = (await this.view(userId)) ?? (await this.refreshIdentity(userId, [...hint, ...(this.self?.relays ?? [])], { force: true, quiet: true }));
538
+ entry.found = v !== undefined;
539
+ return v;
540
+ })();
541
+ this.discovered.set(userId, entry);
542
+ return entry.p;
543
+ }
544
+ /** History of our own chain up to (and including) `hash`, oldest first, for back-filling relays. */
545
+ async ownHistory(hash) {
546
+ const stored = await this.store.getIdentity(this.userId);
547
+ if (!stored)
548
+ return [];
549
+ return IdentityChain.fromStored(stored)
550
+ .ancestors(hash)
551
+ .map((d) => d.jws);
552
+ }
553
+ /** Publishes `doc` (already in our chain) to `relays`; remembers the ones that didn't take it. */
554
+ async publishDoc(doc, relays) {
555
+ const pool = this.pool ?? (await this.connect({ allowNone: true }));
556
+ const peek = peekIdentityDoc(doc);
557
+ const history = peek.prev ? await this.ownHistory(peek.prev) : [];
558
+ const ok = [];
559
+ const failed = [];
560
+ await Promise.all(relays.map(async (r) => {
561
+ try {
562
+ let code;
563
+ try {
564
+ code = await pool.publishIdentity(r, doc, history);
565
+ }
566
+ catch (e) {
567
+ // A relay whose held document doesn't list this device yet (after a restore):
568
+ // identity publishes go over a restricted connection (R4-M2).
569
+ if (e.code !== "auth_failed")
570
+ throw e;
571
+ code = await pool.publishIdentityRestricted(r, doc, history);
572
+ }
573
+ if (code === "ok") {
574
+ ok.push(r);
575
+ this.publishMaybeStored = true;
576
+ }
577
+ else
578
+ failed.push({ relay: r, code });
579
+ }
580
+ catch (e) {
581
+ const code = e.code ?? "network";
582
+ failed.push({ relay: r, code });
583
+ // Unknown outcome: the document may have reached the relay.
584
+ if (code !== "unreachable")
585
+ this.publishMaybeStored = true;
586
+ }
587
+ }));
588
+ await this.updateSelf((s) => recordPublishOutcome(s, ok, failed, Date.now()));
589
+ return { ok, failed };
590
+ }
591
+ /** On connect: relays that failed transiently, and outright refusals whose backoff has passed. */
592
+ async retryUnpublished() {
593
+ const view = await this.view(this.userId);
594
+ if (!view || !this.self)
595
+ return;
596
+ const list = relaysToRetry(this.self, Date.now(), this.tun.refusedPublishRetrySec * 1000);
597
+ if (list.length === 0)
598
+ return;
599
+ this.self = { ...this.self, unpublished: [] };
600
+ await this.publishDoc(view.head.jws, list).catch(() => { });
601
+ }
602
+ /** Publishes our current head again to every relay it lists (R4-M2: `p2p identity republish`). */
603
+ async republish() {
604
+ await this.connect({ allowNone: true });
605
+ await this.refreshIdentity(this.userId, this.relays, { force: true, quiet: true });
606
+ const view = await this.ownView();
607
+ const r = await this.publishDoc(view.head.jws, view.relays);
608
+ return { ver: view.head.ver, ...r };
609
+ }
610
+ /** Takes a newer certificate for this device from disk (another process renewed it) or our own document. */
611
+ async reloadCert() {
612
+ const keys = await this.state.get("keys");
613
+ if (keys && keys.did === this.did && certExp(keys.cert) > certExp(this.keys.cert))
614
+ this.keys = { ...this.keys, cert: keys.cert };
615
+ await this.adoptCertFromDoc();
616
+ }
617
+ /**
618
+ * R4-L2: a relay refused this device. Refresh our own document: if some branch still lists
619
+ * this device (e.g. it was linked during a fork, so it isn't in the intersection yet), retry
620
+ * later with backoff; if none does, it was revoked.
621
+ */
622
+ async authRefusedVerdict(relay) {
623
+ // A hostile relay can refuse on every dial: refresh at most once per P2P_REFUSED_REFRESH_SEC
624
+ // per relay, and reuse the verdict in between.
625
+ const last = this.refusedVerdicts.get(relay);
626
+ if (last && Date.now() - last.at < this.tun.refusedRefreshSec * 1000)
627
+ return last.verdict;
628
+ await this.refreshIdentity(this.userId, this.relays, { force: true, quiet: true });
629
+ const view = await this.view(this.userId);
630
+ const verdict = view && view.tips.some((t) => t.devices.includes(this.did)) ? "retry" : "fatal";
631
+ this.refusedVerdicts.set(relay, { at: Date.now(), verdict });
632
+ return verdict;
633
+ }
634
+ async updateSelf(fn) {
635
+ const next = await this.state.update("self", (cur) => {
636
+ const n = fn(cur ?? this.self);
637
+ return { next: n, result: n };
638
+ });
639
+ this.self = next;
640
+ return next;
641
+ }
642
+ /**
643
+ * Builds, signs and publishes the next version of our identity document
644
+ * (§2.5): fetches the head from every listed relay first and builds on the
645
+ * newest, keeps the device certificates current, and records what this
646
+ * device added (compromise detection).
647
+ */
648
+ async publishNext(change, opts = {}) {
649
+ const ik = this.requireKeyholder("Publishing the identity document");
650
+ // §2.5: build on the newest head the relays hold, or not at all (review H2: a stale key holder
651
+ // republishing blind could fork the identity).
652
+ await this.refreshIdentity(this.userId, this.relays, { force: true, strict: true });
653
+ let view = await this.ownView();
654
+ // What the tips list before any merge: a merge keeps only the intersection (§2.5), so devices
655
+ // only one branch listed are re-added below unless they were revoked (review N-H1).
656
+ const unionDevices = [...new Set(view.tips.flatMap((t) => t.devices))];
657
+ const preTips = view.tips.map((t) => t.hash);
658
+ const unionKeyholders = [...new Set(view.tips.flatMap((t) => t.keyholders))];
659
+ const allCerts = [...new Set(view.tips.flatMap((t) => t.certs ?? []))];
660
+ const merges = [];
661
+ // §2.5 fork resolution: merge pairwise until one tip remains. Each merge names the higher tip
662
+ // as prev (mergePrevTip), keeps the intersection of devices and key holders, and is published
663
+ // `by` one of its key holders: this device when it is one, else the scheduled writer (the
664
+ // lowest did among the common key holders). The identity key signs either way.
665
+ while (view.tips.length > 1) {
666
+ const [a, b] = view.tips;
667
+ const f = mergeFields(a, b);
668
+ const by = f.keyholders.includes(this.did) ? this.did : scheduledWriter(f.keyholders);
669
+ if (f.devices.length > 0 && !by) {
670
+ throw new CliError("fork_unmergeable", "your identity document is forked and the branches share no key holder, so it can't be merged (§2.5). A lost key holder may be publishing: rotate your identity (`p2p identity rotate`, §2.8)");
671
+ }
672
+ const prev = mergePrevTip(a, b).prev;
673
+ const m = createIdentityDoc(ik, {
674
+ ...f,
675
+ by: by ?? this.did,
676
+ certs: allCerts.filter((c) => f.devices.includes(certDid(c) ?? "")),
677
+ ...(prev.proofs ? { proofs: [...prev.proofs] } : {}),
678
+ ...(prev.profile ? { profile: { ...prev.profile } } : {}),
679
+ });
680
+ if ((await addIdentityVersion(this.store, m)).status === "gap")
681
+ throw new CliError("internal", "the merge does not chain onto the held tips");
682
+ // R3-L2: `by` is nominal on a merge (a common key holder, maybe another device: §2.5 only
683
+ // requires it to be one of the version's key holders). This device records the merge as its
684
+ // own, so its "versions I didn't publish" check never flags it. Another device of ours sees a
685
+ // pure intersection of its parents, which adds no device, relay or proof, so core's
686
+ // detectUnpublishedVersion doesn't alert on it either.
687
+ await this.store.recordPublished({ hash: peekIdentityDoc(m).hash });
688
+ merges.push(m);
689
+ view = await this.ownView();
690
+ }
691
+ const head = view.head;
692
+ const stored = await this.store.getIdentity(this.userId);
693
+ // Only devices a merge dropped come back: never one revoked along the head's ancestry, nor one
694
+ // core denies after a history jump.
695
+ const plan = stored && merges.length > 0 ? planReadd(IdentityChain.fromStored(stored), preTips, unionDevices, view.devices, head.hash, stored.denied ?? []) : { readd: [], skipped: [] };
696
+ for (const d of plan.skipped)
697
+ this.warn(`device ${d} was dropped by the merge of your identity document's branches; link it again (this device's copy of the history can't prove it wasn't revoked)`);
698
+ const readd = plan.readd;
699
+ const devices = [...view.devices, ...readd].slice(0, MAX_DEVICES);
700
+ const keyholders = [...view.keyholders, ...unionKeyholders.filter((d) => readd.includes(d) && devices.includes(d))];
701
+ if (!opts.restoring && (!devices.includes(this.did) || !keyholders.includes(this.did))) {
702
+ throw new CliError("device_revoked", "this device is no longer a listed key holder of your identity: it can't publish (only identity rotation, §2.8, replaces a lost key holder's key; run it from a listed key holder)");
703
+ }
704
+ const p = {
705
+ ver: head.ver + 1,
706
+ prev: head.hash,
707
+ name: head.name,
708
+ relays: [...head.relays],
709
+ devices,
710
+ keyholders,
711
+ by: this.did,
712
+ certs: [...new Set([...(head.certs ?? []), ...allCerts])],
713
+ ...(head.proofs ? { proofs: [...head.proofs] } : {}),
714
+ ...(head.profile ? { profile: { ...head.profile } } : {}),
715
+ };
716
+ change(p);
717
+ p.by = this.did;
718
+ // docs/compatibility.md: this device's caps and version (`dinfo`), when the user opted in and every
719
+ // relay stores documents with fields it doesn't know; the entries of devices still listed carry
720
+ // over. Off, the document carries none, so clients from before protocol 3.1 can read it.
721
+ if (!opts.rotation && deviceInfoEnabled(this.env, this.home) && (await relaysSupport(this, [...new Set([...p.relays, ...head.relays])], RELAY_FEATURE_LENIENT_IDENTITY))) {
722
+ const kept = Object.fromEntries(Object.entries(head.dinfo ?? {}).filter(([did]) => p.devices.includes(did)));
723
+ p.dinfo = { ...kept, [this.did]: { caps: [...CLI_CAPS], client: VERSION } };
724
+ }
725
+ else {
726
+ delete p.dinfo;
727
+ }
728
+ if (opts.rotation) {
729
+ // The final version lists nobody: relays then refuse every old did, and nothing may follow it.
730
+ p.devices = [];
731
+ p.keyholders = [];
732
+ delete p.certs;
733
+ p.rotation = opts.rotation;
734
+ }
735
+ else {
736
+ if (!p.keyholders.includes(this.did))
737
+ throw new CliError("usage", "this device can't drop itself as a key holder");
738
+ p.certs = await this.currentCerts(ik, p.devices, p.certs ?? []);
739
+ }
740
+ const doc = createIdentityDoc(ik, p);
741
+ const added = await addIdentityVersion(this.store, doc);
742
+ if (added.status === "gap")
743
+ throw new CliError("internal", "the new version does not chain onto the held head");
744
+ await this.store.recordPublished({
745
+ hash: peekIdentityDoc(doc).hash,
746
+ devices: p.devices.filter((d) => !head.devices.includes(d)),
747
+ relays: p.relays.filter((r) => !head.relays.includes(r)),
748
+ });
749
+ const targets = [...new Set([...p.relays, ...head.relays])];
750
+ for (const m of merges)
751
+ await this.publishDoc(m, targets);
752
+ const r = await this.publishDoc(doc, targets);
753
+ await this.updateSelf((s) => ({ ...s, relays: p.relays, name: p.name }));
754
+ return { doc, ver: p.ver, ...r, merged: merges.length };
755
+ }
756
+ /** One certificate per listed device: renewed when within 30 days of expiry (key holders renew, §2.3). */
757
+ async currentCerts(ik, devices, certs) {
758
+ const out = [];
759
+ const now = nowSec();
760
+ for (const d of devices) {
761
+ const candidates = certs.filter((c) => certDid(c) === d);
762
+ if (d === this.did)
763
+ candidates.push(this.keys.cert);
764
+ const stored = await this.store.getDeviceCert(d);
765
+ if (stored)
766
+ candidates.push(stored.jws);
767
+ let best;
768
+ for (const c of candidates) {
769
+ try {
770
+ const v = verifyDeviceCertV3(c, { now });
771
+ if (v.iss !== this.userId)
772
+ continue;
773
+ if (!best || v.exp > best.exp)
774
+ best = { jws: c, exp: v.exp, spk: v.signingPublicKey, kpk: v.agreementPublicKey, label: v.label };
775
+ }
776
+ catch {
777
+ // expired or malformed: maybe another candidate
778
+ }
779
+ }
780
+ if (!best)
781
+ continue;
782
+ if (best.exp - now <= RENEW_CERT_WITHIN_SEC) {
783
+ const renewed = createDeviceCert(ik, { signingPublicKey: best.spk, agreementPublicKey: best.kpk, ...(best.label ? { label: best.label } : {}) });
784
+ best = { ...best, jws: renewed };
785
+ if (d === this.did)
786
+ await this.adoptCert(renewed);
787
+ }
788
+ out.push(best.jws);
789
+ }
790
+ return out;
791
+ }
792
+ /** Switches this device to a newer certificate for itself (renewal keeps did, spk and kpk). */
793
+ async adoptCert(cert) {
794
+ const v = verifyDeviceCertV3(cert);
795
+ if (v.did !== this.did || v.iss !== this.userId)
796
+ return;
797
+ if (v.exp <= certExp(this.keys.cert))
798
+ return;
799
+ const keys = await this.state.update("keys", (k) => {
800
+ const n = { ...(k ?? this.keys), cert };
801
+ return { next: n, result: n };
802
+ });
803
+ this.keys = keys;
804
+ await this.store.putDeviceCert({ userId: this.userId, did: this.did, exp: v.exp, jws: cert });
805
+ }
806
+ /** A non-key-holding device takes a renewed certificate from its own document (§2.3 renewal by sync or document). */
807
+ async adoptCertFromDoc() {
808
+ const view = await this.view(this.userId);
809
+ if (!view)
810
+ return;
811
+ for (const t of view.tips) {
812
+ for (const c of t.certs ?? []) {
813
+ if (certDid(c) === this.did)
814
+ await this.adoptCert(c).catch(() => { });
815
+ }
816
+ }
817
+ }
818
+ // -------------------------------------------------------------------------
819
+ // Names
820
+ async nameOf(userId) {
821
+ const v = await this.view(userId);
822
+ return v?.head.name ?? "?";
823
+ }
824
+ /** `<petname or name>@<fp>` (§2.1: always with the fingerprint). */
825
+ async addressOf(userId) {
826
+ if (!isUserId(userId))
827
+ return userId;
828
+ const pet = await this.store.getPetname(userId);
829
+ return displayAddress(userId, await this.nameOf(userId), pet);
830
+ }
831
+ /**
832
+ * A userId from what the user typed: a userId, a petname, a display
833
+ * address `name@xxxx-xxxx-xxxx-xxxx`, or a name when it is unique among
834
+ * known identities. Decisions always use the full userId (§2.1).
835
+ */
836
+ async resolveUser(input) {
837
+ const s = input.trim();
838
+ if (isUserId(s))
839
+ return s;
840
+ if (s === "me" || s === "self")
841
+ return this.userId;
842
+ const pets = await this.store.listPetnames();
843
+ const byPet = Object.entries(pets).filter(([, p]) => p === s);
844
+ if (byPet.length === 1)
845
+ return byPet[0][0];
846
+ const known = await this.store.listIdentities();
847
+ const at = /^(.+)@([a-z2-7]{4}-[a-z2-7]{4}-[a-z2-7]{4}-[a-z2-7]{4})$/.exec(s);
848
+ if (at) {
849
+ const hits = [];
850
+ for (const u of known) {
851
+ if (displayFingerprint(u) !== at[2])
852
+ continue;
853
+ const name = await this.nameOf(u);
854
+ if (pets[u] === at[1] || name === at[1])
855
+ hits.push(u);
856
+ }
857
+ if (hits.length === 1)
858
+ return hits[0];
859
+ if (hits.length > 1)
860
+ throw new CliError("ambiguous", `${s} matches more than one identity`, { candidates: hits });
861
+ throw new CliError("not_found", `no known identity is ${s}`);
862
+ }
863
+ if (isValidName(s)) {
864
+ const hits = [];
865
+ for (const u of known)
866
+ if ((await this.nameOf(u)) === s)
867
+ hits.push(u);
868
+ if (hits.length === 1)
869
+ return hits[0];
870
+ if (hits.length > 1) {
871
+ throw new CliError("ambiguous", `more than one known identity is called ${s}: use name@fingerprint, the userId, or a petname`, {
872
+ candidates: await Promise.all(hits.map(async (u) => ({ userId: u, address: await this.addressOf(u) }))),
873
+ });
874
+ }
875
+ }
876
+ throw new CliError("not_found", `no known identity matches ${s}`);
877
+ }
878
+ // -------------------------------------------------------------------------
879
+ // Capabilities (§5.3)
880
+ /** A cap minted by this device for our own mailboxes (any of our devices may issue one for itself). */
881
+ selfCap() {
882
+ return createCap(this.device, this.keys.cert, { purpose: "friend", sub: this.userId, relays: this.relays, ttlSec: 7 * 86_400 });
883
+ }
884
+ /** Caps we hold that let us reach `to` with `kind`, by relay (best first). */
885
+ async capsFor(to, kind, extra = []) {
886
+ const now = nowSec();
887
+ const cands = [];
888
+ if (to === this.userId) {
889
+ const c = this.selfCap();
890
+ cands.push({ jws: c, relays: this.relays, kinds: ["*"], exp: now + 7 * 86_400 });
891
+ }
892
+ for (const c of await this.store.listCapsHeld(to)) {
893
+ if (c.sub === this.userId || c.sub === "*")
894
+ cands.push({ jws: c.jws, relays: c.relays, kinds: c.kinds, exp: c.exp });
895
+ }
896
+ const joinCaps = [...extra];
897
+ // Co-member caps only while both of us are in the circle (§5.3: they are for co-members).
898
+ for (const rec of await this.store.listCircles()) {
899
+ if (!rec.joinedByMe)
900
+ continue;
901
+ const s = rec.statements[to];
902
+ if (s?.op === "join" && CircleChain.fromStored(rec.chain).head.members.includes(to)) {
903
+ const cap = joinCapOf(s.jws);
904
+ if (cap)
905
+ joinCaps.push(cap);
906
+ }
907
+ }
908
+ for (const j of joinCaps) {
909
+ const p = capPeek(j);
910
+ if (p && p.iss === to && (p.sub === "*" || p.sub === this.userId))
911
+ cands.push({ jws: j, relays: p.relays, kinds: p.kinds, exp: p.exp });
912
+ }
913
+ const usable = cands.filter((c) => c.exp > now + 60 && capAllowsKind(c.kinds, kind)).sort((a, b) => CAP_PRIORITY(a) - CAP_PRIORITY(b) || b.exp - a.exp);
914
+ const out = new Map();
915
+ for (const c of usable)
916
+ for (const r of c.relays)
917
+ if (!out.has(r))
918
+ out.set(r, c.jws);
919
+ return out;
920
+ }
921
+ /** Records a cap this device issued, so it can be revoked later (§5.3). */
922
+ async recordIssued(capJws) {
923
+ const p = capPeek(capJws);
924
+ const c = { capid: p.capid, iss: p.iss, sub: p.sub, relays: p.relays, kinds: p.kinds, exp: p.exp, jws: capJws };
925
+ await this.store.addCapIssued(c);
926
+ return c;
927
+ }
928
+ /** Sends `revoke` for each cap to every relay it names. */
929
+ async revokeCaps(caps) {
930
+ if (caps.length === 0)
931
+ return 0;
932
+ const pool = this.pool ?? (await this.connect({ allowNone: true }));
933
+ let n = 0;
934
+ for (const c of caps)
935
+ if ((await pool.revoke(c.capid, c.relays)).length > 0)
936
+ n++;
937
+ return n;
938
+ }
939
+ // -------------------------------------------------------------------------
940
+ // Delivery (§4.1, §5.4, §5.8)
941
+ /**
942
+ * Seals `plaintext` to every current device of `to` and sends each copy to
943
+ * up to 3 of their relays. Our own devices are reached with a cap this
944
+ * device mints; others with a held cap, or PoW for a cap-less `contact`.
945
+ */
946
+ async deliver(to, kind, session, plaintext, opts = {}) {
947
+ const pool = this.pool ?? (await this.connect());
948
+ const view = to === this.userId ? await this.ownView() : await this.viewFor(to, { refresh: opts.refresh, hint: opts.hint });
949
+ if (!view)
950
+ throw new CliError("unknown_user", `no identity document for ${to}: can't find their devices or relays`);
951
+ // This device only when named in onlyDevices (a message to another session of ours here, or a
952
+ // receipt for one): sealed to itself and sent through a relay like any other copy.
953
+ const devices = view.devices.filter((d) => (to !== this.userId || d !== this.did || opts.onlyDevices?.includes(d) === true) && (!opts.onlyDevices || opts.onlyDevices.includes(d)));
954
+ const relays = orderRelays(view.head.relays, view.relays).slice(0, 3);
955
+ const caps = await this.capsFor(to, kind, opts.extraCaps);
956
+ const resolveCert = storeCertResolver(this.store);
957
+ const sentVia = new Set();
958
+ const errors = [];
959
+ // Certificates first (each verified, as before), then one seq block for every copy, then the
960
+ // copies go out together: one round trip for all of the recipient's devices, not one each.
961
+ const ready = [];
962
+ for (const d of devices) {
963
+ const certJws = await resolveCert(to, d);
964
+ if (!certJws) {
965
+ errors.push({ did: d, relay: "", code: "no-cert" });
966
+ continue;
967
+ }
968
+ try {
969
+ ready.push({ d, kpk: verifyDeviceCertV3(certJws, { identityDoc: { iss: view.iss, ik: view.ik, devices: view.devices } }).agreementPublicKey });
970
+ }
971
+ catch (e) {
972
+ errors.push({ did: d, relay: "", code: e.reason ?? "bad-cert" });
973
+ }
974
+ }
975
+ const seqs = ready.length > 0 ? await this.state.nextSeqs(session.own, session.sid, ready.length) : [];
976
+ if (opts.beforeSend && ready.length > 0)
977
+ await opts.beforeSend(ready.map((r, i) => ({ did: r.d, seq: seqs[i] })));
978
+ const targets = relays.map((r) => ({ relay: r, cap: caps.get(r) })).filter((t) => t.cap !== undefined || kind === "contact");
979
+ const outgoing = [];
980
+ for (const [i, { d, kpk }] of ready.entries()) {
981
+ const env = sealEnvelopeV3({
982
+ from: this.userId,
983
+ fdid: this.did,
984
+ fcert: this.keys.cert,
985
+ to,
986
+ tdid: d,
987
+ own: session.own,
988
+ sid: session.sid,
989
+ seq: seqs[i],
990
+ ts: Date.now(),
991
+ kind,
992
+ plaintext,
993
+ sender: { signingSecretKey: this.device.signingSecretKey, agreementSecretKey: this.device.agreementSecretKey },
994
+ recipientKpk: kpk,
995
+ });
996
+ if (targets.length === 0)
997
+ errors.push({ did: d, relay: "", code: "no-cap" });
998
+ else
999
+ outgoing.push({ d, env });
1000
+ }
1001
+ const sealed = ready.length;
1002
+ const results = await Promise.all(outgoing.map(({ d, env }) => pool.sendEnvelope(env, to, d, kind, targets)));
1003
+ const unsent = [];
1004
+ for (const [i, res] of results.entries()) {
1005
+ for (const r of res.sent)
1006
+ sentVia.add(r);
1007
+ for (const e of res.errors)
1008
+ errors.push({ did: outgoing[i].d, relay: e.relay, code: e.code, ...(e.written ? { written: true } : {}) });
1009
+ if (res.sent.length === 0)
1010
+ unsent.push({ did: outgoing[i].d, env: outgoing[i].env, targets, codes: res.errors.map((e) => e.code) });
1011
+ }
1012
+ return { userId: to, devices: sealed, relays: [...sentVia], ...(errors.length > 0 ? { errors } : {}), ...(unsent.length > 0 ? { unsent } : {}) };
1013
+ }
1014
+ /** Delivers to our other devices, when there are any (sync, §4.3). */
1015
+ async syncOwn(body) {
1016
+ const view = await this.view(this.userId);
1017
+ if (!view || view.devices.filter((d) => d !== this.did).length === 0)
1018
+ return undefined;
1019
+ try {
1020
+ return await this.deliver(this.userId, "sync", { own: this.userId, sid: "~sync" }, body);
1021
+ }
1022
+ catch (e) {
1023
+ this.io.err(`sync to your other devices failed: ${e.message}`);
1024
+ return undefined;
1025
+ }
1026
+ }
1027
+ }
1028
+ /**
1029
+ * Does the held history cover every branch back to their common ancestor?
1030
+ * (Each version above the common ancestry has its parents held.) Only then
1031
+ * is revokedAlong complete for those branches (R3-M3).
1032
+ */
1033
+ export function branchesCovered(chain, tips) {
1034
+ if (tips.length < 2)
1035
+ return true;
1036
+ const ancestry = tips.map((t) => new Set(chain.ancestors(t).map((v) => v.hash)));
1037
+ const common = ancestry.reduce((a, b) => new Set([...a].filter((x) => b.has(x))));
1038
+ if (common.size === 0)
1039
+ return false;
1040
+ for (const anc of ancestry) {
1041
+ for (const h of anc) {
1042
+ if (common.has(h))
1043
+ continue;
1044
+ const v = chain.get(h);
1045
+ if (!v)
1046
+ return false;
1047
+ if (v.prev !== null && !chain.has(v.prev))
1048
+ return false;
1049
+ if (v.merge !== undefined && !chain.has(v.merge))
1050
+ return false;
1051
+ }
1052
+ }
1053
+ return true;
1054
+ }
1055
+ /**
1056
+ * After merging `tips` into `head`: the devices to re-add (listed by some
1057
+ * pre-merge tip, dropped by the merge, not revoked along the head's
1058
+ * ancestry, not denied after a jump), but only when the held history covers
1059
+ * every branch; otherwise they are `skipped` (fail closed, R3-M3).
1060
+ */
1061
+ export function planReadd(chain, tips, unionDevices, mergedDevices, head, denied) {
1062
+ const revoked = chain.revokedAlong(head);
1063
+ const cands = unionDevices.filter((d) => !mergedDevices.includes(d) && !revoked.has(d) && !denied.includes(d));
1064
+ if (cands.length === 0)
1065
+ return { readd: [], skipped: [] };
1066
+ return branchesCovered(chain, tips) ? { readd: cands, skipped: [] } : { readd: [], skipped: cands };
1067
+ }
1068
+ /** Publish failures worth retrying on every connect; anything else is an outright refusal. */
1069
+ export const TRANSIENT_PUBLISH_CODES = ["network", "auth_failed", "identity-gap"];
1070
+ /**
1071
+ * After a publish: transient failures go to `unpublished` (retried on every connect); outright
1072
+ * refusals (e.g. `forbidden`) are timestamped in `refusedPublish` (retried at most hourly, or by an
1073
+ * explicit `p2p identity republish`); relays that took it are cleared from both.
1074
+ */
1075
+ export function recordPublishOutcome(s, ok, failed, now) {
1076
+ const refused = { ...(s.refusedPublish ?? {}) };
1077
+ for (const r of ok)
1078
+ delete refused[r];
1079
+ const unpublished = [];
1080
+ for (const f of failed) {
1081
+ if (TRANSIENT_PUBLISH_CODES.includes(f.code)) {
1082
+ unpublished.push(f.relay);
1083
+ delete refused[f.relay];
1084
+ }
1085
+ else
1086
+ refused[f.relay] = now;
1087
+ }
1088
+ const out = { ...s, unpublished };
1089
+ if (Object.keys(refused).length > 0)
1090
+ out.refusedPublish = refused;
1091
+ else
1092
+ delete out.refusedPublish;
1093
+ return out;
1094
+ }
1095
+ /** The relays to retry on connect: transient failures, and refusals older than `backoffMs`. */
1096
+ export function relaysToRetry(s, now, backoffMs) {
1097
+ const due = Object.entries(s.refusedPublish ?? {})
1098
+ .filter(([, at]) => now - at >= backoffMs)
1099
+ .map(([r]) => r);
1100
+ return [...new Set([...(s.unpublished ?? []), ...due])];
1101
+ }
1102
+ /** The relays a document lists, head's first, then any other tip's. */
1103
+ export function orderRelays(head, all) {
1104
+ return [...new Set([...head, ...all])];
1105
+ }
1106
+ export function certDid(jws) {
1107
+ try {
1108
+ const d = decodeTyped(jws, TYP3.device).payload.did;
1109
+ return typeof d === "string" ? d : undefined;
1110
+ }
1111
+ catch {
1112
+ return undefined;
1113
+ }
1114
+ }
1115
+ export function certExp(jws) {
1116
+ try {
1117
+ const e = decodeTyped(jws, TYP3.device).payload.exp;
1118
+ return typeof e === "number" ? e : 0;
1119
+ }
1120
+ catch {
1121
+ return 0;
1122
+ }
1123
+ }
1124
+ /** A cap's payload, unverified (for routing our own sends; the relay and the issuer verify). */
1125
+ export function capPeek(jws) {
1126
+ try {
1127
+ const p = decodeTyped(jws, TYP3.cap).payload;
1128
+ if (typeof p.iss !== "string" || typeof p.sub !== "string" || typeof p.capid !== "string" || typeof p.exp !== "number")
1129
+ return undefined;
1130
+ const relays = Array.isArray(p.relays) ? p.relays.filter((x) => typeof x === "string") : [];
1131
+ const kinds = Array.isArray(p.kinds) ? p.kinds.filter((x) => typeof x === "string") : [];
1132
+ return { iss: p.iss, sub: p.sub, capid: p.capid, relays, kinds, exp: p.exp };
1133
+ }
1134
+ catch {
1135
+ return undefined;
1136
+ }
1137
+ }
1138
+ /** The co-member cap a join statement carries (§3.3, review M3). */
1139
+ export function joinCapOf(statementJws) {
1140
+ try {
1141
+ const cap = decodeTyped(statementJws, TYP3.join).payload.cap;
1142
+ return typeof cap === "string" ? cap : undefined;
1143
+ }
1144
+ catch {
1145
+ return undefined;
1146
+ }
1147
+ }
1148
+ /** A default display name from the OS user: `[a-z0-9._-]{1,32}`, else "me". */
1149
+ export function defaultName() {
1150
+ let n;
1151
+ try {
1152
+ n = userInfo().username.toLowerCase().replace(/[^a-z0-9._-]/g, "").slice(0, 32);
1153
+ }
1154
+ catch {
1155
+ n = "";
1156
+ }
1157
+ return isValidName(n) ? n : "me";
1158
+ }
1159
+ /** A device label: the host name, sanitized and capped at 64. */
1160
+ export function defaultLabel() {
1161
+ const h = hostname().replace(/[^\w.-]/g, "").slice(0, 64);
1162
+ return h || "device";
1163
+ }
1164
+ export function newKeysDoc(userId, device, cert, ik) {
1165
+ return {
1166
+ v: 1,
1167
+ userId,
1168
+ did: device.did,
1169
+ spk: b64uEncode(device.signingSecretKey),
1170
+ kpk: b64uEncode(device.agreementSecretKey),
1171
+ cert,
1172
+ ...(ik ? { ik: b64uEncode(ik.secretKey) } : {}),
1173
+ };
1174
+ }
1175
+ /** P2P_DEBUG lines for a store lock that was waited for or held long enough to matter. */
1176
+ function lockLogger(p) {
1177
+ return ({ dir, waitedMs, attempts, heldMs }) => {
1178
+ if (waitedMs >= 10 || heldMs >= 50)
1179
+ debug(p, `lock ${basename(dir)}: waited ${waitedMs}ms (${attempts} tries), held ${heldMs}ms`);
1180
+ };
1181
+ }