@peer2peer/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +370 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +368 -0
  6. package/dist/app.js +1181 -0
  7. package/dist/bin.d.ts +2 -0
  8. package/dist/bin.js +56 -0
  9. package/dist/circle-ops.d.ts +402 -0
  10. package/dist/circle-ops.js +1725 -0
  11. package/dist/cli.d.ts +660 -0
  12. package/dist/cli.js +1787 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +159 -0
  16. package/dist/config.js +294 -0
  17. package/dist/doctor.d.ts +113 -0
  18. package/dist/doctor.js +930 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +38 -0
  22. package/dist/ext-host.js +293 -0
  23. package/dist/extensions.d.ts +487 -0
  24. package/dist/extensions.js +406 -0
  25. package/dist/features.d.ts +91 -0
  26. package/dist/features.js +164 -0
  27. package/dist/format.d.ts +57 -0
  28. package/dist/format.js +248 -0
  29. package/dist/graph-memory.d.ts +107 -0
  30. package/dist/graph-memory.js +393 -0
  31. package/dist/history.d.ts +155 -0
  32. package/dist/history.js +697 -0
  33. package/dist/identity.d.ts +239 -0
  34. package/dist/identity.js +759 -0
  35. package/dist/inbound.d.ts +32 -0
  36. package/dist/inbound.js +261 -0
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.js +14 -0
  39. package/dist/ix-local.d.ts +76 -0
  40. package/dist/ix-local.js +203 -0
  41. package/dist/join-answers.d.ts +49 -0
  42. package/dist/join-answers.js +149 -0
  43. package/dist/outbox.d.ts +109 -0
  44. package/dist/outbox.js +337 -0
  45. package/dist/pretty.d.ts +100 -0
  46. package/dist/pretty.js +256 -0
  47. package/dist/procstart.d.ts +1 -0
  48. package/dist/procstart.js +66 -0
  49. package/dist/progress.d.ts +30 -0
  50. package/dist/progress.js +78 -0
  51. package/dist/projects.d.ts +491 -0
  52. package/dist/projects.js +1383 -0
  53. package/dist/prompt/picker.d.ts +64 -0
  54. package/dist/prompt/picker.js +152 -0
  55. package/dist/prompt/tty.d.ts +29 -0
  56. package/dist/prompt/tty.js +122 -0
  57. package/dist/readonly.d.ts +20 -0
  58. package/dist/readonly.js +50 -0
  59. package/dist/receipts.d.ts +99 -0
  60. package/dist/receipts.js +182 -0
  61. package/dist/relay-client.d.ts +277 -0
  62. package/dist/relay-client.js +873 -0
  63. package/dist/relay-info.d.ts +24 -0
  64. package/dist/relay-info.js +53 -0
  65. package/dist/rotation.d.ts +402 -0
  66. package/dist/rotation.js +2054 -0
  67. package/dist/running.d.ts +5 -0
  68. package/dist/running.js +74 -0
  69. package/dist/sessions.d.ts +355 -0
  70. package/dist/sessions.js +1247 -0
  71. package/dist/shortcode.d.ts +149 -0
  72. package/dist/shortcode.js +465 -0
  73. package/dist/social.d.ts +139 -0
  74. package/dist/social.js +485 -0
  75. package/dist/state.d.ts +509 -0
  76. package/dist/state.js +220 -0
  77. package/dist/stdin.d.ts +17 -0
  78. package/dist/stdin.js +46 -0
  79. package/dist/sync.d.ts +77 -0
  80. package/dist/sync.js +375 -0
  81. package/dist/transient.d.ts +1 -0
  82. package/dist/transient.js +28 -0
  83. package/dist/trust.d.ts +37 -0
  84. package/dist/trust.js +134 -0
  85. package/dist/tty-confirm.d.ts +2 -0
  86. package/dist/tty-confirm.js +53 -0
  87. package/dist/tui/command.d.ts +20 -0
  88. package/dist/tui/command.js +70 -0
  89. package/dist/tui/frame.d.ts +43 -0
  90. package/dist/tui/frame.js +111 -0
  91. package/dist/tui/model.d.ts +221 -0
  92. package/dist/tui/model.js +259 -0
  93. package/dist/tui/sanitize.d.ts +13 -0
  94. package/dist/tui/sanitize.js +151 -0
  95. package/dist/tui/terminal.d.ts +88 -0
  96. package/dist/tui/terminal.js +354 -0
  97. package/dist/tui/tui.d.ts +78 -0
  98. package/dist/tui/tui.js +612 -0
  99. package/dist/tui/view.d.ts +4 -0
  100. package/dist/tui/view.js +358 -0
  101. package/dist/unknown-kinds.d.ts +12 -0
  102. package/dist/unknown-kinds.js +66 -0
  103. package/dist/version.d.ts +1 -0
  104. package/dist/version.js +5 -0
  105. package/dist/want-pow.d.ts +12 -0
  106. package/dist/want-pow.js +46 -0
  107. package/dist/watch.d.ts +35 -0
  108. package/dist/watch.js +331 -0
  109. package/dist/xstate.d.ts +125 -0
  110. package/dist/xstate.js +422 -0
  111. package/package.json +60 -4
@@ -0,0 +1,149 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // What a joiner holds of each confirmer's answer to its `want` (§3.3), while
4
+ // the answer arrives in parts. One document per (circle, confirmer), so a part
5
+ // rewrites only its sender's document, never the joins index. Bounded and
6
+ // filtered as it comes in (review M4): only versions of the circle being
7
+ // joined, at most MAX_NEWER_VERSIONS above the offered head, at most two per
8
+ // `ver`, each at most a JWS's 16 KiB; at most a few statements per member; at
9
+ // most 8 answers' part records; and a byte ceiling per confirmer. Anything
10
+ // beyond is dropped. (Versions newer than the offered head are kept, within
11
+ // that margin: the join confirms the newest head the members send, review M3.)
12
+ import { createHash } from "node:crypto";
13
+ import { decodeTyped, MAX_CHAIN_IN_BUNDLE, MAX_JWS_BYTES, parseCircleVersion, TYP3 } from "@peer2peer/core/v3";
14
+ /** Distinct versions kept per `ver` (a sibling, at most: more is someone else's noise). */
15
+ export const MAX_VERSIONS_PER_VER = 2;
16
+ /** Versions above the offered head kept per confirmer: a link can be older than the circle's head. */
17
+ export const MAX_NEWER_VERSIONS = 256;
18
+ /**
19
+ * Answers a member sends one asker per rolling hour, and so the new answers (part ids) a joiner
20
+ * takes from one confirmer per rolling hour: one limit on both sides (review N-D; the joiner took 4
21
+ * while a member may send 10, so a legitimate fifth answer was dropped). Parts of answers already
22
+ * tracked always count.
23
+ */
24
+ export const ANSWERS_PER_HOUR = 10;
25
+ export const MAX_NEW_ANSWERS_PER_HOUR = ANSWERS_PER_HOUR;
26
+ /** Answers whose parts are tracked per confirmer (the newest): more than a confirmer may start in an hour. */
27
+ export const MAX_PART_RECORDS = ANSWERS_PER_HOUR + 2;
28
+ /** A statement for `cid` (a `p2p-join+jws` naming it), parsed before it is stored (review F4). */
29
+ function isStatementFor(j, cid) {
30
+ if (typeof j !== "string" || j.length > MAX_JWS_BYTES)
31
+ return false;
32
+ try {
33
+ return decodeTyped(j, TYP3.join).payload.cid === cid;
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
39
+ /**
40
+ * The fixed ceiling on what one confirmer's answer may take, whatever the offered head claims
41
+ * (re-review N1: the head comes from a link, unverified, so whoever writes the link must not set
42
+ * the ceiling).
43
+ */
44
+ export const ANSWER_MAX_BYTES = 32 * 1024 * 1024;
45
+ /** The highest `ver` kept: no chain longer than a bundle may carry is bootstrapped (MAX_CHAIN_IN_BUNDLE). */
46
+ export function maxVerFor(offeredVer) {
47
+ return Math.min(Math.min(offeredVer, MAX_CHAIN_IN_BUNDLE) + MAX_NEWER_VERSIONS, MAX_CHAIN_IN_BUNDLE);
48
+ }
49
+ /**
50
+ * A confirmer's byte ceiling: two full versions per `ver` up to the (clamped) offered head, plus 4
51
+ * statements per member of 16 KiB, never more than ANSWER_MAX_BYTES.
52
+ */
53
+ export function answerByteCap(offeredVer, members) {
54
+ const vers = Math.min(Math.max(0, offeredVer), MAX_CHAIN_IN_BUNDLE);
55
+ const m = Math.min(Math.max(0, members), MAX_CHAIN_IN_BUNDLE);
56
+ return Math.min(ANSWER_MAX_BYTES, vers * MAX_VERSIONS_PER_VER * MAX_JWS_BYTES + (m + 4) * 4 * MAX_JWS_BYTES);
57
+ }
58
+ export const answerDocName = (cid, from) => `joinans-${createHash("sha256").update(`${cid}|${from}`).digest("hex").slice(0, 16)}`;
59
+ /**
60
+ * Adds what one envelope brought to `from`'s answer for `cid`, within the bounds above. Returns
61
+ * whether anything was kept.
62
+ */
63
+ export async function addToAnswer(app, cid, from, bound, versions, joins, part) {
64
+ const maxVer = maxVerFor(bound.offeredVer);
65
+ const cap = answerByteCap(maxVer, bound.members);
66
+ // Parsing is outside the lock: only what fits the circle and the offered head goes further.
67
+ const fit = [];
68
+ let top = 0;
69
+ for (const v of versions) {
70
+ if (typeof v !== "string" || v.length > MAX_JWS_BYTES)
71
+ continue;
72
+ try {
73
+ const p = parseCircleVersion(v);
74
+ if (p.cid !== cid || p.ver > maxVer)
75
+ continue;
76
+ fit.push({ jws: v, ver: p.ver });
77
+ if (p.ver > top)
78
+ top = p.ver;
79
+ }
80
+ catch {
81
+ // not a version
82
+ }
83
+ }
84
+ const stmts = joins.filter((j) => isStatementFor(j, cid));
85
+ await app.state.updateDoc(answerDocName(cid, from), (cur) => {
86
+ const doc = cur && cur.cid === cid && cur.from === from ? cur : { cid, from, versions: [], joins: [], parts: {}, bytes: 0 };
87
+ const have = new Set(doc.versions);
88
+ const perVer = new Map();
89
+ for (const v of doc.versions) {
90
+ try {
91
+ const ver = parseCircleVersion(v).ver;
92
+ perVer.set(ver, (perVer.get(ver) ?? 0) + 1);
93
+ }
94
+ catch {
95
+ // kept versions parse
96
+ }
97
+ }
98
+ let changed = false;
99
+ let bytes = doc.bytes;
100
+ const versionsNext = [...doc.versions];
101
+ for (const f of fit) {
102
+ if (have.has(f.jws) || (perVer.get(f.ver) ?? 0) >= MAX_VERSIONS_PER_VER || bytes + f.jws.length > cap)
103
+ continue;
104
+ have.add(f.jws);
105
+ perVer.set(f.ver, (perVer.get(f.ver) ?? 0) + 1);
106
+ versionsNext.push(f.jws);
107
+ bytes += f.jws.length;
108
+ changed = true;
109
+ }
110
+ const haveJ = new Set(doc.joins);
111
+ const joinsNext = [...doc.joins];
112
+ const maxJoins = (bound.members + 4) * 4;
113
+ for (const j of stmts) {
114
+ if (haveJ.has(j) || joinsNext.length >= maxJoins || bytes + j.length > cap)
115
+ continue;
116
+ haveJ.add(j);
117
+ joinsNext.push(j);
118
+ bytes += j.length;
119
+ changed = true;
120
+ }
121
+ let parts = doc.parts;
122
+ const now = Date.now();
123
+ const newIds = Object.values(parts).filter((r) => r.at !== undefined && now - r.at < 3_600_000).length;
124
+ // review F4: a new answer id is taken only while the confirmer hasn't started too many this hour.
125
+ if (part && (parts[part.id] !== undefined || newIds < MAX_NEW_ANSWERS_PER_HOUR)) {
126
+ const r = parts[part.id] ?? { n: part.n, got: [], top: 0, at: now };
127
+ if (r.n === part.n && !r.got.includes(part.i)) {
128
+ parts = { ...parts, [part.id]: { ...r, got: [...r.got, part.i], top: Math.max(r.top, top) } };
129
+ changed = true;
130
+ const ids = Object.keys(parts);
131
+ // The newest records only (insertion order): an asker who re-asks often can't grow this.
132
+ if (ids.length > MAX_PART_RECORDS)
133
+ parts = Object.fromEntries(ids.slice(-MAX_PART_RECORDS).map((k) => [k, parts[k]]));
134
+ }
135
+ }
136
+ // Re-review N5: a part that adds nothing (a duplicate, or all of it over a bound) writes nothing.
137
+ if (!changed && cur)
138
+ return { result: undefined };
139
+ return { next: { cid, from, versions: versionsNext, joins: joinsNext, parts, bytes }, result: undefined };
140
+ });
141
+ }
142
+ export async function readAnswer(app, cid, from) {
143
+ const d = await app.state.getDoc(answerDocName(cid, from));
144
+ return d && d.cid === cid && d.from === from ? d : undefined;
145
+ }
146
+ export async function dropAnswers(app, cid, froms) {
147
+ for (const f of froms)
148
+ await app.state.removeDoc(answerDocName(cid, f)).catch(() => undefined);
149
+ }
@@ -0,0 +1,109 @@
1
+ import { type App } from "./app.js";
2
+ export declare const OUTBOX_TTL_MS: number;
3
+ export declare const OUTBOX_PER_RECIPIENT = 10;
4
+ export declare const OUTBOX_MAX = 200;
5
+ export declare const OUTBOX_MAX_BYTES: number;
6
+ export declare const OUTBOX_RETRY_MS = 15000;
7
+ export declare const OUTBOX_RETRY_MAX_MS: number;
8
+ export declare const OUTBOX_RECIPIENT_BYTES: number;
9
+ /** Answered refusals: a relay that took the request and said no. Only these expire an item early (P3). */
10
+ export declare const OUTBOX_ANSWERED: Set<string>;
11
+ /**
12
+ * A recipient's share (pre-release re-review P4): 1/20 of the items and bytes, halved while the outbox is
13
+ * more than half full, so twenty recipients can always queue and no one of them can fill it.
14
+ */
15
+ export declare function recipientShare(items: number, bytes: number): {
16
+ items: number;
17
+ bytes: number;
18
+ };
19
+ /** Seqs the session may move past a queued envelope before it is given up: REPLAY_WINDOW less a margin. */
20
+ export declare const OUTBOX_WINDOW: number;
21
+ /** Retryable failures in a row, while our own relays work, before an item is expired early. */
22
+ export declare const OUTBOX_STUCK_MS = 3600000;
23
+ /** Relay and connection failures that a later attempt can get past; anything else is final. */
24
+ export declare const OUTBOX_RETRYABLE: Set<string>;
25
+ export interface OutboxItem {
26
+ /** SHA-256 of the envelope (one item per sealed copy). */
27
+ id: string;
28
+ to: string;
29
+ tdid: string;
30
+ kind: string;
31
+ env: string;
32
+ targets: {
33
+ relay: string;
34
+ cap?: string;
35
+ }[];
36
+ /** Where it goes and who wrote it, for the events about it. */
37
+ dest: {
38
+ userId: string;
39
+ address: string;
40
+ own: string;
41
+ sid: string;
42
+ ref: string;
43
+ };
44
+ fromSession: string;
45
+ queuedAt: number;
46
+ expiresAt: number;
47
+ tries: number;
48
+ nextAt: number;
49
+ /** The seq it was sealed with, for the replay window check. */
50
+ seq?: number;
51
+ /** When its run of retryable failures (with this device online) started. */
52
+ failingSince?: number;
53
+ }
54
+ export interface OutboxDoc {
55
+ items: OutboxItem[];
56
+ }
57
+ /** Every copy failed only for reasons a retry can get past (and at least one copy was sealed). */
58
+ export declare function retryable(unsent: readonly {
59
+ codes: readonly string[];
60
+ }[]): boolean;
61
+ /** Queues sealed copies; refuses (outbox_full) when a cap would be passed. Returns when they expire. */
62
+ export declare function enqueue(app: App, copies: readonly {
63
+ did: string;
64
+ env: string;
65
+ targets: {
66
+ relay: string;
67
+ cap?: string;
68
+ }[];
69
+ }[], meta: {
70
+ kind: string;
71
+ dest: OutboxItem["dest"];
72
+ fromSession: string;
73
+ }, now?: number): Promise<{
74
+ expiresAt: number;
75
+ queued: number;
76
+ }>;
77
+ export declare function outboxCount(app: App): Promise<number>;
78
+ /**
79
+ * Sends the due items (all of them with `force`) over the connected pool. Each is claimed under
80
+ * the state lock first (its next attempt moved on), so two processes don't send it at once;
81
+ * a second copy would be harmless anyway (the same envelope). Returns how many went out.
82
+ */
83
+ export declare function flushOutbox(app: App, opts?: {
84
+ force?: boolean;
85
+ now?: number;
86
+ }): Promise<{
87
+ sent: number;
88
+ expired: number;
89
+ failed: number;
90
+ }>;
91
+ /** One round's identity views, by recipient (P5): refreshed once, shared by all their items. */
92
+ export type RoundViews = Map<string, Promise<{
93
+ view: Awaited<ReturnType<App["view"]>>;
94
+ fresh: boolean;
95
+ }>>;
96
+ /**
97
+ * O1: may this queued copy still go out, and over which relays? "refused" when not: the
98
+ * recipient blocked; for their session, no longer a friend or co-member; for one of ours, no
99
+ * longer on its roster; the device no longer on their current document; or their identity rotated.
100
+ * "later" (P1) when that can't be told this round: the document couldn't be refreshed and the one
101
+ * held is past its freshness bound. The relays (P2) are those of their current document, then the
102
+ * ones it was sealed for, each with a cap of this moment.
103
+ */
104
+ export declare function stillAllowed(app: App, item: OutboxItem, views?: RoundViews): Promise<{
105
+ targets: {
106
+ relay: string;
107
+ cap?: string;
108
+ }[];
109
+ } | "refused" | "later">;
package/dist/outbox.js ADDED
@@ -0,0 +1,337 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // The sender's outbox: messages no relay accepted when they were sent (this device's network was
4
+ // down, or every relay of the recipient was unreachable). Relays store ciphertext for 7 days; this
5
+ // is the same promise on the sender's side, so a message written during a dropped connection is
6
+ // not simply lost.
7
+ //
8
+ // - What is kept is the sealed envelope itself, never the intent: a retry sends the same bytes,
9
+ // so if a relay did store an earlier copy (its answer was lost) the recipient's replay window
10
+ // drops the second one. No retry can deliver a message twice.
11
+ // - It lives in the p2p home's state (`<home>/cli/outbox.json`, 0600, under the state lock),
12
+ // next to the caps it was sealed with, which are held in the trust store already.
13
+ // - `p2p watch` retries due items with backoff (OUTBOX_RETRY_MS doubling, at most
14
+ // OUTBOX_RETRY_MAX_MS); a send from this device sends due ones too.
15
+ // - An item expires OUTBOX_TTL_MS after it was sealed: a recipient refuses an envelope whose ts
16
+ // is more than 7 days old anyway. Expired, delivered and refused items leave a `p2p.outbox`
17
+ // event for the session that wrote them (data only: state, recipient, when it was queued).
18
+ // - Bounded: OUTBOX_PER_RECIPIENT items per recipient, OUTBOX_MAX in all, OUTBOX_MAX_BYTES of
19
+ // envelopes (OUTBOX_RECIPIENT_BYTES per recipient); a send past a cap is refused
20
+ // (outbox_full), never queued by dropping another.
21
+ // - Re-checked before every retry (pre-release review O1): a recipient blocked or no longer a friend or
22
+ // co-member (or, for one of our own sessions, no longer on its roster), a device no longer on
23
+ // their current identity document (refreshed when older than the usual bound), or an identity
24
+ // that rotated: dropped as `refused`, never sent. Caps are taken fresh, not as sealed.
25
+ // - Inside the replay window (O2): a recipient drops an envelope more than REPLAY_WINDOW seqs
26
+ // below the highest it has seen from this device in that session. One that this device's seq
27
+ // for the session has passed by more than OUTBOX_WINDOW is refused at queue time
28
+ // (outbox_window) and dropped as `expired` at flush time, never reported delivered.
29
+ // - Fair (O5): one recipient can't hold the outbox. It has at most 1/10 of the items and 1/8 of
30
+ // the bytes; a flush stops at a recipient's first retryable failure (one slow timeout per
31
+ // recipient per round, not twenty); and items that have failed for OUTBOX_STUCK_MS straight
32
+ // while this device's own relays answered are expired early: their relays answer but refuse.
33
+ import { createHash } from "node:crypto";
34
+ import { CircleChain, decodeEnvelopeV3, liveFriendshipsV3, REPLAY_WINDOW } from "@peer2peer/core/v3";
35
+ import { orderRelays } from "./app.js";
36
+ import { CliError } from "./errors.js";
37
+ import { makeEvent } from "./inbound.js";
38
+ import { sessKey } from "./state.js";
39
+ import { getSession, mayReach, rosterAudience } from "./sessions.js";
40
+ export const OUTBOX_TTL_MS = 7 * 24 * 3600 * 1000;
41
+ export const OUTBOX_PER_RECIPIENT = 10;
42
+ export const OUTBOX_MAX = 200;
43
+ export const OUTBOX_MAX_BYTES = 4 * 1024 * 1024;
44
+ export const OUTBOX_RETRY_MS = 15_000;
45
+ export const OUTBOX_RETRY_MAX_MS = 30 * 60_000;
46
+ export const OUTBOX_RECIPIENT_BYTES = OUTBOX_MAX_BYTES / 20;
47
+ /** Answered refusals: a relay that took the request and said no. Only these expire an item early (P3). */
48
+ export const OUTBOX_ANSWERED = new Set(["relay-error", "rate-limited"]);
49
+ /**
50
+ * A recipient's share (pre-release re-review P4): 1/20 of the items and bytes, halved while the outbox is
51
+ * more than half full, so twenty recipients can always queue and no one of them can fill it.
52
+ */
53
+ export function recipientShare(items, bytes) {
54
+ const crowded = items > OUTBOX_MAX / 2 || bytes > OUTBOX_MAX_BYTES / 2;
55
+ return crowded ? { items: OUTBOX_PER_RECIPIENT / 2, bytes: OUTBOX_RECIPIENT_BYTES / 2 } : { items: OUTBOX_PER_RECIPIENT, bytes: OUTBOX_RECIPIENT_BYTES };
56
+ }
57
+ /** Seqs the session may move past a queued envelope before it is given up: REPLAY_WINDOW less a margin. */
58
+ export const OUTBOX_WINDOW = REPLAY_WINDOW - 64;
59
+ /** Retryable failures in a row, while our own relays work, before an item is expired early. */
60
+ export const OUTBOX_STUCK_MS = 3600_000;
61
+ /** Relay and connection failures that a later attempt can get past; anything else is final. */
62
+ export const OUTBOX_RETRYABLE = new Set(["network", "timeout", "unreachable", "no_relay", "closing", "rate-limited", "relay-error"]);
63
+ /** Every copy failed only for reasons a retry can get past (and at least one copy was sealed). */
64
+ export function retryable(unsent) {
65
+ return unsent.length > 0 && unsent.every((u) => u.codes.every((c) => OUTBOX_RETRYABLE.has(c)));
66
+ }
67
+ const backoff = (tries) => Math.min(OUTBOX_RETRY_MAX_MS, OUTBOX_RETRY_MS * 2 ** Math.max(0, tries - 1));
68
+ /** Queues sealed copies; refuses (outbox_full) when a cap would be passed. Returns when they expire. */
69
+ export async function enqueue(app, copies, meta, now = Date.now()) {
70
+ const expiresAt = now + OUTBOX_TTL_MS;
71
+ const seqOf = (env) => {
72
+ try {
73
+ return decodeEnvelopeV3(env).payload.seq;
74
+ }
75
+ catch {
76
+ return undefined;
77
+ }
78
+ };
79
+ const counter = (await app.state.get("seq"))?.[sessKey(meta.dest.own, meta.dest.sid)];
80
+ for (const c of copies) {
81
+ const q = seqOf(c.env);
82
+ if (q !== undefined && counter !== undefined && counter - q > OUTBOX_WINDOW) {
83
+ throw new CliError("outbox_window", `this session has sent ${counter - q} envelopes since this one was sealed; a recipient would drop it as too old (it keeps the last ${REPLAY_WINDOW}): not queued`, { delivered: false });
84
+ }
85
+ }
86
+ const fresh = copies.map((c) => ({
87
+ id: createHash("sha256").update(c.env).digest("base64url"),
88
+ to: meta.dest.userId,
89
+ tdid: c.did,
90
+ kind: meta.kind,
91
+ env: c.env,
92
+ targets: c.targets.map((t) => ({ relay: t.relay, ...(t.cap ? { cap: t.cap } : {}) })),
93
+ dest: meta.dest,
94
+ fromSession: meta.fromSession,
95
+ queuedAt: now,
96
+ expiresAt,
97
+ tries: 0,
98
+ nextAt: now + OUTBOX_RETRY_MS,
99
+ ...(seqOf(c.env) !== undefined ? { seq: seqOf(c.env) } : {}),
100
+ }));
101
+ await app.state.update("outbox", (cur = { items: [] }) => {
102
+ const items = cur.items.filter((i) => i.expiresAt > now);
103
+ const ids = new Set(items.map((i) => i.id));
104
+ const add = fresh.filter((i) => !ids.has(i.id));
105
+ const theirs = items.filter((i) => i.to === meta.dest.userId);
106
+ const addBytes = add.reduce((t, i) => t + i.env.length, 0);
107
+ const bytes = items.reduce((t, i) => t + i.env.length, 0) + addBytes;
108
+ const theirBytes = theirs.reduce((t, i) => t + i.env.length, 0) + addBytes;
109
+ const share = recipientShare(items.length, bytes - addBytes);
110
+ if (theirs.length + add.length > share.items || theirBytes > share.bytes || items.length + add.length > OUTBOX_MAX || bytes > OUTBOX_MAX_BYTES) {
111
+ throw new CliError("outbox_full", `this device's outbox is full (at most ${share.items} messages per person while it is this full, ${OUTBOX_MAX} in all): the message was not sent; try again when you're back online`, {
112
+ delivered: false,
113
+ });
114
+ }
115
+ return { next: { items: [...items, ...add] }, result: undefined };
116
+ });
117
+ return { expiresAt, queued: fresh.length };
118
+ }
119
+ export async function outboxCount(app) {
120
+ return ((await app.state.get("outbox"))?.items ?? []).length;
121
+ }
122
+ /**
123
+ * Sends the due items (all of them with `force`) over the connected pool. Each is claimed under
124
+ * the state lock first (its next attempt moved on), so two processes don't send it at once;
125
+ * a second copy would be harmless anyway (the same envelope). Returns how many went out.
126
+ */
127
+ export async function flushOutbox(app, opts = {}) {
128
+ const out = { sent: 0, expired: 0, failed: 0 };
129
+ const pool = app.pool;
130
+ if (!pool || pool.connected.length === 0)
131
+ return out;
132
+ const now = opts.now ?? Date.now();
133
+ const doc = await app.state.get("outbox");
134
+ if (!doc || doc.items.length === 0)
135
+ return out;
136
+ // Expired ones first: gone, with a notice to the session that wrote them.
137
+ const expired = await app.state.update("outbox", (cur = { items: [] }) => {
138
+ const gone = cur.items.filter((i) => i.expiresAt <= now);
139
+ return gone.length === 0 ? { result: gone } : { next: { items: cur.items.filter((i) => i.expiresAt > now) }, result: gone };
140
+ });
141
+ if (expired.length > 0)
142
+ await note(app, expired, "expired", now);
143
+ out.expired = expired.length;
144
+ const claimed = await app.state.update("outbox", (cur = { items: [] }) => {
145
+ const due = cur.items.filter((i) => opts.force || i.nextAt <= now);
146
+ if (due.length === 0)
147
+ return { result: due };
148
+ const ids = new Set(due.map((i) => i.id));
149
+ return { next: { items: cur.items.map((i) => (ids.has(i.id) ? { ...i, tries: i.tries + 1, nextAt: now + backoff(i.tries + 1) } : i)) }, result: due };
150
+ });
151
+ const done = [];
152
+ const failing = [];
153
+ const outage = [];
154
+ const seqs = (await app.state.get("seq")) ?? {};
155
+ // One recipient at a time, oldest first; at its first retryable failure the rest of its items
156
+ // wait for the next round (O5: a recipient whose relays time out costs one timeout a round).
157
+ const stalled = new Set();
158
+ // P5: each recipient's document is refreshed once a round, whatever the number of their items.
159
+ const views = new Map();
160
+ for (const item of [...claimed].sort((x, y) => x.queuedAt - y.queuedAt)) {
161
+ if (stalled.has(item.to))
162
+ continue;
163
+ // O2: the session has moved on past the recipient's replay window: it would be dropped there.
164
+ const counter = seqs[sessKey(item.dest.own, item.dest.sid)];
165
+ if (item.seq !== undefined && counter !== undefined && counter - item.seq > OUTBOX_WINDOW) {
166
+ done.push({ item, state: "expired" });
167
+ continue;
168
+ }
169
+ // O5: failing for an hour straight while this device's own relays answer.
170
+ if (item.failingSince !== undefined && now - item.failingSince >= OUTBOX_STUCK_MS) {
171
+ done.push({ item, state: "expired" });
172
+ continue;
173
+ }
174
+ // O1: everything that allowed this send still holds; caps taken fresh. P1: when that can't be
175
+ // known this round (the document couldn't be refreshed and the one held is stale), it waits.
176
+ const allowed = await stillAllowed(app, item, views).catch(() => "later");
177
+ if (allowed === "later") {
178
+ stalled.add(item.to);
179
+ continue;
180
+ }
181
+ if (allowed === "refused") {
182
+ done.push({ item, state: "refused" });
183
+ continue;
184
+ }
185
+ const targets = allowed.targets;
186
+ let res;
187
+ try {
188
+ res = await pool.sendEnvelope(item.env, item.to, item.tdid, item.kind, targets);
189
+ }
190
+ catch {
191
+ stalled.add(item.to);
192
+ continue; // closing: the next attempt
193
+ }
194
+ if (res.sent.length > 0)
195
+ done.push({ item, state: "delivered" });
196
+ else if (res.errors.length > 0 && res.errors.every((e) => !OUTBOX_RETRYABLE.has(e.code)))
197
+ done.push({ item, state: "refused" });
198
+ else {
199
+ stalled.add(item.to);
200
+ // P3: only relays that answered and refused (every one of them) start or continue the run
201
+ // that expires an item early; a timeout or an unreachable relay is an outage, which keeps the
202
+ // 7-day expiry, and breaks the run.
203
+ if (res.errors.length > 0 && res.errors.every((e) => OUTBOX_ANSWERED.has(e.code))) {
204
+ if (item.failingSince === undefined)
205
+ failing.push(item);
206
+ }
207
+ else if (item.failingSince !== undefined)
208
+ outage.push(item);
209
+ }
210
+ }
211
+ if (failing.length > 0 || outage.length > 0) {
212
+ const start = new Set(failing.map((i) => i.id));
213
+ const clear = new Set(outage.map((i) => i.id));
214
+ await app.state.update("outbox", (cur = { items: [] }) => ({
215
+ next: {
216
+ items: cur.items.map((i) => {
217
+ if (start.has(i.id) && i.failingSince === undefined)
218
+ return { ...i, failingSince: now };
219
+ if (clear.has(i.id)) {
220
+ const { failingSince: _gone, ...rest } = i;
221
+ return rest;
222
+ }
223
+ return i;
224
+ }),
225
+ },
226
+ result: undefined,
227
+ }));
228
+ }
229
+ if (done.length > 0) {
230
+ const ids = new Set(done.map((d) => d.item.id));
231
+ await app.state.update("outbox", (cur = { items: [] }) => ({ next: { items: cur.items.filter((i) => !ids.has(i.id)) }, result: undefined }));
232
+ const delivered = done.filter((d) => d.state === "delivered").map((d) => d.item);
233
+ const refused = done.filter((d) => d.state === "refused").map((d) => d.item);
234
+ const gone = done.filter((d) => d.state === "expired").map((d) => d.item);
235
+ if (delivered.length > 0)
236
+ await note(app, delivered, "delivered", now);
237
+ if (refused.length > 0)
238
+ await note(app, refused, "refused", now);
239
+ if (gone.length > 0)
240
+ await note(app, gone, "expired", now);
241
+ out.sent = delivered.length;
242
+ out.failed = refused.length;
243
+ out.expired += gone.length;
244
+ }
245
+ return out;
246
+ }
247
+ /** One `p2p.outbox` event per message (its copies to several devices count once) for the session that wrote it. */
248
+ async function note(app, items, state, now) {
249
+ const seen = new Set();
250
+ const events = [];
251
+ for (const i of items) {
252
+ const key = `${i.dest.userId}|${i.dest.sid}|${i.queuedAt}`;
253
+ if (seen.has(key))
254
+ continue;
255
+ seen.add(key);
256
+ events.push(makeEvent(i.env, "p2p.outbox", now, { state, to: i.dest, queuedAt: i.queuedAt }, { toSession: i.fromSession }, state));
257
+ }
258
+ await app.state.addEvents(events);
259
+ }
260
+ /**
261
+ * The recipient's view for this round: refreshed (once per round), and whether it is fresh: the
262
+ * refresh went through now, or the one held was refreshed within the usual bound
263
+ * (P2P_DOC_REFRESH_SEC, at least FETCHED_SLACK_MS as `fetched` is recorded).
264
+ */
265
+ function roundView(app, to, views) {
266
+ let p = views.get(to);
267
+ if (!p) {
268
+ p = (async () => {
269
+ let view = await app.view(to);
270
+ try {
271
+ view = (await app.refreshIdentity(to, view?.relays ?? [], { quiet: true })) ?? view;
272
+ }
273
+ catch {
274
+ // not refreshed: judged by how old the held one is
275
+ }
276
+ const fetched = (await app.state.get("fetched"))?.[to];
277
+ const bound = Math.max(app.tun.docRefreshSec * 1000, 10_000);
278
+ return { view, fresh: fetched !== undefined && Date.now() - fetched <= bound };
279
+ })();
280
+ views.set(to, p);
281
+ }
282
+ return p;
283
+ }
284
+ /**
285
+ * O1: may this queued copy still go out, and over which relays? "refused" when not: the
286
+ * recipient blocked; for their session, no longer a friend or co-member; for one of ours, no
287
+ * longer on its roster; the device no longer on their current document; or their identity rotated.
288
+ * "later" (P1) when that can't be told this round: the document couldn't be refreshed and the one
289
+ * held is past its freshness bound. The relays (P2) are those of their current document, then the
290
+ * ones it was sealed for, each with a cap of this moment.
291
+ */
292
+ export async function stillAllowed(app, item, views = new Map()) {
293
+ const to = item.to;
294
+ let relays;
295
+ if (to !== app.userId) {
296
+ if (await app.store.isBlocked(to))
297
+ return "refused";
298
+ const { view, fresh } = await roundView(app, to, views);
299
+ if (!fresh)
300
+ return "later";
301
+ if (!view || (view.rotations?.length ?? 0) > 0 || !view.devices.includes(item.tdid))
302
+ return "refused";
303
+ relays = orderRelays(view.head.relays, view.relays).slice(0, 3);
304
+ // Still within the sending session's projects (projects.ts): a session that has since worked in
305
+ // a private project sends nothing more, queued copies included.
306
+ if (!(await mayReach(app, item.fromSession, to)))
307
+ return "refused";
308
+ if (item.dest.own === app.userId) {
309
+ const sess = await getSession(app, item.dest.sid).catch(() => undefined);
310
+ if (!sess || !(await rosterAudience(app, sess)).includes(to))
311
+ return "refused";
312
+ }
313
+ else {
314
+ const friend = (await liveFriendshipsV3(app.store, app.signerCtx(), (f) => [f.inviter, f.invitee].includes(to))).some((f) => f.inviter === to || f.invitee === to);
315
+ let comember = false;
316
+ if (!friend) {
317
+ for (const rec of await app.store.listCircles()) {
318
+ const members = CircleChain.fromStored(rec.chain).head.members;
319
+ if (rec.joinedByMe && members.includes(to) && members.includes(app.userId))
320
+ comember = true;
321
+ }
322
+ }
323
+ if (!friend && !comember)
324
+ return "refused";
325
+ }
326
+ }
327
+ else {
328
+ const own = await app.ownView();
329
+ if (!own.devices.includes(item.tdid))
330
+ return "refused";
331
+ relays = orderRelays(own.head.relays, own.relays).slice(0, 3);
332
+ }
333
+ const caps = await app.capsFor(to, item.kind);
334
+ const candidates = [...new Set([...relays, ...item.targets.map((t) => t.relay)])];
335
+ const targets = candidates.filter((r) => caps.has(r)).slice(0, 3).map((r) => ({ relay: r, cap: caps.get(r) }));
336
+ return targets.length > 0 ? { targets } : "refused";
337
+ }