@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.
- package/LICENSE +201 -0
- package/README.md +366 -2
- package/dist/ancestry.d.ts +13 -0
- package/dist/ancestry.js +71 -0
- package/dist/app.d.ts +363 -0
- package/dist/app.js +1177 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +56 -0
- package/dist/circle-ops.d.ts +402 -0
- package/dist/circle-ops.js +1725 -0
- package/dist/cli.d.ts +611 -0
- package/dist/cli.js +1650 -0
- package/dist/codes.d.ts +231 -0
- package/dist/codes.js +998 -0
- package/dist/config.d.ts +112 -0
- package/dist/config.js +243 -0
- package/dist/doctor.d.ts +99 -0
- package/dist/doctor.js +817 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +29 -0
- package/dist/ext-host.d.ts +32 -0
- package/dist/ext-host.js +259 -0
- package/dist/extensions.d.ts +386 -0
- package/dist/extensions.js +395 -0
- package/dist/features.d.ts +91 -0
- package/dist/features.js +164 -0
- package/dist/format.d.ts +57 -0
- package/dist/format.js +248 -0
- package/dist/identity.d.ts +236 -0
- package/dist/identity.js +751 -0
- package/dist/inbound.d.ts +32 -0
- package/dist/inbound.js +258 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +14 -0
- package/dist/join-answers.d.ts +49 -0
- package/dist/join-answers.js +149 -0
- package/dist/outbox.d.ts +109 -0
- package/dist/outbox.js +337 -0
- package/dist/pretty.d.ts +100 -0
- package/dist/pretty.js +256 -0
- package/dist/procstart.d.ts +1 -0
- package/dist/procstart.js +66 -0
- package/dist/progress.d.ts +30 -0
- package/dist/progress.js +78 -0
- package/dist/projects.d.ts +240 -0
- package/dist/projects.js +699 -0
- package/dist/prompt/picker.d.ts +64 -0
- package/dist/prompt/picker.js +152 -0
- package/dist/prompt/tty.d.ts +29 -0
- package/dist/prompt/tty.js +122 -0
- package/dist/readonly.d.ts +20 -0
- package/dist/readonly.js +50 -0
- package/dist/receipts.d.ts +99 -0
- package/dist/receipts.js +180 -0
- package/dist/relay-client.d.ts +277 -0
- package/dist/relay-client.js +873 -0
- package/dist/relay-info.d.ts +24 -0
- package/dist/relay-info.js +53 -0
- package/dist/rotation.d.ts +402 -0
- package/dist/rotation.js +2054 -0
- package/dist/running.d.ts +5 -0
- package/dist/running.js +74 -0
- package/dist/sessions.d.ts +340 -0
- package/dist/sessions.js +1152 -0
- package/dist/shortcode.d.ts +149 -0
- package/dist/shortcode.js +465 -0
- package/dist/social.d.ts +139 -0
- package/dist/social.js +485 -0
- package/dist/state.d.ts +483 -0
- package/dist/state.js +217 -0
- package/dist/stdin.d.ts +17 -0
- package/dist/stdin.js +46 -0
- package/dist/sync.d.ts +77 -0
- package/dist/sync.js +375 -0
- package/dist/transient.d.ts +1 -0
- package/dist/transient.js +28 -0
- package/dist/trust.d.ts +37 -0
- package/dist/trust.js +134 -0
- package/dist/tty-confirm.d.ts +2 -0
- package/dist/tty-confirm.js +53 -0
- package/dist/tui/command.d.ts +20 -0
- package/dist/tui/command.js +70 -0
- package/dist/tui/frame.d.ts +43 -0
- package/dist/tui/frame.js +111 -0
- package/dist/tui/model.d.ts +215 -0
- package/dist/tui/model.js +255 -0
- package/dist/tui/sanitize.d.ts +13 -0
- package/dist/tui/sanitize.js +151 -0
- package/dist/tui/terminal.d.ts +88 -0
- package/dist/tui/terminal.js +354 -0
- package/dist/tui/tui.d.ts +71 -0
- package/dist/tui/tui.js +571 -0
- package/dist/tui/view.d.ts +4 -0
- package/dist/tui/view.js +356 -0
- package/dist/unknown-kinds.d.ts +12 -0
- package/dist/unknown-kinds.js +66 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +5 -0
- package/dist/want-pow.d.ts +12 -0
- package/dist/want-pow.js +46 -0
- package/dist/watch.d.ts +35 -0
- package/dist/watch.js +325 -0
- package/dist/xstate.d.ts +125 -0
- package/dist/xstate.js +422 -0
- package/package.json +60 -4
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export { isTransient } from "./transient.js";
|
|
2
|
+
import { type AcceptedMessageV3 } from "@peer2peer/core/v3";
|
|
3
|
+
import type { App } from "./app.js";
|
|
4
|
+
import type { EventRec } from "./state.js";
|
|
5
|
+
/**
|
|
6
|
+
* The command is exiting with these attempts still running (its close waited CLOSE_GRACE_MS):
|
|
7
|
+
* their claims are released now, without counting an attempt, and they apply nothing more. Left
|
|
8
|
+
* as they were, each exit counted an attempt against the envelope, and three short commands cut
|
|
9
|
+
* off in a row gave a legitimate envelope up unapplied (pre-release review M-A). If an attempt had written
|
|
10
|
+
* some effects already, the redelivery applies the envelope again: events are deduplicated by id,
|
|
11
|
+
* as after a crash between applying and committing (review M2).
|
|
12
|
+
*/
|
|
13
|
+
export declare function abandonInFlight(app: App): Promise<number>;
|
|
14
|
+
export type NewEvent = Omit<EventRec, "n">;
|
|
15
|
+
export interface EventFrom {
|
|
16
|
+
userId: string;
|
|
17
|
+
did: string;
|
|
18
|
+
address: string;
|
|
19
|
+
self: boolean;
|
|
20
|
+
}
|
|
21
|
+
export declare function fromOf(app: App, r: AcceptedMessageV3): Promise<EventFrom>;
|
|
22
|
+
/** Builds an event; `id` is derived from the envelope so every process logs it once. */
|
|
23
|
+
export declare function makeEvent(env: string, kind: string, at: number, data: Record<string, unknown>, extra?: Partial<NewEvent>, salt?: string): NewEvent;
|
|
24
|
+
/**
|
|
25
|
+
* How long one envelope may take before the command goes on without it (review M-A): the attempt
|
|
26
|
+
* keeps running (its claim stays alive) and counts toward the envelope's attempt limit, but a
|
|
27
|
+
* short command's drain isn't spent on it. P2P_ENVELOPE_TIMEOUT_MS overrides it.
|
|
28
|
+
*/
|
|
29
|
+
export declare const ENVELOPE_TIMEOUT_MS = 8000;
|
|
30
|
+
export declare function processEnvelope(app: App, env: string, relay: string): Promise<"ack" | "keep">;
|
|
31
|
+
/** Installs the handler and returns the app, for commands that connect. */
|
|
32
|
+
export declare function receiving(app: App): App;
|
package/dist/inbound.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Every envelope a relay delivers goes through here, whichever command is
|
|
4
|
+
// connected: verifyIncomingV3 (the §4 receive chain, including the replay
|
|
5
|
+
// window that drops the copies other relays deliver), then the effect of the
|
|
6
|
+
// accepted kind, and finally zero or more events appended to the event log
|
|
7
|
+
// that `p2p watch` prints from. Keeping processing apart from printing means
|
|
8
|
+
// a message picked up by `p2p ls` still reaches the session's watcher.
|
|
9
|
+
import { randomBytes } from "node:crypto";
|
|
10
|
+
import { hostname } from "node:os";
|
|
11
|
+
import { processStartMs } from "./procstart.js";
|
|
12
|
+
import { isTransient } from "./transient.js";
|
|
13
|
+
export { isTransient } from "./transient.js";
|
|
14
|
+
import { decodeEnvelopeV3, jwsHash, P2PError, sanitizePeerText, verifyIncomingV3 } from "@peer2peer/core/v3";
|
|
15
|
+
import { answerDeferredWants, onCircleEnvelope } from "./circle-ops.js";
|
|
16
|
+
import { onSessionEnvelope } from "./sessions.js";
|
|
17
|
+
import { onReceipt } from "./receipts.js";
|
|
18
|
+
import { onUnknownKind } from "./unknown-kinds.js";
|
|
19
|
+
import { onContact, onUnfriendKind } from "./social.js";
|
|
20
|
+
import { importSync } from "./sync.js";
|
|
21
|
+
import { finishCodeJoins } from "./codes.js";
|
|
22
|
+
import { alertForeignRotations, retryRotationJoins } from "./rotation.js";
|
|
23
|
+
/** Rejections that only mean "already handled" (another relay's copy). */
|
|
24
|
+
const DUPLICATE = new Set(["replayed-seq", "replayed-nonce"]);
|
|
25
|
+
// Replay claims (core IncomingContextV3.replayClaim): an envelope enters the replay window only
|
|
26
|
+
// once it was applied, so a crash in between can't make its redelivery a "replayed" drop.
|
|
27
|
+
// A claim is alive while the attempt holding it runs: in this process, while its token is
|
|
28
|
+
// in flight; in another process on this machine, while that process lives; from another
|
|
29
|
+
// machine (a shared home), until the claim's TTL.
|
|
30
|
+
const HOST = hostname();
|
|
31
|
+
/** When this process started (ms). */
|
|
32
|
+
const STARTED = Math.round(Date.now() - process.uptime() * 1000);
|
|
33
|
+
/** Start times are compared to the second (ps prints seconds), with room for clock rounding. */
|
|
34
|
+
const START_SLACK_MS = 2500;
|
|
35
|
+
const PROCESS_TOKEN = randomBytes(9).toString("base64url");
|
|
36
|
+
let attempts = 0;
|
|
37
|
+
const inFlight = new Set();
|
|
38
|
+
/** Attempts running now, by token, with their envelope (abandonInFlight). */
|
|
39
|
+
const running = new Map();
|
|
40
|
+
/** Attempts given up because this process is exiting with them still running. */
|
|
41
|
+
const abandoned = new Set();
|
|
42
|
+
/**
|
|
43
|
+
* The command is exiting with these attempts still running (its close waited CLOSE_GRACE_MS):
|
|
44
|
+
* their claims are released now, without counting an attempt, and they apply nothing more. Left
|
|
45
|
+
* as they were, each exit counted an attempt against the envelope, and three short commands cut
|
|
46
|
+
* off in a row gave a legitimate envelope up unapplied (pre-release review M-A). If an attempt had written
|
|
47
|
+
* some effects already, the redelivery applies the envelope again: events are deduplicated by id,
|
|
48
|
+
* as after a crash between applying and committing (review M2).
|
|
49
|
+
*/
|
|
50
|
+
export async function abandonInFlight(app) {
|
|
51
|
+
let n = 0;
|
|
52
|
+
for (const [token, a] of running) {
|
|
53
|
+
if (a.app !== app || abandoned.has(token))
|
|
54
|
+
continue;
|
|
55
|
+
abandoned.add(token);
|
|
56
|
+
n++;
|
|
57
|
+
try {
|
|
58
|
+
const p = decodeEnvelopeV3(a.env).payload;
|
|
59
|
+
await app.store.releaseReplay(p.fdid, p, token, { uncount: true });
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// Malformed (it would never have been claimed), or the store is unwritable: the claim's
|
|
63
|
+
// holder is gone in a moment either way, and the next attempt takes it over.
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return n;
|
|
67
|
+
}
|
|
68
|
+
function pidAlive(pid) {
|
|
69
|
+
try {
|
|
70
|
+
process.kill(pid, 0);
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
catch (e) {
|
|
74
|
+
return e.code === "EPERM";
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** Liveness only on this machine (never age: pre-release re-review M-1); another host's claim: the TTL decides. */
|
|
78
|
+
function claimAlive(c) {
|
|
79
|
+
if (c.host !== HOST)
|
|
80
|
+
return undefined;
|
|
81
|
+
if (c.pid === process.pid && (c.started === undefined || Math.abs(c.started - STARTED) < START_SLACK_MS))
|
|
82
|
+
return inFlight.has(c.token);
|
|
83
|
+
if (!pidAlive(c.pid))
|
|
84
|
+
return false;
|
|
85
|
+
// review L-C: a pid can be reused; it is the holder only if it started when the holder did.
|
|
86
|
+
if (c.started === undefined)
|
|
87
|
+
return true;
|
|
88
|
+
const started = processStartMs(c.pid);
|
|
89
|
+
return started === undefined ? true : Math.abs(started - c.started) < START_SLACK_MS;
|
|
90
|
+
}
|
|
91
|
+
export async function fromOf(app, r) {
|
|
92
|
+
return { userId: r.envelope.from, did: r.envelope.fdid, address: await app.addressOf(r.envelope.from), self: r.envelope.from === app.userId };
|
|
93
|
+
}
|
|
94
|
+
/** Builds an event; `id` is derived from the envelope so every process logs it once. */
|
|
95
|
+
export function makeEvent(env, kind, at, data, extra = {}, salt = "") {
|
|
96
|
+
return { id: `${kind}:${jwsHash(env + salt).slice(0, 22)}`, at, kind, data, ...extra };
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* How long one envelope may take before the command goes on without it (review M-A): the attempt
|
|
100
|
+
* keeps running (its claim stays alive) and counts toward the envelope's attempt limit, but a
|
|
101
|
+
* short command's drain isn't spent on it. P2P_ENVELOPE_TIMEOUT_MS overrides it.
|
|
102
|
+
*/
|
|
103
|
+
export const ENVELOPE_TIMEOUT_MS = 8000;
|
|
104
|
+
export async function processEnvelope(app, env, relay) {
|
|
105
|
+
const token = `${PROCESS_TOKEN}.${++attempts}`;
|
|
106
|
+
inFlight.add(token);
|
|
107
|
+
running.set(token, { app, env });
|
|
108
|
+
const work = processClaimed(app, env, relay, token).finally(() => {
|
|
109
|
+
inFlight.delete(token);
|
|
110
|
+
running.delete(token);
|
|
111
|
+
abandoned.delete(token);
|
|
112
|
+
});
|
|
113
|
+
const limit = Number(app.env.P2P_ENVELOPE_TIMEOUT_MS ?? "") || ENVELOPE_TIMEOUT_MS;
|
|
114
|
+
let timer;
|
|
115
|
+
const late = new Promise((r) => {
|
|
116
|
+
timer = setTimeout(() => r("timeout"), limit);
|
|
117
|
+
timer.unref();
|
|
118
|
+
});
|
|
119
|
+
try {
|
|
120
|
+
const v = await Promise.race([work, late]);
|
|
121
|
+
if (v !== "timeout")
|
|
122
|
+
return v;
|
|
123
|
+
// Not acked: the relay redelivers it, and the attempt still running may finish it first.
|
|
124
|
+
work.catch(() => undefined);
|
|
125
|
+
app.io.err(`handling an envelope from ${sanitizePeerText(relay, 200)} is taking over ${Math.round(limit / 1000)}s; going on without it`);
|
|
126
|
+
return "keep";
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
clearTimeout(timer);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** Envelopes this device dropped unapplied, for `p2p doctor` (a count only, never content). */
|
|
133
|
+
async function noteGaveUp(app) {
|
|
134
|
+
await app.state.update("inbound", (cur = { gaveUp: 0 }) => ({ next: { gaveUp: cur.gaveUp + 1, at: Date.now() }, result: undefined })).catch(() => undefined);
|
|
135
|
+
}
|
|
136
|
+
async function processClaimed(app, env, relay, token) {
|
|
137
|
+
const r = await verifyIncomingV3(env, {
|
|
138
|
+
self: { userId: app.userId, did: app.did, agreementSecretKey: app.device.agreementSecretKey, cert: app.keys.cert },
|
|
139
|
+
store: app.store,
|
|
140
|
+
resolveIdentity: (u) => app.discover(u, [relay]),
|
|
141
|
+
onWarning: (m) => app.io.err(`warning: ${sanitizePeerText(m, 300)}`),
|
|
142
|
+
replayClaim: { claimant: { token, host: HOST, pid: process.pid, started: STARTED }, isAlive: claimAlive, retryable: isTransient },
|
|
143
|
+
});
|
|
144
|
+
// Another process (or another relay's copy here) is applying it right now: not acked, so the
|
|
145
|
+
// relay keeps it until that one acks (or redelivers it, if that one never finishes).
|
|
146
|
+
if (!r.ok && r.reason === "replay-in-progress")
|
|
147
|
+
return "keep";
|
|
148
|
+
if (!r.ok && r.reason === "gave-up") {
|
|
149
|
+
app.io.err(`gave-up: an envelope from ${sanitizePeerText(relay, 200)} failed every attempt; dropped unapplied (see \`p2p doctor\`)`);
|
|
150
|
+
await noteGaveUp(app);
|
|
151
|
+
return "ack";
|
|
152
|
+
}
|
|
153
|
+
if (!r.ok && r.reason === "seq-too-old") {
|
|
154
|
+
// Below the replay window: a duplicate, or an envelope that arrived after more than 512 later
|
|
155
|
+
// ones from the same session. Either way it can't be told apart from a replay, so it is acked
|
|
156
|
+
// (it would only come back), but counted for `p2p doctor` (review M1): never silently.
|
|
157
|
+
await app.state.update("inbound", (cur = { gaveUp: 0 }) => ({ next: { ...cur, tooOld: (cur.tooOld ?? 0) + 1, at: Date.now() }, result: undefined })).catch(() => undefined);
|
|
158
|
+
return "ack";
|
|
159
|
+
}
|
|
160
|
+
if (!r.ok) {
|
|
161
|
+
// Core messages can quote raw envelope fields: one line, sanitized (review M2).
|
|
162
|
+
if (!DUPLICATE.has(r.reason))
|
|
163
|
+
app.io.err(`rejected an envelope from ${sanitizePeerText(relay, 200)}: ${sanitizePeerText(r.reason, 64)}: ${sanitizePeerText(r.message, 300)}`);
|
|
164
|
+
return "ack";
|
|
165
|
+
}
|
|
166
|
+
// Abandoned while it was being verified (and claimed): give the claim back, uncounted.
|
|
167
|
+
if (abandoned.has(token)) {
|
|
168
|
+
await r.releaseReplay?.({ uncount: true }).catch(() => undefined);
|
|
169
|
+
return "keep";
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
const events = await dispatch(app, env, r, relay);
|
|
173
|
+
if (abandoned.has(token)) {
|
|
174
|
+
await r.releaseReplay?.({ uncount: true }).catch(() => undefined);
|
|
175
|
+
return "keep";
|
|
176
|
+
}
|
|
177
|
+
await app.state.addEvents(events);
|
|
178
|
+
}
|
|
179
|
+
catch (e) {
|
|
180
|
+
const what = `applying ${sanitizePeerText(r.envelope.kind, 40)} from ${r.envelope.from} failed: ${sanitizePeerText(e.message, 300)}`;
|
|
181
|
+
if (!(e instanceof P2PError) && isTransient(e)) {
|
|
182
|
+
// This command closing, a lock timeout, a full disk: give the claim up unrecorded and don't
|
|
183
|
+
// ack, so it is applied in full on a redelivery (review L-2), within the attempt limit.
|
|
184
|
+
app.io.err(`${what} (attempt ${r.attempt ?? 1}; kept for a retry)`);
|
|
185
|
+
// Cut off by this process exiting: not an attempt that failed (pre-release review M-A).
|
|
186
|
+
await r.releaseReplay?.({ uncount: abandoned.has(token) }).catch(() => undefined);
|
|
187
|
+
return "keep";
|
|
188
|
+
}
|
|
189
|
+
// A protocol rejection, or anything else (a bug, the network): final, as retrying would only
|
|
190
|
+
// repeat it, and its side effects.
|
|
191
|
+
app.io.err(what);
|
|
192
|
+
if (!(e instanceof P2PError))
|
|
193
|
+
await noteGaveUp(app);
|
|
194
|
+
}
|
|
195
|
+
// Abandoned after its effects were written: not recorded; the redelivery applies it again
|
|
196
|
+
// (events deduplicated by id), as after a crash here.
|
|
197
|
+
if (abandoned.has(token)) {
|
|
198
|
+
await r.releaseReplay?.({ uncount: true }).catch(() => undefined);
|
|
199
|
+
return "keep";
|
|
200
|
+
}
|
|
201
|
+
// Applied (its effects and events written), or failed for good: only now is it a replay.
|
|
202
|
+
const lost = await r.commitReplay?.();
|
|
203
|
+
// Another host's attempt recorded it first (its claim was taken over after the TTL): this one
|
|
204
|
+
// was a duplicate. Its events were deduplicated by id; say so, and go on.
|
|
205
|
+
if (lost)
|
|
206
|
+
app.io.err(`an envelope from ${r.envelope.from} was also handled elsewhere meanwhile (${sanitizePeerText(lost.reason, 64)})`);
|
|
207
|
+
return "ack";
|
|
208
|
+
}
|
|
209
|
+
async function dispatch(app, env, r, relay) {
|
|
210
|
+
switch (r.rule) {
|
|
211
|
+
case "contact":
|
|
212
|
+
return onContact(app, env, r);
|
|
213
|
+
case "self-sync": {
|
|
214
|
+
// review L3: a device revoked moments ago could still sync. Refresh our own document
|
|
215
|
+
// (rate-limited by P2P_DOC_REFRESH_SEC) and require the sender to still be listed.
|
|
216
|
+
await app.refreshIdentity(app.userId, app.relays, { quiet: true });
|
|
217
|
+
const own = await app.view(app.userId);
|
|
218
|
+
if (!own?.devices.includes(r.envelope.fdid)) {
|
|
219
|
+
app.io.err(`ignored a sync from ${r.envelope.fdid}: no longer one of your devices`);
|
|
220
|
+
return [];
|
|
221
|
+
}
|
|
222
|
+
await importSync(app, r.plaintext.body, { fdid: r.envelope.fdid });
|
|
223
|
+
// §2.8: a rotation of our identity this device didn't publish is raised loudly.
|
|
224
|
+
await alertForeignRotations(app);
|
|
225
|
+
return [];
|
|
226
|
+
}
|
|
227
|
+
case "unfriend":
|
|
228
|
+
return onUnfriendKind(app, env, r);
|
|
229
|
+
case "receipt":
|
|
230
|
+
return onReceipt(app, env, r);
|
|
231
|
+
case "unknown-kind":
|
|
232
|
+
return onUnknownKind(app, env, r);
|
|
233
|
+
case "circle":
|
|
234
|
+
// "circle" names both the circle kind's rule and an exchange rule (§4.2: a circle-mate writing
|
|
235
|
+
// into a session shared with the circle). Only the kind tells them apart: a message routed to
|
|
236
|
+
// the circle handler failed there and was dropped (found by the doctor tests).
|
|
237
|
+
return r.plaintext.kind === "circle" ? onCircleEnvelope(app, env, r, relay) : onSessionEnvelope(app, env, r);
|
|
238
|
+
default:
|
|
239
|
+
return onSessionEnvelope(app, env, r);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
/** Installs the handler and returns the app, for commands that connect. */
|
|
243
|
+
export function receiving(app) {
|
|
244
|
+
app.onEnvelope = (env, relay) => processEnvelope(app, env, relay);
|
|
245
|
+
app.afterDrain = async () => {
|
|
246
|
+
// §2.8 (pre-release review H2): nothing here ever follows a rotation of our own identity; that is the
|
|
247
|
+
// user's own `p2p identity follow`. A rotation this device didn't publish is raised, and rotated
|
|
248
|
+
// members whose old identity's final version is now out are swapped in.
|
|
249
|
+
await alertForeignRotations(app);
|
|
250
|
+
await retryRotationJoins(app);
|
|
251
|
+
// Re-review N6: a want the first device in line didn't answer in time, answered here.
|
|
252
|
+
await answerDeferredWants(app).catch((e) => app.io.err(`p2p: ${e.message}`));
|
|
253
|
+
return finishCodeJoins(app);
|
|
254
|
+
};
|
|
255
|
+
app.onIdentityRotated = () => alertForeignRotations(app);
|
|
256
|
+
app.onAbandon = () => abandonInFlight(app);
|
|
257
|
+
return app;
|
|
258
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from "./relay-client.js";
|
|
2
|
+
export * from "./config.js";
|
|
3
|
+
export * from "./errors.js";
|
|
4
|
+
export { App, type Io, type AppOptions, type Delivery } from "./app.js";
|
|
5
|
+
export { buildProgram, main, realOps, VERSION } from "./cli.js";
|
|
6
|
+
export { processEnvelope, receiving } from "./inbound.js";
|
|
7
|
+
export * from "./extensions.js";
|
|
8
|
+
export { sendExtension, MAX_EXT_PLAINTEXT_BYTES, type SendExtOpts } from "./sessions.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// @peer2peer/cli: the standalone `p2p` CLI for Peer2Peer v3. The binary is
|
|
4
|
+
// `p2p` (./bin.ts); this entry point exposes the pieces for embedding and
|
|
5
|
+
// tests: the relay client, the App context and the command functions.
|
|
6
|
+
export * from "./relay-client.js";
|
|
7
|
+
export * from "./config.js";
|
|
8
|
+
export * from "./errors.js";
|
|
9
|
+
export { App } from "./app.js";
|
|
10
|
+
export { buildProgram, main, realOps, VERSION } from "./cli.js";
|
|
11
|
+
export { processEnvelope, receiving } from "./inbound.js";
|
|
12
|
+
// The extension seam (extensions.ts): the contract an @peer2peer/ext-* package implements.
|
|
13
|
+
export * from "./extensions.js";
|
|
14
|
+
export { sendExtension, MAX_EXT_PLAINTEXT_BYTES } from "./sessions.js";
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type AnswerPart } from "@peer2peer/core/v3";
|
|
2
|
+
import type { App } from "./app.js";
|
|
3
|
+
import type { AnswerPartsRec } from "./state.js";
|
|
4
|
+
export interface JoinAnswerDoc {
|
|
5
|
+
cid: string;
|
|
6
|
+
from: string;
|
|
7
|
+
versions: string[];
|
|
8
|
+
joins: string[];
|
|
9
|
+
parts: Record<string, AnswerPartsRec>;
|
|
10
|
+
bytes: number;
|
|
11
|
+
}
|
|
12
|
+
/** Distinct versions kept per `ver` (a sibling, at most: more is someone else's noise). */
|
|
13
|
+
export declare const MAX_VERSIONS_PER_VER = 2;
|
|
14
|
+
/** Versions above the offered head kept per confirmer: a link can be older than the circle's head. */
|
|
15
|
+
export declare const MAX_NEWER_VERSIONS = 256;
|
|
16
|
+
/**
|
|
17
|
+
* Answers a member sends one asker per rolling hour, and so the new answers (part ids) a joiner
|
|
18
|
+
* takes from one confirmer per rolling hour: one limit on both sides (review N-D; the joiner took 4
|
|
19
|
+
* while a member may send 10, so a legitimate fifth answer was dropped). Parts of answers already
|
|
20
|
+
* tracked always count.
|
|
21
|
+
*/
|
|
22
|
+
export declare const ANSWERS_PER_HOUR = 10;
|
|
23
|
+
export declare const MAX_NEW_ANSWERS_PER_HOUR = 10;
|
|
24
|
+
/** Answers whose parts are tracked per confirmer (the newest): more than a confirmer may start in an hour. */
|
|
25
|
+
export declare const MAX_PART_RECORDS: number;
|
|
26
|
+
/**
|
|
27
|
+
* The fixed ceiling on what one confirmer's answer may take, whatever the offered head claims
|
|
28
|
+
* (re-review N1: the head comes from a link, unverified, so whoever writes the link must not set
|
|
29
|
+
* the ceiling).
|
|
30
|
+
*/
|
|
31
|
+
export declare const ANSWER_MAX_BYTES: number;
|
|
32
|
+
/** The highest `ver` kept: no chain longer than a bundle may carry is bootstrapped (MAX_CHAIN_IN_BUNDLE). */
|
|
33
|
+
export declare function maxVerFor(offeredVer: number): number;
|
|
34
|
+
/**
|
|
35
|
+
* A confirmer's byte ceiling: two full versions per `ver` up to the (clamped) offered head, plus 4
|
|
36
|
+
* statements per member of 16 KiB, never more than ANSWER_MAX_BYTES.
|
|
37
|
+
*/
|
|
38
|
+
export declare function answerByteCap(offeredVer: number, members: number): number;
|
|
39
|
+
export declare const answerDocName: (cid: string, from: string) => string;
|
|
40
|
+
/**
|
|
41
|
+
* Adds what one envelope brought to `from`'s answer for `cid`, within the bounds above. Returns
|
|
42
|
+
* whether anything was kept.
|
|
43
|
+
*/
|
|
44
|
+
export declare function addToAnswer(app: App, cid: string, from: string, bound: {
|
|
45
|
+
offeredVer: number;
|
|
46
|
+
members: number;
|
|
47
|
+
}, versions: readonly string[], joins: readonly string[], part?: AnswerPart): Promise<void>;
|
|
48
|
+
export declare function readAnswer(app: App, cid: string, from: string): Promise<JoinAnswerDoc | undefined>;
|
|
49
|
+
export declare function dropAnswers(app: App, cid: string, froms: readonly string[]): Promise<void>;
|
|
@@ -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
|
+
}
|
package/dist/outbox.d.ts
ADDED
|
@@ -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">;
|