@peer2peer/cli 0.1.0 → 0.1.2

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/receipts.js CHANGED
@@ -125,12 +125,14 @@ export async function sendReceipt(app, o) {
125
125
  return { sent: false, reason: "not-yours" };
126
126
  // A private session (shared with nobody) sends none: one would tell the sender it exists. Nor does
127
127
  // the copy of a private ended session's message. A session with no roster here counts as private.
128
+ // Except to this user's own sessions (another device, or this one): they list it anyway, and the
129
+ // receipt is how one of them learns its message waits for Deliver.
128
130
  const sessions = (await app.state.get("sessions")) ?? {};
129
131
  const isPrivate = (sid) => {
130
132
  const doc = sessions[sid];
131
133
  return !doc || (doc.vis === "private" && doc.parts.length === 0);
132
134
  };
133
- if (isPrivate(o.fromSession) || (asked.unclaimedFor !== undefined && isPrivate(asked.unclaimedFor)))
135
+ if (asked.from !== app.userId && (isPrivate(o.fromSession) || (asked.unclaimedFor !== undefined && isPrivate(asked.unclaimedFor))))
134
136
  return { sent: false, reason: "private" };
135
137
  const key = `${asked.from}|${asked.id}`;
136
138
  const verdict = await withDoc(app, (d, now) => {
package/dist/rotation.js CHANGED
@@ -64,6 +64,7 @@ import { deliverCircle, memberCaps, ownerPublish, signOwnJoin } from "./circle-o
64
64
  import { accept, dropHeld, getHeld, hold, mintInvite, withHeldId } from "./social.js";
65
65
  import { exportAll, exportCircle, mergeRemovals, sendSync } from "./sync.js";
66
66
  import { linkJoin } from "./identity.js";
67
+ import { renewPersonToken } from "./projects.js";
67
68
  import { makeEvent, receiving } from "./inbound.js";
68
69
  const STEPS = ["created", "published", "devices", "social", "final", "done"];
69
70
  const rotationDir = (home) => join(home, "rotation");
@@ -157,10 +158,10 @@ function certLabel(cert) {
157
158
  return "";
158
159
  }
159
160
  }
160
- /** Our own identity's chain, verified (or undefined). */
161
+ /** Our own identity's chain, verified (or undefined); pending heads never narrow our own view (#65 review M1). */
161
162
  async function ownChain(app) {
162
163
  const stored = await app.store.getIdentity(app.userId);
163
- return stored && stored.versions.length > 0 ? IdentityChain.fromStored(stored) : undefined;
164
+ return stored && stored.versions.length > 0 ? IdentityChain.fromStored({ ...stored, pendingHeads: [] }) : undefined;
164
165
  }
165
166
  /**
166
167
  * The newest version of our identity that is not a rotation's final one:
@@ -189,7 +190,8 @@ async function foreignRotations(app) {
189
190
  return [];
190
191
  const log = await app.store.getPublishLog();
191
192
  const out = [];
192
- for (const t of chain.tips()) {
193
+ // Every held tip, a stray's too (#74): a rotation on any held branch is the owner's to know about.
194
+ for (const t of chain.allTips()) {
193
195
  if (t.rotation === undefined || log.published.includes(t.hash))
194
196
  continue;
195
197
  try {
@@ -505,8 +507,10 @@ async function begin(app, opts) {
505
507
  }
506
508
  else {
507
509
  await app.connectAndDrain();
508
- // Build on the relays' head: a stale view could miss a competing rotation or a new device.
509
- await app.refreshIdentity(app.userId, app.relays, { force: true, strict: true });
510
+ // Build on the relays' head: a stale view could miss a competing rotation or a new device. #67: a listed
511
+ // relay serving versions that don't connect (a thief's, signed with the old identity key) is left out
512
+ // when the others confirm the head (App.ownStrictFallback): rotation is the remedy for exactly that.
513
+ await app.refreshIdentity(app.userId, app.relays, { force: true, strict: true, setAside: { unconnected: true } });
510
514
  }
511
515
  const view = await app.ownView();
512
516
  const foreign = await foreignRotations(app);
@@ -585,6 +589,9 @@ async function begin(app, opts) {
585
589
  await rm(home, { recursive: true, force: true });
586
590
  const napp = await appAt(app, home);
587
591
  const self = { name: base.name, relays: [...base.relays], createdAt: Date.now() };
592
+ // The new identity's home gets its own person token (projects.ts renewPersonToken), before its keys;
593
+ // front ends read it again.
594
+ renewPersonToken(home);
588
595
  await napp.state.put("keys", newKeysDoc(newIk.userId, device, cert, newIk));
589
596
  await napp.state.put("self", self);
590
597
  await napp.load(true);
@@ -971,12 +978,13 @@ async function publishFinal(app, st) {
971
978
  const ik = app.requireKeyholder("Publishing your old identity's final version");
972
979
  const contesting = st.contest || (await foreignRotations(app)).length > 0;
973
980
  await app.connect({ allowNone: true });
974
- await app.refreshIdentity(app.userId, app.relays, contesting ? { force: true, quiet: true } : { force: true, strict: true });
981
+ // #67: as in begin, a relay serving versions that don't connect is left out when the others confirm the head.
982
+ await app.refreshIdentity(app.userId, app.relays, contesting ? { force: true, quiet: true } : { force: true, strict: true, setAside: { unconnected: true } });
975
983
  const chain = await ownChain(app);
976
984
  if (!chain)
977
985
  throw new CliError("no_identity", "this device holds no identity document for its user");
978
986
  const tips = chain.tips();
979
- const mine = tips.find((t) => t.rotation !== undefined && rotationKey(t.rotation) === rotationKey(st.statement));
987
+ const mine = chain.allTips().find((t) => t.rotation !== undefined && rotationKey(t.rotation) === rotationKey(st.statement));
980
988
  if (mine) {
981
989
  // Published by an interrupted run: make sure the relays have it.
982
990
  const r = await app.publishDoc(mine.jws, mine.relays);
@@ -1,6 +1,6 @@
1
1
  import { type AcceptedMessageV3, type ProjectBound, type StatusAgent, type StatusBody } from "@peer2peer/core/v3";
2
2
  import type { App, Delivery } from "./app.js";
3
- import { type SessionProjectView } from "./projects.js";
3
+ import { type OverWhy, type SessionProjectView } from "./projects.js";
4
4
  import { type ExtSendResult } from "./extensions.js";
5
5
  import { type NewEvent } from "./inbound.js";
6
6
  import { type PeerStatusRec, type SessionDoc } from "./state.js";
@@ -120,8 +120,12 @@ export interface StatusOpts {
120
120
  * project for the rest of its life (projects.ts), which can only narrow who sees it.
121
121
  */
122
122
  projectDirs?: string[];
123
- /** The front end dropped folders past its cap (`--project-dirs-over`): private. */
124
- projectDirsOver?: boolean;
123
+ /**
124
+ * The front end dropped folders past its cap, or couldn't resolve a path (`--project-dirs-over`):
125
+ * private. A list says why (projects.ts OverWhy: `--project-dirs-over=unresolved,folders`); `true`
126
+ * is an older front end's bare flag.
127
+ */
128
+ projectDirsOver?: boolean | string[];
125
129
  /**
126
130
  * The session's subagents (`--agents-json`), as the caller has them: entries
127
131
  * are normalized (sanitized, capped, ordered, trimmed), never trusted as is.
@@ -231,12 +235,20 @@ export interface SendOpts {
231
235
  /** Directories the sending session works in besides its working directory (see StatusOpts.projectDirs). */
232
236
  projectDirs?: string[];
233
237
  /** See StatusOpts.projectDirsOver. */
234
- projectDirsOver?: boolean;
238
+ projectDirsOver?: boolean | string[];
235
239
  /**
236
240
  * The person at their own terminal (`p2p send` typed with no --from-session, `p2p tui`): their
237
241
  * session is theirs, never bound to a project. Set only by those two paths, never from a flag.
238
242
  */
239
243
  person?: boolean;
244
+ /**
245
+ * Set by sendMessage to whether a copy of this message may have reached a relay: true from the
246
+ * moment one is about to go out, and after delivery whether one did or was written to a relay
247
+ * whose answer never came. sendSharing undoes its share only while it is false.
248
+ */
249
+ wire?: {
250
+ maybe: boolean;
251
+ };
240
252
  }
241
253
  export interface SendResult {
242
254
  delivered: boolean;
@@ -285,6 +297,17 @@ export declare function parseTarget(to: string): {
285
297
  * refused as before (not_found), so a sender never queues into one long gone.
286
298
  */
287
299
  export declare const OFFLINE_TARGET_MS: number;
300
+ /** How long a same-device send's record (Docs.localSends) is kept: as long as a relay keeps the envelope. */
301
+ export declare const LOCAL_SEND_TTL_MS: number;
302
+ /** At most this many same-device send records; the oldest go first. */
303
+ export declare const LOCAL_SENDS_MAX = 4096;
304
+ /** How long after a bounded session's text reached `tui` a send from there to someone else is warned about. */
305
+ export declare const TUI_TAINT_MS: number;
306
+ /**
307
+ * A warning (never a refusal) for the person sending from their own session `tui` to someone else
308
+ * after a message from a bounded session of theirs reached it: they may be passing its text on.
309
+ */
310
+ export declare function tuiTaintNote(app: App, toUserId: string, now?: number): Promise<string | undefined>;
288
311
  /**
289
312
  * A send by a person at a terminal (the `tui` session: `p2p send` with no --from-session, or `p2p tui`):
290
313
  * a recipient who isn't in the session's audience is added to its roster first, so the message can
@@ -322,7 +345,7 @@ export declare function onSessionEnvelope(app: App, env: string, r: AcceptedMess
322
345
  */
323
346
  export declare function bindFromEnv(app: App, sid: string, extra?: readonly string[], o?: {
324
347
  person?: boolean;
325
- over?: boolean;
348
+ over?: OverWhy[];
326
349
  }): Promise<void>;
327
350
  /** This device's live sessions already within a bound (and the person's own terminal session): who may hold an own-session message that carries it. */
328
351
  export declare function sessionsWithin(app: App, b: ProjectBound, now?: number): Promise<string[]>;
package/dist/sessions.js CHANGED
@@ -21,12 +21,13 @@ import { enqueue, flushOutbox, OUTBOX_RETRYABLE, OUTBOX_TTL_MS, retryable } from
21
21
  import { basename, dirname, resolve as resolvePath } from "node:path";
22
22
  import { createRosterV3, displayStatus, extensionFallbackText, FALLBACK_MAX, isExtensionKind, isLive, isSafeRelativePath, liveFriendshipsV3, loadCircle, partyAuthorizedV3, sanitizePeerText, sha256, standsLookup, circlePolicy, isStatusCap, STATUS_CAP_MAX_LEN, STATUS_CAPS_MAX, STATUS_CAP_RECEIPTS, STATUS_CAP_AGENTS, STATUS_AGENTS_MAX, STATUS_AGENT_FILES_MAX, STATUS_AGENT_TASK_MAX, isStatusAgentBranch, isStatusAgentFile, isStatusAgentId, isStatusAgentType, statusAgentsError, summaryWithAgents, redactSecrets, stripAbsolutePaths, parseBound, } from "@peer2peer/core/v3";
23
23
  import { CliError } from "./errors.js";
24
- import { assertMayReach, bindSession, ceilingAudience, defaultCircleNotice, friendIds, PERSON_SESSION, sessionBinding, agentContext, sessionCeiling, sessionProjectView, sessionDirs, sessionWorkdir, MAX_SESSION_DIRS, shareHint, } from "./projects.js";
24
+ import { assertMayReach, bindSession, ceilingAudience, defaultCircleNotice, friendIds, PERSON_SESSION, sessionBinding, agentContext, sessionCeiling, sessionProjectView, sessionDirs, sessionWorkdir, MAX_SESSION_DIRS, SCRATCH_ENV, sessionScratch, overWhys, privateRemedy, shareHint, } from "./projects.js";
25
25
  import { renderExtension } from "./extensions.js";
26
26
  import { fromOf, makeEvent } from "./inbound.js";
27
27
  import { receiptsEnabled, statusCapsEnabled } from "./config.js";
28
28
  import { CAP_PROJECTS, CLI_CAPS, protoMinor, supportsIn } from "./features.js";
29
29
  import { asksReceipts, newReceiptId, rememberAsked, rememberWanted } from "./receipts.js";
30
+ import { recordSent } from "./history.js";
30
31
  import { sessKey } from "./state.js";
31
32
  import { isStateEnvelope, liveStates, onStateEnvelope, stateKindCaps, stateSummaries } from "./xstate.js";
32
33
  /** Session ids: what Claude Code and Codex use (UUIDs and the like). */
@@ -261,7 +262,10 @@ export async function roster(app, sid, opts) {
261
262
  const names = Object.values((await sessionBinding(app, sid))?.projects ?? {}).map((p) => p.name);
262
263
  const ceiling = ctx.ceiling;
263
264
  const deny = (what) => {
264
- throw new CliError("not_shared", `session ${sid} works in ${names.join(", ")}, which ${ceiling.kind === "private" ? `is private (${ceiling.why}), so it isn't shared` : "isn't shared"} ${what}: ${shareHint(names)}`);
265
+ const remedy = ceiling.kind === "private" ? privateRemedy(ceiling.causes, ceiling.blocking?.length ? ceiling.blocking : names) : shareHint(names);
266
+ throw new CliError("not_shared", `session ${sid} works in ${names.join(", ")}, which ${ceiling.kind === "private" ? `is private (${ceiling.why}), so it isn't shared` : "isn't shared"} ${what}: ${remedy}`, {
267
+ project: { names, policy: ceiling.kind, ...(ceiling.kind === "private" ? { causes: ceiling.causes } : {}) },
268
+ });
265
269
  };
266
270
  if (opts.circle !== undefined && circle !== undefined && (ceiling.kind !== "shared" || !ceiling.circles.includes(circle)))
267
271
  deny(`with circle ${circle}`);
@@ -560,7 +564,7 @@ export async function sendStatus(app, o) {
560
564
  // a path through a symlink): each binds its project.
561
565
  const work = sessionWorkdir(app.env);
562
566
  const fileDirs = (o.files ?? []).filter((f) => typeof f === "string").map((f) => dirname(resolvePath(work, f)));
563
- await bindFromEnv(app, sid, [...(o.projectDirs ?? []), ...fileDirs], { ...(o.projectDirsOver ? { over: true } : {}) });
567
+ await bindFromEnv(app, sid, [...(o.projectDirs ?? []), ...fileDirs], { ...(o.projectDirsOver !== undefined && o.projectDirsOver !== false ? { over: overOf(o.projectDirsOver) } : {}) });
564
568
  const prev = (await app.state.get("peers"))?.[sessKey(app.userId, sid)];
565
569
  const before = (await app.state.get("sessions"))?.[sid];
566
570
  const warnings = [];
@@ -622,6 +626,10 @@ export async function sendStatus(app, o) {
622
626
  // This device keeps the full status: its own `ls` and ExtContext.ownStatus see the agents.
623
627
  const rec = { own: app.userId, sid, did: app.did, ts: Date.now(), status, self: true };
624
628
  await app.state.update("peers", (cur = {}) => ({ next: { ...cur, [sessKey(app.userId, sid)]: rec }, result: undefined }));
629
+ // Another session here asked to hear when this one next goes idle (`send --notify-when-idle` to a
630
+ // session on this device): its statuses never come back here as envelopes, so it is noticed here.
631
+ if (status.state === "idle" && prev?.status.state === "busy")
632
+ await localIdle(app, sid, rec.ts);
625
633
  // `bound`: the folders the front end passed are bound for good (it can stop sending them).
626
634
  return { status, roster: await rosterView(app, sess), delivered, failed, ...(warnings.length > 0 ? { warnings } : {}), project: await sessionProjectView(app, sid), bound: true };
627
635
  }
@@ -703,9 +711,15 @@ async function rosterCircleOf(app, own, sid) {
703
711
  /** `user`, `user [ref]`, `user/ref` or `user/sid`. */
704
712
  export function parseTarget(to) {
705
713
  const s = to.trim();
706
- const br = /^(.*?)\s*\[([0-9a-f]{6})\]$/.exec(s);
707
- if (br)
708
- return { user: br[1].trim(), pick: br[2] };
714
+ // `user [ref]`, scanned from the end (a backtracking regex here was quadratic on long whitespace runs).
715
+ const n = s.length;
716
+ if (n >= 8 && s[n - 1] === "]" && s[n - 8] === "[") {
717
+ const ref = s.slice(n - 7, n - 1);
718
+ const user = s.slice(0, n - 8).trimEnd();
719
+ // As /^(.*?)\s*\[([0-9a-f]{6})\]$/ did: `.` never spans a line break.
720
+ if (/^[0-9a-f]{6}$/.test(ref) && !/[\n\r\u2028\u2029]/.test(user))
721
+ return { user: user.trim(), pick: ref };
722
+ }
709
723
  // userIds, addresses and petnames never contain "/", so the last one separates a session.
710
724
  const i = s.lastIndexOf("/");
711
725
  if (i > 0 && i < s.length - 1)
@@ -724,15 +738,27 @@ export const OFFLINE_TARGET_MS = 24 * 3600 * 1000;
724
738
  /**
725
739
  * Where a message to `toArg` goes: one of their live sessions, or our own
726
740
  * session `fromSession` when its roster lets them in (see the header).
741
+ *
742
+ * Our own sessions on this device are reached only by name (`<you> [ref]`, `<you>/<sid>`), never
743
+ * by a bare `--to <you>`, and never `fromSession` itself (`self_send`). The message is sealed to
744
+ * this device and goes through a relay like one to our other devices, so the receive side applies
745
+ * the same checks: signature, replay, the receiving session's roster and project bound.
727
746
  */
728
747
  async function resolveTarget(app, fromSession, toArg) {
729
748
  const { user, pick } = parseTarget(toArg);
730
749
  const userId = await app.resolveUser(user);
731
750
  if (await app.store.isBlocked(userId))
732
751
  throw new CliError("blocked", "you blocked that user");
752
+ // A session never messages itself (a loop with nothing in between): refused, never "not found".
753
+ if (userId === app.userId && pick !== undefined && (pick === fromSession || pick === sessionRef(app.userId, fromSession))) {
754
+ throw new CliError("self_send", `that is session ${fromSession} itself: a session can't send to itself`, { delivered: false });
755
+ }
733
756
  const peers = (await app.state.get("peers")) ?? {};
734
757
  const now = Date.now();
735
- const live = Object.values(peers).filter((p) => p.own === userId && isLive(p.ts, now) && !(p.own === app.userId && (p.sid === fromSession || p.did === app.did)) && (!pick || p.sid === pick || sessionRef(p.own, p.sid) === pick));
758
+ // Our own sessions on this device are candidates only when one is named (`[ref]` or `/sid`): a bare
759
+ // `--to <you>` still means your other devices' sessions, never every session here at once.
760
+ const eligible = (p) => p.own === userId && !(p.own === app.userId && (p.sid === fromSession || (p.did === app.did && pick === undefined))) && (!pick || p.sid === pick || sessionRef(p.own, p.sid) === pick);
761
+ const live = Object.values(peers).filter((p) => eligible(p) && isLive(p.ts, now));
736
762
  let target;
737
763
  let offlineSince;
738
764
  // Not live now, but seen recently (a dropped connection, a laptop asleep): the same sessions a
@@ -740,10 +766,7 @@ async function resolveTarget(app, fromSession, toArg) {
740
766
  const recent = live.length > 0
741
767
  ? []
742
768
  : Object.values(peers)
743
- .filter((p) => p.own === userId &&
744
- now - p.ts <= OFFLINE_TARGET_MS &&
745
- !(p.own === app.userId && (p.sid === fromSession || p.did === app.did)) &&
746
- (!pick || p.sid === pick || sessionRef(p.own, p.sid) === pick))
769
+ .filter((p) => eligible(p) && now - p.ts <= OFFLINE_TARGET_MS)
747
770
  .sort((a, b) => b.ts - a.ts);
748
771
  if (live.length === 1)
749
772
  target = { own: userId, sid: live[0].sid, did: live[0].did };
@@ -783,6 +806,57 @@ async function rosterFor(app, target) {
783
806
  const here = target.own === app.userId && (target.did === undefined || target.did === app.did);
784
807
  return here ? (await getSession(app, target.sid)).jws : (await app.store.getRoster(target.own, target.sid))?.jws;
785
808
  }
809
+ /** How long a same-device send's record (Docs.localSends) is kept: as long as a relay keeps the envelope. */
810
+ export const LOCAL_SEND_TTL_MS = 7 * 86_400_000 + 600_000;
811
+ /** At most this many same-device send records; the oldest go first. */
812
+ export const LOCAL_SENDS_MAX = 4096;
813
+ /**
814
+ * For a message to another session on this device: before the copy goes out, this device notes which
815
+ * session sent it and whether the person did (Docs.localSends). Local only: nothing changes on the
816
+ * wire, and the receive side (this same device) reads it by the envelope's (sid, seq).
817
+ */
818
+ function localSend(app, target, fromSession, person) {
819
+ if (target.own !== app.userId || target.did !== app.did)
820
+ return {};
821
+ const via = person || fromSession === PERSON_SESSION ? "person" : "agent";
822
+ return {
823
+ beforeSend: async (copies) => {
824
+ const now = Date.now();
825
+ await app.state.update("localSends", (cur = {}) => {
826
+ const kept = Object.entries(cur).filter(([, v]) => now - v.at < LOCAL_SEND_TTL_MS);
827
+ for (const c of copies)
828
+ if (c.did === app.did)
829
+ kept.push([`${target.sid}|${c.seq}`, { from: fromSession, via, at: now }]);
830
+ return { next: Object.fromEntries(kept.sort((a, b) => a[1].at - b[1].at).slice(-LOCAL_SENDS_MAX)), result: undefined };
831
+ });
832
+ },
833
+ };
834
+ }
835
+ /**
836
+ * What an own-session message's event says about where it came from (sessions on this device only):
837
+ * `via` "person" for the person's own terminal session, else "agent" (also for every other device
838
+ * of yours, which this device can't tell apart: fail closed); `fromRef` names the sending session
839
+ * here. Whether `p2p own-agents` lets it through is never stamped here: the front end asks at
840
+ * delivery time (`p2p own-agents check <did>`).
841
+ */
842
+ async function ownOrigin(app, e) {
843
+ const local = e.fdid === app.did ? (await app.state.get("localSends"))?.[`${e.sid}|${e.seq}`] : undefined;
844
+ return { via: local?.via ?? "agent", ...(local ? { fromRef: sessionRef(app.userId, local.from) } : {}) };
845
+ }
846
+ /** How long after a bounded session's text reached `tui` a send from there to someone else is warned about. */
847
+ export const TUI_TAINT_MS = 24 * 3600 * 1000;
848
+ /**
849
+ * A warning (never a refusal) for the person sending from their own session `tui` to someone else
850
+ * after a message from a bounded session of theirs reached it: they may be passing its text on.
851
+ */
852
+ export async function tuiTaintNote(app, toUserId, now = Date.now()) {
853
+ if (toUserId === app.userId)
854
+ return undefined;
855
+ const t = await app.state.get("tuiTaint");
856
+ if (!t || now - t.at > TUI_TAINT_MS)
857
+ return undefined;
858
+ return `a ${t.bound === "private" ? "private" : "project-bounded"} session of yours sent text to this terminal session lately: check you aren't passing it on`;
859
+ }
786
860
  /**
787
861
  * A send by a person at a terminal (the `tui` session: `p2p send` with no --from-session, or `p2p tui`):
788
862
  * a recipient who isn't in the session's audience is added to its roster first, so the message can
@@ -792,22 +866,41 @@ async function rosterFor(app, target) {
792
866
  export async function sendSharing(app, o) {
793
867
  const sid = checkSid(o.fromSession, "--from-session");
794
868
  const uid = await app.resolveUser(o.to.replace(/\s*\[[^\]]*\]\s*$/, "").replace(/\/[^/]*$/, ""));
795
- let added = false;
796
- if (uid !== app.userId && !(await rosterAudience(app, await getSession(app, sid))).includes(uid)) {
797
- await roster(app, sid, { add: [uid] });
798
- added = true;
869
+ let added;
870
+ if (uid !== app.userId) {
871
+ const had = await getSession(app, sid);
872
+ if (!(await rosterAudience(app, had)).includes(uid))
873
+ added = { ver: (await roster(app, sid, { add: [uid] })).ver, had };
799
874
  }
875
+ const wire = { maybe: false };
800
876
  try {
801
- const result = await sendMessage(app, { ...o, person: true });
877
+ const result = await sendMessage(app, { ...o, person: true, wire });
802
878
  return added ? { result, shared: { userId: uid, address: await app.addressOf(uid) } } : { result };
803
879
  }
804
880
  catch (e) {
805
- // Nothing was sent: the session goes back to whom it was shared with before.
806
- if (added)
807
- await roster(app, sid, { remove: [uid] }).catch(() => undefined);
881
+ // Undone only when nothing can have gone out (issue #3): a send cut off by the command deadline
882
+ // (`outcome_unknown`), or one a relay may have stored without answering, may have reached them,
883
+ // and their reply must still land here.
884
+ if (added && !wire.maybe)
885
+ await unshare(app, sid, uid, added).catch(() => undefined);
808
886
  throw e;
809
887
  }
810
888
  }
889
+ /**
890
+ * Takes back the share sendSharing made for a send that never went out: only while the roster is
891
+ * still exactly the version that share wrote (issue #3). Anything since (another send's share, the
892
+ * person's own `session roster`, a status following the project) stands as it is. Back to whom it
893
+ * was shared with before, `uid` included if they were on it already, and following the default
894
+ * again if it did.
895
+ */
896
+ async function unshare(app, sid, uid, added) {
897
+ await writeRoster(app, sid, (have) => {
898
+ if (!have || have.ver !== added.ver)
899
+ return undefined;
900
+ const parts = added.had.parts.includes(uid) ? have.parts : have.parts.filter((u) => u !== uid);
901
+ return { vis: have.vis, ...(have.circle ? { circle: have.circle } : {}), parts, ...(added.had.auto !== undefined ? { auto: added.had.auto } : {}) };
902
+ });
903
+ }
811
904
  export async function sendMessage(app, o) {
812
905
  const fromSession = checkSid(o.fromSession, "--from-session");
813
906
  if (Buffer.byteLength(o.text, "utf8") > MAX_TEXT_BYTES)
@@ -815,7 +908,7 @@ export async function sendMessage(app, o) {
815
908
  if (o.text === "" && !o.notifyWhenIdle)
816
909
  throw new CliError("usage", "nothing to send (give text, or --notify-when-idle)");
817
910
  // Bound before anything is read or sent: the project ceiling decides who this may reach.
818
- await bindFromEnv(app, fromSession, o.projectDirs ?? [], { person: o.person === true, ...(o.projectDirsOver ? { over: true } : {}) });
911
+ await bindFromEnv(app, fromSession, o.projectDirs ?? [], { person: o.person === true, ...(o.projectDirsOver !== undefined && o.projectDirsOver !== false ? { over: overOf(o.projectDirsOver) } : {}) });
819
912
  // This device can't reach any of its relays: the message can still be sealed and kept in the
820
913
  // outbox (outbox.ts) for `watch` to send once it can.
821
914
  let offline = false;
@@ -835,6 +928,8 @@ export async function sendMessage(app, o) {
835
928
  // whole message for `rcpt` (§4.3). Not when this device can't reach a relay either: the sealed copy
836
929
  // may wait in the outbox for days, long past the status that advertised it (pre-release review R2).
837
930
  const rcpt = o.text !== "" && !offline && offlineSince === undefined && (await asksReceipts(app, target.own, target.sid)) ? newReceiptId() : undefined;
931
+ // Whether a copy that may reach them still asks (below: copies kept for later are sealed without it).
932
+ let receiptAsked = rcpt !== undefined;
838
933
  if (o.text !== "") {
839
934
  // Anything this device couldn't send earlier goes first (order, and it may be the same peer).
840
935
  if (!offline)
@@ -843,14 +938,42 @@ export async function sendMessage(app, o) {
843
938
  const plaintext = { text: o.text, ...(rcpt ? { rcpt } : {}), ...(rosterJws ? { roster: rosterJws } : {}), ...(o.person ? {} : await ownBound(app, fromSession, target, userId)) };
844
939
  if (rcpt)
845
940
  await rememberWanted(app, rcpt, { to: userId, own: target.own, ref: to.ref, fromSession });
846
- d = await app.deliver(userId, "msg", target, plaintext, userId === app.userId && target.did ? { onlyDevices: [target.did] } : {});
941
+ const local = userId === app.userId && target.did ? { onlyDevices: [target.did], ...localSend(app, target, fromSession, o.person === true) } : {};
942
+ d = await app.deliver(userId, "msg", target, plaintext, {
943
+ ...local,
944
+ beforeSend: async (copies) => {
945
+ // From here a copy may go out (sendSharing's undo reads this).
946
+ if (o.wire)
947
+ o.wire.maybe = true;
948
+ await local.beforeSend?.(copies);
949
+ },
950
+ });
847
951
  const unsent = d.unsent ?? [];
952
+ // The devices whose copy went out on a connection whose answer never came (it may be stored).
953
+ const written = new Set((d.errors ?? []).filter((e) => e.written).map((e) => e.did));
954
+ if (o.wire)
955
+ o.wire.maybe = d.relays.length > 0 || written.size > 0;
848
956
  if (d.relays.length === 0 && !retryable(unsent)) {
849
957
  throw new CliError("undelivered", `delivered via 0 relays${d.errors?.length ? ` (${[...new Set(d.errors.map((e) => e.code))].join(", ")})` : ""}`, { delivered: false, to });
850
958
  }
851
959
  // Copies no relay took, for reasons a retry gets past: kept, sealed, for watch to send. When
852
960
  // other copies did go out the message is delivered already; these reach the other devices.
853
- const later = d.relays.length === 0 ? unsent : unsent.filter((u) => u.codes.every((c) => OUTBOX_RETRYABLE.has(c)));
961
+ let later = d.relays.length === 0 ? unsent : unsent.filter((u) => u.codes.every((c) => OUTBOX_RETRYABLE.has(c)));
962
+ // A copy kept for later never asks for a receipt (issue #3, §4.3): it may go out days from now,
963
+ // after the recipient's client downgraded, and a client without receipts.v1 rejects the whole
964
+ // message for `rcpt`. Sealed again without it, unless it went out on a connection already (a
965
+ // relay may hold it: a second envelope could deliver the message twice; the outbox resends those
966
+ // same bytes, which the recipient's replay window drops).
967
+ if (rcpt && later.length > 0) {
968
+ const fresh = later.filter((u) => !written.has(u.did));
969
+ if (fresh.length > 0) {
970
+ const { rcpt: _asked, ...plain } = plaintext;
971
+ void _asked;
972
+ const resealed = await app.seal(userId, "msg", target, plain, { onlyDevices: fresh.map((u) => u.did), ...(local.beforeSend ? { beforeSend: local.beforeSend } : {}) });
973
+ later = [...later.filter((u) => written.has(u.did)), ...resealed.map((c) => ({ ...c, codes: [] }))];
974
+ }
975
+ receiptAsked = d.relays.length > 0 || later.some((u) => written.has(u.did));
976
+ }
854
977
  if (later.length > 0)
855
978
  outboxed = await enqueue(app, later, { kind: "msg", dest: to, fromSession });
856
979
  }
@@ -867,6 +990,9 @@ export async function sendMessage(app, o) {
867
990
  : d && offlineSince !== undefined
868
991
  ? { queued: true, state: "offline", lastSeen: offlineSince, expiresAt: Date.now() + OUTBOX_TTL_MS }
869
992
  : {};
993
+ // Message history (history.ts): what this session sent, kept on this device only.
994
+ if (d)
995
+ await recordSent(app, { fromSession, to, text: o.text, state: "state" in queued ? queued.state : "sent" });
870
996
  return {
871
997
  ...(o.person ? {} : { bound: true }),
872
998
  // Accepted by a relay (it stores ciphertext for its session for 7 days), or not yet.
@@ -877,7 +1003,7 @@ export async function sendMessage(app, o) {
877
1003
  ...(d ? { messageId: `m${Date.now().toString(36)}` } : {}),
878
1004
  ...(o.notifyWhenIdle ? { notifyWhenIdle: true } : {}),
879
1005
  ...queued,
880
- ...(d ? (rcpt ? { receipts: "requested", receiptId: rcpt } : { receipts: "unsupported" }) : {}),
1006
+ ...(d ? (rcpt && receiptAsked ? { receipts: "requested", receiptId: rcpt } : { receipts: "unsupported" }) : {}),
881
1007
  };
882
1008
  }
883
1009
  /**
@@ -904,13 +1030,15 @@ export async function sendExtension(app, o) {
904
1030
  await assertMayReach(app, fromSession, userId, { address: to.address });
905
1031
  const rosterJws = await rosterFor(app, target);
906
1032
  const plaintext = { ext, fallback: o.fallback, ...(rosterJws ? { roster: rosterJws } : {}), ...(await ownBound(app, fromSession, target, userId)) };
907
- const d = await app.deliver(userId, o.kind, target, plaintext, userId === app.userId && target.did ? { onlyDevices: [target.did] } : {});
1033
+ const d = await app.deliver(userId, o.kind, target, plaintext, userId === app.userId && target.did ? { onlyDevices: [target.did], ...localSend(app, target, fromSession, false) } : {});
908
1034
  if (d.relays.length === 0) {
909
1035
  throw new CliError("undelivered", `delivered via 0 relays${d.errors?.length ? ` (${[...new Set(d.errors.map((e) => e.code))].join(", ")})` : ""}`, { delivered: false, to });
910
1036
  }
911
1037
  if (target.own !== app.userId) {
912
1038
  await app.state.update("spoke", (cur = {}) => ({ next: { ...cur, [sessKey(target.own, target.sid)]: fromSession }, result: undefined }));
913
1039
  }
1040
+ // Message history: an extension kind as its one-line fallback, never its body.
1041
+ await recordSent(app, { fromSession, to, text: o.fallback, ext: o.kind });
914
1042
  return { delivered: true, to, relays: d.relays.length, devices: d.devices, kind: o.kind, bytes, bound: true };
915
1043
  }
916
1044
  // ---------------------------------------------------------------------------
@@ -937,6 +1065,12 @@ export async function onSessionEnvelope(app, env, r) {
937
1065
  if (carries && from.self && bound !== undefined && toSession !== undefined && toSession !== PERSON_SESSION) {
938
1066
  await bindSession(app, toSession, [], { constraint: bound, inbound: true });
939
1067
  }
1068
+ // The person's own session is never bound: it only remembers that a bounded session's text reached it,
1069
+ // so `p2p tui` can warn before the person passes it on.
1070
+ if (carries && from.self && bound !== undefined && toSession === PERSON_SESSION) {
1071
+ await app.state.update("tuiTaint", () => ({ next: { at: Date.now(), bound: bound === "private" ? "private" : "shared" }, result: undefined }));
1072
+ }
1073
+ const origin = carries && from.self ? await ownOrigin(app, e) : {};
940
1074
  const sess = { own: e.own, sid: e.sid, ref, rule: r.rule, ...(r.viewerRule ? { viewerRule: r.viewerRule } : {}) };
941
1075
  const extra = { own: e.own, sid: e.sid, ...(toSession ? { toSession } : {}) };
942
1076
  // Named for no session of ours: which local sessions may hold it (watch shows it only to those).
@@ -946,7 +1080,7 @@ export async function onSessionEnvelope(app, env, r) {
946
1080
  // §4.3 "Delivery receipts": the sender asked. Remembered for `p2p receipt` (receipts.ts), which
947
1081
  // decides what goes back; the event says only that one may (`receipt: true`), never the id.
948
1082
  const asks = typeof pt.rcpt === "string" && receiptsEnabled(app.env, app.home);
949
- const main = makeEvent(env, "p2p.message", e.ts, { from, ...sess, text: pt.text, ...(asks ? { receipt: true } : {}), ...routable }, extra);
1083
+ const main = makeEvent(env, "p2p.message", e.ts, { from, ...sess, ...origin, text: pt.text, ...(asks ? { receipt: true } : {}), ...routable }, extra);
950
1084
  const out = [main];
951
1085
  if (asks)
952
1086
  await rememberAsked(app, main.id, { id: pt.rcpt, from: e.from, did: e.fdid, ...(toSession !== undefined ? { toSession } : {}) });
@@ -959,7 +1093,7 @@ export async function onSessionEnvelope(app, env, r) {
959
1093
  // From another session of ours with a bound: only sessions already within it may hold it, and the
960
1094
  // one that does takes the bound on (the front end binds it on Deliver: `bound` rides with it).
961
1095
  const held = from.self ? (bound !== undefined ? { routable: await sessionsWithin(app, bound), bound } : {}) : { routable: await routableSessions(app, e.from) };
962
- const copy = makeEvent(env, "p2p.message", e.ts, { from, ...sess, text: pt.text, unclaimedFor: toSession, ...(asks ? { receipt: true } : {}), ...held }, {}, "unclaimed");
1096
+ const copy = makeEvent(env, "p2p.message", e.ts, { from, ...sess, ...origin, text: pt.text, unclaimedFor: toSession, ...(asks ? { receipt: true } : {}), ...held }, {}, "unclaimed");
963
1097
  out.push(copy);
964
1098
  if (asks)
965
1099
  await rememberAsked(app, copy.id, { id: pt.rcpt, from: e.from, did: e.fdid, unclaimedFor: toSession });
@@ -1014,7 +1148,7 @@ export async function onSessionEnvelope(app, env, r) {
1014
1148
  from: { userId: from.userId, address: from.address, self: from.self },
1015
1149
  session: { own: e.own, sid: e.sid, ref },
1016
1150
  });
1017
- const data = { from, ...sess, ext: pt.kind, fallback, ...routable };
1151
+ const data = { from, ...sess, ...origin, ext: pt.kind, fallback, ...routable };
1018
1152
  if (r.rendered)
1019
1153
  data.rendered = r.rendered;
1020
1154
  if (r.extError)
@@ -1033,10 +1167,19 @@ export async function onSessionEnvelope(app, env, r) {
1033
1167
  * P2P_PROJECT_DIRS, past its cap private) and any more the caller names.
1034
1168
  */
1035
1169
  export async function bindFromEnv(app, sid, extra = [], o = {}) {
1036
- const { dirs, over } = sessionDirs(app.env);
1170
+ const { dirs, why } = sessionDirs(app.env);
1037
1171
  // Past the cap in folders named on the command line too: private, never the first N.
1038
- const tooMany = extra.length > MAX_SESSION_DIRS;
1039
- await bindSession(app, sid, [...dirs, ...extra.slice(0, MAX_SESSION_DIRS)], { ...(o.person ? { person: true } : {}), ...(over || tooMany || o.over ? { over: true } : {}) });
1172
+ const over = new Set([...why, ...(o.over ?? [])]);
1173
+ if (extra.length > MAX_SESSION_DIRS)
1174
+ over.add("folders");
1175
+ // The session's own scratch, as its front end names it: only a front end holding the person token.
1176
+ const scratch = app.front === true ? sessionScratch(app.env[SCRATCH_ENV]) : undefined;
1177
+ await bindSession(app, sid, [...dirs, ...extra.slice(0, MAX_SESSION_DIRS)], { ...(o.person ? { person: true } : {}), ...(over.size > 0 ? { over: [...over] } : {}), ...(scratch ? { scratch } : {}) });
1178
+ }
1179
+ /** A front end's `--project-dirs-over` as reasons: a bare flag (an older front end) is `front`. */
1180
+ function overOf(v) {
1181
+ const out = v === true ? ["front"] : overWhys(Array.isArray(v) ? v.flatMap((x) => String(x).split(",")) : []);
1182
+ return out.length > 0 ? out : ["front"];
1040
1183
  }
1041
1184
  /** Whether a ceiling is within a bound (narrower or equal): private always is. */
1042
1185
  function within(c, b) {
@@ -1124,6 +1267,15 @@ export async function routableSessions(app, sender, now = Date.now()) {
1124
1267
  }
1125
1268
  return [...out].sort();
1126
1269
  }
1270
+ /** `p2p.idle` for the subscriptions of this device's sessions to `sid`, another session on this device. */
1271
+ async function localIdle(app, sid, ts) {
1272
+ const subs = await takeSubs(app, app.userId, sid);
1273
+ if (subs.length === 0)
1274
+ return;
1275
+ const from = { userId: app.userId, did: app.did, address: await app.addressOf(app.userId), self: true };
1276
+ const ref = sessionRef(app.userId, sid);
1277
+ await app.state.addEvents(subs.map((s) => ({ id: `p2p.idle:local:${sid}:${s.toSession}:${ts}`, at: ts, kind: "p2p.idle", own: app.userId, sid, toSession: s.toSession, data: { from, own: app.userId, sid, ref, reason: "idle" } })));
1278
+ }
1127
1279
  async function takeSubs(app, own, sid) {
1128
1280
  return app.state.update("subs", (cur = []) => {
1129
1281
  const hit = cur.filter((s) => s.own === own && s.sid === sid);
package/dist/social.js CHANGED
@@ -294,10 +294,21 @@ export async function onUnfriendKind(app, env, r) {
294
294
  return [makeEvent(env, "p2p.unfriend", r.envelope.ts, { from: await fromOf(app, r), peer: r.envelope.from })];
295
295
  }
296
296
  async function afterUnfriend(app, peer) {
297
+ // Only when it ended the last friendship with them (issue #3). An unfriend that arrives after a
298
+ // re-friend (a late copy, another device's, one queued while this device was away) ends only the
299
+ // friendships invited at or before it: the new one stands, and so must the caps it exchanged
300
+ // (caps name no friendship). Revoking them anyway left a "friend" neither side could message.
301
+ if (await stillFriends(app, peer))
302
+ return;
297
303
  const caps = await capsToRevokeOnUnfriend(app.store, peer);
298
304
  await app.revokeCaps(caps).catch(() => 0);
299
305
  await app.store.removeCapsHeld((c) => c.iss === peer);
300
306
  }
307
+ /** A friendship with `peer` that no unfriend this device holds ends. */
308
+ async function stillFriends(app, peer) {
309
+ const unfriends = await app.store.listUnfriends();
310
+ return (await liveFriendshipsV3(app.store, app.signerCtx())).some((f) => (f.inviter === peer || f.invitee === peer) && !unfriends.some((u) => unfriendApplies(f, u)));
311
+ }
301
312
  export async function unfriend(app, who) {
302
313
  const peer = await app.resolveUser(who);
303
314
  // Handle what's queued first: it was sent while we were still friends.
package/dist/state.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { OutboxDoc } from "./outbox.js";
2
2
  import type { ReceiptsDoc } from "./receipts.js";
3
3
  import type { RelayInfoRec } from "./relay-info.js";
4
4
  import type { ProjectsDoc, SessionProjectsDoc } from "./projects.js";
5
+ import type { GraphMemoryDoc } from "./graph-memory.js";
5
6
  import { type LockOptions } from "@peer2peer/core/v3/node";
6
7
  import type { DocBackend, RotationStatement, StatusBody } from "@peer2peer/core/v3";
7
8
  import { type Progress } from "./progress.js";
@@ -101,6 +102,14 @@ export interface XStateSenderDoc {
101
102
  n: number;
102
103
  };
103
104
  }
105
+ /** One same-device send (Docs.localSends). */
106
+ export interface LocalSend {
107
+ /** The sending session. */
108
+ from: string;
109
+ /** `person`: the person's own terminal session (`tui`, or a send as them); `agent`: any other session. */
110
+ via: "person" | "agent";
111
+ at: number;
112
+ }
104
113
  export interface PeerStatusRec {
105
114
  own: string;
106
115
  sid: string;
@@ -380,6 +389,17 @@ type Docs = {
380
389
  xstateSent: Record<string, number>;
381
390
  /** Sealed messages no relay accepted yet, retried by `watch` (outbox.ts). */
382
391
  outbox: OutboxDoc;
392
+ /**
393
+ * Messages one session of this device sent to another session of this device, by `<target sid>|<seq>`:
394
+ * which session sent it and whether the person did (sessions.ts). Local only, never on the wire: the
395
+ * receiving side (this same device) reads it to frame the message and to apply the hold rule.
396
+ */
397
+ localSends: Record<string, LocalSend>;
398
+ /** When a message from a bounded session of yours last reached the person's own session (`tui`): for a warning there. */
399
+ tuiTaint: {
400
+ at: number;
401
+ bound: "private" | "shared";
402
+ };
383
403
  /** Delivery receipts (receipts.ts, §4.3). */
384
404
  receipts: ReceiptsDoc;
385
405
  /** When each (sender, kind) of an envelope this version doesn't know was last noticed (unknown-kinds.ts). */
@@ -390,6 +410,12 @@ type Docs = {
390
410
  projects: ProjectsDoc;
391
411
  /** Which projects each session has worked in (projects.ts), by sid: sticky until the session ends. */
392
412
  sessionProjects: SessionProjectsDoc;
413
+ /** When this device showed the one-time notice that new installs turn the Ix extension on (ix-local.ts). */
414
+ ixNotice: {
415
+ at: number;
416
+ };
417
+ /** Graph memory (graph-memory.ts): this device's sessions' context waiting for the local Ix graph, and counters. */
418
+ graphMemory: GraphMemoryDoc;
393
419
  };
394
420
  export declare const sessKey: (own: string, sid: string) => string;
395
421
  /** Events older than this, or beyond the count cap, are pruned. */
package/dist/state.js CHANGED
@@ -34,6 +34,9 @@
34
34
  // relayInfo the relays' /.well-known/p2p-relay.json (features and frames), as last fetched
35
35
  // projects project policies (projects.ts): shared with circles and people, or private (the default)
36
36
  // sessionProjects the projects each session worked in (projects.ts), by sid
37
+ // ixNotice when the one-time "Ix on by default" notice was shown (ix-local.ts)
38
+ // graphMemory graph memory (graph-memory.ts): what was recorded of each own session, the bounded queue, counters
39
+ // history, history-<n> message history (history.ts): sealed with the key in history.key, never plaintext
37
40
  import { join } from "node:path";
38
41
  import { FileDocBackend } from "@peer2peer/core/v3/node";
39
42
  import { debug, step } from "./progress.js";