@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,873 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// The relay client (docs/protocol.md §5): one WebSocket per relay, the §5.2
|
|
4
|
+
// hello check and device-signature auth, request/reply by `id`, and a pool
|
|
5
|
+
// over all of the user's relays (1–5) that
|
|
6
|
+
// - receives from every one of them (each delivery is handed to one
|
|
7
|
+
// serial handler and acked on the connection it came from once handled;
|
|
8
|
+
// multi-relay copies are deduplicated by the receiver's replay window);
|
|
9
|
+
// - sends each envelope to up to 3 of the recipient's relays, with a cap
|
|
10
|
+
// or, for a cap-less `contact`, proof of work, and reports which relays
|
|
11
|
+
// took it ("delivered via N relays");
|
|
12
|
+
// - publishes identity documents (back-filling a relay that is behind),
|
|
13
|
+
// revokes caps, and runs the pre-auth link mailbox operations;
|
|
14
|
+
// - reconnects with backoff (1 s → 30 s) when asked to (`watch`).
|
|
15
|
+
// The HTTP document API (§5.6) is here too: head, tips and chain fetches.
|
|
16
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
17
|
+
import { get as httpGet } from "node:http";
|
|
18
|
+
import { get as httpsGet } from "node:https";
|
|
19
|
+
import WebSocket from "ws";
|
|
20
|
+
import { checkHelloRelay, signRelayAuth, solvePow, MAX_RELAY_FRAME_BYTES } from "@peer2peer/core/v3";
|
|
21
|
+
import { CliError } from "./errors.js";
|
|
22
|
+
import { PRIVATE_RESOLVE_MARK } from "./shortcode.js";
|
|
23
|
+
import { debug, hostKey, step } from "./progress.js";
|
|
24
|
+
/** Close codes the relay uses (packages/relay CLOSE). */
|
|
25
|
+
export const CLOSE_AUTH_FAILED = 4001;
|
|
26
|
+
/** The device certificate expired: reconnect with a renewed one (R4-L1). */
|
|
27
|
+
export const CLOSE_CERT_EXPIRED = 4003;
|
|
28
|
+
const REQUEST_TIMEOUT_MS = 15_000;
|
|
29
|
+
/** How long a short command waits for a relay's closing frame on its way out (pre-release review L1). */
|
|
30
|
+
export const CLOSE_WAIT_MS = 1000;
|
|
31
|
+
/** review M2: a relay's error code, as far as we repeat it: `[a-z-]{1,32}`, else "relay-error". */
|
|
32
|
+
export function relayCode(v) {
|
|
33
|
+
return typeof v === "string" && /^[a-z-]{1,32}$/.test(v) ? v : "relay-error";
|
|
34
|
+
}
|
|
35
|
+
export class RelayConnection {
|
|
36
|
+
relay;
|
|
37
|
+
transport;
|
|
38
|
+
opts;
|
|
39
|
+
ws;
|
|
40
|
+
hello;
|
|
41
|
+
authed = false;
|
|
42
|
+
/** Authenticated, but only for identity publishes (see packages/relay ConnAuth.restricted). */
|
|
43
|
+
restricted = false;
|
|
44
|
+
/** Set by a members-only relay that follows a circle: which, and the version it holds (0: none yet). */
|
|
45
|
+
circle;
|
|
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 = false;
|
|
51
|
+
closeCode;
|
|
52
|
+
pending = new Map();
|
|
53
|
+
nextId = 1;
|
|
54
|
+
closedResolve;
|
|
55
|
+
closed;
|
|
56
|
+
constructor(relay, transport, opts) {
|
|
57
|
+
this.relay = relay;
|
|
58
|
+
this.transport = transport;
|
|
59
|
+
this.opts = opts;
|
|
60
|
+
this.closed = new Promise((r) => (this.closedResolve = r));
|
|
61
|
+
}
|
|
62
|
+
get isOpen() {
|
|
63
|
+
return this.ws?.readyState === WebSocket.OPEN;
|
|
64
|
+
}
|
|
65
|
+
/** Dials, checks `hello.relay` against the canonical URL (H5), and authenticates when a device is given. */
|
|
66
|
+
open() {
|
|
67
|
+
return step(this.opts.progress, `connecting to ${this.relay}${this.opts.what ?? ""}`, () => this.openInner());
|
|
68
|
+
}
|
|
69
|
+
async openInner() {
|
|
70
|
+
const ws = new WebSocket(this.transport.ws, {
|
|
71
|
+
handshakeTimeout: this.opts.timeoutMs,
|
|
72
|
+
maxPayload: 2 * MAX_RELAY_FRAME_BYTES,
|
|
73
|
+
perMessageDeflate: false,
|
|
74
|
+
...(this.opts.lookup ? { lookup: this.opts.lookup } : {}),
|
|
75
|
+
// A short command on its way out waits for the relay's closing frame (so the acks it sent
|
|
76
|
+
// are read before the socket goes), but not ws's default 30 s if the relay never answers.
|
|
77
|
+
...(this.opts.rememberUnreachable !== false ? { closeTimeout: CLOSE_WAIT_MS } : {}),
|
|
78
|
+
});
|
|
79
|
+
this.ws = ws;
|
|
80
|
+
let helloResolve;
|
|
81
|
+
const helloP = new Promise((r) => (helloResolve = r));
|
|
82
|
+
ws.on("message", (data, isBinary) => {
|
|
83
|
+
if (isBinary)
|
|
84
|
+
return;
|
|
85
|
+
let f;
|
|
86
|
+
try {
|
|
87
|
+
f = JSON.parse(String(data));
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (typeof f !== "object" || f === null || typeof f.t !== "string")
|
|
93
|
+
return;
|
|
94
|
+
if (f.t === "hello" && !this.hello)
|
|
95
|
+
return helloResolve(f);
|
|
96
|
+
if (f.t === "env" && typeof f.rid === "string" && typeof f.env === "string") {
|
|
97
|
+
this.opts.onEnv?.(f.rid, f.env, this);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
// Sent once after `ok`, behind the backlog. It only ends a wait early: a relay that lies
|
|
101
|
+
// about it can do no more than one that withholds envelopes.
|
|
102
|
+
if (f.t === "caught-up" && f.id === undefined) {
|
|
103
|
+
this.caughtUp = true;
|
|
104
|
+
this.opts.onCaughtUp?.(this);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const id = typeof f.id === "string" ? f.id : undefined;
|
|
108
|
+
const p = id !== undefined ? this.pending.get(id) : undefined;
|
|
109
|
+
if (p) {
|
|
110
|
+
this.pending.delete(id);
|
|
111
|
+
clearTimeout(p.timer);
|
|
112
|
+
p.resolve(f);
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
ws.on("error", () => { });
|
|
116
|
+
ws.on("close", (code) => {
|
|
117
|
+
this.closeCode = code;
|
|
118
|
+
this.authed = false;
|
|
119
|
+
for (const p of this.pending.values()) {
|
|
120
|
+
clearTimeout(p.timer);
|
|
121
|
+
p.reject(new CliError("network", `relay ${this.relay} closed the connection (${code})`));
|
|
122
|
+
}
|
|
123
|
+
this.pending.clear();
|
|
124
|
+
this.closedResolve(code);
|
|
125
|
+
this.opts.onClose?.(code, this);
|
|
126
|
+
});
|
|
127
|
+
const timeout = (p, what) => Promise.race([
|
|
128
|
+
p,
|
|
129
|
+
new Promise((_, reject) => setTimeout(() => reject(new CliError("timeout", `${this.relay}: timed out ${what} (after ${Math.round(this.opts.timeoutMs / 1000)}s)`)), this.opts.timeoutMs).unref()),
|
|
130
|
+
this.closed.then((code) => {
|
|
131
|
+
throw new CliError(code === CLOSE_AUTH_FAILED ? "auth_failed" : "network", `${this.relay}: connection closed (${code}) ${what}`);
|
|
132
|
+
}),
|
|
133
|
+
]);
|
|
134
|
+
const { key, port } = hostKey(this.transport.ws);
|
|
135
|
+
// One clear message when the relay can't be reached at all (no answer to the TCP/TLS dial, a
|
|
136
|
+
// refusal, no route, no DNS), remembered for the rest of the command (see Progress.unreachable).
|
|
137
|
+
let dialed = false;
|
|
138
|
+
const unreachable = (why) => {
|
|
139
|
+
const e = new CliError("unreachable", `can't reach ${this.relay} (${why}: check your network or firewall)`);
|
|
140
|
+
if (!dialed && this.opts.rememberUnreachable !== false)
|
|
141
|
+
this.opts.progress?.unreachable?.set(key, e);
|
|
142
|
+
return e;
|
|
143
|
+
};
|
|
144
|
+
let dialTimer;
|
|
145
|
+
try {
|
|
146
|
+
await Promise.race([
|
|
147
|
+
new Promise((resolve, reject) => {
|
|
148
|
+
ws.once("open", () => resolve());
|
|
149
|
+
ws.once("error", (e) => {
|
|
150
|
+
const code = e.code ?? "";
|
|
151
|
+
if (code === "ECONNREFUSED")
|
|
152
|
+
reject(unreachable(`connection refused on port ${port}`));
|
|
153
|
+
else if (code === "ENOTFOUND" || code === "EAI_AGAIN")
|
|
154
|
+
reject(unreachable(`can't resolve ${new URL(this.transport.ws).hostname}`));
|
|
155
|
+
else if (["EHOSTUNREACH", "ENETUNREACH", "ETIMEDOUT", "EHOSTDOWN"].includes(code) || /handshake has timed out/i.test(e.message)) {
|
|
156
|
+
reject(unreachable(`no response on port ${port} after ${Math.round(this.opts.timeoutMs / 1000)}s`));
|
|
157
|
+
}
|
|
158
|
+
else
|
|
159
|
+
reject(new CliError("network", `${this.relay}: ${e.message}`));
|
|
160
|
+
});
|
|
161
|
+
ws.once("unexpected-response", (_req, res) => reject(new CliError("network", `${this.relay}: HTTP ${res.statusCode}`)));
|
|
162
|
+
}),
|
|
163
|
+
new Promise((_, reject) => {
|
|
164
|
+
dialTimer = setTimeout(() => reject(unreachable(`no response on port ${port} after ${Math.round(this.opts.timeoutMs / 1000)}s`)), this.opts.timeoutMs);
|
|
165
|
+
dialTimer.unref();
|
|
166
|
+
}),
|
|
167
|
+
]).finally(() => {
|
|
168
|
+
// The dial is settled: a late timer or socket error must not record this relay as unreachable
|
|
169
|
+
// for the rest of the command (Progress.unreachable) although it answered.
|
|
170
|
+
dialed = true;
|
|
171
|
+
if (dialTimer)
|
|
172
|
+
clearTimeout(dialTimer);
|
|
173
|
+
});
|
|
174
|
+
const h = await timeout(helloP, "waiting for hello");
|
|
175
|
+
if (typeof h.relay !== "string" || typeof h.nonce !== "string")
|
|
176
|
+
throw new CliError("bad_relay", `${this.relay}: malformed hello`);
|
|
177
|
+
// §5.2 step 2 (review H5): the relay must name the URL we meant to reach.
|
|
178
|
+
try {
|
|
179
|
+
checkHelloRelay(h.relay, this.relay);
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
throw new CliError("relay_mismatch", `${this.relay} introduced itself as another relay; closing`);
|
|
183
|
+
}
|
|
184
|
+
this.hello = { relay: h.relay, nonce: h.nonce, pow: typeof h.pow === "number" ? h.pow : 0, limits: h.limits };
|
|
185
|
+
if (this.opts.auth) {
|
|
186
|
+
const sig = signRelayAuth(this.hello.relay, this.hello.nonce, this.opts.auth.signingSecretKey);
|
|
187
|
+
const admit = this.opts.auth.admits?.[this.relay];
|
|
188
|
+
const r = await timeout(this.request({ t: "auth", cert: this.opts.auth.cert, sig, ...(admit ? { admit } : {}) }), "authenticating");
|
|
189
|
+
if (r.t === "error" && r.code === "not-member") {
|
|
190
|
+
throw new CliError("not_member", `${this.relay} is members-only and doesn't admit this identity: ask a member for an invite code, or its operator to add your userId`);
|
|
191
|
+
}
|
|
192
|
+
if (r.t !== "ok")
|
|
193
|
+
throw new CliError("auth_failed", `${this.relay} refused this device (${relayCode(r.code ?? r.t)})`);
|
|
194
|
+
if (r.admitted !== undefined)
|
|
195
|
+
this.opts.auth.onAdmitted?.(this.relay);
|
|
196
|
+
const c = r.circle;
|
|
197
|
+
if (c && typeof c.cid === "string" && typeof c.ver === "number")
|
|
198
|
+
this.circle = { cid: c.cid, ver: c.ver };
|
|
199
|
+
if (r.restricted === true && !this.opts.allowRestricted) {
|
|
200
|
+
throw new CliError("auth_failed", `${this.relay} refused this device (not listed in your identity document)`);
|
|
201
|
+
}
|
|
202
|
+
this.restricted = r.restricted === true;
|
|
203
|
+
this.authed = true;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
catch (e) {
|
|
207
|
+
this.close();
|
|
208
|
+
throw e;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** Sends a frame with an `id` and resolves with the reply echoing it. */
|
|
212
|
+
request(frame, timeoutMs = this.opts.requestTimeoutMs ?? REQUEST_TIMEOUT_MS) {
|
|
213
|
+
// The label names the relay and the frame type only (never its contents).
|
|
214
|
+
return step(this.opts.progress, `waiting for ${this.relay} to answer ${frame.t}`, () => this.requestInner(frame, timeoutMs));
|
|
215
|
+
}
|
|
216
|
+
requestInner(frame, timeoutMs) {
|
|
217
|
+
const id = `c${this.nextId++}`;
|
|
218
|
+
return new Promise((resolve, reject) => {
|
|
219
|
+
if (!this.isOpen)
|
|
220
|
+
return reject(new CliError("network", `relay ${this.relay} is not connected`));
|
|
221
|
+
const timer = setTimeout(() => {
|
|
222
|
+
this.pending.delete(id);
|
|
223
|
+
reject(new CliError("timeout", `${this.relay}: no reply to ${frame.t} after ${Math.round(timeoutMs / 1000)}s`));
|
|
224
|
+
}, timeoutMs);
|
|
225
|
+
timer.unref();
|
|
226
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
227
|
+
this.ws.send(JSON.stringify({ ...frame, id }));
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/** Fire-and-forget (the relay does not reply to `ack`). */
|
|
231
|
+
send(frame) {
|
|
232
|
+
if (this.isOpen)
|
|
233
|
+
this.ws.send(JSON.stringify(frame));
|
|
234
|
+
}
|
|
235
|
+
close() {
|
|
236
|
+
try {
|
|
237
|
+
this.ws?.close();
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
// already closed
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/** The pool whose envelope handler is running (App.connect uses it: pre-release review M1). */
|
|
245
|
+
export const handlerPool = new AsyncLocalStorage();
|
|
246
|
+
const BACKOFF_MS = [1000, 2000, 4000, 8000, 16000, 30000];
|
|
247
|
+
/** §5.8: each envelope goes to at most this many of the recipient's relays. */
|
|
248
|
+
export const MAX_SEND_RELAYS = 3;
|
|
249
|
+
/** A watch's first wait before handling an envelope it kept again (RelayPool.retryKept). */
|
|
250
|
+
export const KEEP_RETRY_MS = 2000;
|
|
251
|
+
/** How many times a watch handles a kept envelope again on the same connection. */
|
|
252
|
+
export const KEEP_RETRIES = 10;
|
|
253
|
+
/** How long a drain waits, past its own bound, for envelope handlers already running. */
|
|
254
|
+
export const DRAIN_HANDLER_GRACE_MS = 10_000;
|
|
255
|
+
export class RelayPool {
|
|
256
|
+
opts;
|
|
257
|
+
conns = new Map();
|
|
258
|
+
connecting = new Map();
|
|
259
|
+
own;
|
|
260
|
+
fatal = new Set();
|
|
261
|
+
attempts = new Map();
|
|
262
|
+
/** At most one pending reconnect per relay (timers used to double on every failure). */
|
|
263
|
+
pending = new Map();
|
|
264
|
+
/** Connection attempts made, per relay (for diagnostics and tests). */
|
|
265
|
+
dials = new Map();
|
|
266
|
+
/** The last failure per own relay, cleared on success. */
|
|
267
|
+
lastError = new Map();
|
|
268
|
+
closing = false;
|
|
269
|
+
queue = Promise.resolve();
|
|
270
|
+
inflight = 0;
|
|
271
|
+
lastEnvAt = 0;
|
|
272
|
+
timers = new Set();
|
|
273
|
+
/** Envelope handlers queued or running. */
|
|
274
|
+
get busy() {
|
|
275
|
+
return this.inflight > 0;
|
|
276
|
+
}
|
|
277
|
+
/** stopHandling(): the process is exiting; envelopes not started yet are left on the relays. */
|
|
278
|
+
stopped = false;
|
|
279
|
+
/**
|
|
280
|
+
* The command gave up on its handlers (App.close past its grace): nothing more is started, so
|
|
281
|
+
* nothing more is claimed and then cut off by the exit. Not acked: the relays keep them. The
|
|
282
|
+
* abandoned handlers send nothing more either (sendEnvelope refuses): their claims went back
|
|
283
|
+
* and the envelope is applied again elsewhere, so a send now (a circle want's answer) would go
|
|
284
|
+
* out twice (pre-release re-review F1).
|
|
285
|
+
*/
|
|
286
|
+
stopHandling() {
|
|
287
|
+
this.stopped = true;
|
|
288
|
+
}
|
|
289
|
+
/** Wakes a drain waiting on the queue or on a relay's `caught-up`. */
|
|
290
|
+
wakers = new Set();
|
|
291
|
+
constructor(opts) {
|
|
292
|
+
this.opts = opts;
|
|
293
|
+
this.own = new Set(opts.relays);
|
|
294
|
+
}
|
|
295
|
+
/** Every open, authenticated connection (own relays and recipients'). */
|
|
296
|
+
authedConnections() {
|
|
297
|
+
return [...this.conns.values()].filter((c) => c.authed && c.isOpen);
|
|
298
|
+
}
|
|
299
|
+
/** Own relays currently authenticated. */
|
|
300
|
+
get connected() {
|
|
301
|
+
return [...this.own].filter((r) => this.conns.get(r)?.authed);
|
|
302
|
+
}
|
|
303
|
+
/** Connects to every own relay. Resolves when each has succeeded or failed. */
|
|
304
|
+
async connect() {
|
|
305
|
+
const failed = [];
|
|
306
|
+
const all = [...this.own];
|
|
307
|
+
await Promise.all(all.map(async (r, i) => {
|
|
308
|
+
try {
|
|
309
|
+
await this.ensure(r, ` (relay ${i + 1}/${all.length})`);
|
|
310
|
+
}
|
|
311
|
+
catch (e) {
|
|
312
|
+
failed.push({ relay: r, error: e.message });
|
|
313
|
+
if (e.code === "auth_failed")
|
|
314
|
+
await this.refused(r);
|
|
315
|
+
else
|
|
316
|
+
this.scheduleReconnect(r);
|
|
317
|
+
}
|
|
318
|
+
}));
|
|
319
|
+
this.checkFatal();
|
|
320
|
+
return { connected: this.connected, failed };
|
|
321
|
+
}
|
|
322
|
+
/** A relay refused this device: retried with backoff when the app says so (R4-L2), else fatal. */
|
|
323
|
+
async refused(relay) {
|
|
324
|
+
const verdict = this.opts.onAuthRefused ? await this.opts.onAuthRefused(relay).catch(() => "fatal") : "fatal";
|
|
325
|
+
if (verdict === "retry" && this.opts.reconnect) {
|
|
326
|
+
this.scheduleReconnect(relay);
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
this.fatal.add(relay);
|
|
330
|
+
this.checkFatal();
|
|
331
|
+
}
|
|
332
|
+
checkFatal() {
|
|
333
|
+
if (this.own.size > 0 && [...this.own].every((r) => this.fatal.has(r))) {
|
|
334
|
+
this.opts.onFatal?.("every relay refused this device: it may have been revoked");
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
scheduleReconnect(relay) {
|
|
338
|
+
if (!this.opts.reconnect || this.closing || !this.own.has(relay) || this.fatal.has(relay))
|
|
339
|
+
return;
|
|
340
|
+
if (this.pending.has(relay) || this.connecting.has(relay))
|
|
341
|
+
return;
|
|
342
|
+
const n = this.attempts.get(relay) ?? 0;
|
|
343
|
+
this.attempts.set(relay, n + 1);
|
|
344
|
+
const wait = BACKOFF_MS[Math.min(n, BACKOFF_MS.length - 1)];
|
|
345
|
+
const t = setTimeout(() => {
|
|
346
|
+
this.timers.delete(t);
|
|
347
|
+
this.pending.delete(relay);
|
|
348
|
+
if (this.closing)
|
|
349
|
+
return;
|
|
350
|
+
this.ensure(relay).then(() => this.attempts.set(relay, 0), (e) => {
|
|
351
|
+
if (e.code === "auth_failed")
|
|
352
|
+
void this.refused(relay);
|
|
353
|
+
else
|
|
354
|
+
this.scheduleReconnect(relay);
|
|
355
|
+
});
|
|
356
|
+
}, wait);
|
|
357
|
+
this.timers.add(t);
|
|
358
|
+
this.pending.set(relay, t);
|
|
359
|
+
}
|
|
360
|
+
/** An authenticated connection to `relay` (own or a recipient's), opened on demand. */
|
|
361
|
+
ensure(relay, what = "") {
|
|
362
|
+
// A closed pool never dials again: a handler that outlived its command (still sending an
|
|
363
|
+
// answer, say) would otherwise open a connection nobody closes, as this device, and take
|
|
364
|
+
// envelopes meant for the next command or the running watch (pre-release review: a want answered,
|
|
365
|
+
// and acked, by a dead process).
|
|
366
|
+
if (this.closing)
|
|
367
|
+
return Promise.reject(new CliError("closing", "this command closed its relay connections"));
|
|
368
|
+
const have = this.conns.get(relay);
|
|
369
|
+
if (have?.authed && have.isOpen)
|
|
370
|
+
return Promise.resolve(have);
|
|
371
|
+
const inflight = this.connecting.get(relay);
|
|
372
|
+
if (inflight)
|
|
373
|
+
return inflight;
|
|
374
|
+
// Found unreachable earlier in this command: fail at once (watch keeps retrying with backoff).
|
|
375
|
+
if (!this.opts.reconnect) {
|
|
376
|
+
const known = this.opts.progress?.unreachable?.get(hostKey(this.opts.transport(relay).ws).key);
|
|
377
|
+
if (known)
|
|
378
|
+
return Promise.reject(known);
|
|
379
|
+
}
|
|
380
|
+
const p = (async () => {
|
|
381
|
+
this.dials.set(relay, (this.dials.get(relay) ?? 0) + 1);
|
|
382
|
+
let opened = false;
|
|
383
|
+
const auth = typeof this.opts.auth === "function" ? await this.opts.auth() : this.opts.auth;
|
|
384
|
+
const lookup = this.opts.lookupFor?.(relay);
|
|
385
|
+
const conn = new RelayConnection(relay, this.opts.transport(relay), {
|
|
386
|
+
auth,
|
|
387
|
+
...(lookup ? { lookup } : {}),
|
|
388
|
+
allowRestricted: this.opts.allowRestricted,
|
|
389
|
+
timeoutMs: this.opts.timeoutMs,
|
|
390
|
+
requestTimeoutMs: this.opts.requestTimeoutMs,
|
|
391
|
+
progress: this.opts.progress,
|
|
392
|
+
what,
|
|
393
|
+
rememberUnreachable: !this.opts.reconnect,
|
|
394
|
+
onEnv: (rid, env, c) => this.onEnv(rid, env, c),
|
|
395
|
+
onCaughtUp: () => this.onCaughtUp(),
|
|
396
|
+
onClose: (code, c) => {
|
|
397
|
+
if (this.conns.get(relay) === c)
|
|
398
|
+
this.conns.delete(relay);
|
|
399
|
+
// A connection that never opened is handled by the caller (one reconnect, not two).
|
|
400
|
+
if (this.closing || !opened)
|
|
401
|
+
return;
|
|
402
|
+
if (code === CLOSE_AUTH_FAILED && this.own.has(relay)) {
|
|
403
|
+
this.opts.log?.(`${relay} closed this device's connection: not allowed`);
|
|
404
|
+
void this.refused(relay);
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
if (code === CLOSE_CERT_EXPIRED && this.own.has(relay)) {
|
|
408
|
+
this.opts.log?.(`${relay}: this device's certificate expired; reconnecting with a renewed one`);
|
|
409
|
+
this.scheduleReconnect(relay);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (this.own.has(relay)) {
|
|
413
|
+
this.opts.log?.(`${relay} disconnected (${code}); reconnecting`);
|
|
414
|
+
this.scheduleReconnect(relay);
|
|
415
|
+
}
|
|
416
|
+
},
|
|
417
|
+
});
|
|
418
|
+
try {
|
|
419
|
+
await conn.open();
|
|
420
|
+
opened = true;
|
|
421
|
+
this.lastError.delete(relay);
|
|
422
|
+
}
|
|
423
|
+
catch (e) {
|
|
424
|
+
this.lastError.set(relay, e.message);
|
|
425
|
+
throw e;
|
|
426
|
+
}
|
|
427
|
+
finally {
|
|
428
|
+
this.connecting.delete(relay);
|
|
429
|
+
}
|
|
430
|
+
this.conns.set(relay, conn);
|
|
431
|
+
this.opts.onAuthed?.(conn);
|
|
432
|
+
return conn;
|
|
433
|
+
})();
|
|
434
|
+
this.connecting.set(relay, p);
|
|
435
|
+
return p;
|
|
436
|
+
}
|
|
437
|
+
onEnv(rid, env, conn, retry = 0) {
|
|
438
|
+
this.lastEnvAt = Date.now();
|
|
439
|
+
this.inflight++;
|
|
440
|
+
const run = async () => {
|
|
441
|
+
if (this.stopped) {
|
|
442
|
+
this.inflight--;
|
|
443
|
+
this.wake();
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
let verdict = "ack";
|
|
447
|
+
try {
|
|
448
|
+
const handle = this.opts.onEnvelope;
|
|
449
|
+
if (handle)
|
|
450
|
+
verdict = await handlerPool.run(this, () => handle(env, conn.relay));
|
|
451
|
+
}
|
|
452
|
+
catch (e) {
|
|
453
|
+
this.opts.log?.(`handling an envelope from ${conn.relay} failed: ${e.message}`);
|
|
454
|
+
verdict = "keep";
|
|
455
|
+
}
|
|
456
|
+
finally {
|
|
457
|
+
this.inflight--;
|
|
458
|
+
this.lastEnvAt = Date.now();
|
|
459
|
+
}
|
|
460
|
+
if (verdict === "ack")
|
|
461
|
+
conn.send({ t: "ack", rids: [rid] });
|
|
462
|
+
else
|
|
463
|
+
this.retryKept(rid, env, conn, retry);
|
|
464
|
+
this.wake();
|
|
465
|
+
};
|
|
466
|
+
this.queue = this.queue.then(run, run);
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* A long-lived pool (a watch) handles an envelope it answered "keep" again later, on the same
|
|
470
|
+
* connection. A relay sends each envelope once per connection (and again only to one that
|
|
471
|
+
* authenticates), so an envelope a watch kept because another process held its claim was
|
|
472
|
+
* never seen by that watch again: if the holder then exited without finishing, nothing on the
|
|
473
|
+
* device applied it until some command connected (pre-release review M-A). Backs off from
|
|
474
|
+
* KEEP_RETRY_MS (doubling, at most a minute), KEEP_RETRIES times, while the connection lasts.
|
|
475
|
+
*/
|
|
476
|
+
retryKept(rid, env, conn, retry) {
|
|
477
|
+
if (!this.opts.reconnect || this.closing || this.stopped || retry >= KEEP_RETRIES)
|
|
478
|
+
return;
|
|
479
|
+
const wait = Math.min(60_000, (this.opts.keepRetryMs ?? KEEP_RETRY_MS) * 2 ** retry);
|
|
480
|
+
const t = setTimeout(() => {
|
|
481
|
+
this.timers.delete(t);
|
|
482
|
+
if (this.closing || this.stopped || !conn.isOpen || this.conns.get(conn.relay) !== conn)
|
|
483
|
+
return;
|
|
484
|
+
this.onEnv(rid, env, conn, retry + 1);
|
|
485
|
+
}, wait);
|
|
486
|
+
t.unref?.();
|
|
487
|
+
this.timers.add(t);
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* The backlog: what the relays delivered before the last of them said `caught-up`. Envelopes
|
|
491
|
+
* are handled in arrival order, and a relay sends `caught-up` after its backlog, so the queue
|
|
492
|
+
* as it stands then ends with the backlog. `backlogHandled` turns true when that much of the
|
|
493
|
+
* queue is through; envelopes arriving live after it don't hold the drain (pre-release soak: during a
|
|
494
|
+
* burst of statuses a short command's drain never saw the queue empty and ran to its 5 s cap).
|
|
495
|
+
*/
|
|
496
|
+
backlogTail;
|
|
497
|
+
backlogHandled = false;
|
|
498
|
+
onCaughtUp() {
|
|
499
|
+
if (this.caughtUp) {
|
|
500
|
+
const tail = this.queue;
|
|
501
|
+
this.backlogTail = tail;
|
|
502
|
+
this.backlogHandled = false;
|
|
503
|
+
void tail.then(() => {
|
|
504
|
+
if (this.backlogTail !== tail)
|
|
505
|
+
return;
|
|
506
|
+
this.backlogHandled = true;
|
|
507
|
+
this.wake();
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
this.wake();
|
|
511
|
+
}
|
|
512
|
+
wake() {
|
|
513
|
+
const ws = [...this.wakers];
|
|
514
|
+
this.wakers.clear();
|
|
515
|
+
for (const w of ws)
|
|
516
|
+
w();
|
|
517
|
+
}
|
|
518
|
+
/** Resolves after `ms`, or sooner when a handler finishes or a relay says `caught-up`. */
|
|
519
|
+
nap(ms) {
|
|
520
|
+
return new Promise((resolve) => {
|
|
521
|
+
const done = () => {
|
|
522
|
+
clearTimeout(t);
|
|
523
|
+
this.wakers.delete(done);
|
|
524
|
+
resolve();
|
|
525
|
+
};
|
|
526
|
+
const t = setTimeout(done, ms);
|
|
527
|
+
this.wakers.add(done);
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Every own relay this pool is connected to said `caught-up` (§5.4): nothing more is queued for
|
|
532
|
+
* this device on them, beyond what is already being handled.
|
|
533
|
+
*/
|
|
534
|
+
get caughtUp() {
|
|
535
|
+
const live = [...this.own].map((r) => this.conns.get(r)).filter((c) => c !== undefined && c.authed && c.isOpen);
|
|
536
|
+
return live.length > 0 && live.every((c) => c.caughtUp);
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Waits until no envelope has arrived (or is being handled) for `quietMs`, at most `maxMs`.
|
|
540
|
+
*
|
|
541
|
+
* `backlog`: this is the drain right after connecting, for what was queued while this device
|
|
542
|
+
* was away. Then the wait ends as soon as every connected own relay has said `caught-up`
|
|
543
|
+
* (§5.4) and everything it delivered was handled; a relay from before that is waited out as
|
|
544
|
+
* above. Without it (a command waiting for answers to arrive live), the quiet period applies.
|
|
545
|
+
*/
|
|
546
|
+
async drain(quietMs, maxMs, opts = {}) {
|
|
547
|
+
const start = Date.now();
|
|
548
|
+
let backlogDone = false;
|
|
549
|
+
await step(this.opts.progress, "receiving what your relays queued for this device", async () => {
|
|
550
|
+
for (;;) {
|
|
551
|
+
const now = Date.now();
|
|
552
|
+
// A `caught-up` that came before its connection was registered: take the queue now.
|
|
553
|
+
if (opts.backlog && this.caughtUp && !this.backlogTail)
|
|
554
|
+
this.onCaughtUp();
|
|
555
|
+
if (opts.backlog && this.caughtUp && (this.inflight === 0 || this.backlogHandled)) {
|
|
556
|
+
backlogDone = true;
|
|
557
|
+
break;
|
|
558
|
+
}
|
|
559
|
+
if (this.inflight === 0 && now - Math.max(this.lastEnvAt, start) >= quietMs)
|
|
560
|
+
break;
|
|
561
|
+
if (now - start >= maxMs)
|
|
562
|
+
break;
|
|
563
|
+
await this.nap(Math.max(1, Math.min(50, quietMs, maxMs - (now - start))));
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
// The backlog is handled: what arrived live meanwhile is handled as it comes, not waited for.
|
|
567
|
+
if (backlogDone || this.inflight === 0)
|
|
568
|
+
return;
|
|
569
|
+
// Handling an envelope can take network round trips (each bounded); waiting for the rest of
|
|
570
|
+
// the queue is bounded too, so a backlog never stalls a command without a word.
|
|
571
|
+
const left = Math.max(0, maxMs - (Date.now() - start)) + (this.opts.handlerGraceMs ?? DRAIN_HANDLER_GRACE_MS);
|
|
572
|
+
let done = false;
|
|
573
|
+
await step(this.opts.progress, `handling ${this.inflight} queued message(s)`, () => Promise.race([
|
|
574
|
+
this.queue.then(() => {
|
|
575
|
+
done = true;
|
|
576
|
+
}),
|
|
577
|
+
new Promise((r) => setTimeout(r, left).unref()),
|
|
578
|
+
]));
|
|
579
|
+
if (!done)
|
|
580
|
+
this.opts.log?.(`still handling ${this.inflight} queued message(s) from your relays; going on (they stay queued until handled)`);
|
|
581
|
+
}
|
|
582
|
+
/** Sends one envelope to up to 3 recipient relays (§5.8). */
|
|
583
|
+
async sendEnvelope(env, to, tdid, kind, targets) {
|
|
584
|
+
if (this.stopped)
|
|
585
|
+
throw new CliError("closing", "this command gave up on its envelope handlers: not sending");
|
|
586
|
+
const res = { sent: [], errors: [] };
|
|
587
|
+
await Promise.all(targets.slice(0, MAX_SEND_RELAYS).map(async (t) => {
|
|
588
|
+
let written = false;
|
|
589
|
+
try {
|
|
590
|
+
const conn = await this.ensure(t.relay);
|
|
591
|
+
const frame = { t: "send", to, tdid, env };
|
|
592
|
+
if (t.cap)
|
|
593
|
+
frame.cap = t.cap;
|
|
594
|
+
else if (kind !== "contact")
|
|
595
|
+
throw new CliError("no_cap", "no capability for this relay");
|
|
596
|
+
else if ((conn.hello?.pow ?? 0) > 0) {
|
|
597
|
+
// Synchronous and possibly slow: always say so first (it blocks every timer).
|
|
598
|
+
const bits = conn.hello.pow;
|
|
599
|
+
if (bits >= 12 || this.opts.progress?.debug) {
|
|
600
|
+
this.opts.progress?.log(`no capability for ${t.relay}: solving its ${bits}-bit proof of work (this can take a while)…`);
|
|
601
|
+
// Let the notice reach the terminal first (TTY writes are asynchronous on Windows).
|
|
602
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
603
|
+
}
|
|
604
|
+
const t0 = Date.now();
|
|
605
|
+
frame.pow = solvePow(env, bits);
|
|
606
|
+
debug(this.opts.progress, `proof of work for ${t.relay}: ${Date.now() - t0}ms`);
|
|
607
|
+
}
|
|
608
|
+
// From here the frame goes onto an open connection (request refuses a closed one first).
|
|
609
|
+
written = conn.isOpen;
|
|
610
|
+
const r = await conn.request(frame);
|
|
611
|
+
if (r.t === "sent")
|
|
612
|
+
res.sent.push(t.relay);
|
|
613
|
+
else
|
|
614
|
+
res.errors.push({ relay: t.relay, code: relayCode(r.code ?? r.t), written: true });
|
|
615
|
+
}
|
|
616
|
+
catch (e) {
|
|
617
|
+
res.errors.push({ relay: t.relay, code: e.code ?? "network", ...(written ? { written: true } : {}) });
|
|
618
|
+
}
|
|
619
|
+
}));
|
|
620
|
+
return res;
|
|
621
|
+
}
|
|
622
|
+
/** `{"t":"identity"}` to one relay; back-fills `history` (oldest first) on `identity-gap`. */
|
|
623
|
+
async publishIdentity(relay, doc, history = []) {
|
|
624
|
+
return publishOver(await this.ensure(relay), doc, history);
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* The same, over a fresh restricted-capable connection: for a relay whose held document
|
|
628
|
+
* doesn't list this device yet (after a restore, R4-M2). Identity publishes only.
|
|
629
|
+
*/
|
|
630
|
+
async publishIdentityRestricted(relay, doc, history = []) {
|
|
631
|
+
const auth = typeof this.opts.auth === "function" ? await this.opts.auth() : this.opts.auth;
|
|
632
|
+
const conn = new RelayConnection(relay, this.opts.transport(relay), { auth, allowRestricted: true, timeoutMs: this.opts.timeoutMs, progress: this.opts.progress });
|
|
633
|
+
try {
|
|
634
|
+
await conn.open();
|
|
635
|
+
return await publishOver(conn, doc, history);
|
|
636
|
+
}
|
|
637
|
+
finally {
|
|
638
|
+
conn.close();
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
/** `{"t":"revoke","capid"}` to every relay the cap names; returns the relays that confirmed. */
|
|
642
|
+
async revoke(capid, relays) {
|
|
643
|
+
const ok = [];
|
|
644
|
+
await Promise.all(relays.map(async (r) => {
|
|
645
|
+
try {
|
|
646
|
+
const conn = await this.ensure(r);
|
|
647
|
+
const reply = await conn.request({ t: "revoke", capid });
|
|
648
|
+
if (reply.t === "ok")
|
|
649
|
+
ok.push(r);
|
|
650
|
+
}
|
|
651
|
+
catch {
|
|
652
|
+
// unreachable relay: the cap still expires on its own
|
|
653
|
+
}
|
|
654
|
+
}));
|
|
655
|
+
return ok;
|
|
656
|
+
}
|
|
657
|
+
close() {
|
|
658
|
+
this.closing = true;
|
|
659
|
+
this.pending.clear();
|
|
660
|
+
for (const t of this.timers)
|
|
661
|
+
clearTimeout(t);
|
|
662
|
+
this.timers.clear();
|
|
663
|
+
for (const c of this.conns.values())
|
|
664
|
+
c.close();
|
|
665
|
+
this.conns.clear();
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
/** `{"t":"identity"}` on a connection; back-fills `history` (oldest first) on `identity-gap` (§2.5). */
|
|
669
|
+
export async function publishOver(conn, doc, history = []) {
|
|
670
|
+
let r = await conn.request({ t: "identity", doc });
|
|
671
|
+
if (r.t === "error" && r.code === "identity-gap" && history.length > 0) {
|
|
672
|
+
for (const h of history)
|
|
673
|
+
await conn.request({ t: "identity", doc: h });
|
|
674
|
+
r = await conn.request({ t: "identity", doc });
|
|
675
|
+
}
|
|
676
|
+
return r.t === "ok" ? "ok" : relayCode(r.code ?? r.t);
|
|
677
|
+
}
|
|
678
|
+
/** An unauthenticated connection for the pre-auth link mailbox (§5.7). */
|
|
679
|
+
export async function openLinkConnection(relay, transport, timeoutMs, progress, opts = {}) {
|
|
680
|
+
const c = new RelayConnection(relay, transport(relay), { timeoutMs, progress, ...(opts.lookup ? { lookup: opts.lookup } : {}) });
|
|
681
|
+
await c.open();
|
|
682
|
+
return c;
|
|
683
|
+
}
|
|
684
|
+
export async function linkPut(conn, lid, slot, data) {
|
|
685
|
+
const r = await conn.request({ t: "link-put", lid, slot, data });
|
|
686
|
+
if (r.t !== "ok")
|
|
687
|
+
throw new CliError("link_failed", `link mailbox refused the ${slot} (${relayCode(r.code ?? r.t)})`);
|
|
688
|
+
}
|
|
689
|
+
/** The entries of a slot, or undefined when the mailbox is gone. */
|
|
690
|
+
export async function linkGet(conn, lid, slot) {
|
|
691
|
+
const r = await conn.request({ t: "link-get", lid, slot });
|
|
692
|
+
if (r.t === "link" && Array.isArray(r.entries))
|
|
693
|
+
return r.entries.filter((x) => typeof x === "string");
|
|
694
|
+
if (r.t === "error" && r.code === "not-found")
|
|
695
|
+
return undefined;
|
|
696
|
+
if (r.t === "error" && r.code === "rate-limited")
|
|
697
|
+
return [];
|
|
698
|
+
throw new CliError("link_failed", `link-get failed (${relayCode(r.code ?? r.t)})`);
|
|
699
|
+
}
|
|
700
|
+
// ---------------------------------------------------------------------------
|
|
701
|
+
// P4 short-code invite mailboxes
|
|
702
|
+
/** Puts a sealed invite (authenticated connection); resolves with the expiry the relay set (seconds). */
|
|
703
|
+
export async function invitePut(conn, lid, blob, ttlSec, admit) {
|
|
704
|
+
// `admit`: on a members-only relay, the code also admits whoever redeems it (open relays ignore it).
|
|
705
|
+
const r = await conn.request({ t: "invite-put", lid, blob, ttl: ttlSec, ...(admit ? { admit } : {}) });
|
|
706
|
+
if (r.t !== "ok")
|
|
707
|
+
throw new CliError("not_published", `${conn.relay} refused the invite (${relayCode(r.code ?? r.t)})`, { code: relayCode(r.code ?? r.t) });
|
|
708
|
+
return typeof r.exp === "number" ? r.exp : Math.floor(Date.now() / 1000) + ttlSec;
|
|
709
|
+
}
|
|
710
|
+
/** Takes the invite under `lid` (single use); undefined when there is none. */
|
|
711
|
+
export async function inviteGet(conn, lid) {
|
|
712
|
+
const r = await conn.request({ t: "invite-get", lid });
|
|
713
|
+
if (r.t === "invite" && typeof r.blob === "string")
|
|
714
|
+
return r.blob;
|
|
715
|
+
if (r.t === "error" && r.code === "not-found")
|
|
716
|
+
return undefined;
|
|
717
|
+
if (r.t === "error" && r.code === "rate-limited")
|
|
718
|
+
throw new CliError("rate_limited", `${conn.relay} is rate-limiting invite lookups from your network: try again in a few minutes`);
|
|
719
|
+
throw new CliError("network", `${conn.relay}: invite-get failed (${relayCode(r.code ?? r.t)})`);
|
|
720
|
+
}
|
|
721
|
+
/** The lids this user holds open on the relay, and those it evicted to make room (not yet expired). */
|
|
722
|
+
export async function inviteList(conn) {
|
|
723
|
+
const r = await conn.request({ t: "invite-list" });
|
|
724
|
+
const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
|
|
725
|
+
if (r.t === "invites" && Array.isArray(r.lids))
|
|
726
|
+
return { lids: strs(r.lids), evicted: strs(r.evicted) };
|
|
727
|
+
throw new CliError("network", `${conn.relay}: invite-list failed (${relayCode(r.code ?? r.t)})`);
|
|
728
|
+
}
|
|
729
|
+
/** Deletes an open invite; false when the relay held none under `lid`. */
|
|
730
|
+
export async function inviteDel(conn, lid) {
|
|
731
|
+
const r = await conn.request({ t: "invite-del", lid });
|
|
732
|
+
if (r.t === "ok")
|
|
733
|
+
return true;
|
|
734
|
+
if (r.t === "error" && r.code === "not-found")
|
|
735
|
+
return false;
|
|
736
|
+
throw new CliError("network", `${conn.relay}: invite-del failed (${relayCode(r.code ?? r.t)})`);
|
|
737
|
+
}
|
|
738
|
+
// ---------------------------------------------------------------------------
|
|
739
|
+
// §5.6 document API
|
|
740
|
+
/** review L6: a relay's document API answer is at most this big (64 tips or chain entries of ≤ 16 KiB, with room). */
|
|
741
|
+
export const MAX_HTTP_BODY_BYTES = 2 * 1024 * 1024;
|
|
742
|
+
/** Reads a response body, refusing more than `max` bytes. */
|
|
743
|
+
export async function readCapped(res, max) {
|
|
744
|
+
const len = Number(res.headers.get("content-length") ?? "0");
|
|
745
|
+
if (len > max)
|
|
746
|
+
throw new CliError("network", "relay answer too large");
|
|
747
|
+
if (!res.body)
|
|
748
|
+
return "";
|
|
749
|
+
const reader = res.body.getReader();
|
|
750
|
+
const chunks = [];
|
|
751
|
+
let total = 0;
|
|
752
|
+
for (;;) {
|
|
753
|
+
const { done, value } = await reader.read();
|
|
754
|
+
if (done)
|
|
755
|
+
break;
|
|
756
|
+
total += value.byteLength;
|
|
757
|
+
if (total > max) {
|
|
758
|
+
await reader.cancel().catch(() => { });
|
|
759
|
+
throw new CliError("network", "relay answer too large");
|
|
760
|
+
}
|
|
761
|
+
chunks.push(value);
|
|
762
|
+
}
|
|
763
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
764
|
+
}
|
|
765
|
+
async function getJson(url, timeoutMs, progress, what = "identity documents", lookup) {
|
|
766
|
+
const known = progress?.unreachable?.get(hostKey(url).key);
|
|
767
|
+
if (known)
|
|
768
|
+
throw known;
|
|
769
|
+
return step(progress, `fetching ${what} from ${new URL(url).origin}`, () => (lookup ? getJsonGuarded(url, timeoutMs, lookup) : getJsonInner(url, timeoutMs)));
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* getJsonInner through node:http(s) with `lookup` (a code's relay: privateGuardLookup), so the
|
|
773
|
+
* address the name resolves to is checked and dialed as checked. No redirects are followed.
|
|
774
|
+
*/
|
|
775
|
+
function getJsonGuarded(url, timeoutMs, lookup) {
|
|
776
|
+
const get = url.startsWith("https:") ? httpsGet : httpGet;
|
|
777
|
+
return new Promise((resolve, reject) => {
|
|
778
|
+
let done = false;
|
|
779
|
+
// One overall deadline, as fetch's abort had: a relay that trickles bytes can't hold the command.
|
|
780
|
+
const deadline = setTimeout(() => {
|
|
781
|
+
req.destroy();
|
|
782
|
+
fail(new CliError("timeout", `${url}: no answer after ${Math.round(timeoutMs / 1000)}s`));
|
|
783
|
+
}, timeoutMs);
|
|
784
|
+
deadline.unref();
|
|
785
|
+
const settle = () => {
|
|
786
|
+
done = true;
|
|
787
|
+
clearTimeout(deadline);
|
|
788
|
+
};
|
|
789
|
+
const fail = (e) => {
|
|
790
|
+
if (done)
|
|
791
|
+
return;
|
|
792
|
+
settle();
|
|
793
|
+
reject(e instanceof CliError ? e : new CliError(e.message.includes(PRIVATE_RESOLVE_MARK) ? "private_relay" : "network", `${url}: ${e.message}`));
|
|
794
|
+
};
|
|
795
|
+
const req = get(url, { lookup, agent: false, timeout: timeoutMs, headers: { accept: "application/json" } }, (res) => {
|
|
796
|
+
if (res.statusCode === 404) {
|
|
797
|
+
res.resume();
|
|
798
|
+
settle();
|
|
799
|
+
return resolve(undefined);
|
|
800
|
+
}
|
|
801
|
+
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
|
802
|
+
res.resume();
|
|
803
|
+
return fail(new CliError("network", `${url}: HTTP ${res.statusCode ?? "?"}`));
|
|
804
|
+
}
|
|
805
|
+
const chunks = [];
|
|
806
|
+
let total = 0;
|
|
807
|
+
res.on("data", (c) => {
|
|
808
|
+
total += c.length;
|
|
809
|
+
if (total > MAX_HTTP_BODY_BYTES) {
|
|
810
|
+
req.destroy();
|
|
811
|
+
fail(new CliError("network", "relay answer too large"));
|
|
812
|
+
}
|
|
813
|
+
else
|
|
814
|
+
chunks.push(c);
|
|
815
|
+
});
|
|
816
|
+
res.on("end", () => {
|
|
817
|
+
if (done)
|
|
818
|
+
return;
|
|
819
|
+
try {
|
|
820
|
+
const v = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
821
|
+
settle();
|
|
822
|
+
resolve(v);
|
|
823
|
+
}
|
|
824
|
+
catch (e) {
|
|
825
|
+
fail(e);
|
|
826
|
+
}
|
|
827
|
+
});
|
|
828
|
+
res.on("error", fail);
|
|
829
|
+
});
|
|
830
|
+
req.on("timeout", () => {
|
|
831
|
+
req.destroy();
|
|
832
|
+
fail(new CliError("timeout", `${url}: no answer after ${Math.round(timeoutMs / 1000)}s`));
|
|
833
|
+
});
|
|
834
|
+
req.on("error", fail);
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
async function getJsonInner(url, timeoutMs) {
|
|
838
|
+
const ctl = new AbortController();
|
|
839
|
+
const t = setTimeout(() => ctl.abort(), timeoutMs);
|
|
840
|
+
t.unref();
|
|
841
|
+
try {
|
|
842
|
+
const res = await fetch(url, { signal: ctl.signal, headers: { accept: "application/json" } });
|
|
843
|
+
if (res.status === 404)
|
|
844
|
+
return undefined;
|
|
845
|
+
if (!res.ok)
|
|
846
|
+
throw new CliError("network", `${url}: HTTP ${res.status}`);
|
|
847
|
+
return JSON.parse(await readCapped(res, MAX_HTTP_BODY_BYTES));
|
|
848
|
+
}
|
|
849
|
+
catch (e) {
|
|
850
|
+
if (e instanceof CliError)
|
|
851
|
+
throw e;
|
|
852
|
+
if (ctl.signal.aborted)
|
|
853
|
+
throw new CliError("timeout", `${url}: no answer after ${Math.round(timeoutMs / 1000)}s`);
|
|
854
|
+
throw new CliError("network", `${url}: ${e.message}`);
|
|
855
|
+
}
|
|
856
|
+
finally {
|
|
857
|
+
clearTimeout(t);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
/** GET /.well-known/p2p-relay.json from the relay's host (undefined: 404, an older relay). */
|
|
861
|
+
export async function fetchRelayInfo(t, timeoutMs, progress) {
|
|
862
|
+
return getJson(new URL("/.well-known/p2p-relay.json", t.http).toString(), timeoutMs, progress, "the relay's features");
|
|
863
|
+
}
|
|
864
|
+
const strList = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
|
|
865
|
+
export async function fetchTips(t, userId, timeoutMs, progress, lookup) {
|
|
866
|
+
const j = await getJson(`${t.http}/identity/${encodeURIComponent(userId)}/tips`, timeoutMs, progress, `${userId}'s identity`, lookup);
|
|
867
|
+
return j ? strList(j.tips) : [];
|
|
868
|
+
}
|
|
869
|
+
export async function fetchChain(t, userId, to, n, timeoutMs, progress, lookup) {
|
|
870
|
+
const j = await getJson(`${t.http}/identity/${encodeURIComponent(userId)}/chain?to=${encodeURIComponent(to)}&n=${n}`, timeoutMs, progress, `${userId}'s identity history`, lookup);
|
|
871
|
+
return j ? strList(j.docs) : [];
|
|
872
|
+
}
|
|
873
|
+
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|