@peer2peer/cli 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/app.d.ts CHANGED
@@ -6,6 +6,15 @@ import type { Pretty } from "./pretty.js";
6
6
  import { CliState, type KeysDoc, type SelfDoc } from "./state.js";
7
7
  import { type Progress } from "./progress.js";
8
8
  import type { ExtensionRegistry } from "./extensions.js";
9
+ /**
10
+ * #67: relays a strict refresh of our own identity may leave out when it can't confirm the head over all of
11
+ * them (App.ownStrictFallback): the ones an edit removes, and (rotation) the ones that sent versions it
12
+ * couldn't connect.
13
+ */
14
+ export interface SetAside {
15
+ relays?: readonly string[];
16
+ unconnected?: boolean;
17
+ }
9
18
  export interface Io {
10
19
  /** Human output (stdout). */
11
20
  out(s: string): void;
@@ -76,6 +85,16 @@ export interface Delivery {
76
85
  export declare class App {
77
86
  /** The person's front end vouched for this command (P2P_PERSON_TOKEN, checked once and removed: projects.ts). */
78
87
  front: boolean;
88
+ /**
89
+ * The token `front` rests on, kept in memory (never in the environment), so the keys this command
90
+ * loads are checked against it (load): a home whose files change after the start never lends the
91
+ * token to other keys. Undefined for an embedder that vouches without one.
92
+ */
93
+ frontToken?: string;
94
+ /** The home held no identity when the token was checked (a front end's first run). */
95
+ frontFresh: boolean;
96
+ /** This command made, restored or swapped in the identity it holds (init, link join, restore, a rotation's swap). */
97
+ identityMadeHere: boolean;
79
98
  /** The person's "yes" on their controlling terminal (tty-confirm.ts); cli.ts may stand another in (tests). */
80
99
  confirmTty: (question: string) => Promise<boolean>;
81
100
  readonly env: Env;
@@ -135,6 +154,13 @@ export declare class App {
135
154
  constructor(opts: AppOptions);
136
155
  /** Loads this device's keys. With `require`, a missing identity is an error. */
137
156
  load(require?: boolean): Promise<boolean>;
157
+ /**
158
+ * The person token this command was given must be the one these keys derive (projects.ts
159
+ * personTokenMatchesKeys), unless this command made the identity itself. A home that had no
160
+ * identity when the token was checked, and has one now that this command didn't make, never
161
+ * keeps it. Otherwise the command stops: the home changed under it.
162
+ */
163
+ private checkFrontKeys;
138
164
  setKeys(keys: KeysDoc, self: SelfDoc): void;
139
165
  get userId(): string;
140
166
  get did(): string;
@@ -187,12 +213,24 @@ export declare class App {
187
213
  /** Connects and handles everything queued for this device. */
188
214
  connectAndDrain(): Promise<RelayPool>;
189
215
  close(): Promise<void>;
216
+ /**
217
+ * Our own identity's view. Pending heads (core #35) never narrow it: they are for trusting others'
218
+ * devices, and a version only the identity key signed must not stop this device from editing or
219
+ * rotating the identity (#65 review M1).
220
+ */
190
221
  ownView(): Promise<IdentityView>;
222
+ /** The stored view of `userId`; our own identity's never narrowed by pending heads (#65 re-review N1, see ownView). */
191
223
  view(userId: string): Promise<IdentityView | undefined>;
192
224
  /**
193
225
  * Network I/O for core's refreshIdentity (§5.6), per relay so core can cap
194
226
  * each relay's answer on its own: `tips` and the `chain` walk
195
227
  * (`/v3/identity/<id>/chain?to=&n=`) on every listed relay (at most 5).
228
+ *
229
+ * #78: a relay that couldn't be reached (an error or a timeout) is left out of the answer, and when none
230
+ * of the relays asked answered the call fails, so core counts it as a relay that didn't answer (core asks
231
+ * one relay per call), never as one that answered "nothing": its silence doesn't make up a majority that
232
+ * clears pending heads or counts as fresh, and a relay is never named as forging over a gap the silent
233
+ * one wasn't really asked about.
196
234
  */
197
235
  fetcher(): IdentityFetcher;
198
236
  /**
@@ -200,12 +238,70 @@ export declare class App {
200
238
  * gap filling, automatic jumps only over unanchored history). This is the
201
239
  * only way an identity enters the store: bundled documents never do.
202
240
  * Failures leave the held view (or none) and are reported as a warning.
241
+ *
242
+ * `setAside` (#67, strict refreshes of our own identity only): relays to leave out when the refresh over
243
+ * all of them can't confirm the head. See ownStrictFallback.
203
244
  */
204
245
  refreshIdentity(userId: string, relays: readonly string[], opts?: {
205
246
  force?: boolean;
206
247
  quiet?: boolean;
207
248
  strict?: boolean;
249
+ setAside?: SetAside;
208
250
  }): Promise<IdentityView | undefined>;
251
+ /**
252
+ * For a strict refresh of our own identity that failed: what to do. The key-compromise wording only for relays
253
+ * core named (#67 review F1): each sent a version whose missing parent every relay was asked for and none had,
254
+ * so nothing a device of ours published would be there. Otherwise only which relays sent the newer versions.
255
+ */
256
+ private unconnectedHint;
257
+ /**
258
+ * #67: a strict refresh of our OWN identity couldn't confirm the head over every listed relay. Before an
259
+ * identity edit that removes relays (`setAside.relays`: the ones it removes), or a rotation step
260
+ * (`setAside.unconnected`: the relays that sent versions the refresh couldn't connect), it is retried over
261
+ * the other listed relays, and the caller goes ahead only if that refresh is complete.
262
+ *
263
+ * Why this is safe:
264
+ * - The strict refresh is there so we don't fork our own chain by building on a stale head (review H2):
265
+ * a newer version another of our key holders published went to every relay the document lists. The
266
+ * relays kept must still give a complete refresh, so a newer version any of them serves is still found,
267
+ * connected and built on (or, far behind, the refresh is incomplete and the edit refused: trying again
268
+ * goes on where the walk stopped). Leaving a relay out is what the strict refresh already allows when
269
+ * that relay doesn't answer.
270
+ * - Which relays are left out is the user's choice (the ones the edit removes) or each relay's own
271
+ * evidence (it sent identity-key-signed versions that don't connect): one relay can't get another left
272
+ * out. Any other edit still refuses while such a relay is listed, and names it (fork and compromise
273
+ * detection stay: the user is told someone else may hold the key).
274
+ * - What is published is still head.ver + 1 on the head the kept relays confirmed: a relay left out can't
275
+ * make it lower, or make it fork from anything but what those relays serve.
276
+ * - Nothing is left out when no relay would be left; the kept relays' refresh must reach one of them.
277
+ * - #67 review F1: core names a relay only for versions on a dead gap (asked of every relay, held by
278
+ * none), never one whose genuine gap the walk merely didn't reach. And the confirmed head must not be
279
+ * below any version the full refresh left unconnected, unless every relay that sent that version is set
280
+ * aside: a lagging kept relay can't "confirm" a stale head while another relay serves a newer version.
281
+ * (A newer version an earlier refresh stored as a pending head, from a relay silent now: ownPendingGuard.)
282
+ * Returns the view, or undefined when this doesn't apply (the caller then refuses as before).
283
+ */
284
+ private ownStrictFallback;
285
+ /**
286
+ * #78: a strict refresh of our own identity skips relays that don't answer, so a lagging relay could
287
+ * "confirm" a stale head while the up-to-date one times out. This device may already hold the newer
288
+ * version, as a pending head an earlier, incomplete refresh recorded with the relays that sent it. Refuses
289
+ * when a pending head above the confirmed head was sent by a relay that:
290
+ * - is still listed and isn't set aside by this edit (`setAside.relays`: the relays it removes), so
291
+ * `p2p relays remove` always gets past a relay that holds the owner up. A pending head another relay
292
+ * sent too still holds the edit up while that one is silent (#78 re-review: removing a relay that
293
+ * replayed an honest relay's version, and now withholds it, mustn't fork against it); silent relays
294
+ * that hold each other up are removed together (`relays remove` takes several);
295
+ * - wasn't named as serving versions that don't connect (a forged chain's, core's unconnectedRelays);
296
+ * - didn't answer this refresh: a relay that answered gave its current tips, so what it still serves is
297
+ * already in this refresh (connected, or the refresh failed or was cut short), and what it no longer
298
+ * serves doesn't hold the owner up.
299
+ * So one relay can hold an edit up only while it stays silent, and only with a version signed with the
300
+ * identity key above the head the other relays confirm (a genuine newer version, which building below would
301
+ * fork, or a thief's); removing that relay always goes ahead. A pending head stored without its senders
302
+ * (older builds), expired, or not a valid version of this identity never holds an edit up.
303
+ */
304
+ private ownPendingGuard;
209
305
  /** Relays a (bundled, unverified) identity document lists: only a hint for where to refresh from. */
210
306
  static relaysOf(docJws: string | undefined): string[];
211
307
  /** The view of `userId`, refreshed from the relays its document lists (or `hint`, then ours, when unknown). */
@@ -261,6 +357,8 @@ export declare class App {
261
357
  restoring?: boolean;
262
358
  /** §2.8 step 6: the old identity's final version: no devices, no key holders, carrying the statement (P3). */
263
359
  rotation?: RotationStatement;
360
+ /** #67: relays this edit removes (see ownStrictFallback). */
361
+ removing?: readonly string[];
264
362
  }): Promise<{
265
363
  doc: string;
266
364
  ver: number;
@@ -313,6 +411,28 @@ export declare class App {
313
411
  seq: number;
314
412
  }[]) => Promise<void>;
315
413
  }): Promise<Delivery>;
414
+ /**
415
+ * Seals `plaintext` for `to` exactly as deliver does (the same devices, a fresh seq each, the same
416
+ * relays and caps) and sends nothing: copies for the outbox to send later (outbox.ts).
417
+ */
418
+ seal(to: string, kind: EnvelopeKindV3, session: {
419
+ own: string;
420
+ sid: string;
421
+ }, plaintext: object, opts?: {
422
+ onlyDevices?: readonly string[];
423
+ beforeSend?: (copies: {
424
+ did: string;
425
+ seq: number;
426
+ }[]) => Promise<void>;
427
+ }): Promise<{
428
+ did: string;
429
+ env: string;
430
+ targets: {
431
+ relay: string;
432
+ cap?: string;
433
+ }[];
434
+ }[]>;
435
+ private sealCopies;
316
436
  /** Delivers to our other devices, when there are any (sync, §4.3). */
317
437
  syncOwn(body: Record<string, unknown>): Promise<Delivery | undefined>;
318
438
  }
package/dist/app.js CHANGED
@@ -9,10 +9,10 @@
9
9
  // next version of our own), sealing and delivering envelopes (§4.1, §5.4,
10
10
  // §5.8), finding caps, resolving addresses and petnames, and syncing state to
11
11
  // the user's other devices.
12
- import { personTokenOk } from "./projects.js";
12
+ import { identityHere, personTokenMatchesKeys, personTokenOk } from "./projects.js";
13
13
  import { confirmOnTty } from "./tty-confirm.js";
14
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";
15
+ import { addIdentityVersion, b64uDecode, b64uEncode, capAllowsKind, CircleChain, createCap, createDeviceCert, createIdentityDoc, decodeTyped, deviceKeysV3FromSecrets, displayAddress, displayFingerprint, getIdentityView, MAX_DEVICES, mergeFields, mergePrevTip, scheduledWriter, refreshIdentity as coreRefreshIdentity, heldBackByOf, unconnectedRelaysOf, unconnectedVersionsOf, IdentityChain, identityKeyFromSeed, isUserId, isValidName, nowSec, P2PError, peekIdentityDoc, pendingHeadSenders, canonicalRelayUrl, sealEnvelopeV3, storeCertResolver, storeSignerContext, TYP3, verifyDeviceCertV3, verifyRotationSignatures, } from "@peer2peer/core/v3";
16
16
  import { FileDocBackend, FileTrustStoreV3 } from "@peer2peer/core/v3/node";
17
17
  import { OverlayDocBackend, ReadOnlyTrustStoreV3 } from "./readonly.js";
18
18
  import { basename, join } from "node:path";
@@ -44,6 +44,16 @@ const CAP_PRIORITY = (c) => (c.kinds[0] === "*" ? 0 : 1);
44
44
  export class App {
45
45
  /** The person's front end vouched for this command (P2P_PERSON_TOKEN, checked once and removed: projects.ts). */
46
46
  front = false;
47
+ /**
48
+ * The token `front` rests on, kept in memory (never in the environment), so the keys this command
49
+ * loads are checked against it (load): a home whose files change after the start never lends the
50
+ * token to other keys. Undefined for an embedder that vouches without one.
51
+ */
52
+ frontToken;
53
+ /** The home held no identity when the token was checked (a front end's first run). */
54
+ frontFresh = false;
55
+ /** This command made, restored or swapped in the identity it holds (init, link join, restore, a rotation's swap). */
56
+ identityMadeHere = false;
47
57
  /** The person's "yes" on their controlling terminal (tty-confirm.ts); cli.ts may stand another in (tests). */
48
58
  confirmTty = confirmOnTty;
49
59
  env;
@@ -98,6 +108,10 @@ export class App {
98
108
  // An embedder holding the person token is a front end (the CLI's main() checks and removes it first,
99
109
  // then sets this from its own check).
100
110
  this.front = personTokenOk(this.env, this.home);
111
+ if (this.front) {
112
+ this.frontToken = this.env.P2P_PERSON_TOKEN?.trim();
113
+ this.frontFresh = !identityHere(this.home);
114
+ }
101
115
  // Progress and P2P_DEBUG lines go to stderr (never secrets: see progress.ts).
102
116
  this.progress = { ...makeProgress(opts.env, (m) => opts.io.err(`p2p: ${m}`)), signal: this.abort.signal };
103
117
  this.readOnly = opts.readOnly === true;
@@ -120,9 +134,24 @@ export class App {
120
134
  throw new CliError("no_identity", "no identity here yet: run `p2p init` (or `p2p link join` / `p2p backup restore`)");
121
135
  return false;
122
136
  }
137
+ this.checkFrontKeys(keys);
123
138
  this.setKeys(keys, self);
124
139
  return true;
125
140
  }
141
+ /**
142
+ * The person token this command was given must be the one these keys derive (projects.ts
143
+ * personTokenMatchesKeys), unless this command made the identity itself. A home that had no
144
+ * identity when the token was checked, and has one now that this command didn't make, never
145
+ * keeps it. Otherwise the command stops: the home changed under it.
146
+ */
147
+ checkFrontKeys(keys) {
148
+ if (!this.front || this.frontToken === undefined || this.identityMadeHere)
149
+ return;
150
+ if (!this.frontFresh && personTokenMatchesKeys(this.home, keys.spk, this.frontToken))
151
+ return;
152
+ this.front = false;
153
+ throw new CliError("refused", `the person token doesn't belong to the identity ${this.home} holds now (its files changed while the command ran): it stopped here. Run it again`);
154
+ }
126
155
  setKeys(keys, self) {
127
156
  this.keys = keys;
128
157
  this.self = self;
@@ -397,27 +426,45 @@ export class App {
397
426
  }
398
427
  // -------------------------------------------------------------------------
399
428
  // Identity documents (§2.5, §5.6)
429
+ /**
430
+ * Our own identity's view. Pending heads (core #35) never narrow it: they are for trusting others'
431
+ * devices, and a version only the identity key signed must not stop this device from editing or
432
+ * rotating the identity (#65 review M1).
433
+ */
400
434
  ownView() {
401
- return getIdentityView(this.store, this.userId).then((v) => {
435
+ return getIdentityView(this.store, this.userId, { ignorePending: true }).then((v) => {
402
436
  if (!v)
403
437
  throw new CliError("no_identity", "this device holds no identity document for its user");
404
438
  return v;
405
439
  });
406
440
  }
441
+ /** The stored view of `userId`; our own identity's never narrowed by pending heads (#65 re-review N1, see ownView). */
407
442
  async view(userId) {
408
- return getIdentityView(this.store, userId);
443
+ return getIdentityView(this.store, userId, userId === this.keys?.userId ? { ignorePending: true } : {});
409
444
  }
410
445
  /**
411
446
  * Network I/O for core's refreshIdentity (§5.6), per relay so core can cap
412
447
  * each relay's answer on its own: `tips` and the `chain` walk
413
448
  * (`/v3/identity/<id>/chain?to=&n=`) on every listed relay (at most 5).
449
+ *
450
+ * #78: a relay that couldn't be reached (an error or a timeout) is left out of the answer, and when none
451
+ * of the relays asked answered the call fails, so core counts it as a relay that didn't answer (core asks
452
+ * one relay per call), never as one that answered "nothing": its silence doesn't make up a majority that
453
+ * clears pending heads or counts as fresh, and a relay is never named as forging over a gap the silent
454
+ * one wasn't really asked about.
414
455
  */
415
456
  fetcher() {
416
457
  const t = this.tun.connectTimeoutMs;
417
458
  const perRelay = async (relays, get) => {
418
459
  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]]));
460
+ const answers = await Promise.allSettled(list.map((r) => get(r)));
461
+ const ok = list.flatMap((r, i) => {
462
+ const a = answers[i];
463
+ return a.status === "fulfilled" ? [[r, a.value]] : [];
464
+ });
465
+ if (list.length > 0 && ok.length === 0)
466
+ throw answers[0].reason;
467
+ return Object.fromEntries(ok);
421
468
  };
422
469
  return {
423
470
  tips: (userId, relays) => perRelay(relays, (r) => fetchTips(this.transport(r), userId, t, this.progress, this.guardedLookup(r))),
@@ -429,6 +476,9 @@ export class App {
429
476
  * gap filling, automatic jumps only over unanchored history). This is the
430
477
  * only way an identity enters the store: bundled documents never do.
431
478
  * Failures leave the held view (or none) and are reported as a warning.
479
+ *
480
+ * `setAside` (#67, strict refreshes of our own identity only): relays to leave out when the refresh over
481
+ * all of them can't confirm the head. See ownStrictFallback.
432
482
  */
433
483
  async refreshIdentity(userId, relays, opts = {}) {
434
484
  const fetched = (await this.state.get("fetched"))?.[userId];
@@ -442,36 +492,177 @@ export class App {
442
492
  throw new CliError("refresh_failed", `no relays to refresh ${userId} from`);
443
493
  return held;
444
494
  }
495
+ const own = userId === this.keys?.userId;
496
+ const refreshFrom = (rs) => step(this.progress, `refreshing ${userId}'s identity document from ${rs.join(", ")}`, () => coreRefreshIdentity(this.store, userId, this.fetcher(), { relays: rs, own }));
497
+ let v;
498
+ /** #78: the relays core named as serving versions that don't connect (a forged chain's). */
499
+ let named = [];
445
500
  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");
501
+ v = await refreshFrom(list);
502
+ }
503
+ catch (e) {
504
+ if (!(e instanceof P2PError))
505
+ throw e;
506
+ // Strict callers (publishing our own next version) must not build on a head they couldn't confirm.
507
+ if (opts.strict) {
508
+ // #79: relays core held the refresh back for count like the ones it names (see the incomplete case below).
509
+ const unconnected = [...new Set([...unconnectedRelaysOf(e), ...(own ? heldBackByOf(e) : [])])];
510
+ const versions = unconnectedVersionsOf(e);
511
+ const fb = e.reason === "chain-broken" ? await this.ownStrictFallback(userId, list, unconnected, versions, opts.setAside, refreshFrom) : undefined;
512
+ if (!fb)
513
+ throw new CliError("refresh_failed", `couldn't confirm the current identity document on the relays (${e.reason}): not publishing on a possibly stale head${this.unconnectedHint(unconnected, versions, userId)}`);
514
+ v = fb;
515
+ named = unconnected;
516
+ }
517
+ else {
518
+ if (e.reason === "chain-broken" && held && !opts.quiet) {
519
+ 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`);
520
+ }
521
+ return held;
522
+ }
523
+ }
524
+ if (v.incomplete) {
525
+ if (!opts.strict) {
450
526
  // Cut short by core's work bound: the head may be stale. Not refreshed; don't act on it as fresh.
451
527
  if (!opts.quiet)
452
528
  this.warn(`refreshing ${await this.addressOf(userId)}'s identity document was cut short; using what was held before (try again)`);
453
529
  return held;
454
530
  }
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;
531
+ // #79: relays core held the refresh back for (they sent a version of our identity that doesn't connect to
532
+ // a current one we hold and lists more than it) count like the relays it names as serving versions that
533
+ // don't connect: a rotation sets them aside, any other edit refuses and names them.
534
+ const unconnected = [...new Set([...(v.unconnectedRelays ?? []), ...(own ? (v.heldBackBy ?? []) : [])])];
535
+ const fb = await this.ownStrictFallback(userId, list, unconnected, v.unconnectedVersions ?? [], opts.setAside, refreshFrom);
536
+ if (!fb)
537
+ throw new CliError("refresh_failed", `refreshing the identity document was cut short; try again${this.unconnectedHint(unconnected, v.unconnectedVersions ?? [], userId)}`);
538
+ named = unconnected;
539
+ v = fb;
540
+ }
541
+ if (opts.strict && own)
542
+ await this.ownPendingGuard(userId, list, v, named, opts.setAside);
543
+ // Recorded moments ago by another p2p process of this home (a watch and a command refresh
544
+ // the same people in a burst): no write. Only ever leaves the time a little older, so the
545
+ // next refresh comes no later.
546
+ const now = Date.now();
547
+ const last = (await this.state.get("fetched"))?.[userId];
548
+ if (last === undefined || last < now - FETCHED_SLACK_MS)
549
+ await this.state.update("fetched", (cur = {}) => ({ next: { ...cur, [userId]: Math.max(cur[userId] ?? 0, now) }, result: undefined }));
550
+ return v;
551
+ }
552
+ /**
553
+ * For a strict refresh of our own identity that failed: what to do. The key-compromise wording only for relays
554
+ * core named (#67 review F1): each sent a version whose missing parent every relay was asked for and none had,
555
+ * so nothing a device of ours published would be there. Otherwise only which relays sent the newer versions.
556
+ */
557
+ unconnectedHint(unconnected, versions, userId) {
558
+ if (userId !== this.keys?.userId)
559
+ return "";
560
+ if (unconnected.length > 0) {
561
+ const one = unconnected.length === 1;
562
+ return `. ${unconnected.join(", ")} ${one ? "serves" : "serve"} versions of your identity, signed with your identity key, that don't connect to your history and that no relay holds the history of: if no device of yours published them, someone else holds your identity key. Remove ${one ? "that relay" : "those relays"} (\`p2p relays remove <url>\`) or rotate your identity (\`p2p identity rotate\`)`;
563
+ }
564
+ const from = [...new Set(versions.flatMap((x) => x.relays))];
565
+ if (from.length === 0)
566
+ return "";
567
+ return `. Newer versions of your identity from ${from.join(", ")} don't connect to the history this device holds yet; if one of those relays keeps serving versions no device of yours published, remove it (\`p2p relays remove <url>\`)`;
568
+ }
569
+ /**
570
+ * #67: a strict refresh of our OWN identity couldn't confirm the head over every listed relay. Before an
571
+ * identity edit that removes relays (`setAside.relays`: the ones it removes), or a rotation step
572
+ * (`setAside.unconnected`: the relays that sent versions the refresh couldn't connect), it is retried over
573
+ * the other listed relays, and the caller goes ahead only if that refresh is complete.
574
+ *
575
+ * Why this is safe:
576
+ * - The strict refresh is there so we don't fork our own chain by building on a stale head (review H2):
577
+ * a newer version another of our key holders published went to every relay the document lists. The
578
+ * relays kept must still give a complete refresh, so a newer version any of them serves is still found,
579
+ * connected and built on (or, far behind, the refresh is incomplete and the edit refused: trying again
580
+ * goes on where the walk stopped). Leaving a relay out is what the strict refresh already allows when
581
+ * that relay doesn't answer.
582
+ * - Which relays are left out is the user's choice (the ones the edit removes) or each relay's own
583
+ * evidence (it sent identity-key-signed versions that don't connect): one relay can't get another left
584
+ * out. Any other edit still refuses while such a relay is listed, and names it (fork and compromise
585
+ * detection stay: the user is told someone else may hold the key).
586
+ * - What is published is still head.ver + 1 on the head the kept relays confirmed: a relay left out can't
587
+ * make it lower, or make it fork from anything but what those relays serve.
588
+ * - Nothing is left out when no relay would be left; the kept relays' refresh must reach one of them.
589
+ * - #67 review F1: core names a relay only for versions on a dead gap (asked of every relay, held by
590
+ * none), never one whose genuine gap the walk merely didn't reach. And the confirmed head must not be
591
+ * below any version the full refresh left unconnected, unless every relay that sent that version is set
592
+ * aside: a lagging kept relay can't "confirm" a stale head while another relay serves a newer version.
593
+ * (A newer version an earlier refresh stored as a pending head, from a relay silent now: ownPendingGuard.)
594
+ * Returns the view, or undefined when this doesn't apply (the caller then refuses as before).
595
+ */
596
+ async ownStrictFallback(userId, list, unconnected, versions, setAside, refreshFrom) {
597
+ if (!setAside || userId !== this.keys?.userId)
598
+ return undefined;
599
+ const aside = new Set([...(setAside.relays ?? []), ...(setAside.unconnected ? unconnected : [])].filter((r) => list.includes(r)));
600
+ const rest = list.filter((r) => !aside.has(r));
601
+ if (aside.size === 0 || rest.length === 0)
602
+ return undefined;
603
+ let v;
604
+ try {
605
+ v = await refreshFrom(rest);
463
606
  }
464
607
  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;
608
+ if (e instanceof P2PError)
609
+ return undefined;
610
+ throw e;
611
+ }
612
+ if (v.incomplete)
613
+ return undefined;
614
+ if (versions.some((x) => x.ver > v.head.ver && (x.relays.length === 0 || x.relays.some((r) => !aside.has(r)))))
615
+ return undefined;
616
+ // §2.5 compromise detection: say so, whatever the user goes on to do (only for relays core named, F1).
617
+ const forged = unconnected.filter((r) => aside.has(r));
618
+ if (forged.length > 0) {
619
+ const one = forged.length === 1;
620
+ this.warn(`${forged.join(", ")} ${one ? "serves" : "serve"} versions of your identity, signed with your identity key, that don't connect to the history your other relays confirm (left out of this check). If no device of yours published them, someone else holds your identity key: rotate your identity (\`p2p identity rotate\`)`);
474
621
  }
622
+ return v;
623
+ }
624
+ /**
625
+ * #78: a strict refresh of our own identity skips relays that don't answer, so a lagging relay could
626
+ * "confirm" a stale head while the up-to-date one times out. This device may already hold the newer
627
+ * version, as a pending head an earlier, incomplete refresh recorded with the relays that sent it. Refuses
628
+ * when a pending head above the confirmed head was sent by a relay that:
629
+ * - is still listed and isn't set aside by this edit (`setAside.relays`: the relays it removes), so
630
+ * `p2p relays remove` always gets past a relay that holds the owner up. A pending head another relay
631
+ * sent too still holds the edit up while that one is silent (#78 re-review: removing a relay that
632
+ * replayed an honest relay's version, and now withholds it, mustn't fork against it); silent relays
633
+ * that hold each other up are removed together (`relays remove` takes several);
634
+ * - wasn't named as serving versions that don't connect (a forged chain's, core's unconnectedRelays);
635
+ * - didn't answer this refresh: a relay that answered gave its current tips, so what it still serves is
636
+ * already in this refresh (connected, or the refresh failed or was cut short), and what it no longer
637
+ * serves doesn't hold the owner up.
638
+ * So one relay can hold an edit up only while it stays silent, and only with a version signed with the
639
+ * identity key above the head the other relays confirm (a genuine newer version, which building below would
640
+ * fork, or a thief's); removing that relay always goes ahead. A pending head stored without its senders
641
+ * (older builds), expired, or not a valid version of this identity never holds an edit up.
642
+ */
643
+ async ownPendingGuard(userId, list, v, named, setAside) {
644
+ const stored = await this.store.getIdentity(userId);
645
+ if (!stored)
646
+ return;
647
+ const heard = new Set(v.answeredRelays);
648
+ const skip = new Set([...(setAside?.relays ?? []), ...named]);
649
+ const silent = new Set();
650
+ let newest = 0;
651
+ for (const p of pendingHeadSenders(stored)) {
652
+ if (p.ver <= v.head.ver)
653
+ continue;
654
+ const by = p.relays.filter((r) => list.includes(r) && !skip.has(r) && !heard.has(r));
655
+ if (by.length === 0)
656
+ continue;
657
+ for (const r of by)
658
+ silent.add(r);
659
+ newest = Math.max(newest, p.ver);
660
+ }
661
+ if (silent.size === 0)
662
+ return;
663
+ const rs = [...silent];
664
+ const one = rs.length === 1;
665
+ throw new CliError("refresh_failed", `${rs.join(", ")} didn't answer, and ${one ? "it" : "they"} earlier sent a newer version of your identity (ver ${newest}) than the relays that answered confirm (ver ${v.head.ver}): not publishing on a possibly stale head. Try again when ${one ? "it answers" : "they answer"}; if ${one ? "that relay is" : "those relays are"} gone for good, or no device of yours published that version, remove ${one ? "it" : "them"} (\`p2p relays remove ${one ? "<url>" : "<url> <url>"}\`)`, { heldBy: rs, pendingVer: newest, confirmedVer: v.head.ver });
475
666
  }
476
667
  /** Relays a (bundled, unverified) identity document lists: only a hint for where to refresh from. */
477
668
  static relaysOf(docJws) {
@@ -522,6 +713,7 @@ export class App {
522
713
  /** Signer resolution for core verifiers, finding unknown identities on the relays (once per process). */
523
714
  signerCtx(hint = []) {
524
715
  return storeSignerContext(this.store, {
716
+ own: this.keys?.userId,
525
717
  resolveIdentity: (u) => this.discover(u, hint),
526
718
  });
527
719
  }
@@ -649,7 +841,10 @@ export class App {
649
841
  const ik = this.requireKeyholder("Publishing the identity document");
650
842
  // §2.5: build on the newest head the relays hold, or not at all (review H2: a stale key holder
651
843
  // republishing blind could fork the identity).
652
- await this.refreshIdentity(this.userId, this.relays, { force: true, strict: true });
844
+ // #67: an edit that removes relays, or the rotation's final version, may leave out a listed relay
845
+ // serving versions that don't connect (a thief's, signed with the identity key): see ownStrictFallback.
846
+ const setAside = opts.rotation ? { unconnected: true } : opts.removing?.length ? { relays: opts.removing } : undefined;
847
+ await this.refreshIdentity(this.userId, this.relays, { force: true, strict: true, ...(setAside ? { setAside } : {}) });
653
848
  let view = await this.ownView();
654
849
  // What the tips list before any merge: a merge keeps only the intersection (§2.5), so devices
655
850
  // only one branch listed are re-added below unless they were revoked (review N-H1).
@@ -692,13 +887,19 @@ export class App {
692
887
  const stored = await this.store.getIdentity(this.userId);
693
888
  // Only devices a merge dropped come back: never one revoked along the head's ancestry, nor one
694
889
  // 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: [] };
890
+ const plan = stored && merges.length > 0 ? planReadd(IdentityChain.fromStored({ ...stored, pendingHeads: [] }), preTips, unionDevices, view.devices, head.hash, stored.denied ?? []) : { readd: [], skipped: [] };
696
891
  for (const d of plan.skipped)
697
892
  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
893
  const readd = plan.readd;
699
894
  const devices = [...view.devices, ...readd].slice(0, MAX_DEVICES);
700
895
  const keyholders = [...view.keyholders, ...unionKeyholders.filter((d) => readd.includes(d) && devices.includes(d))];
701
896
  if (!opts.restoring && (!devices.includes(this.did) || !keyholders.includes(this.did))) {
897
+ // #75: the merges above were never published; kept, they'd leave this device unlisted in its own
898
+ // view (a fork made by a version that leaves it out), and rotation, the remedy, couldn't find its branch.
899
+ if (merges.length > 0) {
900
+ const drop = new Set(merges.map((m) => peekIdentityDoc(m).hash));
901
+ await this.store.updateIdentity(this.userId, (cur) => (cur ? { next: { ...cur, versions: cur.versions.filter((v) => !drop.has(peekIdentityDoc(v).hash)) }, result: undefined } : { result: undefined }));
902
+ }
702
903
  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
904
  }
704
905
  const p = {
@@ -945,6 +1146,29 @@ export class App {
945
1146
  */
946
1147
  async deliver(to, kind, session, plaintext, opts = {}) {
947
1148
  const pool = this.pool ?? (await this.connect());
1149
+ const { targets, outgoing, errors, sealed } = await this.sealCopies(to, kind, session, plaintext, opts);
1150
+ const sentVia = new Set();
1151
+ const results = await Promise.all(outgoing.map(({ d, env }) => pool.sendEnvelope(env, to, d, kind, targets)));
1152
+ const unsent = [];
1153
+ for (const [i, res] of results.entries()) {
1154
+ for (const r of res.sent)
1155
+ sentVia.add(r);
1156
+ for (const e of res.errors)
1157
+ errors.push({ did: outgoing[i].d, relay: e.relay, code: e.code, ...(e.written ? { written: true } : {}) });
1158
+ if (res.sent.length === 0)
1159
+ unsent.push({ did: outgoing[i].d, env: outgoing[i].env, targets, codes: res.errors.map((e) => e.code) });
1160
+ }
1161
+ return { userId: to, devices: sealed, relays: [...sentVia], ...(errors.length > 0 ? { errors } : {}), ...(unsent.length > 0 ? { unsent } : {}) };
1162
+ }
1163
+ /**
1164
+ * Seals `plaintext` for `to` exactly as deliver does (the same devices, a fresh seq each, the same
1165
+ * relays and caps) and sends nothing: copies for the outbox to send later (outbox.ts).
1166
+ */
1167
+ async seal(to, kind, session, plaintext, opts = {}) {
1168
+ const { targets, outgoing } = await this.sealCopies(to, kind, session, plaintext, opts);
1169
+ return outgoing.map(({ d, env }) => ({ did: d, env, targets }));
1170
+ }
1171
+ async sealCopies(to, kind, session, plaintext, opts) {
948
1172
  const view = to === this.userId ? await this.ownView() : await this.viewFor(to, { refresh: opts.refresh, hint: opts.hint });
949
1173
  if (!view)
950
1174
  throw new CliError("unknown_user", `no identity document for ${to}: can't find their devices or relays`);
@@ -954,7 +1178,6 @@ export class App {
954
1178
  const relays = orderRelays(view.head.relays, view.relays).slice(0, 3);
955
1179
  const caps = await this.capsFor(to, kind, opts.extraCaps);
956
1180
  const resolveCert = storeCertResolver(this.store);
957
- const sentVia = new Set();
958
1181
  const errors = [];
959
1182
  // Certificates first (each verified, as before), then one seq block for every copy, then the
960
1183
  // copies go out together: one round trip for all of the recipient's devices, not one each.
@@ -998,18 +1221,7 @@ export class App {
998
1221
  else
999
1222
  outgoing.push({ d, env });
1000
1223
  }
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 } : {}) };
1224
+ return { targets, outgoing, errors, sealed: ready.length };
1013
1225
  }
1014
1226
  /** Delivers to our other devices, when there are any (sync, §4.3). */
1015
1227
  async syncOwn(body) {