@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/sessions.js CHANGED
@@ -21,7 +21,7 @@ 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, overWhys, privateRemedy, 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";
@@ -711,9 +711,15 @@ async function rosterCircleOf(app, own, sid) {
711
711
  /** `user`, `user [ref]`, `user/ref` or `user/sid`. */
712
712
  export function parseTarget(to) {
713
713
  const s = to.trim();
714
- const br = /^(.*?)\s*\[([0-9a-f]{6})\]$/.exec(s);
715
- if (br)
716
- 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
+ }
717
723
  // userIds, addresses and petnames never contain "/", so the last one separates a session.
718
724
  const i = s.lastIndexOf("/");
719
725
  if (i > 0 && i < s.length - 1)
@@ -860,22 +866,41 @@ export async function tuiTaintNote(app, toUserId, now = Date.now()) {
860
866
  export async function sendSharing(app, o) {
861
867
  const sid = checkSid(o.fromSession, "--from-session");
862
868
  const uid = await app.resolveUser(o.to.replace(/\s*\[[^\]]*\]\s*$/, "").replace(/\/[^/]*$/, ""));
863
- let added = false;
864
- if (uid !== app.userId && !(await rosterAudience(app, await getSession(app, sid))).includes(uid)) {
865
- await roster(app, sid, { add: [uid] });
866
- 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 };
867
874
  }
875
+ const wire = { maybe: false };
868
876
  try {
869
- const result = await sendMessage(app, { ...o, person: true });
877
+ const result = await sendMessage(app, { ...o, person: true, wire });
870
878
  return added ? { result, shared: { userId: uid, address: await app.addressOf(uid) } } : { result };
871
879
  }
872
880
  catch (e) {
873
- // Nothing was sent: the session goes back to whom it was shared with before.
874
- if (added)
875
- 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);
876
886
  throw e;
877
887
  }
878
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
+ }
879
904
  export async function sendMessage(app, o) {
880
905
  const fromSession = checkSid(o.fromSession, "--from-session");
881
906
  if (Buffer.byteLength(o.text, "utf8") > MAX_TEXT_BYTES)
@@ -903,6 +928,8 @@ export async function sendMessage(app, o) {
903
928
  // whole message for `rcpt` (§4.3). Not when this device can't reach a relay either: the sealed copy
904
929
  // may wait in the outbox for days, long past the status that advertised it (pre-release review R2).
905
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;
906
933
  if (o.text !== "") {
907
934
  // Anything this device couldn't send earlier goes first (order, and it may be the same peer).
908
935
  if (!offline)
@@ -911,14 +938,42 @@ export async function sendMessage(app, o) {
911
938
  const plaintext = { text: o.text, ...(rcpt ? { rcpt } : {}), ...(rosterJws ? { roster: rosterJws } : {}), ...(o.person ? {} : await ownBound(app, fromSession, target, userId)) };
912
939
  if (rcpt)
913
940
  await rememberWanted(app, rcpt, { to: userId, own: target.own, ref: to.ref, fromSession });
914
- d = await app.deliver(userId, "msg", target, plaintext, userId === app.userId && target.did ? { onlyDevices: [target.did], ...localSend(app, target, fromSession, o.person === true) } : {});
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
+ });
915
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;
916
956
  if (d.relays.length === 0 && !retryable(unsent)) {
917
957
  throw new CliError("undelivered", `delivered via 0 relays${d.errors?.length ? ` (${[...new Set(d.errors.map((e) => e.code))].join(", ")})` : ""}`, { delivered: false, to });
918
958
  }
919
959
  // Copies no relay took, for reasons a retry gets past: kept, sealed, for watch to send. When
920
960
  // other copies did go out the message is delivered already; these reach the other devices.
921
- 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
+ }
922
977
  if (later.length > 0)
923
978
  outboxed = await enqueue(app, later, { kind: "msg", dest: to, fromSession });
924
979
  }
@@ -948,7 +1003,7 @@ export async function sendMessage(app, o) {
948
1003
  ...(d ? { messageId: `m${Date.now().toString(36)}` } : {}),
949
1004
  ...(o.notifyWhenIdle ? { notifyWhenIdle: true } : {}),
950
1005
  ...queued,
951
- ...(d ? (rcpt ? { receipts: "requested", receiptId: rcpt } : { receipts: "unsupported" }) : {}),
1006
+ ...(d ? (rcpt && receiptAsked ? { receipts: "requested", receiptId: rcpt } : { receipts: "unsupported" }) : {}),
952
1007
  };
953
1008
  }
954
1009
  /**
@@ -1117,7 +1172,9 @@ export async function bindFromEnv(app, sid, extra = [], o = {}) {
1117
1172
  const over = new Set([...why, ...(o.over ?? [])]);
1118
1173
  if (extra.length > MAX_SESSION_DIRS)
1119
1174
  over.add("folders");
1120
- await bindSession(app, sid, [...dirs, ...extra.slice(0, MAX_SESSION_DIRS)], { ...(o.person ? { person: true } : {}), ...(over.size > 0 ? { over: [...over] } : {}) });
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 } : {}) });
1121
1178
  }
1122
1179
  /** A front end's `--project-dirs-over` as reasons: a bare flag (an older front end) is `front`. */
1123
1180
  function overOf(v) {
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/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.1";
1
+ export declare const VERSION = "0.1.3";
package/dist/version.js CHANGED
@@ -2,4 +2,4 @@
2
2
  //
3
3
  // This CLI's version (scripts/set-version.mjs writes it), on its own so the status and identity
4
4
  // code can advertise it (features.ts) without importing the command line.
5
- export const VERSION = "0.1.1";
5
+ export const VERSION = "0.1.3";
package/dist/watch.js CHANGED
@@ -22,7 +22,7 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
22
22
  import { join } from "node:path";
23
23
  import { certExpiresWithin, mayRepublish, nowSec } from "@peer2peer/core/v3";
24
24
  import { CLOSE_GRACE_MS, REPUBLISH_DOC_WITHIN_SEC } from "./app.js";
25
- import { receiving } from "./inbound.js";
25
+ import { makeEvent, receiving } from "./inbound.js";
26
26
  import { answerDeferredWants, renewOpenJoinCaps } from "./circle-ops.js";
27
27
  import { checkSid, expireSubs } from "./sessions.js";
28
28
  import { CliError } from "./errors.js";
@@ -293,6 +293,43 @@ export async function refreshContacts(app) {
293
293
  await retryRotationJoins(app).catch(() => []);
294
294
  await app.adoptCertFromDoc();
295
295
  }
296
+ /** Whether the head's document or one of its device certificates is due for renewal. */
297
+ function renewalDue(head, now) {
298
+ const certSoon = (head.certs ?? []).some((c) => {
299
+ try {
300
+ const exp = JSON.parse(Buffer.from(c.split(".")[1], "base64url").toString()).exp;
301
+ return certExpiresWithin({ exp }, 30 * 86_400, now);
302
+ }
303
+ catch {
304
+ return false;
305
+ }
306
+ });
307
+ return certSoon || head.exp - now <= REPUBLISH_DOC_WITHIN_SEC;
308
+ }
309
+ /**
310
+ * #78 review: the strict refresh before a renewal was refused because a relay that doesn't answer sent a newer
311
+ * version of our identity earlier (App.ownPendingGuard). Never silent: a warning on every run, and once the
312
+ * renewal is due, a `p2p.alert` (`what: "renewal-held"`) for the mod's status line, raised again each day
313
+ * left, so it escalates as the document nears expiry instead of letting it lapse unnoticed.
314
+ */
315
+ async function renewalHeld(app, e) {
316
+ const heldBy = e.extra.heldBy.filter((r) => typeof r === "string");
317
+ const v = await app.ownView();
318
+ const now = nowSec();
319
+ const daysLeft = Math.max(0, Math.floor((v.head.exp - now) / 86_400));
320
+ const fix = `try again when ${heldBy.length === 1 ? "it answers" : "they answer"}, or remove ${heldBy.length === 1 ? "it" : "them"} (\`p2p relays remove ${heldBy.join(" ")}\`) if gone for good or no device of yours published that version; \`p2p doctor\` shows the details`;
321
+ app.warn(`can't renew your identity document (expires in ${daysLeft} days): ${heldBy.join(", ")} didn't answer and earlier sent a newer version of it; ${fix}`);
322
+ if (!renewalDue(v.head, now))
323
+ return;
324
+ await app.state.addEvents([
325
+ makeEvent(`renewal-held|${v.head.hash}|${daysLeft}`, "p2p.alert", Date.now(), {
326
+ from: { userId: app.userId, did: app.did, address: await app.addressOf(app.userId), self: true },
327
+ what: "renewal-held",
328
+ daysLeft,
329
+ heldBy,
330
+ }),
331
+ ]);
332
+ }
296
333
  /** Key holders keep the document and certificates fresh (§2.3 renewal, §2.5 re-publish, single writer). */
297
334
  export async function maintain(app) {
298
335
  if (!app.isKeyholder) {
@@ -304,25 +341,18 @@ export async function maintain(app) {
304
341
  await app.refreshIdentity(app.userId, app.relays, { force: true, strict: true });
305
342
  }
306
343
  catch (e) {
307
- if (e instanceof CliError)
344
+ if (e instanceof CliError) {
345
+ if (Array.isArray(e.extra.heldBy))
346
+ await renewalHeld(app, e).catch(() => undefined);
308
347
  return;
348
+ }
309
349
  throw e;
310
350
  }
311
351
  const v = await app.ownView();
312
352
  if (!v.devices.includes(app.did) || !v.keyholders.includes(app.did))
313
353
  return;
314
354
  const now = nowSec();
315
- const certSoon = (v.head.certs ?? []).some((c) => {
316
- try {
317
- const exp = JSON.parse(Buffer.from(c.split(".")[1], "base64url").toString()).exp;
318
- return certExpiresWithin({ exp }, 30 * 86_400, now);
319
- }
320
- catch {
321
- return false;
322
- }
323
- });
324
- const docSoon = v.head.exp - now <= REPUBLISH_DOC_WITHIN_SEC;
325
- if ((docSoon || certSoon) && mayRepublish(app.did, v.head, now)) {
355
+ if (renewalDue(v.head, now) && mayRepublish(app.did, v.head, now)) {
326
356
  await app.publishNext(() => { }).catch((e) => {
327
357
  if (!(e instanceof CliError))
328
358
  throw e;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peer2peer/cli",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "The standalone Peer2Peer v3 CLI (`p2p`): an account-free identity, friends, circles, end-to-end encrypted session messaging and status over open relays",
5
5
  "keywords": [
6
6
  "peer2peer",
@@ -53,10 +53,13 @@
53
53
  "registry": "https://registry.npmjs.org/"
54
54
  },
55
55
  "dependencies": {
56
- "@peer2peer/codex-bridge": "0.1.1",
57
- "@peer2peer/core": "0.1.1",
56
+ "@peer2peer/codex-bridge": "0.1.3",
57
+ "@peer2peer/core": "0.1.3",
58
58
  "commander": "15.0.0",
59
59
  "uqr": "0.1.3",
60
60
  "ws": "8.22.0"
61
+ },
62
+ "overrides": {
63
+ "minimatch": "^11.0.8"
61
64
  }
62
65
  }