@peer2peer/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +366 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +363 -0
  6. package/dist/app.js +1177 -0
  7. package/dist/bin.d.ts +2 -0
  8. package/dist/bin.js +56 -0
  9. package/dist/circle-ops.d.ts +402 -0
  10. package/dist/circle-ops.js +1725 -0
  11. package/dist/cli.d.ts +611 -0
  12. package/dist/cli.js +1650 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +112 -0
  16. package/dist/config.js +243 -0
  17. package/dist/doctor.d.ts +99 -0
  18. package/dist/doctor.js +817 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +32 -0
  22. package/dist/ext-host.js +259 -0
  23. package/dist/extensions.d.ts +386 -0
  24. package/dist/extensions.js +395 -0
  25. package/dist/features.d.ts +91 -0
  26. package/dist/features.js +164 -0
  27. package/dist/format.d.ts +57 -0
  28. package/dist/format.js +248 -0
  29. package/dist/identity.d.ts +236 -0
  30. package/dist/identity.js +751 -0
  31. package/dist/inbound.d.ts +32 -0
  32. package/dist/inbound.js +258 -0
  33. package/dist/index.d.ts +8 -0
  34. package/dist/index.js +14 -0
  35. package/dist/join-answers.d.ts +49 -0
  36. package/dist/join-answers.js +149 -0
  37. package/dist/outbox.d.ts +109 -0
  38. package/dist/outbox.js +337 -0
  39. package/dist/pretty.d.ts +100 -0
  40. package/dist/pretty.js +256 -0
  41. package/dist/procstart.d.ts +1 -0
  42. package/dist/procstart.js +66 -0
  43. package/dist/progress.d.ts +30 -0
  44. package/dist/progress.js +78 -0
  45. package/dist/projects.d.ts +240 -0
  46. package/dist/projects.js +699 -0
  47. package/dist/prompt/picker.d.ts +64 -0
  48. package/dist/prompt/picker.js +152 -0
  49. package/dist/prompt/tty.d.ts +29 -0
  50. package/dist/prompt/tty.js +122 -0
  51. package/dist/readonly.d.ts +20 -0
  52. package/dist/readonly.js +50 -0
  53. package/dist/receipts.d.ts +99 -0
  54. package/dist/receipts.js +180 -0
  55. package/dist/relay-client.d.ts +277 -0
  56. package/dist/relay-client.js +873 -0
  57. package/dist/relay-info.d.ts +24 -0
  58. package/dist/relay-info.js +53 -0
  59. package/dist/rotation.d.ts +402 -0
  60. package/dist/rotation.js +2054 -0
  61. package/dist/running.d.ts +5 -0
  62. package/dist/running.js +74 -0
  63. package/dist/sessions.d.ts +340 -0
  64. package/dist/sessions.js +1152 -0
  65. package/dist/shortcode.d.ts +149 -0
  66. package/dist/shortcode.js +465 -0
  67. package/dist/social.d.ts +139 -0
  68. package/dist/social.js +485 -0
  69. package/dist/state.d.ts +483 -0
  70. package/dist/state.js +217 -0
  71. package/dist/stdin.d.ts +17 -0
  72. package/dist/stdin.js +46 -0
  73. package/dist/sync.d.ts +77 -0
  74. package/dist/sync.js +375 -0
  75. package/dist/transient.d.ts +1 -0
  76. package/dist/transient.js +28 -0
  77. package/dist/trust.d.ts +37 -0
  78. package/dist/trust.js +134 -0
  79. package/dist/tty-confirm.d.ts +2 -0
  80. package/dist/tty-confirm.js +53 -0
  81. package/dist/tui/command.d.ts +20 -0
  82. package/dist/tui/command.js +70 -0
  83. package/dist/tui/frame.d.ts +43 -0
  84. package/dist/tui/frame.js +111 -0
  85. package/dist/tui/model.d.ts +215 -0
  86. package/dist/tui/model.js +255 -0
  87. package/dist/tui/sanitize.d.ts +13 -0
  88. package/dist/tui/sanitize.js +151 -0
  89. package/dist/tui/terminal.d.ts +88 -0
  90. package/dist/tui/terminal.js +354 -0
  91. package/dist/tui/tui.d.ts +71 -0
  92. package/dist/tui/tui.js +571 -0
  93. package/dist/tui/view.d.ts +4 -0
  94. package/dist/tui/view.js +356 -0
  95. package/dist/unknown-kinds.d.ts +12 -0
  96. package/dist/unknown-kinds.js +66 -0
  97. package/dist/version.d.ts +1 -0
  98. package/dist/version.js +5 -0
  99. package/dist/want-pow.d.ts +12 -0
  100. package/dist/want-pow.js +46 -0
  101. package/dist/watch.d.ts +35 -0
  102. package/dist/watch.js +325 -0
  103. package/dist/xstate.d.ts +125 -0
  104. package/dist/xstate.js +422 -0
  105. package/package.json +60 -4
package/dist/codes.js ADDED
@@ -0,0 +1,998 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Short-code invites (docs/protocol.md P4): friend, and join circles, in one
4
+ // step.
5
+ //
6
+ // - A code joins up to CODE_MAX_CIRCLES circles the inviter owns or
7
+ // administers (`--circle`, repeatable; by default the default circle). The
8
+ // bundle's `circle` is the first, which every client joins; `circles` holds
9
+ // the rest (heads only), which a client from before multi-circle codes
10
+ // ignores: it joins the first one, and the inviter's adds of the others
11
+ // reach it as ordinary held circle invites.
12
+ // - The code also travels as a web link, `https://ix-infra.com/p2p/invite#<relay>/<CODE>`:
13
+ // the same single-use, relay-held code (the secret is in the fragment, which
14
+ // never reaches the web server).
15
+ // - Before anything is accepted, the redeemer sees who made the code (address
16
+ // and fingerprint) and every circle with its member count, and says yes once
17
+ // (`--yes` for scripts).
18
+ //
19
+ // - `p2p invite [label]` mints an ordinary invite (§3.1), bundles it with the
20
+ // circle to join (by default the default circle, when this user owns or
21
+ // administers it), seals the bundle under a fresh 100-bit code and puts it
22
+ // in one relay's invite mailbox. The code is all the user shares.
23
+ // - `p2p join <code>` takes the bundle (single use), opens and verifies it,
24
+ // and accepts: typing the command is the consent, so nothing is held. When
25
+ // the bundle names a circle, the join completes once the inviter's client
26
+ // adds us (it is told by the accept), under the §3.3 confirmation rules.
27
+ // - The inviter's client completes its side on the accept, because issuing
28
+ // the code was the consent: the friendship is recorded (as for every
29
+ // accept) and the redeemer is added to the circle. It also tells the user
30
+ // who redeemed the code, with `p2p remove <userId>` at hand, since anyone
31
+ // who saw the code first could have used it.
32
+ // - A revoked code's invite is refused even if someone took it before the
33
+ // revoke, and its contact cap is revoked at the relays.
34
+ import { CircleChain, circleDisplayName, circlePolicy, displayFingerprint, inviteHashV3, isUserId, loadCircle, nowSec, parseCircleVersion, verifyCircleVersionAlone, verifyInviteV3, } from "@peer2peer/core/v3";
35
+ import { lookup as dnsLookup } from "node:dns";
36
+ import { capPeek } from "./app.js";
37
+ import { defaultRelays, normalizeRelays } from "./config.js";
38
+ import { CliError } from "./errors.js";
39
+ import { addMemberViaCode, joinCircle, removeMember, resolveCircle, setDefaultCircle } from "./circle-ops.js";
40
+ import { makeEvent } from "./inbound.js";
41
+ import { inviteDel, inviteGet, inviteList, invitePut, openLinkConnection } from "./relay-client.js";
42
+ import { canonicalShortCode, CODE_MAX_CIRCLES, CODE_MAX_TTL_SEC, codeRelayPart, codeWebLink, decodeCodeChars, encodeCodeChars, formatShortCode, groupCode, INVITE_BLOB_MAX, inviteAdmitHash, inviteAdmitKey, inviteLid, newCodeSecret, openInviteBundle, parseInviteBundle, parseShortCode, isOwnRelay, isPrivateAddress, isPrivateRelayHost, PRIVATE_RESOLVE_MARK, privateGuardLookup, privateRelayMessage, sealInviteBundle, } from "./shortcode.js";
43
+ import { accept, dropHeld, guardForeignRelays, inviteRelays, mintInvite, unfriend } from "./social.js";
44
+ import { sendSync } from "./sync.js";
45
+ import { CAP_INVITE_CIRCLES, peerLacks } from "./features.js";
46
+ async function looksOlderThanMultiCircle(app, who) {
47
+ return peerLacks(app, who, CAP_INVITE_CIRCLES).catch(() => false);
48
+ }
49
+ export const CODE_LABEL_MAX = 64;
50
+ /** Records of codes that ended longer ago than this are pruned. */
51
+ const CODE_RECORD_RETENTION_SEC = 30 * 86_400;
52
+ /** A code join still waiting for the inviter after this long is dropped. */
53
+ const CODE_JOIN_RETENTION_MS = 30 * 86_400 * 1000;
54
+ /** `K7QM…`: how a code is named once it is no longer secret. */
55
+ export const codeHint = (code) => `${code.slice(0, 4)}…`;
56
+ /** The Claude Code plugin's install steps, as the invite message gives them. */
57
+ export const PLUGIN_INSTALL = ["/plugin marketplace add ix-infrastructure/Peer2Peer", "/plugin install peer2peer@peer2peer", "/reload-plugins"];
58
+ export const CODEX_INSTALL_URL = "https://github.com/ix-infrastructure/Peer2Peer/blob/main/packages/codex-bridge/README.md#install";
59
+ /** What a code's web link is made of (codeWebLink: the prefix, a relay part, the code): nothing a shell treats specially inside single quotes. */
60
+ const WEB_LINK_SAFE = /^https:\/\/ix-infra\.com\/p2p\/invite#[A-Za-z0-9.:[\]/_~-]+$/;
61
+ /** POSIX single quotes: `'` closes, an escaped quote, and opens again, so nothing can break out. */
62
+ export function shellQuote(s) {
63
+ return `'${s.replace(/'/g, "'\\''")}'`;
64
+ }
65
+ /** The `p2p join` line for a code's web link (quoted for the shell), with --allow-private-relay when it needs it. */
66
+ export function joinCommandFor(web, privateRelay) {
67
+ // A web link is always of the safe charset; anything else is quoted so a `'` can't break out anyway.
68
+ const quoted = WEB_LINK_SAFE.test(web) ? `'${web}'` : shellQuote(web);
69
+ return `p2p join${privateRelay ? " --allow-private-relay" : ""} ${quoted}`;
70
+ }
71
+ /** The message `p2p invite` prints to send: self-contained for someone who has never installed Peer2Peer. */
72
+ export function inviteMessage(web, privateRelay) {
73
+ const flag = privateRelay ? " --allow-private-relay" : "";
74
+ // TODO(after the first npm release): add "No Claude Code? npx @peer2peer/cli join '<web>'". Nothing is
75
+ // published to npm yet, so the line isn't printed.
76
+ return [
77
+ `Join me on Peer2Peer: ${web}`,
78
+ ...(privateRelay ? ["You need to be on the same private network as me (e.g. Tailscale) for it to work."] : []),
79
+ "New to it? In Claude Code run:",
80
+ ...PLUGIN_INSTALL.map((l) => ` ${l}`),
81
+ `then: /peers join${flag} ${web}`,
82
+ `Using Codex? See ${CODEX_INSTALL_URL}`,
83
+ `(Already have the p2p command? ${joinCommandFor(web, privateRelay)})`,
84
+ ].join("\n");
85
+ }
86
+ /**
87
+ * Is this relay on a private network as this machine sees it (its host a private address, or a name
88
+ * resolving to one, as a Tailscale MagicDNS name does)? Bounded; unknown counts as not.
89
+ */
90
+ export async function relayLooksPrivate(relay) {
91
+ let host;
92
+ try {
93
+ host = new URL(relay).hostname;
94
+ }
95
+ catch {
96
+ return false;
97
+ }
98
+ if (isPrivateRelayHost(host))
99
+ return true;
100
+ if (host.startsWith("[") || /^[\d.]+$/.test(host))
101
+ return false;
102
+ const addrs = await new Promise((done) => {
103
+ const t = setTimeout(() => done([]), 1500);
104
+ t.unref?.();
105
+ dnsLookup(host, { all: true }, (err, a) => {
106
+ clearTimeout(t);
107
+ done(err ? [] : a);
108
+ });
109
+ });
110
+ return addrs.some((a) => isPrivateAddress(a.address));
111
+ }
112
+ function checkLabel(label) {
113
+ if (label === undefined)
114
+ return undefined;
115
+ const t = label.trim();
116
+ if (t === "")
117
+ return undefined;
118
+ if (t.length > CODE_LABEL_MAX || /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/.test(t)) {
119
+ throw new CliError("usage", `a label is at most ${CODE_LABEL_MAX} printable characters`);
120
+ }
121
+ return t;
122
+ }
123
+ /** Whether this device may add people to `c`: its owner's key holder, or an admin, and a member. */
124
+ function canAdd(app, c) {
125
+ const h = c.chain.head;
126
+ if (!c.record.joinedByMe || !h.members.includes(app.userId))
127
+ return "you're not a member of it";
128
+ if (h.owner === app.userId && !app.isKeyholder)
129
+ return "this device doesn't hold your identity key";
130
+ if (h.owner !== app.userId && !h.admins.includes(app.userId))
131
+ return "only its owner or an admin can add people";
132
+ // An open circle has a link anyone can use (`p2p circle invite <cid> --link`): a code adds nothing.
133
+ if (circlePolicy(h) === "open")
134
+ return "it is open: share its own link instead (p2p circle invite <cid> --link)";
135
+ return undefined;
136
+ }
137
+ /**
138
+ * The circles a code joins: each one named (in order, without repeats), or the default circle when
139
+ * none is and this device may add people to it. A named circle this device can't add people to is
140
+ * an error naming it: never silently left out.
141
+ */
142
+ async function circlesForCode(app, opts) {
143
+ if (opts.noCircle) {
144
+ if ((opts.circles ?? []).length > 0)
145
+ throw new CliError("usage", "--circle and --no-circle don't go together");
146
+ return [];
147
+ }
148
+ const named = opts.circles ?? [];
149
+ if (named.length === 0) {
150
+ const want = app.self?.defaultCircle;
151
+ if (!want)
152
+ return [];
153
+ let c;
154
+ try {
155
+ c = await resolveCircle(app, want);
156
+ }
157
+ catch {
158
+ app.warn(`your default circle ${want} isn't held here: the code is a friend invite only`);
159
+ return [];
160
+ }
161
+ const why = canAdd(app, c);
162
+ if (why) {
163
+ app.warn(`the code doesn't include your default circle "${circleDisplayName(c.chain.head)}": ${why}`);
164
+ return [];
165
+ }
166
+ return [c];
167
+ }
168
+ const out = [];
169
+ const refused = [];
170
+ for (const name of named) {
171
+ let c;
172
+ try {
173
+ c = await resolveCircle(app, name);
174
+ }
175
+ catch (e) {
176
+ refused.push(`${name}: ${e.message}`);
177
+ continue;
178
+ }
179
+ if (out.some((x) => x.record.cid === c.record.cid))
180
+ continue;
181
+ const why = canAdd(app, c);
182
+ if (why)
183
+ refused.push(`"${circleDisplayName(c.chain.head)}" (${c.record.cid}): ${why}`);
184
+ else
185
+ out.push(c);
186
+ }
187
+ if (refused.length > 0)
188
+ throw new CliError("not_admin", `the code can't join ${refused.length === 1 ? "this circle" : "these circles"}, so no code was made: ${refused.join("; ")}`);
189
+ if (out.length > CODE_MAX_CIRCLES)
190
+ throw new CliError("usage", `a code joins at most ${CODE_MAX_CIRCLES} circles (you named ${out.length})`);
191
+ return out;
192
+ }
193
+ export async function inviteCode(app, opts) {
194
+ const label = checkLabel(opts.label);
195
+ const days = opts.ttlDays ?? 7;
196
+ if (!Number.isFinite(days) || days <= 0 || days * 86_400 > CODE_MAX_TTL_SEC)
197
+ throw new CliError("usage", "--ttl-days must be 1..7");
198
+ if ((opts.circles ?? []).length > CODE_MAX_CIRCLES)
199
+ throw new CliError("usage", `a code joins at most ${CODE_MAX_CIRCLES} circles`);
200
+ const ttlSec = Math.round(days * 86_400);
201
+ const aud = opts.to ? await app.resolveUser(opts.to) : "*";
202
+ if (aud === app.userId)
203
+ throw new CliError("usage", "you can't invite yourself (link a device with `p2p link start`)");
204
+ const pool = await app.connectAndDrain();
205
+ const circles = await circlesForCode(app, opts);
206
+ const targets = opts.relay ? normalizeRelays([opts.relay]) : app.relays;
207
+ const m = await mintInvite(app, { aud, uses: 3, ttlSec });
208
+ const s = newCodeSecret();
209
+ const lid = inviteLid(s);
210
+ // The bundle must fit the relay's blob cap. The first circle's chain may go (the inviter sends it on the
211
+ // accept); a circle never does: past that, no code is made, rather than a code that joins less than asked.
212
+ const [first, ...rest] = circles;
213
+ const more = rest.length > 0 ? { circles: rest.map((c) => ({ head: c.chain.head.jws })) } : {};
214
+ const tries = first
215
+ ? [
216
+ { v: 1, invite: m.jws, circle: { head: first.chain.head.jws, chain: first.chain.versionsFrom(1) }, ...more },
217
+ { v: 1, invite: m.jws, circle: { head: first.chain.head.jws }, ...more },
218
+ ]
219
+ : [{ v: 1, invite: m.jws }];
220
+ const max = Math.min(INVITE_BLOB_MAX, app.tun.inviteBlobMax ?? INVITE_BLOB_MAX);
221
+ let blob;
222
+ let bundle;
223
+ for (const b of tries) {
224
+ const sealed = sealInviteBundle(s, b);
225
+ if (sealed.length <= max) {
226
+ blob = sealed;
227
+ bundle = b;
228
+ break;
229
+ }
230
+ }
231
+ if (!blob || !bundle) {
232
+ throw new CliError("too_large", circles.length > 1
233
+ ? `an invite joining these ${circles.length} circles doesn't fit in a code (at most ${Math.round(max / 1024)} KiB): name fewer circles, or make a second code`
234
+ : `the invite doesn't fit in a code (at most ${Math.round(max / 1024)} KiB); a smaller avatar helps`);
235
+ }
236
+ let relay;
237
+ let exp = 0;
238
+ const errors = [];
239
+ for (const r of targets) {
240
+ try {
241
+ // On a members-only relay the code also admits its redeemer there (open relays ignore `admit`).
242
+ exp = await invitePut(await pool.ensure(r), lid, blob, ttlSec, inviteAdmitHash(inviteAdmitKey(s)));
243
+ relay = r;
244
+ break;
245
+ }
246
+ catch (e) {
247
+ errors.push(`${r}: ${e.message}`);
248
+ }
249
+ }
250
+ if (!relay)
251
+ throw new CliError("not_published", `no relay took the code (${errors.join("; ")})`);
252
+ const chars = encodeCodeChars(s);
253
+ const cap = capPeek(m.cap);
254
+ const cids = circles.map((c) => c.record.cid);
255
+ const rec = {
256
+ lid,
257
+ code: groupCode(chars),
258
+ short: formatShortCode(relay, s),
259
+ relay,
260
+ inv: m.inv,
261
+ ...(cap ? { capid: cap.capid, capRelays: cap.relays } : {}),
262
+ aud,
263
+ ...(label ? { label } : {}),
264
+ ...(cids.length > 0 ? { cid: cids[0], cids } : {}),
265
+ createdAt: nowSec(),
266
+ exp: Math.min(exp, m.exp),
267
+ status: "open",
268
+ };
269
+ await app.state.update("codes", (cur = {}) => ({ next: pruneCodes({ ...cur, [lid]: rec }), result: undefined }));
270
+ await sendSync(app, { codes: [rec] });
271
+ const list = circles.map((c) => ({ cid: c.record.cid, name: circleDisplayName(c.chain.head), members: c.chain.head.members.length }));
272
+ const web = codeWebLink(rec.short);
273
+ const privateRelay = await relayLooksPrivate(relay);
274
+ return {
275
+ code: rec.short,
276
+ line: `Join me on Peer2Peer: ${web} (or: p2p join ${rec.short})`,
277
+ relay,
278
+ label: label ?? null,
279
+ to: aud === "*" ? null : { userId: aud, address: await app.addressOf(aud) },
280
+ circle: list[0] ? { cid: list[0].cid, name: list[0].name } : null,
281
+ circles: list,
282
+ web,
283
+ expiresAt: rec.exp,
284
+ uses: 1,
285
+ lid,
286
+ message: inviteMessage(web, privateRelay),
287
+ privateRelay,
288
+ };
289
+ }
290
+ function pruneCodes(all, now = nowSec()) {
291
+ const out = {};
292
+ for (const [k, c] of Object.entries(all)) {
293
+ const ended = c.status === "open" ? c.exp : (c.redeemedAt ?? c.exp);
294
+ if (now - ended < CODE_RECORD_RETENTION_SEC)
295
+ out[k] = c;
296
+ }
297
+ return out;
298
+ }
299
+ /** Merges code records from another of our devices: a later status wins. */
300
+ export async function importCodes(app, recs) {
301
+ const rank = { open: 0, redeemed: 1, revoked: 2 };
302
+ await app.state.update("codes", (cur = {}) => {
303
+ const next = { ...cur };
304
+ for (const x of recs) {
305
+ const r = x;
306
+ if (typeof r !== "object" || r === null || typeof r.lid !== "string" || !/^[a-z2-7]{26}$/.test(r.lid) || !(r.status in rank))
307
+ continue;
308
+ if (typeof r.inv !== "string" || typeof r.code !== "string" || typeof r.exp !== "number")
309
+ continue;
310
+ const have = next[r.lid];
311
+ if (!have || rank[r.status] > rank[have.status] || (rank[r.status] === rank[have.status] && (r.removedAt ?? 0) > (have.removedAt ?? 0)))
312
+ next[r.lid] = { ...have, ...r };
313
+ }
314
+ return { next: pruneCodes(next), result: undefined };
315
+ });
316
+ }
317
+ // ---------------------------------------------------------------------------
318
+ // The inviter's side of a redeemed code (from the accept, social.ts)
319
+ export async function codeByInv(app, inv) {
320
+ const all = (await app.state.get("codes")) ?? {};
321
+ return Object.values(all).find((c) => c.inv === inv);
322
+ }
323
+ /** Runs after the accept of one of our codes' invites was recorded: the redeemer is added to each circle, the user is told. */
324
+ export async function onCodeRedeemed(app, env, at, from, rec, who) {
325
+ // Compare-and-set under the state lock: only one process (a watch and a short command can both
326
+ // handle copies of the accept) flips open -> redeemed and runs the side effects below.
327
+ const updated = await app.state.update("codes", (cur = {}) => {
328
+ const now = cur[rec.lid];
329
+ if (!now || now.status !== "open")
330
+ return { result: undefined };
331
+ const next = { ...now, status: "redeemed", redeemedBy: who, redeemedAt: nowSec() };
332
+ return { next: { ...cur, [rec.lid]: next }, result: next };
333
+ });
334
+ if (!updated)
335
+ return [];
336
+ // Each circle the code names, the first one first: added, proposed (an admin's add goes to the owner) or failed.
337
+ const outcomes = [];
338
+ for (const cid of rec.cids ?? (rec.cid ? [rec.cid] : [])) {
339
+ try {
340
+ outcomes.push({ cid, ...(await addMemberViaCode(app, cid, who)) });
341
+ }
342
+ catch (e) {
343
+ outcomes.push({ cid, status: "failed", reason: e.message });
344
+ }
345
+ }
346
+ // What `p2p remove` undoes: only the circles this code put them in (added, or proposed to the owner),
347
+ // never one they were in already.
348
+ const added = outcomes.filter((o) => o.status === "added" || o.status === "proposed").map((o) => o.cid);
349
+ const recorded = await app.state.update("codes", (cur = {}) => {
350
+ const now = cur[rec.lid];
351
+ if (!now)
352
+ return { result: updated };
353
+ const next = { ...now, added };
354
+ return { next: { ...cur, [rec.lid]: next }, result: next };
355
+ });
356
+ const circle = outcomes[0] ?? null;
357
+ const address = from.address;
358
+ const lines = outcomes.map((o) => o.status === "added"
359
+ ? ` added to "${o.name ?? o.cid}"`
360
+ : o.status === "already"
361
+ ? ` already in "${o.name ?? o.cid}"`
362
+ : o.status === "proposed"
363
+ ? ` their add to "${o.name ?? o.cid}" went to its owner`
364
+ : ` couldn't add them to "${o.name ?? o.cid}": ${o.reason}`);
365
+ // A redeemer whose client predates multi-circle codes joins only the first circle by itself; the others
366
+ // reach it as held circle invites. Said when its statuses show it (no invite.circles.v1): unknown otherwise.
367
+ const old = outcomes.length > 1 && (await looksOlderThanMultiCircle(app, who));
368
+ // One circle: said in the sentence, as before multi-circle codes; several: one line each.
369
+ const one = outcomes.length === 1 ? outcomes[0] : undefined;
370
+ const where = one?.status === "added" ? ` and was added to "${one.name}"` : one?.status === "already" ? ` (already in "${one.name}")` : one?.status === "proposed" ? ` (their add to "${one.name}" went to the owner)` : "";
371
+ app.io.err(`${address} joined via your code ${codeHint(rec.code)}${rec.label ? ` ("${rec.label}")` : ""}${where}. Not who you meant? p2p remove ${who}` +
372
+ (one ? (one.status === "failed" ? `\n couldn't add them to the circle: ${one.reason}` : "") : lines.length ? `\n${lines.join("\n")}` : "") +
373
+ (old ? `\n their client looks older: it joins only "${outcomes[0].name ?? outcomes[0].cid}" by itself, and shows the others as circle invites to approve` : ""));
374
+ await sendSync(app, { codes: [recorded] });
375
+ return [
376
+ makeEvent(env, "p2p.joined", at, {
377
+ from,
378
+ code: codeHint(rec.code),
379
+ lid: rec.lid,
380
+ ...(rec.label ? { label: rec.label } : {}),
381
+ ...(circle ? { cid: circle.cid, ...(circle.name ? { circleName: circle.name } : {}), circleStatus: circle.status } : {}),
382
+ ...(outcomes.length > 1 ? { circles: outcomes.map((o) => ({ cid: o.cid, ...(o.name ? { name: o.name } : {}), status: o.status })) } : {}),
383
+ ...(old ? { olderClient: true } : {}),
384
+ remove: `p2p remove ${who}`,
385
+ }),
386
+ ];
387
+ }
388
+ async function fetchBlob(app, lid, relays, opts = {}) {
389
+ const errors = [];
390
+ for (const relay of relays) {
391
+ let conn;
392
+ try {
393
+ // The code's own relay: what its name resolves to is checked too, before anyone says yes.
394
+ conn = await openLinkConnection(relay, app.transport, app.tun.connectTimeoutMs, app.progress, opts.guardPrivate ? { lookup: privateGuardLookup() } : {});
395
+ const blob = await inviteGet(conn, lid);
396
+ if (blob !== undefined)
397
+ return { blob, relay };
398
+ }
399
+ catch (e) {
400
+ if (e instanceof CliError && e.code === "rate_limited")
401
+ throw e;
402
+ if (e.message.includes(PRIVATE_RESOLVE_MARK)) {
403
+ const at = /\(([^()]+)\)\s*$/.exec(e.message)?.[1];
404
+ throw new CliError("private_relay", privateRelayMessage("code's relay", new URL(relay).hostname, { code: true, ...(at ? { detail: `it resolves to ${at}` } : {}) }));
405
+ }
406
+ errors.push(`${relay}: ${e.message}`);
407
+ }
408
+ finally {
409
+ conn?.close();
410
+ }
411
+ }
412
+ if (errors.length === relays.length && relays.length > 0)
413
+ throw new CliError("network", `couldn't reach the code's relay (${errors.join("; ")})`);
414
+ return undefined;
415
+ }
416
+ /** What a code offers, in words: who made it and every circle with its member count. */
417
+ export function previewText(p) {
418
+ const circles = p.circles.map((c) => {
419
+ const n = `${c.members} member${c.members === 1 ? "" : "s"}`;
420
+ if (c.note === "unverified")
421
+ return `"${c.name}" (unverified: not joined from this code; if its invite comes, you approve it on its own)`;
422
+ const owner = c.owner === p.from.userId ? "theirs" : `owner ${c.ownerAddress}`;
423
+ if (c.note === "open")
424
+ return `"${c.name}" (${n}, open, ${owner}: not joined from this code; if its invite comes, you approve it on its own)`;
425
+ if (c.note === "not-admin")
426
+ return `"${c.name}" (${n}, ${owner}, which they don't run: not joined from this code; if its invite comes, you approve it on its own)`;
427
+ return `"${c.name}" (${n}, invite-only, ${owner})`;
428
+ });
429
+ const to = p.to ? ` This code is for ${p.toAddress ?? p.to}.` : "";
430
+ return `${p.from.address} (fingerprint ${p.from.fingerprint}) invites you to be friends${circles.length ? `, and to join ${circles.join(", ")}` : ""}.${to}`;
431
+ }
432
+ /** The preview's view of one circle version from a code (never trusted beyond what its signature shows). */
433
+ async function previewCircle(app, inviter, headJws, chain) {
434
+ const head = parseCircleVersion(headJws);
435
+ let verified = false;
436
+ try {
437
+ verifyCircleVersionAlone(headJws);
438
+ verified = true;
439
+ }
440
+ catch {
441
+ // A transfer version verifies only against its parent: with the first circle's chain, if the code carries it.
442
+ if (chain?.length) {
443
+ try {
444
+ verified = CircleChain.bootstrap([...chain, headJws], { head: headJws }).head.jws === headJws;
445
+ }
446
+ catch {
447
+ verified = false;
448
+ }
449
+ }
450
+ }
451
+ const policy = circlePolicy(head);
452
+ const runs = head.owner === inviter || head.admins.includes(inviter);
453
+ const note = !verified ? "unverified" : policy === "open" ? "open" : !runs ? "not-admin" : undefined;
454
+ return {
455
+ cid: head.cid,
456
+ name: circleDisplayName(head),
457
+ members: head.members.length,
458
+ policy,
459
+ owner: head.owner,
460
+ ownerAddress: await app.addressOf(head.owner),
461
+ verified,
462
+ auto: note === undefined,
463
+ ...(note ? { note } : {}),
464
+ };
465
+ }
466
+ export async function joinCode(app, input, opts = {}) {
467
+ const allowPrivate = opts.allowPrivateRelay || app.env.P2P_ALLOW_PRIVATE_RELAY === "1";
468
+ // The user's own relays at the start of the command (a teammate's code on the team's own relay is fine).
469
+ const own = (await app.load(false)) ? (app.self?.relays ?? []) : [];
470
+ const parsed = parseShortCode(input, { allowPrivate, own });
471
+ const codeRelayIsOwn = !!parsed.relay && isOwnRelay(parsed.relay, own);
472
+ // What the messages below name: rebuilt from the parsed code, never the raw input (L2).
473
+ const shown = canonicalShortCode(parsed);
474
+ // A members-only code relay admits whoever presents the code's admission key at auth: keep it
475
+ // before anything connects there (the identity created below publishes to it first).
476
+ if (parsed.relay && !opts.previewOnly)
477
+ await app.saveAdmit(admitRelay(parsed.relay), inviteAdmitKey(parsed.secret));
478
+ const loaded = await app.load(false);
479
+ let defaults = [];
480
+ if (!loaded) {
481
+ defaults = defaultRelays(app.env, app.file);
482
+ if (defaults.length === 0 && !parsed.relay) {
483
+ throw new CliError("no_relays", "no identity here yet and no relays configured: run `p2p setup` first, or use the code with its relay part (relay.example/K7QM-…)");
484
+ }
485
+ }
486
+ // 1. Open the code (single use on the relay; kept here, so a retry or the join after a preview works).
487
+ const lid = inviteLid(parsed.secret);
488
+ const local = (await app.state.get("redeemed"))?.[lid];
489
+ let blob = local?.blob;
490
+ if (!blob) {
491
+ const got = await fetchBlob(app, lid, parsed.relay ? [parsed.relay] : loaded ? app.relays : defaults, { guardPrivate: !!parsed.relay && !allowPrivate && !codeRelayIsOwn });
492
+ if (!got) {
493
+ throw new CliError("code_not_found", `no invite under that code${parsed.relay ? ` on ${parsed.relay}` : " on your relays"}: it was already used or revoked, it expired, or it was mistyped`);
494
+ }
495
+ blob = got.blob;
496
+ if (got.relay !== parsed.relay && !opts.previewOnly)
497
+ await app.saveAdmit(admitRelay(got.relay), inviteAdmitKey(parsed.secret));
498
+ await app.state.update("redeemed", (cur = {}) => {
499
+ const keep = Object.fromEntries(Object.entries(cur).filter(([, r]) => Date.now() - r.at < CODE_JOIN_RETENTION_MS));
500
+ return { next: { ...keep, [lid]: { lid, relay: got.relay, blob: got.blob, at: Date.now() } }, result: undefined };
501
+ });
502
+ }
503
+ let bundle;
504
+ try {
505
+ bundle = parseInviteBundle(openInviteBundle(parsed.secret, blob));
506
+ }
507
+ catch (e) {
508
+ await forgetRedeemed(app, lid);
509
+ throw e;
510
+ }
511
+ // Before an identity exists here, the inviter is found through the code's relay or the default relays.
512
+ // The inviter's document is fetched from the code's relay over HTTP: its name is checked where it resolves too.
513
+ // Guarded for the rest of this command even if it becomes this user's only relay below (a new identity).
514
+ if (parsed.relay && !allowPrivate && !codeRelayIsOwn)
515
+ app.guardRelays([parsed.relay]);
516
+ // The relays the invite inside names (the inviter's), dialed for its document and the accept: the same
517
+ // rule, under the same opt-in, before anything is shown or accepted.
518
+ // Refused here, the code stays kept on this device: the same command with the opt-in joins after all.
519
+ await guardForeignRelays(app, inviteRelays(bundle.invite), "inviter", allowPrivate, { code: true });
520
+ const first = await verifyInviteV3(bundle.invite, app.signerCtx(parsed.relay ? [parsed.relay] : defaults));
521
+ if (loaded && first.iss === app.userId)
522
+ throw new CliError("usage", "that is your own code");
523
+ if (loaded && first.aud !== "*" && first.aud !== app.userId) {
524
+ await forgetRedeemed(app, lid);
525
+ throw new CliError("not_for_you", `this code was made for someone else (${await app.addressOf(first.aud)}); nothing was accepted`);
526
+ }
527
+ // 2. Say what it offers, and have the person say yes once (or --yes): nothing is accepted before.
528
+ const heads = bundle.circle ? [bundle.circle.head, ...(bundle.circles ?? []).map((c) => c.head)] : [];
529
+ const offered = [];
530
+ const offeredHeads = [];
531
+ for (const [i, h] of heads.entries()) {
532
+ let pc;
533
+ try {
534
+ pc = await previewCircle(app, first.iss, h, i === 0 ? bundle.circle?.chain : undefined);
535
+ }
536
+ catch {
537
+ await forgetRedeemed(app, lid);
538
+ throw new CliError("code_invalid", "a circle in this code is malformed; nothing was accepted");
539
+ }
540
+ if (!offered.some((c) => c.cid === pc.cid)) {
541
+ offered.push(pc);
542
+ offeredHeads.push(h);
543
+ }
544
+ }
545
+ const preview = {
546
+ from: { userId: first.iss, address: await app.addressOf(first.iss), fingerprint: displayFingerprint(first.iss) },
547
+ to: first.aud === "*" ? null : first.aud,
548
+ ...(first.aud === "*" ? {} : { toAddress: await app.addressOf(first.aud) }),
549
+ circles: offered,
550
+ expiresAt: first.exp,
551
+ };
552
+ if (opts.previewOnly)
553
+ throw new CodePreviewReady(preview);
554
+ // A code for one person can't be for an identity not made yet: say so before making one (L4). The
555
+ // code stays kept here, so it still joins once that identity is set up on this device.
556
+ if (!loaded && first.aud !== "*") {
557
+ throw new CliError("not_for_you", `this code is for ${preview.toAddress}, and there is no identity here yet: a new one can't be them. Set up that identity here first, then run p2p join ${shown} again; nothing was accepted`, { preview });
558
+ }
559
+ if (!opts.yes && !opts.consent) {
560
+ if (!opts.confirm)
561
+ throw new CliError("confirm_required", `${previewText(preview)} Join with --yes (or run it in a terminal to be asked).`, { preview });
562
+ if (!(await opts.confirm(`${previewText(preview)}\nJoin?`))) {
563
+ throw new CliError("declined", `nothing was accepted. The code is kept here: \`p2p join ${shown}\` again joins after all (it no longer works for anyone else)`, { preview });
564
+ }
565
+ }
566
+ // 3. An identity, if there is none (lowest friction: the first command can be `p2p join`).
567
+ let created = null;
568
+ let relayWarning;
569
+ if (!loaded) {
570
+ // The default relays, or, with none, the code's relay alone, chosen by whoever made the code: never silently (review M1).
571
+ let relays;
572
+ if (defaults.length > 0)
573
+ relays = defaults;
574
+ else {
575
+ relays = [parsed.relay];
576
+ relayWarning = codeRelayPart(parsed.relay);
577
+ }
578
+ if (!opts.create)
579
+ throw new CliError("no_identity", "no identity here yet: run `p2p setup` first");
580
+ if (parsed.relay)
581
+ await app.saveAdmit(admitRelay(parsed.relay), inviteAdmitKey(parsed.secret));
582
+ created = await opts.create(app, { name: opts.name, relays });
583
+ if (relayWarning) {
584
+ app.warn(`Your only relay is ${relayWarning}, chosen by whoever gave you this code: it sees when you are online and could drop your mail. Add another with \`p2p relays add <wss://…>\`.`);
585
+ }
586
+ if (first.aud !== "*" && first.aud !== app.userId) {
587
+ await forgetRedeemed(app, lid);
588
+ throw new CliError("not_for_you", `this code was made for someone else (${await app.addressOf(first.aud)}); nothing was accepted`);
589
+ }
590
+ }
591
+ // 4. Accept: friends at once; the inviter's client adds us to each circle when it gets the accept.
592
+ const inv = inviteHashV3(bundle.invite);
593
+ let delivered = null;
594
+ const already = (await app.store.listFriendships()).find((f) => f.inv === inv);
595
+ if (!already) {
596
+ try {
597
+ delivered = (await accept(app, bundle.invite)).delivered;
598
+ }
599
+ catch (e) {
600
+ if (e instanceof CliError && e.code === "invite_predates_unfriend") {
601
+ // The code was single-use and its invite can never re-friend: say so, keep nothing.
602
+ await forgetRedeemed(app, lid);
603
+ throw new CliError(e.code, `${e.message} (this code is used up)`, e.extra);
604
+ }
605
+ if (!(e instanceof CliError && e.code === "undelivered"))
606
+ throw e;
607
+ delivered = e.extra.delivered ?? null;
608
+ app.warn(`the accept reached 0 relays: run \`p2p join ${shown}\` again later to resend it`);
609
+ await app.state.update("redeemed", (cur = {}) => (cur[lid] ? { next: { ...cur, [lid]: { ...cur[lid], undelivered: true } }, result: undefined } : { result: undefined }));
610
+ }
611
+ }
612
+ else if ((await app.state.get("redeemed"))?.[lid]?.undelivered) {
613
+ delivered = await app.deliver(first.iss, "contact", { own: app.userId, sid: "~contact" }, { text: already.proof.accept }, { extraCaps: first.cap ? [first.cap] : [] });
614
+ if (delivered.relays.length > 0) {
615
+ await app.state.update("redeemed", (cur = {}) => (cur[lid] ? { next: { ...cur, [lid]: { lid, relay: cur[lid].relay, blob: cur[lid].blob, at: cur[lid].at } }, result: undefined } : { result: undefined }));
616
+ }
617
+ }
618
+ const fromAddr = await app.addressOf(first.iss);
619
+ const circles = offered.length > 0 ? await joinCodeCircles(app, first.iss, lid, offeredHeads, offered, opts) : [];
620
+ return {
621
+ from: { userId: first.iss, address: fromAddr, fingerprint: displayFingerprint(first.iss) },
622
+ friend: { userId: first.iss, address: fromAddr },
623
+ delivered,
624
+ circle: circles[0] ?? null,
625
+ circles,
626
+ defaultCircle: app.self?.defaultCircle ?? null,
627
+ created,
628
+ ...(relayWarning ? { relayWarning } : {}),
629
+ };
630
+ }
631
+ /** A code as messages show it: rebuilt from its parsed parts, never the raw input (which may be anything pasted). */
632
+ export function shownCode(input) {
633
+ try {
634
+ return canonicalShortCode(parseShortCode(input, { allowPrivate: true }));
635
+ }
636
+ catch {
637
+ return "<code>";
638
+ }
639
+ }
640
+ /** joinCode with `previewOnly`: what the code offers (thrown so nothing after the preview can run). */
641
+ export class CodePreviewReady extends Error {
642
+ preview;
643
+ constructor(preview) {
644
+ super("preview");
645
+ this.preview = preview;
646
+ }
647
+ }
648
+ /** `p2p join --preview`: opens the code (kept here, used up on the relay) and says what it offers; accepts nothing. */
649
+ export async function previewCode(app, input, opts = {}) {
650
+ try {
651
+ await joinCode(app, input, { previewOnly: true, allowPrivateRelay: opts.allowPrivateRelay });
652
+ }
653
+ catch (e) {
654
+ if (e instanceof CodePreviewReady)
655
+ return e.preview;
656
+ throw e;
657
+ }
658
+ throw new CliError("internal", "no preview");
659
+ }
660
+ /** The relay as connections name it (the key of `admits`). */
661
+ function admitRelay(relay) {
662
+ try {
663
+ return normalizeRelays([relay])[0] ?? relay;
664
+ }
665
+ catch {
666
+ return relay;
667
+ }
668
+ }
669
+ async function forgetRedeemed(app, lid) {
670
+ await app.state.update("redeemed", (cur = {}) => {
671
+ if (!cur[lid])
672
+ return { result: undefined };
673
+ const { [lid]: _gone, ...rest } = cur;
674
+ return { next: rest, result: undefined };
675
+ });
676
+ }
677
+ function findCircleInvite(held, cid, inviter) {
678
+ return [...held].reverse().find((h) => h.type === "circle-invite" && h.cid === cid && h.from === inviter);
679
+ }
680
+ /**
681
+ * The circles a code joins: each one waits for the inviter's client to add us (it does when it gets the
682
+ * accept), all within one wait, then is joined under the §3.3 confirmation rules. Only the code's first
683
+ * circle may become the default circle, and only when there is none.
684
+ */
685
+ async function joinCodeCircles(app, inviter, lid, heads, offered, opts) {
686
+ const out = [];
687
+ for (const [i, headJws] of heads.entries()) {
688
+ const pc = offered[i];
689
+ const cid = pc.cid;
690
+ const rec = await app.store.getCircle(cid);
691
+ if (rec?.joinedByMe) {
692
+ out.push({ cid, name: pc.name, status: "already", default: app.self?.defaultCircle === cid });
693
+ continue;
694
+ }
695
+ // Never joined from the code (M1): its invite, if one comes, is a held item like any other.
696
+ if (!pc.auto) {
697
+ out.push({ cid, name: pc.name, status: "held", default: false, reason: autoRefusal(pc.note) });
698
+ continue;
699
+ }
700
+ // What the person said yes to: the join completes only for this circle, as it was shown.
701
+ const confirmed = { name: pc.name, policy: pc.policy, owner: pc.owner };
702
+ const entry = { cid, inviter, lid, head: headJws, at: Date.now(), confirmed, ...(i === 0 ? { first: true } : {}) };
703
+ await app.state.update("codeJoins", (cur = {}) => ({ next: { ...cur, [cid]: entry }, result: undefined }));
704
+ out.push({ entry });
705
+ }
706
+ const waiting = out.filter((x) => "entry" in x);
707
+ if (waiting.length > 0) {
708
+ const pool = await app.connect();
709
+ const deadline = Date.now() + (opts.waitSec ?? 15) * 1000;
710
+ for (;;) {
711
+ const held = (await app.state.get("held")) ?? [];
712
+ if (waiting.every((w) => findCircleInvite(held, w.entry.cid, inviter)) || Date.now() >= deadline)
713
+ break;
714
+ await pool.drain(Math.min(500, app.tun.drainQuietMs), Math.max(0, Math.min(2000, deadline - Date.now())));
715
+ }
716
+ }
717
+ const held = (await app.state.get("held")) ?? [];
718
+ const results = [];
719
+ for (const x of out) {
720
+ if (!("entry" in x)) {
721
+ results.push(x);
722
+ continue;
723
+ }
724
+ const item = findCircleInvite(held, x.entry.cid, inviter);
725
+ const name = x.entry.confirmed?.name ?? circleDisplayName(parseCircleVersion(x.entry.head));
726
+ // Finished meanwhile by a drain (finishCodeJoins runs after each one): joined, not pending.
727
+ if (!item && (await app.store.getCircle(x.entry.cid))?.joinedByMe)
728
+ results.push({ cid: x.entry.cid, name, status: "joined", default: app.self?.defaultCircle === x.entry.cid });
729
+ else if (!item)
730
+ results.push({ cid: x.entry.cid, name, status: "pending", default: false });
731
+ else
732
+ results.push(await completeCodeJoin(app, x.entry, item, { waitSec: opts.waitSec ?? 15, yes: opts.yes, confirm: opts.confirm }));
733
+ }
734
+ return results;
735
+ }
736
+ function autoRefusal(note) {
737
+ return note === "unverified"
738
+ ? "its version in the code isn't signed by the owner it names"
739
+ : note === "open"
740
+ ? "it is open"
741
+ : "whoever made the code is not its owner or an admin";
742
+ }
743
+ /**
744
+ * Why the circle that arrived can't be joined on the code's yes (M1), or undefined when it can: its
745
+ * chain must verify from version 1, and say what the person saw and said yes to (cid, name, policy,
746
+ * owner), with the inviter its owner or an admin, and the circle not open. A malicious inviter's code
747
+ * can claim anything; this is checked against the circle itself.
748
+ */
749
+ function codeJoinRefusal(entry, item) {
750
+ let h;
751
+ try {
752
+ h = CircleChain.bootstrap(item.chain?.length ? item.chain : [item.head], { head: item.head }).head;
753
+ }
754
+ catch (e) {
755
+ return `its chain doesn't verify (${e.message})`;
756
+ }
757
+ return codeHeadRefusal(entry, h);
758
+ }
759
+ /** The code-join rules on one verified head: the offered one, and again the one the join commits to. */
760
+ function codeHeadRefusal(entry, h) {
761
+ const want = entry.confirmed ?? (() => {
762
+ const v = parseCircleVersion(entry.head);
763
+ return { name: circleDisplayName(v), policy: circlePolicy(v), owner: v.owner };
764
+ })();
765
+ if (h.cid !== entry.cid)
766
+ return "it is another circle";
767
+ if (circlePolicy(h) === "open")
768
+ return "it is open";
769
+ if (h.owner !== entry.inviter && !h.admins.includes(entry.inviter))
770
+ return "whoever made the code is not its owner or an admin";
771
+ if (circleDisplayName(h) !== want.name || circlePolicy(h) !== want.policy || h.owner !== want.owner)
772
+ return "it isn't the circle you said yes to (its name, policy or owner differs)";
773
+ return undefined;
774
+ }
775
+ async function completeCodeJoin(app, entry, item, opts) {
776
+ const refused = codeJoinRefusal(entry, item);
777
+ if (refused) {
778
+ // Not joined, and not the default: the held invite stays for the person to approve on its own.
779
+ await app.state.update("codeJoins", (cur = {}) => {
780
+ const { [entry.cid]: _gone, ...rest } = cur;
781
+ return { next: rest, result: undefined };
782
+ });
783
+ return { cid: entry.cid, name: entry.confirmed?.name ?? circleDisplayName(parseCircleVersion(item.head)), status: "held", default: false, held: item.id, reason: refused };
784
+ }
785
+ const r = await joinCircle(app, { head: item.head, chain: item.chain, joins: item.joins, inviter: entry.inviter, accept: (h) => codeHeadRefusal(entry, h) }, opts);
786
+ const name = r.name;
787
+ if (r.status === "refused") {
788
+ // A newer chain from the members (open now, or another owner or name): not joined from the code.
789
+ await app.state.update("codeJoins", (cur = {}) => {
790
+ const { [entry.cid]: _gone, ...rest } = cur;
791
+ return { next: rest, result: undefined };
792
+ });
793
+ return { cid: entry.cid, name, status: "held", default: false, held: item.id, reason: r.refused };
794
+ }
795
+ if (r.status === "joined" || r.status === "already") {
796
+ await app.state.update("codeJoins", (cur = {}) => {
797
+ const { [entry.cid]: _gone, ...rest } = cur;
798
+ return { next: rest, result: undefined };
799
+ });
800
+ await dropHeld(app, (h) => h.id === item.id);
801
+ let isDefault = app.self?.defaultCircle === entry.cid;
802
+ // Never replaces a default circle; and sessions already running don't move into this one (sessions.ts).
803
+ // A code from before multi-circle codes has one circle, which counts as its first.
804
+ // The policy of the chain as joined and stored (never the offered head's): an open circle is never a code's default.
805
+ const joined = await loadCircle(app.store, entry.cid);
806
+ const open = !joined || circlePolicy(joined.chain.head) === "open" || r.policy === "open";
807
+ if (!app.self?.defaultCircle && entry.first !== false && !open) {
808
+ await setDefaultCircle(app, entry.cid, { byJoin: true });
809
+ isDefault = true;
810
+ }
811
+ return { cid: entry.cid, name, status: r.status, default: isDefault };
812
+ }
813
+ await app.state.update("codeJoins", (cur = {}) => (cur[entry.cid] ? { next: { ...cur, [entry.cid]: { ...cur[entry.cid], needsApproval: item.id } }, result: undefined } : { result: undefined }));
814
+ return { cid: entry.cid, name, status: "needs-approval", default: false, held: item.id };
815
+ }
816
+ let finishing = false;
817
+ /**
818
+ * After a drain (App.afterDrain): finishes code joins whose circle has
819
+ * arrived since `p2p join` returned. Joins that need the user's say stay
820
+ * held (`p2p held approve`).
821
+ */
822
+ export async function finishCodeJoins(app) {
823
+ if (finishing || !app.keys)
824
+ return [];
825
+ finishing = true;
826
+ try {
827
+ const all = (await app.state.get("codeJoins")) ?? {};
828
+ const held = (await app.state.get("held")) ?? [];
829
+ const events = [];
830
+ for (const entry of Object.values(all)) {
831
+ if (Date.now() - entry.at > CODE_JOIN_RETENTION_MS || (await app.store.getCircle(entry.cid))?.joinedByMe) {
832
+ await app.state.update("codeJoins", (cur = {}) => {
833
+ const { [entry.cid]: _gone, ...rest } = cur;
834
+ return { next: rest, result: undefined };
835
+ });
836
+ continue;
837
+ }
838
+ if (entry.needsApproval)
839
+ continue;
840
+ const item = findCircleInvite(held, entry.cid, entry.inviter);
841
+ if (!item)
842
+ continue;
843
+ try {
844
+ const r = await completeCodeJoin(app, entry, item, { waitSec: 5 });
845
+ if (r.status === "joined")
846
+ app.io.err(`joined "${r.name}" (from your code join)${r.default ? "; it is your default circle" : ""}`);
847
+ else if (r.status === "needs-approval")
848
+ app.io.err(`"${r.name}" couldn't be confirmed with a second member: \`p2p held approve ${r.held}\` to join anyway`);
849
+ else if (r.status === "held")
850
+ app.io.err(`"${r.name}" wasn't joined from your code (${r.reason}): \`p2p held approve ${r.held}\` joins it, if you want it`);
851
+ events.push(makeEvent(`code-join|${entry.cid}|${entry.lid}`, "p2p.circle", Math.floor(Date.now()), { event: r.status === "joined" ? "code-joined" : "code-join-held", cid: entry.cid, name: r.name, ...(r.reason ? { reason: r.reason } : {}) }));
852
+ }
853
+ catch (e) {
854
+ app.io.err(`couldn't finish joining ${entry.cid}: ${e.message}`);
855
+ }
856
+ }
857
+ if (events.length)
858
+ await app.state.addEvents(events);
859
+ return events;
860
+ }
861
+ finally {
862
+ finishing = false;
863
+ }
864
+ }
865
+ export async function listCodes(app) {
866
+ let pool;
867
+ try {
868
+ pool = await app.connectAndDrain();
869
+ }
870
+ catch (e) {
871
+ app.io.err(`p2p: offline: ${e.message}`);
872
+ }
873
+ const all = Object.values(pruneCodes((await app.state.get("codes")) ?? {}));
874
+ const now = nowSec();
875
+ const onRelay = new Map();
876
+ for (const r of new Set(all.filter((c) => c.status === "open" && c.exp > now).map((c) => c.relay))) {
877
+ try {
878
+ const l = pool ? await inviteList(await pool.ensure(r)) : undefined;
879
+ onRelay.set(r, l ? { lids: new Set(l.lids), evicted: new Set(l.evicted) } : undefined);
880
+ }
881
+ catch {
882
+ onRelay.set(r, undefined);
883
+ }
884
+ }
885
+ const rows = [];
886
+ for (const c of all.sort((a, b) => b.createdAt - a.createdAt)) {
887
+ let status = c.status;
888
+ if (c.status === "open") {
889
+ if (c.exp <= now)
890
+ status = "expired";
891
+ else {
892
+ const on = onRelay.get(c.relay);
893
+ if (on?.evicted.has(c.lid))
894
+ status = "evicted";
895
+ else if (on && !on.lids.has(c.lid))
896
+ status = "taken";
897
+ }
898
+ }
899
+ const circles = [];
900
+ for (const cid of c.cids ?? (c.cid ? [c.cid] : [])) {
901
+ const lc = await loadCircle(app.store, cid);
902
+ circles.push({ cid, name: lc ? circleDisplayName(lc.chain.head) : cid });
903
+ }
904
+ const circle = circles[0] ?? null;
905
+ rows.push({
906
+ code: c.short,
907
+ label: c.label ?? null,
908
+ to: c.aud === "*" ? null : { userId: c.aud, address: await app.addressOf(c.aud) },
909
+ circle,
910
+ circles,
911
+ createdAt: c.createdAt,
912
+ exp: c.exp,
913
+ status,
914
+ ...(c.redeemedBy ? { redeemedBy: { userId: c.redeemedBy, address: await app.addressOf(c.redeemedBy) } } : {}),
915
+ ...(c.redeemedAt ? { redeemedAt: c.redeemedAt } : {}),
916
+ });
917
+ }
918
+ return rows;
919
+ }
920
+ /** A full code (with or without its relay part), or a unique prefix of at least 4 of its characters. */
921
+ async function findCode(app, input) {
922
+ const all = Object.values((await app.state.get("codes")) ?? {});
923
+ const t = input.trim();
924
+ const last = t.slice(t.lastIndexOf("/") + 1);
925
+ const s = decodeCodeChars(last);
926
+ if (s) {
927
+ const lid = inviteLid(s);
928
+ const hit = all.find((c) => c.lid === lid);
929
+ if (hit)
930
+ return hit;
931
+ }
932
+ const norm = (x) => x.toUpperCase().replace(/[\s-]/g, "").replace(/O/g, "0").replace(/[IL]/g, "1").replace(/…$/, "");
933
+ const want = norm(last);
934
+ if (want.length < 4)
935
+ throw new CliError("not_found", `no code ${input} (give the code, or at least its first 4 characters; see \`p2p invites\`)`);
936
+ const hits = all.filter((c) => norm(c.code).startsWith(want));
937
+ if (hits.length > 1)
938
+ throw new CliError("ambiguous", `${input} matches ${hits.length} codes: give more of it`);
939
+ if (hits.length === 0)
940
+ throw new CliError("not_found", `no code ${input} (see \`p2p invites\`)`);
941
+ return hits[0];
942
+ }
943
+ export async function revokeCode(app, input) {
944
+ const rec = await findCode(app, input);
945
+ if (rec.status === "revoked")
946
+ return { code: rec.short, revoked: true, wasOpen: false, redeemedBy: null };
947
+ const pool = await app.connect({ allowNone: true });
948
+ let wasOpen = false;
949
+ try {
950
+ wasOpen = await inviteDel(await pool.ensure(rec.relay), rec.lid);
951
+ }
952
+ catch (e) {
953
+ app.warn(`couldn't reach ${rec.relay} to delete the code (${e.message}); it is refused here anyway`);
954
+ }
955
+ if (rec.capid) {
956
+ const caps = (await app.store.listCapsIssued()).filter((c) => c.capid === rec.capid);
957
+ await app.revokeCaps(caps).catch(() => 0);
958
+ }
959
+ const updated = { ...rec, status: rec.status === "redeemed" ? "redeemed" : "revoked" };
960
+ if (rec.status !== "redeemed") {
961
+ await app.state.update("codes", (cur = {}) => ({ next: { ...cur, [rec.lid]: updated }, result: undefined }));
962
+ await sendSync(app, { codes: [updated] });
963
+ }
964
+ if (rec.status === "redeemed")
965
+ app.warn(`${codeHint(rec.code)} was already redeemed by ${await app.addressOf(rec.redeemedBy)}: \`p2p remove ${rec.redeemedBy}\` undoes that`);
966
+ return { code: rec.short, revoked: rec.status !== "redeemed", wasOpen, redeemedBy: rec.redeemedBy ?? null };
967
+ }
968
+ /** Undoes a code redemption: unfriends `who` and takes them out of the circles our codes added them to. */
969
+ export async function removeUser(app, who) {
970
+ const u = await app.resolveUser(who);
971
+ if (!isUserId(u) || u === app.userId)
972
+ throw new CliError("usage", "name someone else");
973
+ await app.connectAndDrain();
974
+ const recs = Object.values((await app.state.get("codes")) ?? {}).filter((c) => c.redeemedBy === u);
975
+ const circles = [];
976
+ // Only the circles a code put them in (L3); a record from before `added` was kept: every circle it named.
977
+ for (const cid of new Set(recs.flatMap((c) => c.added ?? c.cids ?? (c.cid ? [c.cid] : [])))) {
978
+ circles.push({ cid, result: await removeMember(app, cid, u) });
979
+ }
980
+ let unfriended = false;
981
+ try {
982
+ await unfriend(app, u);
983
+ unfriended = true;
984
+ }
985
+ catch (e) {
986
+ if (!(e instanceof CliError && e.code === "not_friends"))
987
+ throw e;
988
+ }
989
+ const at = nowSec();
990
+ const changed = recs.map((c) => ({ ...c, removedAt: at }));
991
+ if (changed.length) {
992
+ await app.state.update("codes", (cur = {}) => ({ next: { ...cur, ...Object.fromEntries(changed.map((c) => [c.lid, c])) }, result: undefined }));
993
+ await sendSync(app, { codes: changed });
994
+ }
995
+ if (!unfriended && circles.length === 0)
996
+ throw new CliError("not_found", `${await app.addressOf(u)} is neither a friend nor in a circle one of your codes added them to`);
997
+ return { removed: u, address: await app.addressOf(u), unfriended, circles };
998
+ }