@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.
- package/LICENSE +201 -0
- package/README.md +370 -2
- package/dist/ancestry.d.ts +13 -0
- package/dist/ancestry.js +71 -0
- package/dist/app.d.ts +368 -0
- package/dist/app.js +1181 -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 +660 -0
- package/dist/cli.js +1787 -0
- package/dist/codes.d.ts +231 -0
- package/dist/codes.js +998 -0
- package/dist/config.d.ts +159 -0
- package/dist/config.js +294 -0
- package/dist/doctor.d.ts +113 -0
- package/dist/doctor.js +930 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +29 -0
- package/dist/ext-host.d.ts +38 -0
- package/dist/ext-host.js +293 -0
- package/dist/extensions.d.ts +487 -0
- package/dist/extensions.js +406 -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/graph-memory.d.ts +107 -0
- package/dist/graph-memory.js +393 -0
- package/dist/history.d.ts +155 -0
- package/dist/history.js +697 -0
- package/dist/identity.d.ts +239 -0
- package/dist/identity.js +759 -0
- package/dist/inbound.d.ts +32 -0
- package/dist/inbound.js +261 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +14 -0
- package/dist/ix-local.d.ts +76 -0
- package/dist/ix-local.js +203 -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 +491 -0
- package/dist/projects.js +1383 -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 +182 -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 +355 -0
- package/dist/sessions.js +1247 -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 +509 -0
- package/dist/state.js +220 -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 +221 -0
- package/dist/tui/model.js +259 -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 +78 -0
- package/dist/tui/tui.js +612 -0
- package/dist/tui/view.d.ts +4 -0
- package/dist/tui/view.js +358 -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 +331 -0
- package/dist/xstate.d.ts +125 -0
- package/dist/xstate.js +422 -0
- package/package.json +60 -4
package/dist/receipts.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Delivery receipts (docs/protocol.md §4.3 "Delivery receipts", cap receipts.v1).
|
|
4
|
+
//
|
|
5
|
+
// - Sender: a message to a session whose live status advertises receipts.v1 carries `rcpt`, a
|
|
6
|
+
// random id; this device remembers it (`receipts.wanted`, by id) with the user it went to and
|
|
7
|
+
// the local session that sent it. A `receipt` envelope is taken only from that user, for an
|
|
8
|
+
// id this device sent them, at most RECEIPTS_PER_ID times, and becomes a `p2p.receipt` event
|
|
9
|
+
// for the sending session. Anything else is dropped without a trace.
|
|
10
|
+
// - Receiver: an inbound message that asked is remembered (`receipts.asked`, by event id). The
|
|
11
|
+
// front end that shows messages (the Claude mod) reports what became of it with `p2p receipt
|
|
12
|
+
// <event> --outcome …`; the CLI decides whether one goes out: receipts on, the session not
|
|
13
|
+
// private, the message delivered to that session (or an ended session's unclaimed copy, which
|
|
14
|
+
// only ever says `ended`), each outcome once, nothing after a final one, within the rate
|
|
15
|
+
// limits. A receipt goes only to the authenticated sender's sending device, carries the id and
|
|
16
|
+
// the outcome and nothing else, and is never itself receipted.
|
|
17
|
+
import { randomBytes } from "node:crypto";
|
|
18
|
+
import { RECEIPT_ID_RE, RECEIPT_OUTCOMES, RECEIPT_SID, STATUS_CAP_RECEIPTS } from "@peer2peer/core/v3";
|
|
19
|
+
import { receiptsEnabled } from "./config.js";
|
|
20
|
+
import { peerSupports } from "./features.js";
|
|
21
|
+
import { CliError } from "./errors.js";
|
|
22
|
+
import { fromOf, makeEvent } from "./inbound.js";
|
|
23
|
+
/** Kept for as long as a message can still arrive (relays keep it 7 days), then dropped. */
|
|
24
|
+
export const RECEIPT_TTL_MS = 7 * 24 * 3600 * 1000;
|
|
25
|
+
export const RECEIPTS_WANTED_MAX = 512;
|
|
26
|
+
export const RECEIPTS_ASKED_MAX = 1024;
|
|
27
|
+
/** A message has at most this many outcomes (held, then shown or declined or expired): more are dropped. */
|
|
28
|
+
export const RECEIPTS_PER_ID = 3;
|
|
29
|
+
/**
|
|
30
|
+
* Receipts this device sends in a minute: at most RECEIPT_RATE_PER_USER to one user. Past
|
|
31
|
+
* RECEIPT_RATE_ALL in all, a user gets only their fair share of it (RECEIPT_RATE_ALL divided among
|
|
32
|
+
* the users receipted this minute, this one included), so a few busy peers can't use up everyone
|
|
33
|
+
* else's receipts; RECEIPT_RATE_HARD is the ceiling either way (pre-release review R5).
|
|
34
|
+
*/
|
|
35
|
+
export const RECEIPT_RATE_PER_USER = 30;
|
|
36
|
+
export const RECEIPT_RATE_ALL = 120;
|
|
37
|
+
export const RECEIPT_RATE_HARD = 240;
|
|
38
|
+
/** Whether one more receipt to `user` fits the limits (rate windows of the last minute). */
|
|
39
|
+
export function receiptRateAllows(rate, user) {
|
|
40
|
+
const mine = rate.by[user]?.length ?? 0;
|
|
41
|
+
if (mine >= RECEIPT_RATE_PER_USER || rate.all.length >= RECEIPT_RATE_HARD)
|
|
42
|
+
return false;
|
|
43
|
+
if (rate.all.length < RECEIPT_RATE_ALL)
|
|
44
|
+
return true;
|
|
45
|
+
const users = new Set([...Object.keys(rate.by).filter((u) => (rate.by[u]?.length ?? 0) > 0), user]).size;
|
|
46
|
+
return mine < Math.floor(RECEIPT_RATE_ALL / users);
|
|
47
|
+
}
|
|
48
|
+
const MINUTE = 60_000;
|
|
49
|
+
/** Outcomes after which nothing more is said about a message. */
|
|
50
|
+
const FINAL = new Set(["shown", "declined", "expired", "ended"]);
|
|
51
|
+
const empty = () => ({ wanted: {}, asked: {}, sent: {}, rate: { by: {}, all: [] } });
|
|
52
|
+
/** Drops what is older than the TTL, and the oldest past each cap. */
|
|
53
|
+
function prune(d, now) {
|
|
54
|
+
const fresh = (m, max) => Object.fromEntries(Object.entries(m)
|
|
55
|
+
.filter(([, v]) => now - v.at <= RECEIPT_TTL_MS)
|
|
56
|
+
.sort(([, a], [, b]) => b.at - a.at)
|
|
57
|
+
.slice(0, max));
|
|
58
|
+
const by = {};
|
|
59
|
+
for (const [u, ts] of Object.entries(d.rate.by)) {
|
|
60
|
+
const keep = ts.filter((t) => now - t < MINUTE);
|
|
61
|
+
if (keep.length > 0)
|
|
62
|
+
by[u] = keep;
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
wanted: fresh(d.wanted, RECEIPTS_WANTED_MAX),
|
|
66
|
+
asked: fresh(d.asked, RECEIPTS_ASKED_MAX),
|
|
67
|
+
sent: fresh(d.sent, RECEIPTS_ASKED_MAX),
|
|
68
|
+
rate: { by, all: d.rate.all.filter((t) => now - t < MINUTE) },
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** How many entries a doc holds: pruning changed it iff this went down. */
|
|
72
|
+
const size = (d) => Object.keys(d.wanted).length + Object.keys(d.asked).length + Object.keys(d.sent).length + d.rate.all.length + Object.values(d.rate.by).reduce((n, ts) => n + ts.length + 1, 0);
|
|
73
|
+
/** Read-modify-write under the state lock; nothing is written when nothing changed (pre-release review R3). */
|
|
74
|
+
function withDoc(app, fn) {
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
return app.state.update("receipts", (cur) => {
|
|
77
|
+
const d = prune({ ...empty(), ...(cur ?? {}) }, now);
|
|
78
|
+
const r = fn(d, now);
|
|
79
|
+
if (r.next !== undefined)
|
|
80
|
+
return { next: r.next, result: r.result };
|
|
81
|
+
// Only pruning: written only when it dropped something from a stored doc (prune only drops).
|
|
82
|
+
return { ...(cur !== undefined && size(d) !== size({ ...empty(), ...cur }) ? { next: d } : {}), result: r.result };
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
export function newReceiptId() {
|
|
86
|
+
return randomBytes(12).toString("base64url");
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Whether a message to `(own, sid)` may carry `rcpt`: only when the session is live now (a status
|
|
90
|
+
* within STATUS_LIVE_MS) and that status advertises receipts.v1 (never by substring). A client from
|
|
91
|
+
* before receipts rejects the whole message for an unknown field, so a stale status (the session
|
|
92
|
+
* since restarted on an older client, or turned receipts off) must never decide it: the 24 h
|
|
93
|
+
* offline path sends without one (pre-release review R2).
|
|
94
|
+
*/
|
|
95
|
+
export async function asksReceipts(app, own, sid) {
|
|
96
|
+
return peerSupports(app, own, { sid }, STATUS_CAP_RECEIPTS);
|
|
97
|
+
}
|
|
98
|
+
/** Sender: remember a message that asked for receipts. */
|
|
99
|
+
export async function rememberWanted(app, id, w) {
|
|
100
|
+
await withDoc(app, (d, now) => ({ next: { ...d, wanted: { ...d.wanted, [id]: { ...w, at: now, outcomes: [] } } }, result: undefined }));
|
|
101
|
+
}
|
|
102
|
+
/** Receiver: remember an inbound message that asked (only while receipts are on). */
|
|
103
|
+
export async function rememberAsked(app, eventId, a) {
|
|
104
|
+
if (!receiptsEnabled(app.env, app.home))
|
|
105
|
+
return;
|
|
106
|
+
await withDoc(app, (d, now) => (d.asked[eventId] ? { result: undefined } : { next: { ...d, asked: { ...d.asked, [eventId]: { ...a, at: now } } }, result: undefined }));
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* `p2p receipt <event> --from-session <sid> --outcome <o>`: what became of a message, reported by
|
|
110
|
+
* the session that has it. Never an error for "nothing to send": `{sent: false, reason}`.
|
|
111
|
+
*/
|
|
112
|
+
export async function sendReceipt(app, o) {
|
|
113
|
+
if (!RECEIPT_OUTCOMES.includes(o.outcome))
|
|
114
|
+
throw new CliError("usage", `--outcome must be one of ${RECEIPT_OUTCOMES.join(", ")}`);
|
|
115
|
+
if (!receiptsEnabled(app.env, app.home))
|
|
116
|
+
return { sent: false, reason: "off" };
|
|
117
|
+
const asked = ((await app.state.get("receipts"))?.asked ?? {})[o.eventId];
|
|
118
|
+
if (!asked)
|
|
119
|
+
return { sent: false, reason: "not-asked" };
|
|
120
|
+
// The copy of an ended session's message says only that the session ended, whatever this one did
|
|
121
|
+
// with it: never which session has it now (nor that it was held, shown or declined there).
|
|
122
|
+
const outcome = asked.unclaimedFor !== undefined ? "ended" : o.outcome;
|
|
123
|
+
// A message for no session of ours (`toSession` unknown) is held by whichever session the user picks.
|
|
124
|
+
if (asked.unclaimedFor === undefined && asked.toSession !== undefined && asked.toSession !== o.fromSession)
|
|
125
|
+
return { sent: false, reason: "not-yours" };
|
|
126
|
+
// A private session (shared with nobody) sends none: one would tell the sender it exists. Nor does
|
|
127
|
+
// the copy of a private ended session's message. A session with no roster here counts as private.
|
|
128
|
+
// Except to this user's own sessions (another device, or this one): they list it anyway, and the
|
|
129
|
+
// receipt is how one of them learns its message waits for Deliver.
|
|
130
|
+
const sessions = (await app.state.get("sessions")) ?? {};
|
|
131
|
+
const isPrivate = (sid) => {
|
|
132
|
+
const doc = sessions[sid];
|
|
133
|
+
return !doc || (doc.vis === "private" && doc.parts.length === 0);
|
|
134
|
+
};
|
|
135
|
+
if (asked.from !== app.userId && (isPrivate(o.fromSession) || (asked.unclaimedFor !== undefined && isPrivate(asked.unclaimedFor))))
|
|
136
|
+
return { sent: false, reason: "private" };
|
|
137
|
+
const key = `${asked.from}|${asked.id}`;
|
|
138
|
+
const verdict = await withDoc(app, (d, now) => {
|
|
139
|
+
const done = d.sent[key]?.outcomes ?? [];
|
|
140
|
+
if (done.includes(outcome) || done.some((x) => FINAL.has(x)) || done.length >= RECEIPTS_PER_ID)
|
|
141
|
+
return { result: "done" };
|
|
142
|
+
const mine = d.rate.by[asked.from] ?? [];
|
|
143
|
+
if (!receiptRateAllows(d.rate, asked.from))
|
|
144
|
+
return { result: "rate-limited" };
|
|
145
|
+
// Counted before it goes out: a failed send doesn't free its slot (no retry storms), and an
|
|
146
|
+
// outcome is claimed once even when two processes report it at the same time.
|
|
147
|
+
return {
|
|
148
|
+
next: { ...d, sent: { ...d.sent, [key]: { at: now, outcomes: [...done, outcome] } }, rate: { by: { ...d.rate.by, [asked.from]: [...mine, now] }, all: [...d.rate.all, now] } },
|
|
149
|
+
result: "go",
|
|
150
|
+
};
|
|
151
|
+
});
|
|
152
|
+
if (verdict !== "go")
|
|
153
|
+
return { sent: false, reason: verdict };
|
|
154
|
+
await app.connectAndDrain();
|
|
155
|
+
const d = await app.deliver(asked.from, "receipt", { own: app.userId, sid: RECEIPT_SID }, { receipt: { id: asked.id, outcome } }, { onlyDevices: [asked.did] });
|
|
156
|
+
return d.relays.length > 0 ? { sent: true, outcome } : { sent: false, outcome, reason: "undelivered" };
|
|
157
|
+
}
|
|
158
|
+
/** Sender: a `receipt` envelope. Only from the user the message went to, for an id this device sent them. */
|
|
159
|
+
export async function onReceipt(app, env, r) {
|
|
160
|
+
const pt = r.plaintext;
|
|
161
|
+
const { id, outcome } = pt.receipt;
|
|
162
|
+
if (!RECEIPT_ID_RE.test(id))
|
|
163
|
+
return [];
|
|
164
|
+
const from = r.envelope.from;
|
|
165
|
+
const hit = await withDoc(app, (d, now) => {
|
|
166
|
+
const w = d.wanted[id];
|
|
167
|
+
if (!w || w.to !== from)
|
|
168
|
+
return { result: undefined };
|
|
169
|
+
if (w.outcomes.some((x) => x.outcome === outcome) || w.outcomes.length >= RECEIPTS_PER_ID)
|
|
170
|
+
return { result: undefined };
|
|
171
|
+
const next = { ...w, outcomes: [...w.outcomes, { outcome, at: now }] };
|
|
172
|
+
return { next: { ...d, wanted: { ...d.wanted, [id]: next } }, result: next };
|
|
173
|
+
});
|
|
174
|
+
if (!hit)
|
|
175
|
+
return [];
|
|
176
|
+
const sender = await fromOf(app, r);
|
|
177
|
+
return [makeEvent(env, "p2p.receipt", r.envelope.ts, { from: sender, receiptId: id, outcome, own: hit.own, ref: hit.ref }, { toSession: hit.fromSession }, hit.fromSession)];
|
|
178
|
+
}
|
|
179
|
+
/** `p2p receipts [on|off]`: the setting, as config.json and the environment make it. */
|
|
180
|
+
export function receiptsSetting(app) {
|
|
181
|
+
return { receipts: receiptsEnabled(app.env, app.home), overridden: app.env.P2P_RECEIPTS !== undefined && app.env.P2P_RECEIPTS.trim() !== "" };
|
|
182
|
+
}
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import type { LookupFunction } from "node:net";
|
|
3
|
+
import type { Transport, TransportResolver } from "./config.js";
|
|
4
|
+
import { type Progress } from "./progress.js";
|
|
5
|
+
export interface DeviceAuth {
|
|
6
|
+
cert: string;
|
|
7
|
+
signingSecretKey: Uint8Array;
|
|
8
|
+
/** Members-only relays: an admission key from a redeemed code, by relay (sent in `auth.admit`). */
|
|
9
|
+
admits?: Readonly<Record<string, string>>;
|
|
10
|
+
/** The relay admitted this identity with the key: it isn't needed again. */
|
|
11
|
+
onAdmitted?: (relay: string) => void;
|
|
12
|
+
}
|
|
13
|
+
/** A members-only relay's circle (its auth reply): members push newer versions to it. */
|
|
14
|
+
export interface RelayCircle {
|
|
15
|
+
cid: string;
|
|
16
|
+
ver: number;
|
|
17
|
+
}
|
|
18
|
+
export interface Hello {
|
|
19
|
+
relay: string;
|
|
20
|
+
nonce: string;
|
|
21
|
+
pow: number;
|
|
22
|
+
limits?: Record<string, number>;
|
|
23
|
+
}
|
|
24
|
+
export type Frame = Record<string, unknown> & {
|
|
25
|
+
t: string;
|
|
26
|
+
};
|
|
27
|
+
/** Close codes the relay uses (packages/relay CLOSE). */
|
|
28
|
+
export declare const CLOSE_AUTH_FAILED = 4001;
|
|
29
|
+
/** The device certificate expired: reconnect with a renewed one (R4-L1). */
|
|
30
|
+
export declare const CLOSE_CERT_EXPIRED = 4003;
|
|
31
|
+
/** How long a short command waits for a relay's closing frame on its way out (pre-release review L1). */
|
|
32
|
+
export declare const CLOSE_WAIT_MS = 1000;
|
|
33
|
+
/** review M2: a relay's error code, as far as we repeat it: `[a-z-]{1,32}`, else "relay-error". */
|
|
34
|
+
export declare function relayCode(v: unknown): string;
|
|
35
|
+
export declare class RelayConnection {
|
|
36
|
+
readonly relay: string;
|
|
37
|
+
readonly transport: Transport;
|
|
38
|
+
private readonly opts;
|
|
39
|
+
private ws?;
|
|
40
|
+
hello?: Hello;
|
|
41
|
+
authed: boolean;
|
|
42
|
+
/** Authenticated, but only for identity publishes (see packages/relay ConnAuth.restricted). */
|
|
43
|
+
restricted: boolean;
|
|
44
|
+
/** Set by a members-only relay that follows a circle: which, and the version it holds (0: none yet). */
|
|
45
|
+
circle?: RelayCircle;
|
|
46
|
+
/**
|
|
47
|
+
* The relay said `caught-up` (§5.4): everything stored for this mailbox when it authenticated
|
|
48
|
+
* has been delivered on this connection. Relays from before it never say so.
|
|
49
|
+
*/
|
|
50
|
+
caughtUp: boolean;
|
|
51
|
+
closeCode?: number;
|
|
52
|
+
private pending;
|
|
53
|
+
private nextId;
|
|
54
|
+
private closedResolve;
|
|
55
|
+
readonly closed: Promise<number>;
|
|
56
|
+
constructor(relay: string, transport: Transport, opts: {
|
|
57
|
+
auth?: DeviceAuth;
|
|
58
|
+
/** Accept a restricted connection (a device the relay's document doesn't list yet: §2.7 restore). */
|
|
59
|
+
allowRestricted?: boolean;
|
|
60
|
+
timeoutMs: number;
|
|
61
|
+
/** Per request (default 15 s). */
|
|
62
|
+
requestTimeoutMs?: number;
|
|
63
|
+
progress?: Progress;
|
|
64
|
+
/** Appended to the connect step's label, e.g. " (relay 1/2)". */
|
|
65
|
+
what?: string;
|
|
66
|
+
/** Resolves the host the socket dials (a code's relay: privateGuardLookup). */
|
|
67
|
+
lookup?: import("node:net").LookupFunction;
|
|
68
|
+
/** Remember an unreachable host for the rest of the command (not in `watch`, which retries). */
|
|
69
|
+
rememberUnreachable?: boolean;
|
|
70
|
+
onEnv?: (rid: string, env: string, conn: RelayConnection) => void;
|
|
71
|
+
onCaughtUp?: (conn: RelayConnection) => void;
|
|
72
|
+
onClose?: (code: number, conn: RelayConnection) => void;
|
|
73
|
+
});
|
|
74
|
+
get isOpen(): boolean;
|
|
75
|
+
/** Dials, checks `hello.relay` against the canonical URL (H5), and authenticates when a device is given. */
|
|
76
|
+
open(): Promise<void>;
|
|
77
|
+
private openInner;
|
|
78
|
+
/** Sends a frame with an `id` and resolves with the reply echoing it. */
|
|
79
|
+
request(frame: Frame, timeoutMs?: number): Promise<Frame>;
|
|
80
|
+
private requestInner;
|
|
81
|
+
/** Fire-and-forget (the relay does not reply to `ack`). */
|
|
82
|
+
send(frame: Frame): void;
|
|
83
|
+
close(): void;
|
|
84
|
+
}
|
|
85
|
+
export interface SendTarget {
|
|
86
|
+
relay: string;
|
|
87
|
+
/** The recipient's cap naming this relay; without one only `contact` goes, with PoW. */
|
|
88
|
+
cap?: string;
|
|
89
|
+
}
|
|
90
|
+
export interface SendResult {
|
|
91
|
+
/** Relays that answered `sent`. */
|
|
92
|
+
sent: string[];
|
|
93
|
+
/**
|
|
94
|
+
* `written`: the envelope went out on the connection before this failed (the relay answered
|
|
95
|
+
* an error, or the reply never came), so it may have been stored all the same. Without it the
|
|
96
|
+
* envelope never left this client (no connection, no capability).
|
|
97
|
+
*/
|
|
98
|
+
errors: {
|
|
99
|
+
relay: string;
|
|
100
|
+
code: string;
|
|
101
|
+
written?: boolean;
|
|
102
|
+
}[];
|
|
103
|
+
}
|
|
104
|
+
export type EnvelopeHandler = (env: string, relay: string) => Promise<"ack" | "keep">;
|
|
105
|
+
/** The pool whose envelope handler is running (App.connect uses it: pre-release review M1). */
|
|
106
|
+
export declare const handlerPool: AsyncLocalStorage<RelayPool>;
|
|
107
|
+
export interface PoolOptions {
|
|
108
|
+
/** The user's own relays: connected for receiving. */
|
|
109
|
+
relays: readonly string[];
|
|
110
|
+
transport: TransportResolver;
|
|
111
|
+
/** Read on every (re)connection, so a renewed certificate is used (R4-L1). */
|
|
112
|
+
auth: DeviceAuth | (() => DeviceAuth | Promise<DeviceAuth>);
|
|
113
|
+
/**
|
|
114
|
+
* A relay refused this device (R4-L2): "retry" (with backoff, e.g. the device was linked
|
|
115
|
+
* during a fork and isn't in every branch yet) or "fatal" (revoked). Default: fatal.
|
|
116
|
+
*/
|
|
117
|
+
onAuthRefused?: (relay: string) => Promise<"retry" | "fatal">;
|
|
118
|
+
timeoutMs: number;
|
|
119
|
+
/** Per request (default 15 s). */
|
|
120
|
+
requestTimeoutMs?: number;
|
|
121
|
+
progress?: Progress;
|
|
122
|
+
/** How long a drain waits, past its own bound, for handlers already running (default 10 s). */
|
|
123
|
+
handlerGraceMs?: number;
|
|
124
|
+
/** With `reconnect` (a watch): first wait before an envelope answered "keep" is handled again (default 2 s). */
|
|
125
|
+
keepRetryMs?: number;
|
|
126
|
+
onEnvelope?: EnvelopeHandler;
|
|
127
|
+
/** The lookup a connection to `relay` dials through (App.guardRelays: privateGuardLookup), if any. */
|
|
128
|
+
lookupFor?: (relay: string) => import("node:net").LookupFunction | undefined;
|
|
129
|
+
/** Reconnect own relays with backoff (watch). */
|
|
130
|
+
reconnect?: boolean;
|
|
131
|
+
log?: (msg: string) => void;
|
|
132
|
+
/** Every own relay refused this device (revoked): nothing to reconnect to. */
|
|
133
|
+
onFatal?: (reason: string) => void;
|
|
134
|
+
allowRestricted?: boolean;
|
|
135
|
+
/** Every new authenticated connection (own or a recipient's relay). */
|
|
136
|
+
onAuthed?: (conn: RelayConnection) => void;
|
|
137
|
+
}
|
|
138
|
+
/** §5.8: each envelope goes to at most this many of the recipient's relays. */
|
|
139
|
+
export declare const MAX_SEND_RELAYS = 3;
|
|
140
|
+
/** A watch's first wait before handling an envelope it kept again (RelayPool.retryKept). */
|
|
141
|
+
export declare const KEEP_RETRY_MS = 2000;
|
|
142
|
+
/** How many times a watch handles a kept envelope again on the same connection. */
|
|
143
|
+
export declare const KEEP_RETRIES = 10;
|
|
144
|
+
/** How long a drain waits, past its own bound, for envelope handlers already running. */
|
|
145
|
+
export declare const DRAIN_HANDLER_GRACE_MS = 10000;
|
|
146
|
+
export declare class RelayPool {
|
|
147
|
+
private readonly opts;
|
|
148
|
+
private readonly conns;
|
|
149
|
+
private readonly connecting;
|
|
150
|
+
private readonly own;
|
|
151
|
+
private readonly fatal;
|
|
152
|
+
private readonly attempts;
|
|
153
|
+
/** At most one pending reconnect per relay (timers used to double on every failure). */
|
|
154
|
+
private readonly pending;
|
|
155
|
+
/** Connection attempts made, per relay (for diagnostics and tests). */
|
|
156
|
+
readonly dials: Map<string, number>;
|
|
157
|
+
/** The last failure per own relay, cleared on success. */
|
|
158
|
+
readonly lastError: Map<string, string>;
|
|
159
|
+
private closing;
|
|
160
|
+
private queue;
|
|
161
|
+
private inflight;
|
|
162
|
+
private lastEnvAt;
|
|
163
|
+
private timers;
|
|
164
|
+
/** Envelope handlers queued or running. */
|
|
165
|
+
get busy(): boolean;
|
|
166
|
+
/** stopHandling(): the process is exiting; envelopes not started yet are left on the relays. */
|
|
167
|
+
private stopped;
|
|
168
|
+
/**
|
|
169
|
+
* The command gave up on its handlers (App.close past its grace): nothing more is started, so
|
|
170
|
+
* nothing more is claimed and then cut off by the exit. Not acked: the relays keep them. The
|
|
171
|
+
* abandoned handlers send nothing more either (sendEnvelope refuses): their claims went back
|
|
172
|
+
* and the envelope is applied again elsewhere, so a send now (a circle want's answer) would go
|
|
173
|
+
* out twice (pre-release re-review F1).
|
|
174
|
+
*/
|
|
175
|
+
stopHandling(): void;
|
|
176
|
+
/** Wakes a drain waiting on the queue or on a relay's `caught-up`. */
|
|
177
|
+
private wakers;
|
|
178
|
+
constructor(opts: PoolOptions);
|
|
179
|
+
/** Every open, authenticated connection (own relays and recipients'). */
|
|
180
|
+
authedConnections(): RelayConnection[];
|
|
181
|
+
/** Own relays currently authenticated. */
|
|
182
|
+
get connected(): string[];
|
|
183
|
+
/** Connects to every own relay. Resolves when each has succeeded or failed. */
|
|
184
|
+
connect(): Promise<{
|
|
185
|
+
connected: string[];
|
|
186
|
+
failed: {
|
|
187
|
+
relay: string;
|
|
188
|
+
error: string;
|
|
189
|
+
}[];
|
|
190
|
+
}>;
|
|
191
|
+
/** A relay refused this device: retried with backoff when the app says so (R4-L2), else fatal. */
|
|
192
|
+
private refused;
|
|
193
|
+
private checkFatal;
|
|
194
|
+
private scheduleReconnect;
|
|
195
|
+
/** An authenticated connection to `relay` (own or a recipient's), opened on demand. */
|
|
196
|
+
ensure(relay: string, what?: string): Promise<RelayConnection>;
|
|
197
|
+
private onEnv;
|
|
198
|
+
/**
|
|
199
|
+
* A long-lived pool (a watch) handles an envelope it answered "keep" again later, on the same
|
|
200
|
+
* connection. A relay sends each envelope once per connection (and again only to one that
|
|
201
|
+
* authenticates), so an envelope a watch kept because another process held its claim was
|
|
202
|
+
* never seen by that watch again: if the holder then exited without finishing, nothing on the
|
|
203
|
+
* device applied it until some command connected (pre-release review M-A). Backs off from
|
|
204
|
+
* KEEP_RETRY_MS (doubling, at most a minute), KEEP_RETRIES times, while the connection lasts.
|
|
205
|
+
*/
|
|
206
|
+
private retryKept;
|
|
207
|
+
/**
|
|
208
|
+
* The backlog: what the relays delivered before the last of them said `caught-up`. Envelopes
|
|
209
|
+
* are handled in arrival order, and a relay sends `caught-up` after its backlog, so the queue
|
|
210
|
+
* as it stands then ends with the backlog. `backlogHandled` turns true when that much of the
|
|
211
|
+
* queue is through; envelopes arriving live after it don't hold the drain (pre-release soak: during a
|
|
212
|
+
* burst of statuses a short command's drain never saw the queue empty and ran to its 5 s cap).
|
|
213
|
+
*/
|
|
214
|
+
private backlogTail?;
|
|
215
|
+
private backlogHandled;
|
|
216
|
+
private onCaughtUp;
|
|
217
|
+
private wake;
|
|
218
|
+
/** Resolves after `ms`, or sooner when a handler finishes or a relay says `caught-up`. */
|
|
219
|
+
private nap;
|
|
220
|
+
/**
|
|
221
|
+
* Every own relay this pool is connected to said `caught-up` (§5.4): nothing more is queued for
|
|
222
|
+
* this device on them, beyond what is already being handled.
|
|
223
|
+
*/
|
|
224
|
+
get caughtUp(): boolean;
|
|
225
|
+
/**
|
|
226
|
+
* Waits until no envelope has arrived (or is being handled) for `quietMs`, at most `maxMs`.
|
|
227
|
+
*
|
|
228
|
+
* `backlog`: this is the drain right after connecting, for what was queued while this device
|
|
229
|
+
* was away. Then the wait ends as soon as every connected own relay has said `caught-up`
|
|
230
|
+
* (§5.4) and everything it delivered was handled; a relay from before that is waited out as
|
|
231
|
+
* above. Without it (a command waiting for answers to arrive live), the quiet period applies.
|
|
232
|
+
*/
|
|
233
|
+
drain(quietMs: number, maxMs: number, opts?: {
|
|
234
|
+
backlog?: boolean;
|
|
235
|
+
}): Promise<void>;
|
|
236
|
+
/** Sends one envelope to up to 3 recipient relays (§5.8). */
|
|
237
|
+
sendEnvelope(env: string, to: string, tdid: string, kind: string, targets: readonly SendTarget[]): Promise<SendResult>;
|
|
238
|
+
/** `{"t":"identity"}` to one relay; back-fills `history` (oldest first) on `identity-gap`. */
|
|
239
|
+
publishIdentity(relay: string, doc: string, history?: readonly string[]): Promise<string>;
|
|
240
|
+
/**
|
|
241
|
+
* The same, over a fresh restricted-capable connection: for a relay whose held document
|
|
242
|
+
* doesn't list this device yet (after a restore, R4-M2). Identity publishes only.
|
|
243
|
+
*/
|
|
244
|
+
publishIdentityRestricted(relay: string, doc: string, history?: readonly string[]): Promise<string>;
|
|
245
|
+
/** `{"t":"revoke","capid"}` to every relay the cap names; returns the relays that confirmed. */
|
|
246
|
+
revoke(capid: string, relays: readonly string[]): Promise<string[]>;
|
|
247
|
+
close(): void;
|
|
248
|
+
}
|
|
249
|
+
/** `{"t":"identity"}` on a connection; back-fills `history` (oldest first) on `identity-gap` (§2.5). */
|
|
250
|
+
export declare function publishOver(conn: RelayConnection, doc: string, history?: readonly string[]): Promise<string>;
|
|
251
|
+
/** An unauthenticated connection for the pre-auth link mailbox (§5.7). */
|
|
252
|
+
export declare function openLinkConnection(relay: string, transport: TransportResolver, timeoutMs: number, progress?: Progress, opts?: {
|
|
253
|
+
lookup?: import("node:net").LookupFunction;
|
|
254
|
+
}): Promise<RelayConnection>;
|
|
255
|
+
export declare function linkPut(conn: RelayConnection, lid: string, slot: "req" | "resp", data: string): Promise<void>;
|
|
256
|
+
/** The entries of a slot, or undefined when the mailbox is gone. */
|
|
257
|
+
export declare function linkGet(conn: RelayConnection, lid: string, slot: "req" | "resp"): Promise<string[] | undefined>;
|
|
258
|
+
/** Puts a sealed invite (authenticated connection); resolves with the expiry the relay set (seconds). */
|
|
259
|
+
export declare function invitePut(conn: RelayConnection, lid: string, blob: string, ttlSec: number, admit?: string): Promise<number>;
|
|
260
|
+
/** Takes the invite under `lid` (single use); undefined when there is none. */
|
|
261
|
+
export declare function inviteGet(conn: RelayConnection, lid: string): Promise<string | undefined>;
|
|
262
|
+
/** The lids this user holds open on the relay, and those it evicted to make room (not yet expired). */
|
|
263
|
+
export declare function inviteList(conn: RelayConnection): Promise<{
|
|
264
|
+
lids: string[];
|
|
265
|
+
evicted: string[];
|
|
266
|
+
}>;
|
|
267
|
+
/** Deletes an open invite; false when the relay held none under `lid`. */
|
|
268
|
+
export declare function inviteDel(conn: RelayConnection, lid: string): Promise<boolean>;
|
|
269
|
+
/** review L6: a relay's document API answer is at most this big (64 tips or chain entries of ≤ 16 KiB, with room). */
|
|
270
|
+
export declare const MAX_HTTP_BODY_BYTES: number;
|
|
271
|
+
/** Reads a response body, refusing more than `max` bytes. */
|
|
272
|
+
export declare function readCapped(res: Response, max: number): Promise<string>;
|
|
273
|
+
/** GET /.well-known/p2p-relay.json from the relay's host (undefined: 404, an older relay). */
|
|
274
|
+
export declare function fetchRelayInfo(t: Transport, timeoutMs: number, progress?: Progress): Promise<Record<string, unknown> | undefined>;
|
|
275
|
+
export declare function fetchTips(t: Transport, userId: string, timeoutMs: number, progress?: Progress, lookup?: LookupFunction): Promise<string[]>;
|
|
276
|
+
export declare function fetchChain(t: Transport, userId: string, to: string, n: number, timeoutMs: number, progress?: Progress, lookup?: LookupFunction): Promise<string[]>;
|
|
277
|
+
export declare const sleep: (ms: number) => Promise<void>;
|