sigelo-contact 0.1.13 → 0.1.14
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/carrier.mjs +277 -35
- package/enrol.mjs +34 -17
- package/group.mjs +597 -0
- package/link.mjs +23 -15
- package/package.json +19 -4
- package/page.mjs +278 -19
- package/platform-node.mjs +15 -5
- package/short.mjs +12 -0
- package/store.mjs +21 -2
- package/test-carrier.mjs +18 -4
- package/test-enrol.mjs +36 -2
- package/test-group.mjs +383 -0
- package/test-link.mjs +5 -2
- package/test-presence.mjs +169 -0
- package/test-short.mjs +4 -1
- package/test-transfer.mjs +435 -0
- package/transfer-node.mjs +845 -0
- package/transfer.mjs +371 -0
- package/words-lock.mjs +100 -0
package/carrier.mjs
CHANGED
|
@@ -43,12 +43,22 @@
|
|
|
43
43
|
// (`log`: x.inbox.log, pathsFor), received at or after since (unix seconds);
|
|
44
44
|
// no session, nothing taken
|
|
45
45
|
// c.setTier(who, tier) the owner's tier for a contact (store.mjs setTier) → { did, name, tier, ours }
|
|
46
|
+
// c.setPresence(who, allow) may that contact see whether this agent is online (store.mjs setPresence;
|
|
47
|
+
// off by default, own agents always) → { did, name, presence }; a started
|
|
48
|
+
// carrier applies it at once, another at its next round
|
|
46
49
|
// c.presetTier(did, tier) the same for an original DID not yet a contact, filed when it pairs
|
|
47
50
|
// c.takeLinks(), c.setLink(who, link) link.mjs's: the sigelo-link/1 messages received (never in inbox(), the log
|
|
48
51
|
// or onEvent: a `link` event without content says one came), taken; a
|
|
49
52
|
// contact's link record (store.mjs setLink)
|
|
53
|
+
// c.takeGroups() group.mjs's: the sigelo-group/1 messages received (never in inbox(), the
|
|
54
|
+
// log or onEvent: a `group` event without content says one came), taken
|
|
55
|
+
// c.groupTier what this agent's relay told its last login of its group tier ($sigelo/notice
|
|
56
|
+
// "tier": { tier, groups: { max, members } }, event `group_tier`), or null
|
|
50
57
|
// c.takeDevices() device.mjs's: the sigelo-device/1 messages received (never in inbox(), the
|
|
51
58
|
// log or onEvent: a `device` event without content says one came), taken
|
|
59
|
+
// c.takeTransfers(), c.deliver(item) transfer-node.mjs's: the sigelo-transfer/0 messages received (never in inbox(),
|
|
60
|
+
// the log or onEvent: a `transfer` event without content says one came), taken;
|
|
61
|
+
// a file a transfer saved whole, as an inbox item (kept as #onFile keeps one)
|
|
52
62
|
// c.freshEpochs({ only, retire }) every session (or only's) afresh, as after a rotation (a snapshot's
|
|
53
63
|
// state imported where the seat moved, devices.md §4.3) → the DIDs
|
|
54
64
|
// c.answeredBy(nonce) the original DID that paired through this agent's code `nonce`, or null
|
|
@@ -61,6 +71,10 @@
|
|
|
61
71
|
// c.lastError the error behind the last offline of inbox or forget (SIGELO_DEBUG)
|
|
62
72
|
// c.clockOffset(), await c.checkClock() → { relay, offset, checked } | null: the relay's clock less this one's, seconds
|
|
63
73
|
// await c.start(), c.sync(), c.stop() stay connected, reconnecting with backoff; events reach onEvent
|
|
74
|
+
// await c.tryNow({ confirmed }) the human's "Try now": a login at each relay in use not connected
|
|
75
|
+
// started: 'user' | 'confirmed' (start, invite, accept, tryNow) a search the human started: past
|
|
76
|
+
// POW_SEARCHES a day it is never refused, it asks (pow_confirm),
|
|
77
|
+
// and 'confirmed' goes on; without it (automatic retries) the cap holds
|
|
64
78
|
//
|
|
65
79
|
// identity() → { sign, bundle }: the agent's signer for its current key (sign(body) → the SPEC §3
|
|
66
80
|
// signature; sigelo-agent-keys.ts) and its SPEC §8 bundle, read again at every operation, so a
|
|
@@ -191,6 +205,20 @@
|
|
|
191
205
|
// hinted and proved again; asks for the same operators go at most every RESYNC. A contact
|
|
192
206
|
// learns from the hints only which operator DIDs it guesses right (THREAT-MODEL §2.12). An
|
|
193
207
|
// agent on an older version gets the hints as messages with that label. send refuses the label.
|
|
208
|
+
// - Presence (design/transfer.md §8 T0): a started carrier sets the will $sigelo/presence on its
|
|
209
|
+
// CONNECT and publishes, to each contact that may see it (store.mjs presenceOf: own agents
|
|
210
|
+
// always, others when the owner allowed them), one marker on presenceTopic(K, own original DID,
|
|
211
|
+
// contact's): a kind 6 frame under presenceKey(K, …), {v: "sigelo-presence/0", state: "online",
|
|
212
|
+
// since}. The relay (relay/presence.mjs) holds it, sends it at once to whoever subscribes, and
|
|
213
|
+
// replaces it with its own {"presence": "offline", "at"} when that session ends. A marker toward a
|
|
214
|
+
// contact no longer allowed is cleared (an empty publish, st.presence_out). Sealed by the
|
|
215
|
+
// pairing key, not as an envelope: an envelope is read once (its counter, its replay window), a
|
|
216
|
+
// marker again at every subscribe, and the relay's offline is written after the writer is gone;
|
|
217
|
+
// not signed, so a reader cannot show anyone else when this agent was online. A started
|
|
218
|
+
// carrier subscribes, at QoS 0, to each contact's marker toward it (a short session does not:
|
|
219
|
+
// it would forget it at once, and the subscribes draw on the relay's brake); what it reads is st.presence, which
|
|
220
|
+
// contacts() reports as online, online_since, last_seen, and forgets when the connection to that
|
|
221
|
+
// relay closes (a marker read is true only while the reader is connected).
|
|
194
222
|
// - Mailboxes: an agent holds the topics of every ISO week from `retention` ago to AHEAD (7 days,
|
|
195
223
|
// or its retention if shorter) ahead. The relay drops a publish to a topic nobody claimed (and
|
|
196
224
|
// says no_reader), so next week's topic must be claimed before a contact writes in it while
|
|
@@ -261,7 +289,11 @@ export const POW_MAX = 26, POW_MAX_OTHER = 22, POW_MS = 280000;
|
|
|
261
289
|
// An honest relay asks once per identity, and again only if it forgot it. Without a count, a relay
|
|
262
290
|
// that grants a proven login, closes, then refuses the next login's SUBSCRIBE `pow` had this client
|
|
263
291
|
// search again at each reconnection, without end: success reset every other bound.
|
|
292
|
+
// The cap is for this client's AUTOMATIC retries only (design/profiles.md §6): a search the human
|
|
293
|
+
// started (`started: 'user'`) past it answers pow_confirm, and one confirmed (`'confirmed'`) goes.
|
|
264
294
|
export const POW_SEARCHES = 3;
|
|
295
|
+
const ORDINAL = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth'];
|
|
296
|
+
const hhmmUtc = (t) => new Date(t * 1000).toISOString().slice(11, 16);
|
|
265
297
|
// A delivery this process failed on this many times, its files sound each time, is dropped.
|
|
266
298
|
const POISON_TRIES = 3;
|
|
267
299
|
// Events kept for the next inbox(): pairings, rotations, failed pairings. The oldest go first.
|
|
@@ -272,16 +304,25 @@ const EVENTS_MAX = 1000, INBOX_MAX = 1000;
|
|
|
272
304
|
// devices', and links' (a live invite code).
|
|
273
305
|
export const LOG_MAX = 500, LOG_BYTES = 4 * 1024 * 1024;
|
|
274
306
|
// Labels whose messages carry keys, device material or a live code (enrol, device, link): never logged.
|
|
275
|
-
export const UNLOGGED = /^sigelo-(identity|enrol|device|link)\//;
|
|
307
|
+
export const UNLOGGED = /^sigelo-(identity|enrol|device|link|transfer)\//;
|
|
276
308
|
// Links (link.mjs, sigelo-link/1): never an inbox message. Kept apart in the state (st.links, at most
|
|
277
309
|
// LINKS_MAX, the oldest go) for link.mjs handle(), which takeLinks() them; sent only by link.mjs
|
|
278
310
|
// (send's internal: LINK_SEND), so a caller's label (an MCP client's, a model's) cannot forge one.
|
|
279
311
|
export const LINK_LABEL = 'sigelo-link/1', LINK_SEND = Symbol('sigelo-link send');
|
|
280
312
|
const LINKS_MAX = 64;
|
|
313
|
+
// Groups (group.mjs, sigelo-group/1): the same, kept apart in st.groups (at most GROUPS_MAX) for
|
|
314
|
+
// group.mjs handle(), which checks the sender's inner signature and the roster; sent only with GROUP_SEND.
|
|
315
|
+
export const GROUP_LABEL = 'sigelo-group/1', GROUP_SEND = Symbol('sigelo-group send');
|
|
316
|
+
const GROUPS_MAX = 256;
|
|
281
317
|
// Devices (device.mjs, sigelo-device/1): the same, kept apart in st.devices for sigelo-agent's
|
|
282
318
|
// `device` verbs (takeDevices); sent only with DEVICE_SEND: one carries the operator's keys.
|
|
283
319
|
export const DEVICE_LABEL = 'sigelo-device/1', DEVICE_SEND = Symbol('sigelo-device send');
|
|
284
320
|
const DEVICES_MAX = 16;
|
|
321
|
+
// Transfers (transfer.mjs, sigelo-transfer/0): the introduction of a big file, sent direct or over Tor
|
|
322
|
+
// (design/transfer.md §3). The same: kept apart in st.transfers (at most TRANSFERS_MAX) for the transfer
|
|
323
|
+
// engine, never logged (an offer carries addresses, an onion message a client key); sent only with TRANSFER_SEND.
|
|
324
|
+
export const TRANSFER_LABEL = 'sigelo-transfer/0', TRANSFER_SEND = Symbol('sigelo-transfer send');
|
|
325
|
+
const TRANSFERS_MAX = 256;
|
|
285
326
|
// Received files of one name and hash prefix kept side by side, at most (#onFile).
|
|
286
327
|
const FILE_COPIES = 64;
|
|
287
328
|
// A contact's folder of received files: its name as safeName keeps it, and 16 hex digits of the
|
|
@@ -322,7 +363,7 @@ const LOGIN_CHECKS = new Set(['rate', 'password', 'challenge_unknown', 'challeng
|
|
|
322
363
|
// Refusals of an invite reply that a later round may get past: the reply stays queued.
|
|
323
364
|
const REPLY_RETRY = new Set(['rate', 'relay_full', 'quota_messages']);
|
|
324
365
|
// $sigelo/notice codes that refuse the publish, or the SUBSCRIBE, in flight (relay-plan §3 "Errors").
|
|
325
|
-
const PUBLISH_CODES = new Set(['too_large', 'quota_storage', 'quota_messages', 'rate', 'relay_full', 'pow', 'no_reader']);
|
|
366
|
+
const PUBLISH_CODES = new Set(['too_large', 'quota_storage', 'quota_messages', 'rate', 'relay_full', 'pow', 'no_reader', 'presence_taken', 'presence_will', 'presence_full']);
|
|
326
367
|
// A contact's envelope this agent cannot open for want of its epoch asks the writer for a new epoch
|
|
327
368
|
// by a fresh prekey bundle (RESYNC_CHECKS), at most once in this many seconds per contact after
|
|
328
369
|
// the last such bundle: the check comes before any decryption, so a relay can make one up. A
|
|
@@ -552,6 +593,10 @@ export const operatorHint = (K, kind, from, op) => hex(hmac(sha256, K, utf8ToByt
|
|
|
552
593
|
export const noticeKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-notice/0'), utf8ToBytes(`${from}\n${to}`), 32);
|
|
553
594
|
/** The prekeys frame's key: HKDF-SHA256(K, salt "sigelo-prekeys/0", info = from ‖ "\n" ‖ to), original DIDs. */
|
|
554
595
|
export const prekeysKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-prekeys/0'), utf8ToBytes(`${from}\n${to}`), 32);
|
|
596
|
+
/** Presence (the header's "Presence"): the topic from → to, and its marker's key; original DIDs. */
|
|
597
|
+
export const KIND_PRESENCE = 6, PRESENCE_V = 'sigelo-presence/0', PRESENCE_WILL = '$sigelo/presence';
|
|
598
|
+
export const presenceTopic = (K, from, to) => 'p/' + hex(hkdf(sha256, K, utf8ToBytes('sigelo-presence/0'), utf8ToBytes(`${from}\n${to}`), 16));
|
|
599
|
+
export const presenceKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-presence-key/0'), utf8ToBytes(`${from}\n${to}`), 32);
|
|
555
600
|
|
|
556
601
|
/** A kind 1, 2, 4 or 5 frame (the header's "Frames"). rng(24) gives the nonce: a parameter so a test fixes every byte. */
|
|
557
602
|
export function seal(kind, key, t, value, rng = randomBytes) {
|
|
@@ -725,6 +770,14 @@ export function keepLong(e, long) {
|
|
|
725
770
|
// Whose quota a quota_storage refusal is (relay/allowance.mjs `side`), in this client's words: a
|
|
726
771
|
// contact whose own queue is full, or whose operator's Pro lapsed, must not read as a broken relay.
|
|
727
772
|
const QUOTA_SIDES = new Set(['reader', 'sender', 'relay']);
|
|
773
|
+
// The relay's "tier" notice (relay/allowance.mjs): {tier: free | pro, groups: {max, members}}, whole
|
|
774
|
+
// numbers within what a roster can hold (group.mjs LIMITS.pro.members), else ignored. → {tier, groups} | null.
|
|
775
|
+
const GROUP_MEMBERS_MAX = 64, GROUPS_TOLD_MAX = 10000;
|
|
776
|
+
export function groupTierOf(n) {
|
|
777
|
+
const g = n?.groups, whole = (x, lo, hi) => Number.isSafeInteger(x) && x >= lo && x <= hi;
|
|
778
|
+
if ((n?.tier !== 'free' && n?.tier !== 'pro') || g === null || typeof g !== 'object' || !whole(g.max, 0, GROUPS_TOLD_MAX) || !whole(g.members, 2, GROUP_MEMBERS_MAX)) return null;
|
|
779
|
+
return { tier: n.tier, groups: { max: g.max, members: g.members } };
|
|
780
|
+
}
|
|
728
781
|
const quotaWhy = (r, name) => (r.code !== 'quota_storage' ? null
|
|
729
782
|
: r.side === 'reader' ? `${name}'s side is over its storage quota (its queue is full, or its operator's Pro lapsed): nothing is wrong with your relay or your allowance; send again once ${name}'s agent has collected its messages (${relaySays(r.detail)})`
|
|
730
783
|
: r.side === 'sender' ? `your network has used its share of this relay's free storage: send again once messages are collected or expire (${relaySays(r.detail)})` : null);
|
|
@@ -814,10 +867,12 @@ export function limitPackets(stream, max, cut) {
|
|
|
814
867
|
|
|
815
868
|
// url: mqtts://, or wss:// (MQTT over WebSocket: through the HTTPS proxy when one applies, platform-node.mjs proxyFor;
|
|
816
869
|
// a frame over the largest packet, its fixed header included, refused by ws before it is held).
|
|
870
|
+
// creds.will: the presence will of a started carrier (the header's "Presence").
|
|
817
871
|
function mqttConnect(platform, url, creds, link, onPacket, timeout = CONNECT_MS) {
|
|
818
872
|
return new Promise((resolve, reject) => {
|
|
819
873
|
const client = platform.mqtt(url, { protocolVersion: 4, clean: false, clientId: creds.clientId, username: creds.username, password: creds.password,
|
|
820
|
-
reconnectPeriod: 0, connectTimeout: timeout, keepalive: 60, resubscribe: false, wsOptions: { maxPayload: MAX_PACKET + 5, perMessageDeflate: false }
|
|
874
|
+
reconnectPeriod: 0, connectTimeout: timeout, keepalive: 60, resubscribe: false, wsOptions: { maxPayload: MAX_PACKET + 5, perMessageDeflate: false },
|
|
875
|
+
...(creds.will && { will: creds.will }) });
|
|
821
876
|
link.client = client;
|
|
822
877
|
// connect() has built the socket and nothing has arrived yet. The cut is permanent at a relay
|
|
823
878
|
// other than this agent's own (#retry, accept): it would send the same packet again.
|
|
@@ -864,6 +919,9 @@ class Link {
|
|
|
864
919
|
this.collect = null; this.lastIn = 0; this.since = Date.now(); this.tokens = RATE.burst; this.at = Date.now(); this.pow = false; this.closing = false;
|
|
865
920
|
this.abort = null; // rejects the PUBLISH or SUBSCRIBE in flight when the connection closes
|
|
866
921
|
this.cut = null; // the MsgError of limitPackets, once it cut the connection
|
|
922
|
+
// Presence: the contacts' marker topics subscribed on this connection; this agent's markers
|
|
923
|
+
// published on it (topic → its contact); when it connected (a marker's since); the will set.
|
|
924
|
+
this.presenceIn = new Set(); this.presenceOut = new Map(); this.onlineAt = 0; this.will = false;
|
|
867
925
|
}
|
|
868
926
|
// Nothing delivered for QUIET ms since connecting: the relay's queue for this agent is drained.
|
|
869
927
|
get quiet() { return Date.now() - Math.max(this.lastIn, this.since) >= QUIET; }
|
|
@@ -885,7 +943,7 @@ class Link {
|
|
|
885
943
|
export class Carrier {
|
|
886
944
|
#links = new Map(); #work = Promise.resolve(); #busy = 0; #lastWork = 0; #routes = new Map(); #results = new Map();
|
|
887
945
|
#claimed = new Set(); #refusedTopics = new Map(); #handshakes = new Map(); #soon = new Set();
|
|
888
|
-
#started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map(); #ask = false;
|
|
946
|
+
#started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map(); #powWaits = new Set(); #ask = false;
|
|
889
947
|
#mineMemo = null; #clocks = new Map();
|
|
890
948
|
|
|
891
949
|
constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays, clock = () => Math.floor(Date.now() / 1000),
|
|
@@ -1137,6 +1195,7 @@ export class Carrier {
|
|
|
1137
1195
|
this.#routes = this.#read(({ now, me, store }) => {
|
|
1138
1196
|
const m = new Map(), wide = this.retention + 7 * DAY;
|
|
1139
1197
|
for (const c of this.#liveContacts(store)) for (const w of this.#weeks(now, wide, wide)) m.set(topic(hexToBytes(c.pair_key), c.did, me.did, w.week), { type: 'peer', did: c.did });
|
|
1198
|
+
for (const c of this.#liveContacts(store)) m.set(presenceTopic(hexToBytes(c.pair_key), c.did, me.did), { type: 'presence', did: c.did });
|
|
1140
1199
|
for (const [nonce, p] of Object.entries(store.s.invites)) m.set(inviteKeys(hexToBytes(p.secret)).answer_topic, { type: 'answer', nonce });
|
|
1141
1200
|
for (const [id, p] of Object.entries(store.s.accepts)) m.set(inviteKeys(hexToBytes(p.secret)).reply_topic, { type: 'reply', id });
|
|
1142
1201
|
return m;
|
|
@@ -1184,6 +1243,7 @@ export class Carrier {
|
|
|
1184
1243
|
if (!this.#routes.has(t)) this.#rebuildRoutes();
|
|
1185
1244
|
route = this.#routes.get(t) ?? fail('route', 'a message on a topic this agent does not read');
|
|
1186
1245
|
const events = this.#locked((ctx) => (route.type === 'peer' ? this.#onPeer(ctx, route.did, t, bytes)
|
|
1246
|
+
: route.type === 'presence' ? this.#onPresence(ctx, route.did, t, bytes)
|
|
1187
1247
|
: route.type === 'answer' ? this.#onAnswer(ctx, t, bytes) : this.#onReply(ctx, t, bytes)));
|
|
1188
1248
|
for (const e of events) this.#emit(e);
|
|
1189
1249
|
} catch (e) {
|
|
@@ -1251,12 +1311,39 @@ export class Carrier {
|
|
|
1251
1311
|
let n;
|
|
1252
1312
|
try { n = parseBytes(bytes); } catch { return; }
|
|
1253
1313
|
if (n === null || typeof n !== 'object' || typeof n.code !== 'string') return;
|
|
1314
|
+
// The relay's group tier for this login (relay/allowance.mjs "tier"): kept per relay in the state, refuses nothing.
|
|
1315
|
+
if (n.code === 'tier') {
|
|
1316
|
+
const g = groupTierOf(n);
|
|
1317
|
+
if (g) { try { this.#locked(({ st }) => { (st.group_tier ??= {})[link.relay] = g; }); } catch {} this.#emit({ type: 'group_tier', relay: link.relay, ...g }); }
|
|
1318
|
+
return;
|
|
1319
|
+
}
|
|
1254
1320
|
const note = { code: n.code.slice(0, 64), detail: typeof n.detail === 'string' ? n.detail.slice(0, 200) : '', ...(QUOTA_SIDES.has(n.side) && { side: n.side }) };
|
|
1255
1321
|
// id: the packet id of the PUBLISH a refusal names (#publish), kept out of events.
|
|
1256
1322
|
if (link.collect) link.collect.push(Number.isSafeInteger(n.id) ? { ...note, id: n.id } : note);
|
|
1257
1323
|
else this.#emit({ type: 'notice', relay: link.relay, ...note });
|
|
1258
1324
|
}
|
|
1259
1325
|
|
|
1326
|
+
// A contact's presence marker toward this agent (the header's "Presence"): its sealed online, the
|
|
1327
|
+
// relay's offline, or nothing (cleared). → the presence event.
|
|
1328
|
+
#onPresence({ me, store, st }, did, t, bytes) {
|
|
1329
|
+
const c = store.lookup(did);
|
|
1330
|
+
if (!c || c.revoked || !c.pair_key) return [];
|
|
1331
|
+
const p = (st.presence ??= {});
|
|
1332
|
+
let e = null;
|
|
1333
|
+
if (bytes.length > 0 && bytes[0] === 0x7b) {
|
|
1334
|
+
let v;
|
|
1335
|
+
try { v = parseBytes(bytes); } catch (err) { fail('presence', `the relay's offline marker is not JSON: ${err.message}`); }
|
|
1336
|
+
if (!exact(v, ['at', 'presence']) || v.presence !== 'offline' || !Number.isSafeInteger(v.at) || v.at < 0) fail('presence', 'not the relay\'s {presence: "offline", at}');
|
|
1337
|
+
e = { online: false, since: null, last_seen: v.at };
|
|
1338
|
+
} else if (bytes.length > 0) {
|
|
1339
|
+
const v = unseal(KIND_PRESENCE, presenceKey(hexToBytes(c.pair_key), c.did, me.did), t, bytes);
|
|
1340
|
+
if (!exact(v, ['since', 'state', 'v']) || v.v !== PRESENCE_V || v.state !== 'online' || !Number.isSafeInteger(v.since) || v.since < 0) fail('presence', `not a ${PRESENCE_V} online marker`);
|
|
1341
|
+
e = { online: true, since: v.since, last_seen: null };
|
|
1342
|
+
}
|
|
1343
|
+
if (e) p[c.did] = { ...e, relay: c.relay }; else delete p[c.did];
|
|
1344
|
+
return [{ type: 'presence', did: c.did, name: c.name, online: e ? e.online : null, since: e?.since ?? null, last_seen: e?.last_seen ?? null }];
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1260
1347
|
// A contact's mailbox: an envelope (kind 0), its rotation notice (kind 4) or its prekeys (kind 5).
|
|
1261
1348
|
#onPeer(ctx, did, t, bytes) {
|
|
1262
1349
|
const { now, me, store, st } = ctx;
|
|
@@ -1308,6 +1395,18 @@ export class Carrier {
|
|
|
1308
1395
|
l.push({ from: c.did, name: c.name, current_did: r.body.from, label: r.body.label, content: r.body.content, iat: r.body.iat, received: now });
|
|
1309
1396
|
if (l.length > LINKS_MAX) { st.dropped.links_full = (st.dropped.links_full ?? 0) + l.length - LINKS_MAX; l.splice(0, l.length - LINKS_MAX); }
|
|
1310
1397
|
events.push({ type: 'link', from: c.did, name: c.name });
|
|
1398
|
+
} else if (r.body.label === GROUP_LABEL) {
|
|
1399
|
+
// A group message (group.mjs): kept for handle(), never for inbox() nor onEvent's readers.
|
|
1400
|
+
const l = (st.groups ??= []);
|
|
1401
|
+
l.push({ from: c.did, name: c.name, current_did: r.body.from, label: r.body.label, content: r.body.content, iat: r.body.iat, received: now });
|
|
1402
|
+
if (l.length > GROUPS_MAX) { st.dropped.groups_full = (st.dropped.groups_full ?? 0) + l.length - GROUPS_MAX; l.splice(0, l.length - GROUPS_MAX); }
|
|
1403
|
+
events.push({ type: 'group', from: c.did, name: c.name });
|
|
1404
|
+
} else if (r.body.label === TRANSFER_LABEL) {
|
|
1405
|
+
// A transfer message (transfer-node.mjs): kept for the engine, never for inbox() nor onEvent's readers.
|
|
1406
|
+
const l = (st.transfers ??= []);
|
|
1407
|
+
l.push({ from: c.did, name: c.name, current_did: r.body.from, label: r.body.label, content: r.body.content, iat: r.body.iat, received: now });
|
|
1408
|
+
if (l.length > TRANSFERS_MAX) { st.dropped.transfers_full = (st.dropped.transfers_full ?? 0) + l.length - TRANSFERS_MAX; l.splice(0, l.length - TRANSFERS_MAX); }
|
|
1409
|
+
events.push({ type: 'transfer', from: c.did, name: c.name });
|
|
1311
1410
|
} else if (r.body.label === DEVICE_LABEL) {
|
|
1312
1411
|
// A device message (device.mjs): kept for the `device` verbs, never for inbox() nor onEvent's readers.
|
|
1313
1412
|
const l = (st.devices ??= []);
|
|
@@ -1949,11 +2048,11 @@ export class Carrier {
|
|
|
1949
2048
|
// message as refused (its epoch restarted, its prekey put back, its contact marked absent).
|
|
1950
2049
|
// Nothing leaves before the state that sent it is committed (platform.flush): an envelope whose
|
|
1951
2050
|
// ratchet step a crash lost would be sent again under the same key, a replay at the reader.
|
|
1952
|
-
async #publish(link, t, bytes) {
|
|
2051
|
+
async #publish(link, t, bytes, retain = false) {
|
|
1953
2052
|
await this.platform.flush();
|
|
1954
2053
|
link.collect = [];
|
|
1955
2054
|
try {
|
|
1956
|
-
const id = await link.request('PUBACK', (cb) => link.client.publish(t, bytes, { qos: 1 }, (err, packet) => (err ? cb(new MsgError('connect', err.message)) : cb(null, packet?.messageId))));
|
|
2055
|
+
const id = await link.request('PUBACK', (cb) => link.client.publish(t, bytes, { qos: 1, retain }, (err, packet) => (err ? cb(new MsgError('connect', err.message)) : cb(null, packet?.messageId))));
|
|
1957
2056
|
const mine = (n) => PUBLISH_CODES.has(n.code) && (n.id === undefined || n.id === id);
|
|
1958
2057
|
for (const n of link.collect) if (!mine(n)) this.#emit({ type: 'notice', relay: link.relay, code: n.code, detail: n.detail });
|
|
1959
2058
|
return link.collect.find(mine) ?? null;
|
|
@@ -2067,9 +2166,66 @@ export class Carrier {
|
|
|
2067
2166
|
// have stopped: a relay keeping messages longer than this agent thinks (a Pro reader run with
|
|
2068
2167
|
// the free tier's retention) has then delivered them. #session ends with such a round.
|
|
2069
2168
|
if (stale.length > 0 && link.quiet) await this.#unsubscribe(link, stale);
|
|
2169
|
+
if (!link.up) return;
|
|
2170
|
+
await this.#presence(link);
|
|
2070
2171
|
await this.#flush(link);
|
|
2071
2172
|
}
|
|
2072
2173
|
|
|
2174
|
+
// Presence at one relay (the header's "Presence"): each contact's marker toward this agent read
|
|
2175
|
+
// (QoS 0: a marker is never queued); this agent's published toward those who may see it, once
|
|
2176
|
+
// per connection, by a started carrier only (its CONNECT set the will); cleared toward any other.
|
|
2177
|
+
// A refusal stops the round: the next round tries again.
|
|
2178
|
+
async #presence(link) {
|
|
2179
|
+
const { want, out, clear } = this.#read(({ now, me, store, st }) => {
|
|
2180
|
+
const cs = this.#liveContacts(store, link.relay).filter((c) => !c.re_pair);
|
|
2181
|
+
// Read by a started carrier only: what a session reads is forgotten when it closes (#closed),
|
|
2182
|
+
// so a short one (a CLI verb, an MCP call) would spend one subscribe per contact on the relay's
|
|
2183
|
+
// brake (allowance.mjs RATE.subscribe, 256 at once) for nothing, and verbs in quick succession
|
|
2184
|
+
// were refused rate.
|
|
2185
|
+
const want = link.will ? cs.map((c) => presenceTopic(hexToBytes(c.pair_key), c.did, me.did)) : [];
|
|
2186
|
+
const out = link.will ? cs.filter((c) => store.presenceOf(c, now) !== 'deny').map((c) => {
|
|
2187
|
+
const K = hexToBytes(c.pair_key), t = presenceTopic(K, me.did, c.did);
|
|
2188
|
+
return { did: c.did, topic: t, key: presenceKey(K, me.did, c.did) };
|
|
2189
|
+
}) : [];
|
|
2190
|
+
// Cleared: a marker toward a contact that may no longer see it, gone or denied (any session).
|
|
2191
|
+
const sees = new Set(cs.filter((c) => store.presenceOf(c, now) !== 'deny').map((c) => c.did));
|
|
2192
|
+
const clear = Object.entries(st.presence_out ?? {}).filter(([, x]) => x.relay === link.relay && !sees.has(x.did)).map(([t]) => t);
|
|
2193
|
+
return { want, out, clear };
|
|
2194
|
+
});
|
|
2195
|
+
const fresh = want.filter((t) => !link.presenceIn.has(t));
|
|
2196
|
+
for (let i = 0; i < fresh.length && link.up; i += MAX_TOPICS) {
|
|
2197
|
+
const chunk = fresh.slice(i, i + MAX_TOPICS);
|
|
2198
|
+
link.collect = [];
|
|
2199
|
+
let granted, notes;
|
|
2200
|
+
try {
|
|
2201
|
+
granted = await link.request('SUBACK', (cb) => link.client.subscribe(chunk, { qos: 0 }, (err, _subs, packet) =>
|
|
2202
|
+
(packet?.granted ? cb(null, packet.granted) : cb(new MsgError('connect', err?.message ?? 'no SUBACK')))));
|
|
2203
|
+
notes = link.collect;
|
|
2204
|
+
} finally { link.collect = null; }
|
|
2205
|
+
chunk.forEach((t, j) => { if (granted[j] !== 128) link.presenceIn.add(t); });
|
|
2206
|
+
for (const n of notes) this.#emit({ type: 'notice', relay: link.relay, ...n });
|
|
2207
|
+
if (notes.some((n) => n.code === 'rate')) return;
|
|
2208
|
+
}
|
|
2209
|
+
const note = (topic, x) => this.#locked(({ st }) => { const o = (st.presence_out ??= {}); if (x) o[topic] = x; else delete o[topic]; });
|
|
2210
|
+
for (const x of out) {
|
|
2211
|
+
if (!link.up) return;
|
|
2212
|
+
if (link.presenceOut.has(x.topic)) continue;
|
|
2213
|
+
await this.#throttle(link);
|
|
2214
|
+
const r = await this.#publish(link, x.topic, seal(KIND_PRESENCE, x.key, x.topic, { v: PRESENCE_V, state: 'online', since: link.onlineAt }), true);
|
|
2215
|
+
if (r) { this.#emit({ type: 'notice', relay: link.relay, code: r.code, detail: r.detail }); return; }
|
|
2216
|
+
link.presenceOut.set(x.topic, x.did);
|
|
2217
|
+
note(x.topic, { relay: link.relay, did: x.did });
|
|
2218
|
+
}
|
|
2219
|
+
for (const t of clear) {
|
|
2220
|
+
if (!link.up) return;
|
|
2221
|
+
await this.#throttle(link);
|
|
2222
|
+
const r = await this.#publish(link, t, new Uint8Array(0), true);
|
|
2223
|
+
if (r && r.code !== 'presence_taken') { this.#emit({ type: 'notice', relay: link.relay, code: r.code, detail: r.detail }); return; }
|
|
2224
|
+
link.presenceOut.delete(t);
|
|
2225
|
+
note(t, null);
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
|
|
2073
2229
|
// Work runs one item at a time, after the delivery that queued it is acknowledged: a SUBACK or
|
|
2074
2230
|
// PUBACK it waits for is handled only once the packet before it is.
|
|
2075
2231
|
#later(fn) {
|
|
@@ -2100,7 +2256,7 @@ export class Carrier {
|
|
|
2100
2256
|
|
|
2101
2257
|
// ---- connections
|
|
2102
2258
|
|
|
2103
|
-
async #credentials(relay, ep) {
|
|
2259
|
+
async #credentials(relay, ep, started) {
|
|
2104
2260
|
const { me, proven } = this.#read(({ me, st }) => ({ me, proven: st.relays[relay]?.proven === true }));
|
|
2105
2261
|
const powMax = relay === this.relay ? POW_MAX : POW_MAX_OTHER;
|
|
2106
2262
|
const r = await http(this.platform, `${ep.http}/challenge?did=${encodeURIComponent(me.current_did)}`);
|
|
@@ -2135,11 +2291,16 @@ export class Carrier {
|
|
|
2135
2291
|
// A search of 0 bits costs nothing and is not counted.
|
|
2136
2292
|
if (bits > 0) this.#locked(({ now, st }) => {
|
|
2137
2293
|
const at = (st.relays[relay] ??= { proven: false, claims: {} }), recent = (at.searches ?? []).filter((t) => t > now - DAY);
|
|
2138
|
-
if (recent.length >= POW_SEARCHES) {
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2294
|
+
if (recent.length >= POW_SEARCHES && started !== 'confirmed') {
|
|
2295
|
+
const next = recent[0] + DAY;
|
|
2296
|
+
// The human started it: never refused, asked once (the page: "Go on?"), then `confirmed`.
|
|
2297
|
+
if (started === 'user') {
|
|
2298
|
+
const nth = ORDINAL[recent.length] ?? `${recent.length + 1}th`;
|
|
2299
|
+
throw Object.assign(new MsgError('pow_confirm', `${nth[0].toUpperCase()}${nth.slice(1)} setup at this relay (${relay}) today, up to 2 minutes. Go on?`), { permanent: true, relay, next });
|
|
2300
|
+
}
|
|
2301
|
+
// Automatic: permanent like the bits above, no backoff loop; a timer tries again at `next` (#retry).
|
|
2302
|
+
const e = new MsgError('pow', `setup paused at ${relay}: ${recent.length} proof-of-work searches today, the most this client spends by itself. Next automatic try at ${hhmmUtc(next)} UTC (${new Date(next * 1000).toISOString()}); nothing is lost meanwhile, and a try you start goes now (a search is spent once per identity, and again only when a login with it got no answer)`);
|
|
2303
|
+
throw Object.assign(e, { permanent: true, relay, next });
|
|
2143
2304
|
}
|
|
2144
2305
|
at.searches = [...recent, now];
|
|
2145
2306
|
});
|
|
@@ -2167,6 +2328,8 @@ export class Carrier {
|
|
|
2167
2328
|
}
|
|
2168
2329
|
|
|
2169
2330
|
get retentionDays() { return this.retention / DAY; }
|
|
2331
|
+
/** The group tier this agent's relay told its last login ({tier, groups: {max, members}}), or null (group.mjs tierOf). */
|
|
2332
|
+
get groupTier() { try { return this.#read(({ st }) => st.group_tier?.[this.relay] ?? null); } catch { return null; } }
|
|
2170
2333
|
|
|
2171
2334
|
// The relay's clock less this agent's (this.clock), in seconds, from an answer r of relay: its
|
|
2172
2335
|
// Date header (whole seconds, so +0.5) taken as of the middle of the round trip.
|
|
@@ -2188,10 +2351,12 @@ export class Carrier {
|
|
|
2188
2351
|
return this.clockOffset();
|
|
2189
2352
|
}
|
|
2190
2353
|
|
|
2191
|
-
async #dial(relay) {
|
|
2354
|
+
async #dial(relay, started) {
|
|
2192
2355
|
const ep = endpointOf(relay, this.endpoints), link = new Link(relay, relay === this.relay);
|
|
2193
2356
|
const info = link.own && this.#ask ? this.#relayInfo(ep) : null;
|
|
2194
|
-
const creds = await this.#credentials(relay, ep);
|
|
2357
|
+
const creds = await this.#credentials(relay, ep, started);
|
|
2358
|
+
// A started carrier says it is online (the header's "Presence"): the relay says offline after.
|
|
2359
|
+
if (this.#started) { creds.will = { topic: PRESENCE_WILL, payload: 'offline', qos: 0, retain: false }; link.will = true; }
|
|
2195
2360
|
await info;
|
|
2196
2361
|
// The transport (the header's "Transport"): auto tries ep.mqtt for PROBE_MS, then the WebSocket
|
|
2197
2362
|
// endpoint, and keeps to it for the rest of the process (FELL_BACK). Only a dial that got no
|
|
@@ -2219,7 +2384,7 @@ export class Carrier {
|
|
|
2219
2384
|
if (!link.client.connected) throw link.cut ?? new MsgError('connect', 'the relay closed the connection');
|
|
2220
2385
|
// Deliveries are counted from here (quiet), not from before the login: a proof-of-work search
|
|
2221
2386
|
// of seconds would read as a drained queue, and give up stale claims before what they hold came.
|
|
2222
|
-
link.since = Date.now();
|
|
2387
|
+
link.since = Date.now(); link.onlineAt = this.clock();
|
|
2223
2388
|
if (creds.pow !== undefined) this.#locked(({ st }) => { (st.relays[relay] ??= { proven: false, claims: {} }).proven = true; });
|
|
2224
2389
|
link.client.on('error', () => {}); // a close follows
|
|
2225
2390
|
link.client.on('close', () => this.#closed(link));
|
|
@@ -2229,11 +2394,11 @@ export class Carrier {
|
|
|
2229
2394
|
return link;
|
|
2230
2395
|
}
|
|
2231
2396
|
|
|
2232
|
-
async #connect(relay) {
|
|
2397
|
+
async #connect(relay, started) {
|
|
2233
2398
|
this.#connecting.add(relay);
|
|
2234
2399
|
try {
|
|
2235
2400
|
for (let attempt = 0; ; attempt++) {
|
|
2236
|
-
const link = await this.#dial(relay);
|
|
2401
|
+
const link = await this.#dial(relay, started);
|
|
2237
2402
|
this.#refreshSoon(relay);
|
|
2238
2403
|
await this.#drain();
|
|
2239
2404
|
if (link.up) return link;
|
|
@@ -2246,18 +2411,25 @@ export class Carrier {
|
|
|
2246
2411
|
|
|
2247
2412
|
#closed(link) {
|
|
2248
2413
|
link.abort?.(new MsgError('connect', 'the connection to the relay closed'));
|
|
2414
|
+
// What this connection read of the contacts' presence holds only while it is up.
|
|
2415
|
+
if (link.presenceIn.size > 0) {
|
|
2416
|
+
try {
|
|
2417
|
+
this.#locked(({ st }) => { for (const [d, e] of Object.entries(st.presence ?? {})) if (e.relay === link.relay) delete st.presence[d]; });
|
|
2418
|
+
} catch {}
|
|
2419
|
+
}
|
|
2249
2420
|
if (this.#links.get(link.relay) === link) this.#links.delete(link.relay);
|
|
2250
2421
|
this.#emit({ type: 'disconnected', relay: link.relay });
|
|
2251
2422
|
if (Date.now() - link.since >= STABLE_MS) this.#attempts.delete(link.relay);
|
|
2252
2423
|
if (!this.#started || this.#connecting.has(link.relay) || (link.closing && !link.pow)) return;
|
|
2253
2424
|
if (link.cut?.permanent) {
|
|
2254
|
-
this.#emit({ type: 'error', relay: link.relay, check: link.cut.check, detail: link.cut.message });
|
|
2425
|
+
this.#emit({ type: 'error', relay: link.relay, check: link.cut.check, detail: link.cut.message, ...(link.cut.next !== undefined && { next: link.cut.next }) });
|
|
2255
2426
|
this.#abandon(link.relay, link.cut);
|
|
2256
2427
|
} else this.#retry(link.relay);
|
|
2257
2428
|
}
|
|
2258
2429
|
|
|
2259
|
-
// Exponential backoff with jitter: first, 2 × first, … up to most.
|
|
2260
|
-
|
|
2430
|
+
// Exponential backoff with jitter: first, 2 × first, … up to most. started: the first try's only
|
|
2431
|
+
// (start({ started })); every later one is automatic.
|
|
2432
|
+
#retry(relay, delay, started) {
|
|
2261
2433
|
if (this.#timers.has(relay)) return;
|
|
2262
2434
|
const n = (this.#attempts.get(relay) ?? 0) + 1, [first, most] = this.backoff;
|
|
2263
2435
|
this.#attempts.set(relay, n);
|
|
@@ -2266,11 +2438,11 @@ export class Carrier {
|
|
|
2266
2438
|
this.#timers.delete(relay);
|
|
2267
2439
|
if (!this.#started || this.#links.get(relay)?.up || this.#connecting.has(relay)) return;
|
|
2268
2440
|
try {
|
|
2269
|
-
const link = await this.#connect(relay);
|
|
2441
|
+
const link = await this.#connect(relay, started);
|
|
2270
2442
|
this.#powFails.delete(relay);
|
|
2271
2443
|
if (!this.#started) await this.#hangUp(link); // stop() came while this connected
|
|
2272
2444
|
} catch (e) {
|
|
2273
|
-
this.#emit({ type: 'error', relay, check: e.check ?? 'connect', detail: e.message });
|
|
2445
|
+
this.#emit({ type: 'error', relay, check: e.check ?? 'connect', detail: e.message, ...(e.next !== undefined && { next: e.next }) });
|
|
2274
2446
|
if (e.check === 'pow') this.#powFails.set(relay, (this.#powFails.get(relay) ?? 0) + 1);
|
|
2275
2447
|
// A refusal no retry can fix, or proof of work failing twice (each try may cost POW_MS of
|
|
2276
2448
|
// CPU), or POW_SEARCHES spent: no backoff loop here. The hourly round tries again while a
|
|
@@ -2278,10 +2450,21 @@ export class Carrier {
|
|
|
2278
2450
|
// stranger's code sent there.
|
|
2279
2451
|
if (PERMANENT.has(e.check) || e.permanent || this.#powFails.get(relay) >= 2) this.#abandon(relay, e);
|
|
2280
2452
|
else this.#retry(relay);
|
|
2453
|
+
// The day's searches spent: the next automatic try at the time the refusal named, not later.
|
|
2454
|
+
if (e.check === 'pow' && e.next !== undefined && this.#started) this.#powWait(relay, e.next);
|
|
2281
2455
|
}
|
|
2282
2456
|
}, wait));
|
|
2283
2457
|
}
|
|
2284
2458
|
|
|
2459
|
+
// A timer to `next` (unix seconds): the relay's next automatic try once the day's searches are
|
|
2460
|
+
// spent. The hourly round leaves it be (it holds the relay's timer); sync() and tryNow() clear it.
|
|
2461
|
+
#powWait(relay, next) {
|
|
2462
|
+
if (this.#timers.has(relay)) return;
|
|
2463
|
+
const ms = Math.min(2 ** 31 - 1, Math.max(1000, (next - this.clock()) * 1000 + 1000));
|
|
2464
|
+
this.#timers.set(relay, setTimeout(() => { this.#timers.delete(relay); this.#powWaits.delete(relay); this.#retry(relay, 0); }, ms));
|
|
2465
|
+
this.#powWaits.add(relay);
|
|
2466
|
+
}
|
|
2467
|
+
|
|
2285
2468
|
// A relay other than this agent's own refuses it for good: the answers still waiting to go to it
|
|
2286
2469
|
// are withdrawn, so no later round dials, for them, a host that a stranger's code named. An
|
|
2287
2470
|
// answer the relay already holds stays: the inviter may pair and reply, and its secret is what
|
|
@@ -2316,13 +2499,13 @@ export class Carrier {
|
|
|
2316
2499
|
|
|
2317
2500
|
// Connects (or refreshes) each relay, waits for the round to settle, and hangs up again unless
|
|
2318
2501
|
// started.
|
|
2319
|
-
async #session(relays, idle = {}) {
|
|
2502
|
+
async #session(relays, idle = {}, started) {
|
|
2320
2503
|
const opened = [];
|
|
2321
2504
|
this.#locked((ctx) => this.#expireKeys(ctx));
|
|
2322
2505
|
try {
|
|
2323
2506
|
for (const r of relays) {
|
|
2324
2507
|
if (this.#links.get(r)?.up) this.#refreshSoon(r);
|
|
2325
|
-
else opened.push(await this.#connect(r));
|
|
2508
|
+
else opened.push(await this.#connect(r, started));
|
|
2326
2509
|
}
|
|
2327
2510
|
await this.#idle(idle);
|
|
2328
2511
|
// One more round now that deliveries have stopped: claims past their time are given up
|
|
@@ -2347,7 +2530,7 @@ export class Carrier {
|
|
|
2347
2530
|
// the short code is parked there, and the pairing talks over it.
|
|
2348
2531
|
// local: no session: the code is made and kept only; its answer topic is claimed at this
|
|
2349
2532
|
// identity's next login (a device added offline, device.mjs), so connect once before it answers.
|
|
2350
|
-
async invite({ name, ttl, short = false, relay, local = false } = {}) {
|
|
2533
|
+
async invite({ name, ttl, short = false, relay, local = false, started } = {}) {
|
|
2351
2534
|
const at = relay === undefined ? this.relay : relayArg(relay);
|
|
2352
2535
|
const code = this.#locked(({ now, me, store }) => {
|
|
2353
2536
|
const code = makeInvite({ did: me.current_did, relay: at, now, ...(ttl !== undefined && { ttl }) });
|
|
@@ -2361,7 +2544,7 @@ export class Carrier {
|
|
|
2361
2544
|
// The answer topic is claimed before the code leaves: the relay drops what nobody reads.
|
|
2362
2545
|
const t = inviteKeys(code.secret).answer_topic;
|
|
2363
2546
|
try {
|
|
2364
|
-
await this.#session([code.relay]);
|
|
2547
|
+
await this.#session([code.relay], {}, started);
|
|
2365
2548
|
if (!this.#claimed.has(t)) {
|
|
2366
2549
|
const r = this.#refusedTopics.get(t);
|
|
2367
2550
|
fail(r?.code ?? 'subscribe', `the relay did not let this agent claim the invite's topic${r ? ` (${relaySays(r.detail)})` : ''}`);
|
|
@@ -2369,7 +2552,7 @@ export class Carrier {
|
|
|
2369
2552
|
if (!short) return { code: code.text, did: code.did, relay: code.relay, exp: code.exp };
|
|
2370
2553
|
// Eight characters on the public relay; on any other, twelve: the last four its relay tag.
|
|
2371
2554
|
const s = makeShort(undefined, code.relay === this.shortRelay ? null : relayTag(code.relay)), exp = Math.min(checkNow(this.clock()) + SHORT_TTL, code.exp), ep = endpointOf(code.relay, this.endpoints);
|
|
2372
|
-
const creds = await this.#credentials(code.relay, ep);
|
|
2555
|
+
const creds = await this.#credentials(code.relay, ep, started);
|
|
2373
2556
|
const r = await http(this.platform, `${ep.http}/park`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password, code_hash: codeHash(s), invite: code.text, exp }) });
|
|
2374
2557
|
const check = typeof r.body?.check === 'string' ? r.body.check : null;
|
|
2375
2558
|
if (r.status === 429) refuse('rate', `the relay ${code.relay} parks no more short codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to an hour')}, or use the long code (invite --long)`, r);
|
|
@@ -2491,7 +2674,7 @@ export class Carrier {
|
|
|
2491
2674
|
try { return await this.#answer(long, how, { ...opts, relay: at }); } catch (e) { throw keepLong(e, long); }
|
|
2492
2675
|
}
|
|
2493
2676
|
|
|
2494
|
-
async #answer(text, how, { name, wait = 10, tier, relay } = {}) {
|
|
2677
|
+
async #answer(text, how, { name, wait = 10, tier, relay, started } = {}) {
|
|
2495
2678
|
if (tier !== undefined && !TIERS.includes(tier)) fail('tier', `a tier is ${TIERS.join(', ')}; not ${JSON.stringify(tier)}`);
|
|
2496
2679
|
const named = relay === undefined ? undefined : relayArg(relay);
|
|
2497
2680
|
const { code, id, entry } = this.#locked(({ now, me, store, st }) => {
|
|
@@ -2529,7 +2712,7 @@ export class Carrier {
|
|
|
2529
2712
|
const reply = inviteKeys(code.secret).reply_topic;
|
|
2530
2713
|
// And once the code expires (#lapse): the answer is dead, so --wait does not run out first.
|
|
2531
2714
|
const settled = () => this.#handshakes.has(id) || this.#refusedTopics.has(reply) || Boolean(this.#results.get(entry)?.code) || this.clock() >= code.exp;
|
|
2532
|
-
try { await this.#session([code.relay], { max: wait * 1000, until: settled }); } catch (e) {
|
|
2715
|
+
try { await this.#session([code.relay], { max: wait * 1000, until: settled }, started); } catch (e) {
|
|
2533
2716
|
// A relay other than this agent's own that refuses it for good would be dialled again at
|
|
2534
2717
|
// every connection, until the code expires, for an answer it never takes: and a stranger's
|
|
2535
2718
|
// code names it. Withdrawn only while it waits to go: an answer the relay holds keeps its
|
|
@@ -2598,7 +2781,9 @@ export class Carrier {
|
|
|
2598
2781
|
const e = st.peers[c.did], pair = c.revoked || !c.pair_key ? null : pairId(hexToBytes(c.pair_key));
|
|
2599
2782
|
return { name: c.name, did: c.did, current_did: c.current_did, chain: c.chain, revoked: c.revoked, relay: c.relay, queued: e?.outbox.length ?? 0,
|
|
2600
2783
|
re_pair: c.re_pair ?? null, fingerprint: c.revoked ? null : wordsOf(c.pair_key), pair, ours: store.oursOf(c, now), tier: store.tierOf(c, now), tier_by: c.tier_by ?? null,
|
|
2601
|
-
prekeys: pair !== null && theirPrekeys(c, e?.session, pair, now), waiting: e?.waiting ?? null, link: c.link ?? null
|
|
2784
|
+
prekeys: pair !== null && theirPrekeys(c, e?.session, pair, now), waiting: e?.waiting ?? null, link: c.link ?? null,
|
|
2785
|
+
// Presence (the header's): what this contact sees of mine, and theirs as read now (null: not known).
|
|
2786
|
+
presence: store.presenceOf(c, now), online: st.presence?.[c.did]?.online ?? null, online_since: st.presence?.[c.did]?.since ?? null, last_seen: st.presence?.[c.did]?.last_seen ?? null };
|
|
2602
2787
|
}),
|
|
2603
2788
|
invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay })),
|
|
2604
2789
|
answers: Object.values(s.accepts).filter((p) => p.exp > now).map((p) => ({ name: p.name, did: p.code_did, exp: p.exp, relay: p.relay })),
|
|
@@ -2626,6 +2811,8 @@ export class Carrier {
|
|
|
2626
2811
|
if (typeof label !== 'string') fail('body', 'label must be a string');
|
|
2627
2812
|
if (label === LABEL_PREKEYS || label === OPERATOR_LABEL) fail('body', `the label ${JSON.stringify(label)} is the carrier's own`);
|
|
2628
2813
|
if (label.startsWith('sigelo-link/') && internal !== LINK_SEND) fail('body', `the label ${JSON.stringify(label)} is the link handler's own (sigelo-agent link)`);
|
|
2814
|
+
if (label.startsWith('sigelo-group/') && internal !== GROUP_SEND) fail('body', `the label ${JSON.stringify(label)} is the group handler's own (sigelo-agent group send)`);
|
|
2815
|
+
if (label.startsWith('sigelo-transfer/') && internal !== TRANSFER_SEND) fail('body', `the label ${JSON.stringify(label)} is the transfer engine's own (sigelo-agent transfer)`);
|
|
2629
2816
|
if (label.startsWith('sigelo-device/') && internal !== DEVICE_SEND) fail('body', `the label ${JSON.stringify(label)} is the device verbs' own (sigelo-agent device)`);
|
|
2630
2817
|
if (!Array.isArray(contents) || contents.length === 0) fail('body', 'at least one message');
|
|
2631
2818
|
for (const content of contents) {
|
|
@@ -2705,7 +2892,7 @@ export class Carrier {
|
|
|
2705
2892
|
const want = tiers === undefined ? null : new Set(tiers);
|
|
2706
2893
|
if (want && ![...want].every((t) => TIERS.includes(t))) fail('tier', `tiers: some of ${TIERS.join(', ')}`);
|
|
2707
2894
|
const picks = (store, now) => { const t = want && store.tiers(now); return (m) => !want || want.has(t.get(m.from) ?? 'friend'); };
|
|
2708
|
-
const ready = () => this.#read(({ now, store, st }) => st.inbox.some(picks(store, now)) || (st.links?.length ?? 0) > 0 || (st.devices?.length ?? 0) > 0 || st.events.some((e) => e.type === 'pairing_failed' || (paired && e.type === 'paired')));
|
|
2895
|
+
const ready = () => this.#read(({ now, store, st }) => st.inbox.some(picks(store, now)) || (st.links?.length ?? 0) > 0 || (st.groups?.length ?? 0) > 0 || (st.devices?.length ?? 0) > 0 || st.events.some((e) => e.type === 'pairing_failed' || (paired && e.type === 'paired')));
|
|
2709
2896
|
let offline = null;
|
|
2710
2897
|
if (local) {
|
|
2711
2898
|
for (const end = Date.now() + wait * 1000; Date.now() < end && !ready();) await sleep(250);
|
|
@@ -2759,11 +2946,31 @@ export class Carrier {
|
|
|
2759
2946
|
}
|
|
2760
2947
|
|
|
2761
2948
|
setTier(who, tier) { return this.#locked(({ now, store }) => store.setTier(who, tier, now)); }
|
|
2949
|
+
setPresence(who, allow) {
|
|
2950
|
+
const r = this.#locked(({ now, store }) => { const x = store.setPresence(who, allow, now); return { ...x, relay: store.lookup(x.did)?.relay }; });
|
|
2951
|
+
if (r.relay && this.#links.get(r.relay)?.up) this.#refreshSoon(r.relay);
|
|
2952
|
+
return { did: r.did, name: r.name, presence: r.presence };
|
|
2953
|
+
}
|
|
2762
2954
|
// The owner's tier for an original DID before it is a contact (an enrolled worker): store.mjs presetTier.
|
|
2763
2955
|
presetTier(did, tier) { return this.#locked(({ now, store }) => store.presetTier(did, tier, now)); }
|
|
2764
2956
|
// Links (link.mjs): the link messages received, taken; a contact's link record set (null: dropped).
|
|
2765
2957
|
takeLinks() { return this.#locked(({ st }) => { const l = st.links ?? []; st.links = []; return l; }); }
|
|
2958
|
+
takeGroups() { return this.#locked(({ st }) => { const l = st.groups ?? []; st.groups = []; return l; }); }
|
|
2766
2959
|
takeDevices() { return this.#locked(({ st }) => { const l = st.devices ?? []; st.devices = []; return l; }); }
|
|
2960
|
+
// pick(message) → take it (default all); the rest stay for a later take (an engine's).
|
|
2961
|
+
takeTransfers(pick = () => true) { return this.#locked(({ st }) => { const l = st.transfers ?? [], took = l.filter((m) => pick(m)); st.transfers = l.filter((m) => !took.includes(m)); return took; }); }
|
|
2962
|
+
// A file a transfer saved whole (transfer-node.mjs): an inbox item as #onFile makes one, kept for
|
|
2963
|
+
// inbox() (keep) and handed to onEvent. item: { type: 'file', from, contact, name, size, sha256, path, … }.
|
|
2964
|
+
deliver(item) {
|
|
2965
|
+
const it = { ...item, received: item.received ?? this.#read(({ now }) => now) };
|
|
2966
|
+
this.#locked(({ st }) => {
|
|
2967
|
+
if (!this.keep) return;
|
|
2968
|
+
st.inbox.push(it);
|
|
2969
|
+
if (st.inbox.length > INBOX_MAX) { const n = st.inbox.length - INBOX_MAX; st.inbox.splice(0, n); st.dropped.inbox_full = (st.dropped.inbox_full ?? 0) + n; }
|
|
2970
|
+
});
|
|
2971
|
+
this.#emit(it);
|
|
2972
|
+
return it;
|
|
2973
|
+
}
|
|
2767
2974
|
// A copy of this state may have sent and received after it was taken (devices.md §4.3: the seat
|
|
2768
2975
|
// moved, the state came in a snapshot). Every session with `only`'s contacts (default: all live)
|
|
2769
2976
|
// starts afresh, as after a rotation: the outgoing epoch ends, the contact's one-time prekeys
|
|
@@ -2828,18 +3035,21 @@ export class Carrier {
|
|
|
2828
3035
|
|
|
2829
3036
|
// ---- staying connected
|
|
2830
3037
|
|
|
2831
|
-
|
|
3038
|
+
/** started: 'user' when the human opened this (the page's start): its first login asks past the cap (pow_confirm). */
|
|
3039
|
+
async start({ started } = {}) {
|
|
2832
3040
|
if (this.#started) return;
|
|
2833
3041
|
this.#started = true;
|
|
2834
|
-
for (const r of this.#relaysInUse()) this.#retry(r, 0);
|
|
3042
|
+
for (const r of this.#relaysInUse()) this.#retry(r, 0, started);
|
|
2835
3043
|
this.#tick = setInterval(() => this.#round(), this.tick);
|
|
2836
3044
|
this.#tick.unref?.();
|
|
2837
3045
|
}
|
|
2838
3046
|
|
|
2839
|
-
|
|
3047
|
+
// force (sync, the caller's): a relay waiting for its next automatic try (#powWait) is tried now too.
|
|
3048
|
+
#round(force = false) {
|
|
2840
3049
|
this.#later(() => this.#locked((ctx) => this.#expireKeys(ctx)));
|
|
2841
3050
|
for (const l of this.#links.values()) l.absent.clear(); // an absent contact may be back: try once more
|
|
2842
3051
|
for (const r of this.#relaysInUse()) {
|
|
3052
|
+
if (force) this.#unwait(r);
|
|
2843
3053
|
if (this.#links.get(r)?.up) this.#refreshSoon(r);
|
|
2844
3054
|
else if (!this.#timers.has(r) && !this.#connecting.has(r)) this.#retry(r, 0);
|
|
2845
3055
|
}
|
|
@@ -2847,15 +3057,47 @@ export class Carrier {
|
|
|
2847
3057
|
|
|
2848
3058
|
/** One round now (claims for a new week, queued messages), then wait as `inbox` does. */
|
|
2849
3059
|
async sync({ wait = 0 } = {}) {
|
|
2850
|
-
if (this.#started) { this.#round(); await this.#idle({ max: Math.max(DRAIN, wait * 1000) }); return; }
|
|
3060
|
+
if (this.#started) { this.#round(true); await this.#idle({ max: Math.max(DRAIN, wait * 1000) }); return; }
|
|
2851
3061
|
await this.#session(this.#relaysInUse(), { max: Math.max(DRAIN, wait * 1000) });
|
|
2852
3062
|
}
|
|
2853
3063
|
|
|
3064
|
+
#unwait(relay) {
|
|
3065
|
+
if (!this.#powWaits.delete(relay)) return;
|
|
3066
|
+
clearTimeout(this.#timers.get(relay));
|
|
3067
|
+
this.#timers.delete(relay);
|
|
3068
|
+
}
|
|
3069
|
+
|
|
3070
|
+
/**
|
|
3071
|
+
* The human's "Try now" (design/profiles.md §6): a login now at each relay in use that is not
|
|
3072
|
+
* connected, as a search they started: past the day's POW_SEARCHES it throws pow_confirm, and
|
|
3073
|
+
* { confirmed: true } goes on. → { tried: [relays] }; throws as the login does.
|
|
3074
|
+
*/
|
|
3075
|
+
async tryNow({ confirmed = false } = {}) {
|
|
3076
|
+
const started = confirmed ? 'confirmed' : 'user', todo = this.#relaysInUse().filter((r) => !this.#links.get(r)?.up && !this.#connecting.has(r));
|
|
3077
|
+
for (const r of todo) {
|
|
3078
|
+
this.#unwait(r);
|
|
3079
|
+
clearTimeout(this.#timers.get(r));
|
|
3080
|
+
this.#timers.delete(r);
|
|
3081
|
+
this.#powFails.delete(r);
|
|
3082
|
+
this.#attempts.delete(r);
|
|
3083
|
+
}
|
|
3084
|
+
if (!this.#started) { await this.#session(todo, {}, started); return { tried: todo }; }
|
|
3085
|
+
for (const r of todo) {
|
|
3086
|
+
try { await this.#connect(r, started); } catch (e) {
|
|
3087
|
+
this.#emit({ type: 'error', relay: r, check: e.check ?? 'connect', detail: e.message, ...(e.next !== undefined && { next: e.next }) });
|
|
3088
|
+
if (!(PERMANENT.has(e.check) || e.permanent)) this.#retry(r);
|
|
3089
|
+
throw e;
|
|
3090
|
+
}
|
|
3091
|
+
}
|
|
3092
|
+
return { tried: todo };
|
|
3093
|
+
}
|
|
3094
|
+
|
|
2854
3095
|
async stop() {
|
|
2855
3096
|
this.#started = false;
|
|
2856
3097
|
clearInterval(this.#tick);
|
|
2857
3098
|
for (const t of this.#timers.values()) clearTimeout(t);
|
|
2858
3099
|
this.#timers.clear();
|
|
3100
|
+
this.#powWaits.clear();
|
|
2859
3101
|
await this.#drain();
|
|
2860
3102
|
for (const link of [...this.#links.values()]) await this.#hangUp(link);
|
|
2861
3103
|
}
|