sigelo-contact 0.1.14 → 0.1.21
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/README.md +13 -10
- package/call.mjs +831 -0
- package/carrier.mjs +1013 -112
- package/control.mjs +81 -22
- package/device.mjs +1 -1
- package/enrol.mjs +214 -35
- package/gen-carrier.mjs +4 -4
- package/gen-device.mjs +2 -2
- package/gen-envelope.mjs +3 -3
- package/gen-invite.mjs +3 -3
- package/gen-short.mjs +3 -3
- package/group.mjs +28 -9
- package/invite.mjs +63 -13
- package/kdf.mjs +1 -1
- package/link.mjs +1 -1
- package/package.json +34 -7
- package/page.mjs +1018 -81
- package/photo.mjs +37 -0
- package/platform-node.mjs +110 -13
- package/prekeys.mjs +10 -2
- package/public.mjs +93 -0
- package/relays.mjs +1 -1
- package/restore.mjs +3 -3
- package/rtc-web.mjs +109 -0
- package/short.mjs +19 -3
- package/store.mjs +126 -10
- package/test-carrier.mjs +121 -18
- package/test-device.mjs +1 -1
- package/test-enrol.mjs +123 -8
- package/test-envelope.mjs +16 -3
- package/test-file.mjs +5 -5
- package/test-group.mjs +48 -7
- package/test-invite.mjs +15 -2
- package/test-link.mjs +6 -6
- package/test-platform.mjs +5 -5
- package/test-presence.mjs +5 -5
- package/test-push.mjs +136 -0
- package/test-relay-lane.mjs +323 -0
- package/test-short.mjs +35 -12
- package/test-tier.mjs +6 -6
- package/test-transfer-web.mjs +313 -0
- package/test-transfer.mjs +51 -11
- package/test-voice.mjs +161 -0
- package/test-ws.mjs +5 -5
- package/transfer-engine.mjs +858 -0
- package/transfer-node.mjs +254 -641
- package/transfer-web.mjs +80 -0
- package/transfer.mjs +25 -6
- package/voice-web.mjs +113 -0
- package/voice.mjs +70 -0
- package/words-lock.mjs +25 -10
package/carrier.mjs
CHANGED
|
@@ -4,10 +4,17 @@
|
|
|
4
4
|
// sees random topics and ciphertext; everything here that decides who someone is runs offline.
|
|
5
5
|
//
|
|
6
6
|
// const c = new Carrier({ identity, store, state, relay, endpoints, retentionDays, clock, onEvent, keep, transport, platform })
|
|
7
|
-
// await c.invite({ name, ttl, short, relay, local }) → { code, did, relay, exp, short?, short_exp? } the answer topic is claimed first
|
|
7
|
+
// await c.invite({ name, ttl, short, relay, local, renew }) → { code, did, relay, exp, short?, short_exp?, renew? } the answer topic is claimed first
|
|
8
8
|
// (local: at the next login, no session now);
|
|
9
9
|
// short: the long code is also parked at the relay under a short one;
|
|
10
|
-
// relay: the relay the code names and the short code is parked at (default: this agent's)
|
|
10
|
+
// relay: the relay the code names and the short code is parked at (default: this agent's);
|
|
11
|
+
// renew (with short): a one-person code that renews itself: once it is used, a fresh
|
|
12
|
+
// short code with the same name (numbered), ttl and relay is parked (store.mjs renew)
|
|
13
|
+
// await c.invitePublic({ name, ttl, cap, open, relay }) → { id, name, code: sgl2…, short: PUB-…, words, link, exp, relay, cap, open, did }:
|
|
14
|
+
// a public code (public.mjs, Pro only at the relay): many may use it, each a request
|
|
15
|
+
// (event public_request) approved by approvePublic(id) or refusePublic(id), or at
|
|
16
|
+
// once with open; setPublic(id|PUB code, { paused, cap }); cancelInvite(it): Revoke
|
|
17
|
+
// for all; publics() and contacts().publics: each with its requests waiting
|
|
11
18
|
// await c.unpark(short, { relay }) → the long code parked under a short one, taken from the relay (one use);
|
|
12
19
|
// relay: named, else relayForShort's (unparkFrom: { invite, relay })
|
|
13
20
|
// await c.relayForShort(short, { relay }) → { relay, from }: where a short code is parked: 8 characters, shortRelay
|
|
@@ -16,13 +23,25 @@
|
|
|
16
23
|
// await c.probeRelay(host) → { relay, ok, ms, retention_days, detail? }: does it answer (GET /relay.json, else /challenge)
|
|
17
24
|
// await c.redeemGift(code) → { exp, months }: a gift code (PRO-K7F3-Q9ZP) redeemed at this agent's relay;
|
|
18
25
|
// this identity is the operator whose pool is Pro until exp (relay/gifts.mjs)
|
|
19
|
-
// await c.accept(code, { name, wait, relay }) → { status: 'connected' | 'waiting' | 'pending', … } a long code
|
|
26
|
+
// await c.accept(code, { name, wait, relay, words }) → { status: 'connected' | 'waiting' | 'waiting_approval' | 'pending', … } a long code, a short one,
|
|
27
|
+
// or a public one (PUB-…, its link, sgl2…; words: its page's four words, checked on the reply)
|
|
20
28
|
// (refused after a short code was fetched: .long, keepLong); relay: where a
|
|
21
29
|
// short code was parked, when not at this agent's relay (the inviter's --relay)
|
|
22
|
-
// await c.cancelInvite(code)
|
|
30
|
+
// await c.cancelInvite(code, { relay }) → { cancelled, name, short?, unparked?, detail? }: an unanswered invite of this agent's
|
|
31
|
+
// withdrawn, by its long code, its short code or the short code's hash; a short
|
|
32
|
+
// code parked is cancelled at the relay too (DELETE /park/<hash>, relay/park.mjs):
|
|
33
|
+
// unparked true once nobody can fetch it there, false with detail when the relay
|
|
34
|
+
// could not be told (an older relay, offline: it runs out there by itself, and an
|
|
35
|
+
// answer to it is refused here); a renewing code's series ends
|
|
23
36
|
// c.rename(who, name) the owner's name for a contact (store.mjs rename) → { did, name }
|
|
24
|
-
// c.contacts() → { contacts, invites, answers, failed }
|
|
25
|
-
//
|
|
37
|
+
// c.contacts() → { contacts, invites, answers, failed, renewing } invites: { name, exp, relay, short?, short_exp?, renew? },
|
|
38
|
+
// renewing: { id, name, used: [{ short, did, name, at }], error } per series;
|
|
39
|
+
// each contact with its four words (fingerprint),
|
|
40
|
+
// pair id, chain, ours (an operator attestation of mine marks it), tier, seen_upto
|
|
41
|
+
// (their newest seen receipt: my messages sealed at or before it were shown; null: none) and
|
|
42
|
+
// seen_peer (a receipt came: they read receipts), busy (their busy mark is on), busy_n
|
|
43
|
+
// (agents running by it, 0 when off), busy_peer (they take busy marks), host_peer (they
|
|
44
|
+
// take a hosted agent's settings), tier
|
|
26
45
|
// (store.mjs: own, friend, quiet) and tier_by, prekeys: its
|
|
27
46
|
// bundle is here (false: messages wait for it), waiting: why they wait, or null;
|
|
28
47
|
// failed: pairing_failed events (code_expired: an answer that outlived its code) until inbox
|
|
@@ -33,10 +52,17 @@
|
|
|
33
52
|
// queued wait in files/.out (0600), the state names them; gone once sent or refused.
|
|
34
53
|
// local (all three): no session, queued in the state file for a started carrier
|
|
35
54
|
// of the same identity elsewhere (a watcher), which sends it at its next sync()
|
|
36
|
-
// await c.inbox({ wait, tiers, local, paired }) → { messages, events, dropped, offline? }: all are taken (messages: those kept;
|
|
55
|
+
// await c.inbox({ wait, tiers, local, paired, from }) → { messages, events, dropped, offline? }: all are taken (messages: those kept;
|
|
37
56
|
// tiers: only those from contacts of these tiers, the rest stay); local: no
|
|
38
57
|
// session, the state file only (a started carrier elsewhere is connected);
|
|
39
|
-
// paired: the wait also ends at a pairing (enrol.mjs)
|
|
58
|
+
// paired: the wait also ends at a pairing (enrol.mjs); from: that DID's only.
|
|
59
|
+
// The wait is the caller's: a session the relay ends early is logged in again
|
|
60
|
+
// at the pace backoff sets until then; ended: { code, detail, n }, the relay's
|
|
61
|
+
// last word when it ended one (n times) during this inbox
|
|
62
|
+
// Each message and file has an id (messageId), the same at every read
|
|
63
|
+
// await c.reply(id, content, { label, local }), c.replyFile(id, file, { local }) → as send, sendFile, to the sender of
|
|
64
|
+
// message id (kept RECEIVED_DAYS), with msg_id and delivery; c.replyStatus(id) →
|
|
65
|
+
// { msg_id, from, name, received, reply: { status: queued|published|refused, … } | null, fetched: null }
|
|
40
66
|
// c.peek(), c.take(pick) the messages kept for inbox(), each with its sender's tier: read, or those
|
|
41
67
|
// pick(message, tier) chooses taken; no session (a started carrier's owner)
|
|
42
68
|
// c.history({ since }) → { messages }: what inbox() and take() gave out, again, from the local log
|
|
@@ -50,6 +76,12 @@
|
|
|
50
76
|
// c.takeLinks(), c.setLink(who, link) link.mjs's: the sigelo-link/1 messages received (never in inbox(), the log
|
|
51
77
|
// or onEvent: a `link` event without content says one came), taken; a
|
|
52
78
|
// contact's link record (store.mjs setLink)
|
|
79
|
+
// await c.seen(to, upto) a seen receipt (SEEN_LABEL, the header's "Seen receipts") to contact to: every message of
|
|
80
|
+
// theirs sealed at or before upto (their iat, unix seconds; 0: none yet) was shown → as send
|
|
81
|
+
// await c.busy(to, on, { local, n }) a busy mark (BUSY_LABEL, the header's "Busy marks") to contact to: on (a turn runs)
|
|
82
|
+
// or off → as send, or { status: 'skipped' } for a contact that never said it takes them
|
|
83
|
+
// await c.read(items, { local }) read marks: a seen receipt to each sender of these inbox items, once per message
|
|
84
|
+
// (own contacts always, others as the app does) → [{ to, upto, status | error }]
|
|
53
85
|
// c.takeGroups() group.mjs's: the sigelo-group/1 messages received (never in inbox(), the
|
|
54
86
|
// log or onEvent: a `group` event without content says one came), taken
|
|
55
87
|
// c.groupTier what this agent's relay told its last login of its group tier ($sigelo/notice
|
|
@@ -59,6 +91,9 @@
|
|
|
59
91
|
// c.takeTransfers(), c.deliver(item) transfer-node.mjs's: the sigelo-transfer/0 messages received (never in inbox(),
|
|
60
92
|
// the log or onEvent: a `transfer` event without content says one came), taken;
|
|
61
93
|
// a file a transfer saved whole, as an inbox item (kept as #onFile keeps one)
|
|
94
|
+
// c.takeCalls() call.mjs's: the sigelo-call/0 messages this process received (never in inbox(),
|
|
95
|
+
// the log, onEvent, nor the state file: held in memory until taken; a `call`
|
|
96
|
+
// event without content says one came), taken
|
|
62
97
|
// c.freshEpochs({ only, retire }) every session (or only's) afresh, as after a rotation (a snapshot's
|
|
63
98
|
// state imported where the seat moved, devices.md §4.3) → the DIDs
|
|
64
99
|
// c.answeredBy(nonce) the original DID that paired through this agent's code `nonce`, or null
|
|
@@ -72,6 +107,14 @@
|
|
|
72
107
|
// c.clockOffset(), await c.checkClock() → { relay, offset, checked } | null: the relay's clock less this one's, seconds
|
|
73
108
|
// await c.start(), c.sync(), c.stop() stay connected, reconnecting with backoff; events reach onEvent
|
|
74
109
|
// await c.tryNow({ confirmed }) the human's "Try now": a login at each relay in use not connected
|
|
110
|
+
// c.wake({ now }) a nudge from outside (the Android app's Stay connected: its alarm, the end of
|
|
111
|
+
// Doze): a started carrier retries, with its backoff, each relay in use that is
|
|
112
|
+
// down with no try already waiting; nothing else. now (a push wake): at once
|
|
113
|
+
// c.setPush(reg | null), c.pushStatus() the phone's UnifiedPush endpoint and keys registered at this agent's own relay
|
|
114
|
+
// (sigelo-push/0 on $sigelo/push, relay/push.mjs) at every login; null removes it
|
|
115
|
+
// await c.turnServer() → { urls, username, credential, exp } | null: a TURN credential from this agent's own
|
|
116
|
+
// relay (sigelo-turn/0 on $sigelo/turn, relay/turn.mjs), where GET /challenge says it
|
|
117
|
+
// gives them and the session is up; kept until 10 minutes before exp; null otherwise
|
|
75
118
|
// started: 'user' | 'confirmed' (start, invite, accept, tryNow) a search the human started: past
|
|
76
119
|
// POW_SEARCHES a day it is never refused, it asks (pow_confirm),
|
|
77
120
|
// and 'confirmed' goes on; without it (automatic retries) the cap holds
|
|
@@ -94,7 +137,7 @@
|
|
|
94
137
|
// One connected carrier per identity: every process logs in with the identity's one MQTT client
|
|
95
138
|
// id, so a second login takes the session from a started carrier (the files stay sound under the
|
|
96
139
|
// lock; the started one reconnects with backoff). Beside one, use inbox and send with local: the
|
|
97
|
-
// state file only (sigelo-agent's one-owner rule,
|
|
140
|
+
// state file only (sigelo-agent's one-owner rule, apps/agent/WATCH.md).
|
|
98
141
|
//
|
|
99
142
|
// Transport (transport, or SIGELO_RELAY_TRANSPORT): "auto" (the default), 8883 for PROBE_MS, then
|
|
100
143
|
// 443 for the rest of the process, so a network that lets only HTTPS out needs no setting; "mqtts",
|
|
@@ -205,6 +248,24 @@
|
|
|
205
248
|
// hinted and proved again; asks for the same operators go at most every RESYNC. A contact
|
|
206
249
|
// learns from the hints only which operator DIDs it guesses right (THREAT-MODEL §2.12). An
|
|
207
250
|
// agent on an older version gets the hints as messages with that label. send refuses the label.
|
|
251
|
+
// - Seen receipts (label SEEN_LABEL, a message like any other, inside the envelope): {seen: n}, n the
|
|
252
|
+
// iat of the newest message of the contact's that the reader's app has shown (0: none yet). The
|
|
253
|
+
// sender reads its own messages sealed at or before n as seen. Taken here, never an inbox message,
|
|
254
|
+
// never logged; kept as the contact's seen_upto (the highest) and seen_peer (contacts()), with an
|
|
255
|
+
// event `seen`. The relay sees one more envelope, never which. Sent only through seen() (SEEN_SEND):
|
|
256
|
+
// what to send and when is the app's (apps/contact/page.mjs: one first receipt to a contact not
|
|
257
|
+
// known to read them, further ones only once one came back). A contact on an earlier version takes
|
|
258
|
+
// the first as a message with that label, and never sends one: its messages stay at one tick.
|
|
259
|
+
// Once paired, each side also sends one {seen: 0, name, kind?}: its display name and kind (the "Names" below).
|
|
260
|
+
// Every receipt (the name's too) carries busy: true: this side takes busy marks (below), and host: true: it takes a
|
|
261
|
+
// hosted agent's settings (sigelo-host-caps/0, apps/contact/page.mjs "Agent settings"); kept as host_peer (contacts()).
|
|
262
|
+
// - Busy marks (label BUSY_LABEL, inside the envelope; 2026-11-19): {busy: true|false}, a hosted agent's "I am
|
|
263
|
+
// working on it" (sigelo-agent-host.ts): on at a turn's start and every 20 s while it runs, off before its reply;
|
|
264
|
+
// n (optional, an integer 2..99): that many agents run (the session and its subagents), kept as busy_n (absent: 1).
|
|
265
|
+
// Taken here, never an inbox message, never logged, never an event `message`: the contact's busy_until (now +
|
|
266
|
+
// BUSY_TTL_S, 0 for off; any message or file of theirs ends it too), contacts() busy, an event `busy`. Sent
|
|
267
|
+
// only through busy() (BUSY_SEND), with expires now + BUSY_TTL_S (a stale one goes unsent), and only to a
|
|
268
|
+
// contact whose receipt said busy: true (busy_peer): an earlier version would show it as a message.
|
|
208
269
|
// - Presence (design/transfer.md §8 T0): a started carrier sets the will $sigelo/presence on its
|
|
209
270
|
// CONNECT and publishes, to each contact that may see it (store.mjs presenceOf: own agents
|
|
210
271
|
// always, others when the owner allowed them), one marker on presenceTopic(K, own original DID,
|
|
@@ -246,11 +307,12 @@ import { sha256 } from '@noble/hashes/sha2.js';
|
|
|
246
307
|
import { concatBytes, hexToBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
247
308
|
import { canonicalize, commitmentOf, did as didOf, parseBytes, verify, verifySig } from 'sigelo';
|
|
248
309
|
import { KIND, acceptPrekeys, expire, header, open, pad, prekeysMissing, restartEpoch, send, session, unpad } from './envelope.mjs';
|
|
249
|
-
import { answerId, buildAnswer, buildReply, checkAnswer, checkReply, checkRelay, inviteKeys, keyOf, makeInvite, parseInvite } from './invite.mjs';
|
|
310
|
+
import { PUBLIC_VERSION, admitAnswer, answerId, buildAnswer, buildReply, checkAnswer, checkReply, checkRelay, inviteKeys, keyOf, makeInvite, parseInvite, parsePublicCode, screenAnswer } from './invite.mjs';
|
|
311
|
+
import { PUBLIC_CAP, PUBLIC_TTL_MAX, REQUEST_TTL, SEEN_KEEP, checkCap, formatPub, isPub, joinerKeys, normalisePub, normaliseWords, publicHash, publicKeys, publicLink, readLink } from './public.mjs';
|
|
250
312
|
import { MsgError, checkNow, fail, hex, isoWeek, pairId, signAs, topic } from './kdf.mjs';
|
|
251
313
|
import { Prekeys, exact, kemDecapsulate, kemEncapsulate, kemKey } from './prekeys.mjs';
|
|
252
314
|
import { Contacts, OPERATOR_CTX, TIERS } from './store.mjs';
|
|
253
|
-
import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, giftHash, makeShort, normaliseShort, relayTag, tagOf } from './short.mjs';
|
|
315
|
+
import { ENROL_TTL_MAX, SHORT_TTL, SHORT_TTL_MAX, SHORT_TTL_MIN, codeHash, codeKind, didWords, fingerprint, formatShort, giftHash, isEnrolCode, makeShort, normaliseShort, relayTag, stripEnrol, tagOf } from './short.mjs';
|
|
254
316
|
import { REGISTRY_URL, RELEASE_DID, loadRegistry, readTable, remember, resolveTag } from './relays.mjs';
|
|
255
317
|
import { FILE_LABEL, MAX_FILE, assemble, checkChunk, checkManifest, chunkHead, isManifest, safeName, splitFile } from './file.mjs';
|
|
256
318
|
// Every file, lock, network and CPU call goes through a platform (design/apps.md §4.2): Node's by default.
|
|
@@ -267,6 +329,8 @@ export const OPERATOR_LABEL = 'sigelo-operator/0';
|
|
|
267
329
|
export const LOGIN_V = 'sigelo-relay/0', TYP_LOGIN = 'relay-login';
|
|
268
330
|
// RETENTION_DAYS: the relay's free tier (relay/allowance.mjs TIERS.free), when relay.json says nothing.
|
|
269
331
|
export const RETENTION_DAYS = 14, RETENTION_MAX_DAYS = 90, DAY = 86400, SKEW = 300, AHEAD = 7 * DAY;
|
|
332
|
+
// Seconds before a renewing code that failed to renew is tried again (#renewDue).
|
|
333
|
+
export const RENEW_RETRY = 60;
|
|
270
334
|
// The relay closes a connection whose SUBSCRIBE holds more topics (relay/mailbox.mjs MAX_TOPICS).
|
|
271
335
|
const MAX_TOPICS = 128;
|
|
272
336
|
// An invite topic holds 4 messages and 64 KB (relay/mailbox.mjs INVITE_BYTES); a bundle at most 64
|
|
@@ -279,12 +343,16 @@ export const INVITE_BYTES = 64 * 1024, MAX_ROTATIONS = 64;
|
|
|
279
343
|
// one per rotation, and again at most hourly), and the last REFUSED_NOTICES refused after that
|
|
280
344
|
// check are refused again unchecked (#onContactNotice).
|
|
281
345
|
export const NOTICE_CHECKS = 4, REFUSED_NOTICES = 16;
|
|
282
|
-
// A proof of work must be sent within the
|
|
283
|
-
//
|
|
284
|
-
//
|
|
285
|
-
//
|
|
286
|
-
//
|
|
287
|
-
|
|
346
|
+
// A proof of work (relay/pow.mjs, sigelo-relay-pow/1: Argon2id) must be sent within the
|
|
347
|
+
// challenge's 300 s. One evaluation at 64 MiB, 3 passes takes POW_EVAL_MS on a phone-class ARM64
|
|
348
|
+
// CPU (hash-wasm in Node or a Worker, a big core; measured 2026-11-13; 1.64 s on a little core):
|
|
349
|
+
// 6 bits take 31 s on average, 8 bits 2 minutes, 10 bits 8. A relay asking more than POW_MAX is
|
|
350
|
+
// refused rather than spun for, and the search stops at POW_MS, before the challenge expires. Any
|
|
351
|
+
// host can be named by a stranger's code, so a relay other than this agent's own (SIGELO_RELAY)
|
|
352
|
+
// gets the plan's normal 6 bits at most. POW_COST: the most a relay may ask one evaluation to cost
|
|
353
|
+
// (GET /challenge's `pow`); a cheaper one is computed as stated (it costs the relay only).
|
|
354
|
+
export const POW_MAX = 10, POW_MAX_OTHER = 6, POW_MS = 280000, POW_EVAL_MS = 485;
|
|
355
|
+
export const POW_V = 1, POW_COST = Object.freeze({ m: 65536, t: 3, p: 1 });
|
|
288
356
|
// Searches at one relay in any 24 hours, each counted in the state file as it begins, found or not.
|
|
289
357
|
// An honest relay asks once per identity, and again only if it forgot it. Without a count, a relay
|
|
290
358
|
// that grants a proven login, closes, then refuses the next login's SUBSCRIBE `pow` had this client
|
|
@@ -303,8 +371,8 @@ const EVENTS_MAX = 1000, INBOX_MAX = 1000;
|
|
|
303
371
|
// newest is kept whatever its size). Labels it never holds: enrolment's, one of which carries a key,
|
|
304
372
|
// devices', and links' (a live invite code).
|
|
305
373
|
export const LOG_MAX = 500, LOG_BYTES = 4 * 1024 * 1024;
|
|
306
|
-
// Labels whose messages carry keys, device material or a live code (enrol, device, link): never logged.
|
|
307
|
-
export const UNLOGGED = /^sigelo-(identity|enrol|device|link|transfer)\//;
|
|
374
|
+
// Labels whose messages carry keys, device material or a live code (enrol, device, link), and busy marks: never logged.
|
|
375
|
+
export const UNLOGGED = /^sigelo-(identity|enrol|device|link|transfer|busy)\//;
|
|
308
376
|
// Links (link.mjs, sigelo-link/1): never an inbox message. Kept apart in the state (st.links, at most
|
|
309
377
|
// LINKS_MAX, the oldest go) for link.mjs handle(), which takeLinks() them; sent only by link.mjs
|
|
310
378
|
// (send's internal: LINK_SEND), so a caller's label (an MCP client's, a model's) cannot forge one.
|
|
@@ -323,6 +391,51 @@ const DEVICES_MAX = 16;
|
|
|
323
391
|
// engine, never logged (an offer carries addresses, an onion message a client key); sent only with TRANSFER_SEND.
|
|
324
392
|
export const TRANSFER_LABEL = 'sigelo-transfer/0', TRANSFER_SEND = Symbol('sigelo-transfer send');
|
|
325
393
|
const TRANSFERS_MAX = 256;
|
|
394
|
+
// Calls (call.mjs, sigelo-call/0; design/calls.md §2): the signalling of a voice call. Kept apart in memory (at most
|
|
395
|
+
// CALLS_MAX) for the page's Line (page.mjs) or watch's answer, in the process that received them; never logged and never
|
|
396
|
+
// in the state file (an SDP carries addresses and a DTLS fingerprint; a ring lives 60 s, a restart cannot wait for
|
|
397
|
+
// another process anyway). Sent only with CALL_SEND.
|
|
398
|
+
export const CALL_LABEL = 'sigelo-call/0', CALL_SEND = Symbol('sigelo-call send');
|
|
399
|
+
const CALLS_MAX = 64;
|
|
400
|
+
// Seen receipts (the header's): sent only with SEEN_SEND, never an inbox message.
|
|
401
|
+
export const SEEN_LABEL = 'sigelo-seen/0', SEEN_SEND = Symbol('sigelo-seen send');
|
|
402
|
+
// UnifiedPush (design/push.md, relay/push.mjs): the phone's endpoint and keys, registered with this agent's own
|
|
403
|
+
// relay over its session (setPush), where GET /challenge says the relay takes them.
|
|
404
|
+
export const PUSH_TOPIC = '$sigelo/push', PUSH_V = 'sigelo-push/0';
|
|
405
|
+
// TURN (relay/turn.mjs): a credential for coturn on this agent's own relay host, asked over the session.
|
|
406
|
+
export const TURN_TOPIC = '$sigelo/turn', TURN_V = 'sigelo-turn/0', TURN_WAIT_MS = 5000, TURN_KEEP_S = 600;
|
|
407
|
+
// Busy marks (the header's): sent only with BUSY_SEND, never an inbox message; one is good for BUSY_TTL_S seconds.
|
|
408
|
+
export const BUSY_LABEL = 'sigelo-busy/0', BUSY_SEND = Symbol('sigelo-busy send'), BUSY_TTL_S = 45;
|
|
409
|
+
// Names (0.1.17: "the system allocated some random text" for a new contact). Once paired, each side tells the other its
|
|
410
|
+
// display name (selfName) in a seen receipt {seen: 0, name}: an existing message older clients take as a receipt and
|
|
411
|
+
// whose extra member they ignore (no new label, no new typ). The receiver files the contact under it only while the
|
|
412
|
+
// contact's name was made up here (name_from "auto": an unnamed invite or accept, a public code's) or came from them
|
|
413
|
+
// before; a name the human gave or changed is never replaced. The name: at most THEIR_NAME_MAX characters, trimmed, no
|
|
414
|
+
// control or bidi characters, else ignored; one another contact holds gets " (2)", " (3)"….
|
|
415
|
+
// Kinds (2026-11-26): the same receipt carries kind "agent" or "desk" (a support desk) when this side says it is one
|
|
416
|
+
// (selfKind: sigelo-agent says agent by default, --kind desk; a person's app says nothing). The receiver keeps it as the
|
|
417
|
+
// contact's kind_peer (contacts()); the page shows it, and the human's own choice wins (page.mjs "Kinds"). An earlier
|
|
418
|
+
// version ignores the member, as it ignores busy and host; the pairing card (invite.mjs) refuses an unknown field, so
|
|
419
|
+
// the kind does not go there. A claim only: it can make a contact less (no call), never more than a person.
|
|
420
|
+
export const THEIR_NAME_MAX = 40;
|
|
421
|
+
export const KINDS = Object.freeze(['person', 'agent', 'desk']);
|
|
422
|
+
// Replies (0.1.17: "reply to messages"): a message that answers one names it in its label, re/<h>/<s|r>, h the first 16
|
|
423
|
+
// hex of SHA-256 over the quoted text, s when the sender quotes its own message, r the recipient's. The envelope's body is
|
|
424
|
+
// exact (envelope.mjs BODY): no member can be added, and a label is free text an older client shows as a tag. Each side
|
|
425
|
+
// finds the quoted message among its own by its text and its author; inbox() gives it as re: {sha, by: me | them}.
|
|
426
|
+
export const RE_LABEL = /^re\/([0-9a-f]{16})\/([sr])$/;
|
|
427
|
+
export const quoteHash = (text) => hex(sha256(utf8ToBytes(String(text)))).slice(0, 16);
|
|
428
|
+
/** The label of a reply to `text`, own: the sender's own message, else the recipient's. */
|
|
429
|
+
export const reLabel = (text, own) => `re/${quoteHash(text)}/${own ? 's' : 'r'}`;
|
|
430
|
+
/** A received message's label read as a reply: { sha, by: "them" (its sender quoted its own) | "me" }, or null. */
|
|
431
|
+
export const reOf = (label) => { const m = RE_LABEL.exec(typeof label === 'string' ? label : ''); return m ? { sha: m[1], by: m[2] === 's' ? 'them' : 'me' } : null; };
|
|
432
|
+
const NAME_BAD = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
|
|
433
|
+
/** A name as a peer sent it, for display: trimmed, control and bidi characters dropped, at most THEIR_NAME_MAX; else null. */
|
|
434
|
+
export function theirName(v) {
|
|
435
|
+
if (typeof v !== 'string') return null;
|
|
436
|
+
const t = [...v.replace(NAME_BAD, '').trim()].slice(0, THEIR_NAME_MAX).join('').trim();
|
|
437
|
+
return t === '' ? null : t;
|
|
438
|
+
}
|
|
326
439
|
// Received files of one name and hash prefix kept side by side, at most (#onFile).
|
|
327
440
|
const FILE_COPIES = 64;
|
|
328
441
|
// A contact's folder of received files: its name as safeName keeps it, and 16 hex digits of the
|
|
@@ -353,17 +466,25 @@ const TICK = 3600 * 1000, BACKOFF = [1000, 60000];
|
|
|
353
466
|
// A connection that held this long resets the backoff when it closes; a shorter one does not, so a
|
|
354
467
|
// relay that accepts and closes at once is dialled ever more slowly, as one that refuses is.
|
|
355
468
|
const STABLE_MS = 60000;
|
|
469
|
+
// A session the relay ended itself (its notice session_*: relay/auth.mjs endWith), or a login it
|
|
470
|
+
// turned away (rate, relay_full): the next session waits backoff[0], 2 × that, … up to backoff[1] ms
|
|
471
|
+
// after it (BACKOFF by default: 1 s … 60 s), kept in the state (st.relays[relay].ended) so a new process waits too (0.1.17: a
|
|
472
|
+
// temporary identity cut by the relay logged in again at once, 30 times a minute, until the rate
|
|
473
|
+
// refused it). Reset by a session this client ends itself, or one the relay held ENDED_LASTS ms.
|
|
474
|
+
const ENDED_LASTS = 300000;
|
|
475
|
+
const ENDED_RETRY = new Set(['rate', 'relay_full', 'connect', 'timeout']);
|
|
356
476
|
// Login refusals no retry can fix.
|
|
357
|
-
const PERMANENT = new Set(['password', 'bundle', 'sig', 'retired_recovery', 'client_id', 'closed', 'challenge', 'relay', 'identity']);
|
|
477
|
+
const PERMANENT = new Set(['password', 'bundle', 'sig', 'retired_recovery', 'client_id', 'closed', 'challenge', 'relay', 'identity', 'client_old']);
|
|
358
478
|
// A refusal by one of these is this process failing, not a message: the delivery is not acknowledged.
|
|
359
479
|
const INTERNAL = new Set(['lock', 'state', 'store', 'identity', 'time']);
|
|
360
480
|
// The login checks relay/auth.mjs names on POST /check. Any other word from the relay is `connect`:
|
|
361
481
|
// a check name decides what this client does next, so a relay cannot pick one.
|
|
362
|
-
|
|
482
|
+
// client_old: a client of the dropped SHA-256 proof of work (relay/pow.mjs CLIENT_OLD); this one never is.
|
|
483
|
+
const LOGIN_CHECKS = new Set(['rate', 'password', 'challenge_unknown', 'challenge_expired', 'bundle', 'sig', 'retired_recovery', 'client_id', 'closed', 'pow', 'relay_full', 'client_old']);
|
|
363
484
|
// Refusals of an invite reply that a later round may get past: the reply stays queued.
|
|
364
485
|
const REPLY_RETRY = new Set(['rate', 'relay_full', 'quota_messages']);
|
|
365
486
|
// $sigelo/notice codes that refuse the publish, or the SUBSCRIBE, in flight (relay-plan §3 "Errors").
|
|
366
|
-
const PUBLISH_CODES = new Set(['too_large', 'quota_storage', 'quota_messages', 'rate', 'relay_full', 'pow', 'no_reader', 'presence_taken', 'presence_will', 'presence_full']);
|
|
487
|
+
const PUBLISH_CODES = new Set(['push', 'too_large', 'quota_storage', 'quota_messages', 'rate', 'relay_full', 'pow', 'no_reader', 'presence_taken', 'presence_will', 'presence_full', 'public_cap', 'public_paused', 'public_revoked', 'public_once']);
|
|
367
488
|
// A contact's envelope this agent cannot open for want of its epoch asks the writer for a new epoch
|
|
368
489
|
// by a fresh prekey bundle (RESYNC_CHECKS), at most once in this many seconds per contact after
|
|
369
490
|
// the last such bundle: the check comes before any decryption, so a relay can make one up. A
|
|
@@ -416,6 +537,35 @@ const sameBytes = (a, b) => { if (a.length !== b.length) return false; for (let
|
|
|
416
537
|
const utf8 = new TextDecoder('utf-8', { ignoreBOM: true });
|
|
417
538
|
const textOf = (bytes) => utf8.decode(bytes);
|
|
418
539
|
const randomId = () => hex(randomBytes(8));
|
|
540
|
+
|
|
541
|
+
// The message id (the agent task loop: a hook's SIGELO_MSG_ID, `reply --to`, MCP sigelo_reply): the
|
|
542
|
+
// same for one message wherever and however often it is read. A message: hex of the first 16 bytes of
|
|
543
|
+
// SHA-256 of the lines "sigelo-msg-id/0", the sender's original DID, the epoch id (hex) and the
|
|
544
|
+
// message number, both from the envelope's header (envelope.mjs "Layout"), which no two envelopes of
|
|
545
|
+
// one sender share. A file: of "sigelo-msg-id/0 file", the sender, the file's id (file.mjs). An item
|
|
546
|
+
// kept by an earlier version has none: then of "sigelo-msg-id/0 item" and the canonical JSON of what
|
|
547
|
+
// it holds {from, iat, received, label, content, path}, which do not change while it waits. Nothing
|
|
548
|
+
// of it goes on the wire.
|
|
549
|
+
export const MSG_ID = /^[0-9a-f]{32}$/;
|
|
550
|
+
const idOf = (...parts) => hex(sha256(utf8ToBytes(parts.join('\n'))).subarray(0, 16));
|
|
551
|
+
export function messageId(m) {
|
|
552
|
+
if (typeof m?.id === 'string' && MSG_ID.test(m.id)) return m.id;
|
|
553
|
+
const held = { from: m?.from ?? null, iat: m?.iat ?? null, received: m?.received ?? null, label: m?.label ?? null, content: m?.content ?? null, path: m?.path ?? null };
|
|
554
|
+
let text;
|
|
555
|
+
try { text = canonicalize(held); } catch { text = JSON.stringify(held); }
|
|
556
|
+
return idOf('sigelo-msg-id/0 item', text);
|
|
557
|
+
}
|
|
558
|
+
// What a reply needs of a message received (reply, replyStatus): its sender and when, and the last
|
|
559
|
+
// reply's ids and state, in the state file, RECEIVED_DAYS at most and the newest RECEIVED_MAX.
|
|
560
|
+
export const RECEIVED_DAYS = 30, RECEIVED_MAX = 2048;
|
|
561
|
+
function received(st, id, from, now) {
|
|
562
|
+
const r = (st.received ??= {});
|
|
563
|
+
r[id] ??= { from, ts: now };
|
|
564
|
+
for (const [k, v] of Object.entries(r)) if (!(v.ts > now - RECEIVED_DAYS * DAY)) delete r[k];
|
|
565
|
+
const keys = Object.keys(r);
|
|
566
|
+
if (keys.length > RECEIVED_MAX) for (const k of keys.sort((a, b) => r[a].ts - r[b].ts).slice(0, keys.length - RECEIVED_MAX)) delete r[k];
|
|
567
|
+
return r[id];
|
|
568
|
+
}
|
|
419
569
|
const clientIdOf = (original) => 's' + hex(sha256(utf8ToBytes(original))).slice(0, 24);
|
|
420
570
|
// Operators as hinted and proved: each with its attestation's expiry, so a renewal goes again.
|
|
421
571
|
const opKey = (mine, ops) => [...ops].sort().map((d) => `${d} ${mine.exp.get(d)}`).join();
|
|
@@ -428,7 +578,15 @@ const theirPrekeys = (c, d, pair, now) => {
|
|
|
428
578
|
// The four words of a pairing (short.mjs), from its pairing key as the store holds it (hex), or null.
|
|
429
579
|
const wordsOf = (pairKey) => (typeof pairKey === 'string' ? fingerprint(pairId(hexToBytes(pairKey))) : null);
|
|
430
580
|
// The refusals of POST /park this client names (relay/park.mjs, and the login's: auth.mjs).
|
|
431
|
-
const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', ...LOGIN_CHECKS]);
|
|
581
|
+
const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', 'public_pro', 'public_full', 'public_topic', ...LOGIN_CHECKS]);
|
|
582
|
+
// An accept's reply topic and key: a public code's are the joiner's own (public.mjs joinerKeys), else the code's.
|
|
583
|
+
const replyOf = (id, p) => (p.public ? joinerKeys(hexToBytes(p.secret), id) : inviteKeys(hexToBytes(p.secret)));
|
|
584
|
+
// An accept's answer topic: a public code's mailbox, else the code's invite topic.
|
|
585
|
+
const answerTopicOf = (p) => (p.public ? publicKeys(hexToBytes(p.secret)).answer_topic : inviteKeys(hexToBytes(p.secret)).answer_topic);
|
|
586
|
+
// A public code's state as contacts() and the page show it (requests without the answers they hold).
|
|
587
|
+
const publicView = (nonce, p, now) => ({ id: nonce, name: p.name, short: p.short, words: p.words, link: p.short ? publicLink(p.short, p.words) : null, exp: p.exp, relay: p.relay,
|
|
588
|
+
cap: p.cap, open: p.open, paused: p.paused, today: p.day === Math.floor(now / DAY) ? p.n : 0, chats: p.chats,
|
|
589
|
+
requests: Object.values(p.requests).map(({ id, did, current_did, words, received, exp }) => ({ id, did, current_did, words, received, exp })) });
|
|
432
590
|
// The refusals of POST /gift this client names (relay/gifts.mjs, allowance.mjs, operator.mjs, and the login's).
|
|
433
591
|
const GIFT_CHECKS = new Set(['gift', 'gift_member', 'gift_term', 'pow', ...LOGIN_CHECKS]);
|
|
434
592
|
|
|
@@ -524,6 +682,8 @@ function loadState(files, path, self) {
|
|
|
524
682
|
if (s.v !== V || s.self !== self) fail('state', `${path} is not the ${V} state of ${self}`);
|
|
525
683
|
// Written by an earlier version of this file, which kept neither.
|
|
526
684
|
s.events ??= []; s.failing ??= {}; s.answered ??= {};
|
|
685
|
+
// Call signalling an earlier version kept here (with its SDP): gone at the next save.
|
|
686
|
+
delete s.calls;
|
|
527
687
|
return s;
|
|
528
688
|
}
|
|
529
689
|
|
|
@@ -680,14 +840,27 @@ function recovers(c, bundle, fresh) {
|
|
|
680
840
|
// ---------------------------------------------------------------- relay login (plan §3 "Login")
|
|
681
841
|
|
|
682
842
|
/**
|
|
683
|
-
*
|
|
684
|
-
*
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
843
|
+
* GET /challenge's `pow` → its cost { m, t, p } when this client computes it: {v: 1, alg:
|
|
844
|
+
* "argon2id", m, t, p} with these keys only, 1 lane, and m (KiB) and t within POW_COST; else null.
|
|
845
|
+
*/
|
|
846
|
+
export function powCost(fn) {
|
|
847
|
+
if (!exact(fn, ['v', 'alg', 'm', 't', 'p']) || fn.v !== POW_V || fn.alg !== 'argon2id' || fn.p !== 1) return null;
|
|
848
|
+
if (!Number.isInteger(fn.m) || fn.m < 8 || fn.m > POW_COST.m || !Number.isInteger(fn.t) || fn.t < 1 || fn.t > POW_COST.t) return null;
|
|
849
|
+
return { m: fn.m, t: fn.t, p: 1 };
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/**
|
|
853
|
+
* The first c (0, 1, 2, …) with Argon2id(password = "sigelo-relay-pow/1\n" ‖ host ‖ original DID ‖
|
|
854
|
+
* nonce ‖ c, salt = SHA-256(nonce) cut to 16 bytes; cost's m KiB, t passes, 1 lane; 32 bytes)
|
|
855
|
+
* starting with `bits` zero bits (relay-plan §3 "Proof of work", relay/pow.mjs), or null once
|
|
856
|
+
* Date.now() passes `deadline`. 0 bits: "0", nothing evaluated. pow: the platform's search (Node's
|
|
857
|
+
* yields to the event loop after each evaluation, ~0.5 s on a phone, so the process's connections,
|
|
858
|
+
* keepalives and other identities carry on during a search of minutes); cost: powCost's.
|
|
688
859
|
*/
|
|
689
|
-
export function solvePow(host, original, nonce, bits, deadline = Infinity, pow = nodePlatform.pow) {
|
|
690
|
-
|
|
860
|
+
export function solvePow(host, original, nonce, bits, deadline = Infinity, pow = nodePlatform.pow, cost = POW_COST, onProgress = undefined) {
|
|
861
|
+
if (bits === 0) return Promise.resolve('0');
|
|
862
|
+
const salt = sha256(utf8ToBytes(nonce)).subarray(0, 16);
|
|
863
|
+
return pow({ prefix: `sigelo-relay-pow/1\n${host}${original}${nonce}`, salt, ...cost }, bits, { deadline, ...(onProgress && { onProgress }) });
|
|
691
864
|
}
|
|
692
865
|
|
|
693
866
|
// The answer body is read as it arrives and cut off past HTTP_MAX, whatever Content-Length says:
|
|
@@ -749,7 +922,7 @@ const statusWhy = (r, what) => `the relay answered ${r.status} to ${what}${r.sta
|
|
|
749
922
|
* is refused saying how the input was read, so a mistyped short code never reads "does not
|
|
750
923
|
* start with sgl1". */
|
|
751
924
|
export function readCode(text, now, how = 'long') {
|
|
752
|
-
try { return parseInvite(text, now); } catch (e) {
|
|
925
|
+
try { return typeof text === 'string' && text.startsWith('sgl2') ? parsePublicCode(text, now) : parseInvite(text, now); } catch (e) {
|
|
753
926
|
if (!(e instanceof MsgError) || !['code_checksum', 'code_length', 'code_version'].includes(e.check)) throw e;
|
|
754
927
|
const as = how === 'parked' ? 'the long code the relay holds for this short code does not parse; ask the inviter for a new one'
|
|
755
928
|
: `read as a long code (it starts sgl1, or has more than 12 characters; a short code has 8, like K7F3-Q9ZP, or 12): ${reason(e)}`;
|
|
@@ -778,6 +951,16 @@ export function groupTierOf(n) {
|
|
|
778
951
|
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
952
|
return { tier: n.tier, groups: { max: g.max, members: g.members } };
|
|
780
953
|
}
|
|
954
|
+
// The relay's TURN credential ({code: "turn", turn}, relay/turn.mjs): {v, urls (1 to 4 turn: URIs), username, credential, exp},
|
|
955
|
+
// each checked, else ignored. → {urls, username, credential, exp} | null.
|
|
956
|
+
const TURN_URL = /^turns?:[A-Za-z0-9.-]{1,253}(:\d{1,5})?(\?transport=(udp|tcp))?$/;
|
|
957
|
+
export function turnOf(t) {
|
|
958
|
+
if (t === null || typeof t !== 'object' || Array.isArray(t) || Object.keys(t).sort().join() !== 'credential,exp,urls,username,v' || t.v !== TURN_V) return null;
|
|
959
|
+
if (!Array.isArray(t.urls) || t.urls.length < 1 || t.urls.length > 4 || !t.urls.every((u) => typeof u === 'string' && TURN_URL.test(u))) return null;
|
|
960
|
+
if (typeof t.username !== 'string' || !/^[\x21-\x7e]{1,128}$/.test(t.username) || typeof t.credential !== 'string' || !/^[A-Za-z0-9+/=]{1,128}$/.test(t.credential)) return null;
|
|
961
|
+
if (!Number.isSafeInteger(t.exp) || t.exp <= 0) return null;
|
|
962
|
+
return { urls: [...t.urls], username: t.username, credential: t.credential, exp: t.exp };
|
|
963
|
+
}
|
|
781
964
|
const quotaWhy = (r, name) => (r.code !== 'quota_storage' ? null
|
|
782
965
|
: 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)})`
|
|
783
966
|
: 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);
|
|
@@ -795,7 +978,7 @@ const rePairWhy = (c) => (c.re_pair === 'contact_recovery'
|
|
|
795
978
|
// (`accept --name`): then that name. The inviter's `invite --name` names a new contact only: the
|
|
796
979
|
// code may be answered by anyone, and a re-key code's name is the contact's own. → the contact.
|
|
797
980
|
function renamed(store, c, entry) {
|
|
798
|
-
if (entry.named === true && c.name !== entry.name) { c.name = entry.name; store.save(); }
|
|
981
|
+
if (entry.named === true && c.name !== entry.name) { c.name = store.freeName(entry.name, c.did); store.save(); }
|
|
799
982
|
return c;
|
|
800
983
|
}
|
|
801
984
|
|
|
@@ -919,6 +1102,7 @@ class Link {
|
|
|
919
1102
|
this.collect = null; this.lastIn = 0; this.since = Date.now(); this.tokens = RATE.burst; this.at = Date.now(); this.pow = false; this.closing = false;
|
|
920
1103
|
this.abort = null; // rejects the PUBLISH or SUBSCRIBE in flight when the connection closes
|
|
921
1104
|
this.cut = null; // the MsgError of limitPackets, once it cut the connection
|
|
1105
|
+
this.ended = null; // the relay's notice before it ended this session ({ code, detail }: relay/auth.mjs endWith)
|
|
922
1106
|
// Presence: the contacts' marker topics subscribed on this connection; this agent's markers
|
|
923
1107
|
// published on it (topic → its contact); when it connected (a marker's since); the will set.
|
|
924
1108
|
this.presenceIn = new Set(); this.presenceOut = new Map(); this.onlineAt = 0; this.will = false;
|
|
@@ -943,12 +1127,25 @@ class Link {
|
|
|
943
1127
|
export class Carrier {
|
|
944
1128
|
#links = new Map(); #work = Promise.resolve(); #busy = 0; #lastWork = 0; #routes = new Map(); #results = new Map();
|
|
945
1129
|
#claimed = new Set(); #refusedTopics = new Map(); #handshakes = new Map(); #soon = new Set();
|
|
946
|
-
#
|
|
947
|
-
#
|
|
1130
|
+
#renewing = false;
|
|
1131
|
+
#started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map(); #powWaits = new Set(); #ask = false; #spare = new Map();
|
|
1132
|
+
#push = undefined; #pushState = { state: 'none' }; #turn = null; // #turn: the last TURN credential (turnServer) // setPush: undefined = never set (nothing sent), null = off
|
|
1133
|
+
#mineMemo = null; #clocks = new Map(); #selfName = () => null; #selfKind = () => null;
|
|
1134
|
+
#calls = []; // the sigelo-call/0 messages received, until takeCalls (memory only: the header's "Calls")
|
|
948
1135
|
|
|
949
1136
|
constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays, clock = () => Math.floor(Date.now() / 1000),
|
|
950
1137
|
onEvent, keep, backoff = BACKOFF, tick = TICK, files, log, transport = 'auto', shortRelay = DEFAULT_RELAY, registry = REGISTRY_URL, registryPin = RELEASE_DID, relays, registryFile,
|
|
951
|
-
platform = nodePlatform }) {
|
|
1138
|
+
platform = nodePlatform, selfName = null, selfKind = null, enrolHash = null }) {
|
|
1139
|
+
// enrolHash: the enrolment code this (temporary) identity holds, as its park hash: its first login asks
|
|
1140
|
+
// GET /challenge?…&enrol=<hash>, and a relay states the base proof of work for it (relay/park.mjs enrolGrace).
|
|
1141
|
+
if (enrolHash !== null && !(typeof enrolHash === 'string' && /^[0-9a-f]{64}$/.test(enrolHash))) throw new TypeError('enrolHash: 64 hex (short.mjs codeHash), or null');
|
|
1142
|
+
this.enrolHash = enrolHash;
|
|
1143
|
+
// This side's display name, told to each new contact once paired (the header's "Names"): a string or a function → one, or null.
|
|
1144
|
+
if (selfName !== null && typeof selfName !== 'string' && typeof selfName !== 'function') throw new TypeError('selfName: a string, a function → a string or null, or null');
|
|
1145
|
+
this.#selfName = typeof selfName === 'function' ? selfName : () => selfName;
|
|
1146
|
+
// This side's kind, told with the name (the header's "Kinds"): "agent", "desk", or null (a person: nothing said).
|
|
1147
|
+
if (selfKind !== null && !KINDS.includes(selfKind) && typeof selfKind !== 'function') throw new TypeError('selfKind: agent, desk, person, a function → one, or null');
|
|
1148
|
+
this.#selfKind = typeof selfKind === 'function' ? selfKind : () => selfKind;
|
|
952
1149
|
if (!TRANSPORTS.includes(transport)) throw new TypeError(`transport: ${TRANSPORTS.join(', ')}`);
|
|
953
1150
|
// The platform (design/apps.md §4.2, platform-node.mjs): files, lock, network, proof of work.
|
|
954
1151
|
if (typeof platform?.files?.read !== 'function' || typeof platform.transact !== 'function' || typeof platform.fetch !== 'function' || typeof platform.mqtt !== 'function'
|
|
@@ -1069,7 +1266,7 @@ export class Carrier {
|
|
|
1069
1266
|
const gone = store.lapsed(now);
|
|
1070
1267
|
for (const p of gone) {
|
|
1071
1268
|
this.#emit(this.#note(st, now, { type: 'pairing_failed', did: p.code_did, name: p.name, code: 'code_expired',
|
|
1072
|
-
detail: `the code from ${p.name} expired at ${new Date(p.exp * 1000).toISOString().replace('.000', '')} before the inviter's agent replied: ask the inviter for a new code` }));
|
|
1269
|
+
detail: p.public ? `${p.name} did not approve the request by ${new Date(p.exp * 1000).toISOString().replace('.000', '')} (a public code, 7 days): it has ended; try the code again later` : `the code from ${p.name} expired at ${new Date(p.exp * 1000).toISOString().replace('.000', '')} before the inviter's agent replied: ask the inviter for a new code` }));
|
|
1073
1270
|
}
|
|
1074
1271
|
return gone.length > 0;
|
|
1075
1272
|
}
|
|
@@ -1145,6 +1342,16 @@ export class Carrier {
|
|
|
1145
1342
|
#emit(ev) { try { this.onEvent(ev); } catch {} }
|
|
1146
1343
|
|
|
1147
1344
|
// An event kept for the next inbox() as well: a CLI or MCP agent has no onEvent.
|
|
1345
|
+
// This side's name to a contact just paired (the header's "Names"), in its outbox: it goes with the next round.
|
|
1346
|
+
#tellName(st, did) {
|
|
1347
|
+
let n = null, k = null;
|
|
1348
|
+
try { n = theirName(this.#selfName()); } catch {}
|
|
1349
|
+
try { k = this.#selfKind(); } catch {}
|
|
1350
|
+
if (k !== 'agent' && k !== 'desk') k = null;
|
|
1351
|
+
if (n === null && k === null) return;
|
|
1352
|
+
this.#entry(st, did).outbox.push({ id: randomId(), label: SEEN_LABEL, content: { seen: 0, ...(n !== null && { name: n }), ...(k !== null && { kind: k }), busy: true, host: true } });
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1148
1355
|
#note(st, now, ev) {
|
|
1149
1356
|
st.events.push({ ...ev, at: now });
|
|
1150
1357
|
if (st.events.length > EVENTS_MAX) st.events.splice(0, st.events.length - EVENTS_MAX);
|
|
@@ -1179,8 +1386,9 @@ export class Carrier {
|
|
|
1179
1386
|
#want({ now, me, store }, relay) {
|
|
1180
1387
|
const out = [], seen = new Set();
|
|
1181
1388
|
const add = (x) => { if (!seen.has(x.topic)) { seen.add(x.topic); out.push(x); } };
|
|
1389
|
+
for (const p of Object.values(store.s.publics ?? {})) if (p.relay === relay && p.exp > now) add({ topic: publicKeys(hexToBytes(p.secret)).answer_topic });
|
|
1182
1390
|
for (const p of Object.values(store.s.invites)) if (p.relay === relay && p.exp > now) add({ topic: inviteKeys(hexToBytes(p.secret)).answer_topic });
|
|
1183
|
-
for (const p of Object.
|
|
1391
|
+
for (const [id, p] of Object.entries(store.s.accepts)) if (p.relay === relay && p.exp > now) add({ topic: replyOf(id, p).reply_topic });
|
|
1184
1392
|
// No new mailbox under a burned K (re_pair): those held run out at their time (#refresh).
|
|
1185
1393
|
const contacts = this.#liveContacts(store, relay).filter((c) => !c.re_pair).map((c) => ({ did: c.did, K: hexToBytes(c.pair_key) }));
|
|
1186
1394
|
const weeks = this.#weeks(now), at = Math.max(0, weeks.findIndex((w) => w.week === isoWeek(now)));
|
|
@@ -1197,7 +1405,8 @@ export class Carrier {
|
|
|
1197
1405
|
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
1406
|
for (const c of this.#liveContacts(store)) m.set(presenceTopic(hexToBytes(c.pair_key), c.did, me.did), { type: 'presence', did: c.did });
|
|
1199
1407
|
for (const [nonce, p] of Object.entries(store.s.invites)) m.set(inviteKeys(hexToBytes(p.secret)).answer_topic, { type: 'answer', nonce });
|
|
1200
|
-
for (const [id, p] of Object.entries(store.s.accepts)) m.set(
|
|
1408
|
+
for (const [id, p] of Object.entries(store.s.accepts)) m.set(replyOf(id, p).reply_topic, { type: 'reply', id });
|
|
1409
|
+
for (const [nonce, p] of Object.entries(store.s.publics ?? {})) m.set(publicKeys(hexToBytes(p.secret)).answer_topic, { type: 'public', nonce });
|
|
1201
1410
|
return m;
|
|
1202
1411
|
});
|
|
1203
1412
|
}
|
|
@@ -1206,7 +1415,7 @@ export class Carrier {
|
|
|
1206
1415
|
return this.#read(({ now, store, st }) => {
|
|
1207
1416
|
const s = store.load().s, r = new Set();
|
|
1208
1417
|
for (const c of Object.values(s.contacts)) if (!c.revoked) r.add(c.relay);
|
|
1209
|
-
for (const p of [...Object.values(s.invites), ...Object.values(s.accepts)]) if (p.exp > now) r.add(p.relay);
|
|
1418
|
+
for (const p of [...Object.values(s.invites), ...Object.values(s.accepts), ...Object.values(s.publics ?? {})]) if (p.exp > now) r.add(p.relay);
|
|
1210
1419
|
for (const p of st.pending) r.add(p.relay);
|
|
1211
1420
|
for (const [name, x] of Object.entries(st.relays)) if (Object.keys(x.claims ?? {}).length > 0) r.add(name);
|
|
1212
1421
|
return [...r];
|
|
@@ -1244,9 +1453,14 @@ export class Carrier {
|
|
|
1244
1453
|
route = this.#routes.get(t) ?? fail('route', 'a message on a topic this agent does not read');
|
|
1245
1454
|
const events = this.#locked((ctx) => (route.type === 'peer' ? this.#onPeer(ctx, route.did, t, bytes)
|
|
1246
1455
|
: route.type === 'presence' ? this.#onPresence(ctx, route.did, t, bytes)
|
|
1247
|
-
: route.type === 'answer' ? this.#onAnswer(ctx, t, bytes) : this.#onReply(ctx, t, bytes)));
|
|
1456
|
+
: route.type === 'answer' ? this.#onAnswer(ctx, t, bytes) : route.type === 'public' ? this.#onPublic(ctx, route.nonce, t, bytes) : this.#onReply(ctx, t, bytes)));
|
|
1248
1457
|
for (const e of events) this.#emit(e);
|
|
1458
|
+
if (route.type === 'answer') this.#renewSoon();
|
|
1459
|
+
// A frame from a contact: it read the pairing's reply and holds its mailbox now, so what waits for it after a
|
|
1460
|
+
// no_reader (a name or kind receipt queued at the pairing, operator hints) goes this round, not the next tick's.
|
|
1461
|
+
if (route.type === 'peer') link.absent.delete(route.did);
|
|
1249
1462
|
} catch (e) {
|
|
1463
|
+
if (route?.type === 'answer') this.#renewSoon();
|
|
1250
1464
|
if (e instanceof MsgError && !INTERNAL.has(e.check)) this.#drop(e.check, e.message, route);
|
|
1251
1465
|
else if (!this.#undeliverable(t, bytes, e)) {
|
|
1252
1466
|
this.#emit({ type: 'error', relay: link.relay, check: e.check ?? 'internal', detail: e.message });
|
|
@@ -1312,12 +1526,16 @@ export class Carrier {
|
|
|
1312
1526
|
try { n = parseBytes(bytes); } catch { return; }
|
|
1313
1527
|
if (n === null || typeof n !== 'object' || typeof n.code !== 'string') return;
|
|
1314
1528
|
// The relay's group tier for this login (relay/allowance.mjs "tier"): kept per relay in the state, refuses nothing.
|
|
1529
|
+
// The answer to $sigelo/turn (turnServer): kept on the link for the publish that asked.
|
|
1530
|
+
if (n.code === 'turn') { link.turnGot = turnOf(n.turn); return; }
|
|
1315
1531
|
if (n.code === 'tier') {
|
|
1316
1532
|
const g = groupTierOf(n);
|
|
1317
1533
|
if (g) { try { this.#locked(({ st }) => { (st.group_tier ??= {})[link.relay] = g; }); } catch {} this.#emit({ type: 'group_tier', relay: link.relay, ...g }); }
|
|
1318
1534
|
return;
|
|
1319
1535
|
}
|
|
1320
1536
|
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 }) };
|
|
1537
|
+
// Why the relay is about to end this session (relay/auth.mjs endWith): kept for #closed.
|
|
1538
|
+
if (note.code.startsWith('session_')) link.ended = { code: note.code, detail: note.detail };
|
|
1321
1539
|
// id: the packet id of the PUBLISH a refusal names (#publish), kept out of events.
|
|
1322
1540
|
if (link.collect) link.collect.push(Number.isSafeInteger(n.id) ? { ...note, id: n.id } : note);
|
|
1323
1541
|
else this.#emit({ type: 'notice', relay: link.relay, ...note });
|
|
@@ -1407,6 +1625,45 @@ export class Carrier {
|
|
|
1407
1625
|
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
1626
|
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
1627
|
events.push({ type: 'transfer', from: c.did, name: c.name });
|
|
1628
|
+
} else if (r.body.label === CALL_LABEL) {
|
|
1629
|
+
// A call's signalling (call.mjs): kept for the page's Line, never for inbox() nor onEvent's readers.
|
|
1630
|
+
// In memory (the header's "Calls"): a delivery whose transaction then fails comes again, and the Line drops the repeat.
|
|
1631
|
+
const l = this.#calls;
|
|
1632
|
+
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 });
|
|
1633
|
+
if (l.length > CALLS_MAX) { st.dropped.calls_full = (st.dropped.calls_full ?? 0) + l.length - CALLS_MAX; l.splice(0, l.length - CALLS_MAX); }
|
|
1634
|
+
events.push({ type: 'call', from: c.did, name: c.name });
|
|
1635
|
+
} else if (r.body.label === SEEN_LABEL) {
|
|
1636
|
+
// A seen receipt (the header's): the highest kept; one malformed is counted, never an inbox message.
|
|
1637
|
+
const n = r.body.content?.seen, nm = theirName(r.body.content?.name);
|
|
1638
|
+
// busy: true: they take busy marks (the header's "Busy marks").
|
|
1639
|
+
if (r.body.content?.busy === true) this.#entry(st, c.did).busy_peer = true;
|
|
1640
|
+
if (r.body.content?.host === true) this.#entry(st, c.did).host_peer = true;
|
|
1641
|
+
// Its kind (the header's "Kinds"): agent or desk kept; person, or anything else, says nothing.
|
|
1642
|
+
const said = r.body.content?.kind;
|
|
1643
|
+
if (said === 'agent' || said === 'desk') this.#entry(st, c.did).kind_peer = said;
|
|
1644
|
+
if (nm !== null) {
|
|
1645
|
+
const all = store.load().s.contacts, rec = all[c.did];
|
|
1646
|
+
if (rec && (rec.name_from === 'auto' || rec.name_from === 'them') && rec.name !== nm) {
|
|
1647
|
+
const taken = (x) => Object.values(all).some((y) => !y.revoked && y.did !== rec.did && y.name === x);
|
|
1648
|
+
let to = nm;
|
|
1649
|
+
for (let i = 2; taken(to) && i < 100; i++) to = `${nm} (${i})`;
|
|
1650
|
+
rec.name = to; rec.name_from = 'them'; store.save();
|
|
1651
|
+
events.push({ type: 'named', did: c.did, name: to });
|
|
1652
|
+
} else if (rec && rec.name_from === 'auto') { rec.name_from = 'them'; store.save(); }
|
|
1653
|
+
}
|
|
1654
|
+
// A name's (or a kind's) receipt (seen 0) says nothing of what was shown.
|
|
1655
|
+
if ((nm !== null || said === 'agent' || said === 'desk') && n === 0) { /* the name only */ } else if (!Number.isSafeInteger(n) || n < 0) { st.dropped.seen = (st.dropped.seen ?? 0) + 1; events.push({ type: 'dropped', check: 'seen', detail: 'a seen receipt without its time' }); } else {
|
|
1656
|
+
const e = this.#entry(st, c.did);
|
|
1657
|
+
e.seen_peer = true;
|
|
1658
|
+
e.seen_upto = Math.max(e.seen_upto ?? 0, n);
|
|
1659
|
+
events.push({ type: 'seen', from: c.did, name: c.name, upto: e.seen_upto });
|
|
1660
|
+
}
|
|
1661
|
+
} else if (r.body.label === BUSY_LABEL) {
|
|
1662
|
+
// A busy mark (the header's): good for BUSY_TTL_S, never an inbox message nor logged.
|
|
1663
|
+
const e = this.#entry(st, c.did), on = r.body.content?.busy === true, n = r.body.content?.n;
|
|
1664
|
+
e.busy_until = on ? now + BUSY_TTL_S : 0;
|
|
1665
|
+
e.busy_n = on && Number.isSafeInteger(n) && n > 1 ? Math.min(n, 99) : 1;
|
|
1666
|
+
events.push({ type: 'busy', from: c.did, name: c.name, on, n: e.busy_n });
|
|
1410
1667
|
} else if (r.body.label === DEVICE_LABEL) {
|
|
1411
1668
|
// A device message (device.mjs): kept for the `device` verbs, never for inbox() nor onEvent's readers.
|
|
1412
1669
|
const l = (st.devices ??= []);
|
|
@@ -1416,7 +1673,11 @@ export class Carrier {
|
|
|
1416
1673
|
} else {
|
|
1417
1674
|
// last_resort: the epoch began on the last-resort prekey, which may serve many epochs: weaker
|
|
1418
1675
|
// forward secrecy (plan §3 "Prekeys"), and routine for a while after a rotation (#next).
|
|
1419
|
-
const
|
|
1676
|
+
const id = idOf('sigelo-msg-id/0', c.did, r.epoch, r.n);
|
|
1677
|
+
const m = { id, 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, last_resort: r.last_resort };
|
|
1678
|
+
received(st, id, c.did, now);
|
|
1679
|
+
// A message ends the contact's busy mark (its reply is here).
|
|
1680
|
+
this.#entry(st, c.did).busy_until = 0;
|
|
1420
1681
|
// Plaintext at rest: kept only for inbox() (keep), and only so many (the header).
|
|
1421
1682
|
if (this.keep) {
|
|
1422
1683
|
st.inbox.push(m);
|
|
@@ -1548,8 +1809,11 @@ export class Carrier {
|
|
|
1548
1809
|
delete st.files[key];
|
|
1549
1810
|
files.remove(this.#partDir(key));
|
|
1550
1811
|
if (path === null) return drop(new MsgError('file_exists', `${p.name}: ${FILE_COPIES} files of that name and hash are in ${dir} already; not saved`));
|
|
1551
|
-
const
|
|
1812
|
+
const id = idOf('sigelo-msg-id/0 file', c.did, p.id);
|
|
1813
|
+
const item = { type: 'file', id, from: c.did, contact: c.name, current_did: r.body.from, label: FILE_LABEL, name: p.name, size: p.size, sha256: p.sha256, path,
|
|
1552
1814
|
iat: r.body.iat, received: now, last_resort: r.last_resort };
|
|
1815
|
+
received(st, id, c.did, now);
|
|
1816
|
+
this.#entry(st, c.did).busy_until = 0;
|
|
1553
1817
|
// Kept for inbox() as a message is (#onPeer), and so many at most.
|
|
1554
1818
|
if (this.keep) {
|
|
1555
1819
|
st.inbox.push(item);
|
|
@@ -1778,6 +2042,7 @@ export class Carrier {
|
|
|
1778
2042
|
throw e;
|
|
1779
2043
|
}
|
|
1780
2044
|
const c = store.lookup(res.did), K = hexToBytes(res.pair_key);
|
|
2045
|
+
if (p.auto && !before[c.did] && c.name === p.name) { c.name_from = 'auto'; store.save(); }
|
|
1781
2046
|
// What checkAnswer replaced, put back if the reply cannot reach the answerer (#unpair).
|
|
1782
2047
|
const undo = { contact: before[c.did] ?? null, peer: st.peers[c.did] ?? null };
|
|
1783
2048
|
const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K });
|
|
@@ -1791,11 +2056,69 @@ export class Carrier {
|
|
|
1791
2056
|
}
|
|
1792
2057
|
st.peers[c.did] = { session: dumpSession(s), announced: me.current_did, known: me.current_did, outbox: st.peers[c.did]?.outbox ?? [], prekeys_resend: false, prekeys_iat: now };
|
|
1793
2058
|
this.#queue(st, { ...entry, bytes: frame });
|
|
2059
|
+
this.#tellName(st, c.did);
|
|
1794
2060
|
// Who answered this code (answeredBy): saved with the pairing, whoever reads the paired event.
|
|
1795
2061
|
for (const [x, a] of Object.entries(st.answered)) if (!(a.exp > now)) delete st.answered[x];
|
|
1796
2062
|
st.answered[nonce] = { did: c.did, exp: p.exp + DAY };
|
|
2063
|
+
// A renewing code: who used it, for the state; the fresh one comes after this delivery (#renewDue).
|
|
2064
|
+
if (p.renew) store.renewUsed(p.renew, { short: p.short ?? null, did: c.did, name: c.name, at: now });
|
|
1797
2065
|
this.#routes = new Map();
|
|
1798
|
-
return [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key), invite: nonce })];
|
|
2066
|
+
return [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key), invite: nonce, ...(p.renew && { renew: p.renew }) })];
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
// Alice: an answer to a public code of hers (public.mjs). Screened (invite.mjs screenAnswer), an
|
|
2070
|
+
// answer id seen before dropped (replay), the day's own cap kept, one waiting request per original
|
|
2071
|
+
// DID (a newer replaces it); then a request waiting for the owner's approval, or, with open (let
|
|
2072
|
+
// anyone in), approved at once. Nothing is written for an answer refused.
|
|
2073
|
+
#onPublic(ctx, nonce, t, bytes) {
|
|
2074
|
+
const { now, store, st } = ctx;
|
|
2075
|
+
store.hold();
|
|
2076
|
+
const p = store.load().s.publics?.[nonce];
|
|
2077
|
+
if (!p || p.exp <= now) fail('challenge_unknown', 'no public code of this agent reads this topic');
|
|
2078
|
+
const answer = unseal(KIND.invite_answer, publicKeys(hexToBytes(p.secret)).key, t, bytes);
|
|
2079
|
+
const sc = screenAnswer(answer, { nonce, exp: p.exp }, store, now);
|
|
2080
|
+
if (Object.hasOwn(p.seen, sc.answer_id)) fail('replay', 'an answer to the public code seen before: dropped');
|
|
2081
|
+
const today = Math.floor(now / DAY);
|
|
2082
|
+
if (p.day === today && p.n >= p.cap) fail('public_cap', `the public code took its ${p.cap} new chats today: dropped`);
|
|
2083
|
+
if (p.day !== today) { p.day = today; p.n = 0; }
|
|
2084
|
+
p.n++;
|
|
2085
|
+
p.seen[sc.answer_id] = now + SEEN_KEEP;
|
|
2086
|
+
for (const [id, q] of Object.entries(p.requests)) if (q.did === sc.did) delete p.requests[id];
|
|
2087
|
+
const req = { id: sc.answer_id, did: sc.did, current_did: sc.current_did, words: didWords(sc.did), received: now, exp: Math.min(p.exp, answer.iat + REQUEST_TTL), answer };
|
|
2088
|
+
if (p.open) { store.save(); return this.#approve(ctx, nonce, req); }
|
|
2089
|
+
p.requests[req.id] = req;
|
|
2090
|
+
store.save();
|
|
2091
|
+
return [this.#note(st, now, { type: 'public_request', public: nonce, id: req.id, did: req.did, words: req.words, name: p.name })];
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2094
|
+
// Alice approves a request (or open approves it at once): the rest of the handshake, as
|
|
2095
|
+
// #onAnswer, the reply on the joiner's own topic (public.mjs joinerKeys). The contact is named
|
|
2096
|
+
// after the code (name-1, name-2, …) and marked via {public: nonce}: unchecked, nobody compared.
|
|
2097
|
+
#approve(ctx, nonce, req) {
|
|
2098
|
+
const { now, me, store, st } = ctx;
|
|
2099
|
+
store.hold();
|
|
2100
|
+
const p = store.load().s.publics[nonce], rk = joinerKeys(hexToBytes(p.secret), req.id);
|
|
2101
|
+
const before = structuredClone(store.load().s.contacts);
|
|
2102
|
+
let ct = null;
|
|
2103
|
+
const name = `${p.name ?? 'public'}-${p.chats + 1}`;
|
|
2104
|
+
const res = admitAnswer(req.answer, { nonce, exp: p.exp, secret: p.secret, name, relay: p.relay }, store, now, (pk) => { const k = kemEncapsulate(pk); ct = k.ct; return k.shared; }, { via: { public: nonce } });
|
|
2105
|
+
const c = store.lookup(res.did), K = hexToBytes(res.pair_key);
|
|
2106
|
+
if (!before[c.did] && c.name === name) { c.name_from = 'auto'; store.save(); }
|
|
2107
|
+
const undo = { contact: before[c.did] ?? null, peer: st.peers[c.did] ?? null };
|
|
2108
|
+
const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K });
|
|
2109
|
+
const prekeys = s.in.prekeys.issue({ current_did: me.current_did, sign: me.sign }, s.pair, now);
|
|
2110
|
+
const reply = buildReply({ answer_id: res.answer_id, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_ct: ct, prekeys });
|
|
2111
|
+
const frame = seal(KIND.invite_reply, rk.key, rk.reply_topic, reply);
|
|
2112
|
+
const entry = { relay: p.relay, topic: rk.reply_topic, kind: KIND.invite_reply, control: 'reply', peer: c.did, undo, needs: [topic(K, c.did, me.did, isoWeek(now))], exp: req.exp };
|
|
2113
|
+
delete p.requests[req.id];
|
|
2114
|
+
if (frame.length > INVITE_BYTES) return [this.#unpair(ctx, entry, { code: 'too_large', detail: `the reply is ${frame.length} bytes, more than an invite topic holds (${INVITE_BYTES}): this agent's chain is too long` })];
|
|
2115
|
+
p.chats++;
|
|
2116
|
+
store.save();
|
|
2117
|
+
st.peers[c.did] = { session: dumpSession(s), announced: me.current_did, known: me.current_did, outbox: st.peers[c.did]?.outbox ?? [], prekeys_resend: false, prekeys_iat: now };
|
|
2118
|
+
this.#queue(st, { ...entry, bytes: frame });
|
|
2119
|
+
this.#tellName(st, c.did);
|
|
2120
|
+
this.#routes = new Map();
|
|
2121
|
+
return [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key), public: nonce })];
|
|
1799
2122
|
}
|
|
1800
2123
|
|
|
1801
2124
|
// Alice: her reply will never reach the answerer (refused, too large, or its code expired while
|
|
@@ -1835,9 +2158,9 @@ export class Carrier {
|
|
|
1835
2158
|
// kem_ct to the same K.
|
|
1836
2159
|
#onReply({ now, me, store, st }, t, bytes) {
|
|
1837
2160
|
store.hold();
|
|
1838
|
-
const waiting = Object.entries(store.load().s.accepts).filter(([,
|
|
2161
|
+
const waiting = Object.entries(store.load().s.accepts).filter(([x, p]) => replyOf(x, p).reply_topic === t);
|
|
1839
2162
|
if (waiting.length === 0) fail('challenge_unknown', 'no answer of this agent waits on this topic');
|
|
1840
|
-
const keys =
|
|
2163
|
+
const keys = replyOf(waiting[0][0], waiting[0][1]), spend = (except) => {
|
|
1841
2164
|
for (const [x] of waiting) if (x !== except) { try { store.take('accepts', x, now); } catch {} }
|
|
1842
2165
|
};
|
|
1843
2166
|
let reply, res, id = waiting[0][0];
|
|
@@ -1849,7 +2172,16 @@ export class Carrier {
|
|
|
1849
2172
|
if (!waiting.some(([x]) => x === named)) fail('challenge_unknown', 'the reply names another answer than those whose topic it came on');
|
|
1850
2173
|
id = named;
|
|
1851
2174
|
}
|
|
2175
|
+
// A public code's inviter, checked against the four words its page published (accept --words).
|
|
2176
|
+
const p0 = waiting.find(([x]) => x === id)?.[1];
|
|
2177
|
+
if (p0?.words) {
|
|
2178
|
+
let original = null;
|
|
2179
|
+
try { original = verify(reply?.bundle, now).chain[0]; } catch {}
|
|
2180
|
+
if (original !== null && didWords(original) !== p0.words) fail('words', `the inviter's four words are "${didWords(original)}", not "${p0.words}" as given: this is not the code its page published; nothing was paired`);
|
|
2181
|
+
}
|
|
1852
2182
|
res = checkReply(reply, store, now, (kemCt, sk) => kemDecapsulate(kemCt, hexToBytes(sk)));
|
|
2183
|
+
// Came by a public code: marked, checked when the words matched.
|
|
2184
|
+
if (p0?.public) { const rec = store.load().s.contacts[res.did]; if (rec) { rec.via = { public: true, words: p0.words ? 'checked' : null }; store.save(); } }
|
|
1853
2185
|
} catch (e) {
|
|
1854
2186
|
spend(null);
|
|
1855
2187
|
store.commit();
|
|
@@ -1860,14 +2192,17 @@ export class Carrier {
|
|
|
1860
2192
|
// An entry written before `as` was kept: unknown, so the notice goes (#next `first`).
|
|
1861
2193
|
const answered = waiting.find(([x]) => x === id)[1], held = answered.as ?? null;
|
|
1862
2194
|
const c = renamed(store, store.lookup(res.did), answered);
|
|
2195
|
+
if (!answered.named && c.name === answered.name && c.name_from === undefined && !res.rekeyed) { c.name_from = 'auto'; store.save(); }
|
|
1863
2196
|
const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K: hexToBytes(res.pair_key) });
|
|
1864
|
-
const
|
|
2197
|
+
const pub = answered.public ? { public: true, words_checked: Boolean(answered.words) } : {};
|
|
2198
|
+
const events = [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key), ...pub })];
|
|
1865
2199
|
try { acceptPrekeys(s, reply.prekeys, now); } catch (e) {
|
|
1866
2200
|
if (!(e instanceof MsgError)) throw e;
|
|
1867
2201
|
events.push({ type: 'dropped', check: e.check, detail: `the reply's prekeys: ${e.message}` });
|
|
1868
2202
|
}
|
|
1869
2203
|
st.peers[c.did] = { session: dumpSession(s), announced: held, known: held, outbox: st.peers[c.did]?.outbox ?? [], prekeys_resend: false, prekeys_iat: 0 };
|
|
1870
|
-
|
|
2204
|
+
this.#tellName(st, c.did);
|
|
2205
|
+
for (const [x] of waiting) this.#handshakes.set(x, { contact: { name: c.name, did: c.did, current_did: c.current_did, fingerprint: wordsOf(res.pair_key), ...pub } });
|
|
1871
2206
|
this.#routes = new Map();
|
|
1872
2207
|
return events;
|
|
1873
2208
|
}
|
|
@@ -1895,6 +2230,15 @@ export class Carrier {
|
|
|
1895
2230
|
for (const c of this.#liveContacts(store, relay)) {
|
|
1896
2231
|
const e = st.peers[c.did];
|
|
1897
2232
|
if (!e) continue;
|
|
2233
|
+
// Past its expires (send): dropped unsent, waiting (no reader, no prekeys) or not.
|
|
2234
|
+
if (e.outbox.some((x) => x.exp !== undefined && x.exp <= now)) {
|
|
2235
|
+
e.outbox = e.outbox.filter((x) => {
|
|
2236
|
+
if (x.exp === undefined || x.exp > now) return true;
|
|
2237
|
+
this.#results.set(x.id, { code: 'expired', detail: `not sent before it expired (${x.exp})`, local: true });
|
|
2238
|
+
this.#replyMark(st, x.id, now, { code: 'expired', detail: `not sent before it expired (${x.exp})` });
|
|
2239
|
+
return false;
|
|
2240
|
+
});
|
|
2241
|
+
}
|
|
1898
2242
|
if (absent(c.did)) {
|
|
1899
2243
|
const detail = noReader(c.name);
|
|
1900
2244
|
for (const item of e.outbox) this.#results.set(item.id, { code: null, queued: detail });
|
|
@@ -1940,6 +2284,7 @@ export class Carrier {
|
|
|
1940
2284
|
// exited, and its agent was told it goes at a later connection.
|
|
1941
2285
|
for (const item of e.outbox.splice(0)) {
|
|
1942
2286
|
this.#results.set(item.id, { code: 're_pair', detail: rePairWhy(c), local: true });
|
|
2287
|
+
this.#replyMark(st, item.id, now, { code: 're_pair', detail: rePairWhy(c) });
|
|
1943
2288
|
this.#emit(this.#note(st, now, { type: 'refused', id: item.id, peer: c.did, name: c.name, code: 're_pair', detail: rePairWhy(c) }));
|
|
1944
2289
|
}
|
|
1945
2290
|
continue;
|
|
@@ -1990,6 +2335,7 @@ export class Carrier {
|
|
|
1990
2335
|
// Refused here, before sending (message_too_large, revoked): never reported as the relay's word.
|
|
1991
2336
|
e.outbox.shift();
|
|
1992
2337
|
this.#results.set(item.id, { code: err.check, detail: err.message, local: true });
|
|
2338
|
+
this.#replyMark(st, item.id, now, { code: err.check, detail: err.message });
|
|
1993
2339
|
}
|
|
1994
2340
|
}
|
|
1995
2341
|
}
|
|
@@ -2075,14 +2421,20 @@ export class Carrier {
|
|
|
2075
2421
|
this.#emit({ type: 'error', relay: link.relay, check: err.check ?? 'publish', detail: err.message });
|
|
2076
2422
|
return;
|
|
2077
2423
|
}
|
|
2078
|
-
this.#locked((ctx) => {
|
|
2424
|
+
this.#locked((ctx) => {
|
|
2425
|
+
if (r && this.#refused(ctx, e, r)) return;
|
|
2426
|
+
ctx.st.pending = ctx.st.pending.filter((p) => p.id !== e.id);
|
|
2427
|
+
// A reply's part: published, or refused; back in the outbox (no reader): still queued.
|
|
2428
|
+
if (e.kind === KIND.message && !(r?.code === 'no_reader' && e.item !== undefined)) this.#replyMark(ctx.st, e.id, ctx.now, r && { code: r.code, detail: r.detail });
|
|
2429
|
+
});
|
|
2079
2430
|
if (r?.code === 'pow') { link.pow = true; link.closing = true; link.client.end(true); return; } // log in again, with the proof (#connect, #closed)
|
|
2080
2431
|
if (r?.code === 'no_reader' && e.peer !== undefined && e.control !== 'reply') link.absent.add(e.peer);
|
|
2081
2432
|
// A message the relay had no reader for is back in its outbox (#refused): queued, not refused.
|
|
2082
2433
|
const back = r?.code === 'no_reader' && e.kind === KIND.message && e.item !== undefined;
|
|
2083
2434
|
if (e.control === undefined || e.control === 'answer') this.#results.set(e.id, back ? { code: null, queued: noReader(this.#nameOf(e.peer)) } : r ?? { code: null }); // what a verb waits for
|
|
2084
|
-
|
|
2085
|
-
|
|
2435
|
+
const receipt = e.item?.label === SEEN_LABEL ? { receipt: true } : {};
|
|
2436
|
+
this.#emit(back ? { type: 'queued', id: e.id, peer: e.peer, code: r.code, detail: r.detail, ...receipt }
|
|
2437
|
+
: r ? { type: 'refused', id: e.id, peer: e.peer, control: e.control, code: r.code, ...(r.side && { side: r.side }), detail: r.detail, ...receipt } : { type: 'sent', id: e.id, peer: e.peer, control: e.control, ...receipt });
|
|
2086
2438
|
// A refusal stops this round: what follows would be refused alike (a quota, the rate brake),
|
|
2087
2439
|
// and a control frame would be queued again at once. The next round retries. A mailbox
|
|
2088
2440
|
// nobody holds stops only what goes to that contact (absent, #next).
|
|
@@ -2168,9 +2520,79 @@ export class Carrier {
|
|
|
2168
2520
|
if (stale.length > 0 && link.quiet) await this.#unsubscribe(link, stale);
|
|
2169
2521
|
if (!link.up) return;
|
|
2170
2522
|
await this.#presence(link);
|
|
2523
|
+
if (!link.up) return;
|
|
2524
|
+
await this.#pushOut(link);
|
|
2171
2525
|
await this.#flush(link);
|
|
2172
2526
|
}
|
|
2173
2527
|
|
|
2528
|
+
// The push registration (setPush) at this agent's own relay, once per connection and again when it
|
|
2529
|
+
// changes: the JSON {v, endpoint, p256dh, auth}, or an empty payload (off). A relay that does not
|
|
2530
|
+
// say it takes them is sent nothing (state unsupported); a refusal is kept, not retried this connection.
|
|
2531
|
+
async #pushOut(link) {
|
|
2532
|
+
if (this.#push === undefined || !link.own) return;
|
|
2533
|
+
const bytes = this.#push === null ? '' : canonicalize({ v: PUSH_V, ...this.#push });
|
|
2534
|
+
if (link.pushSent === bytes) return;
|
|
2535
|
+
link.pushSent = bytes;
|
|
2536
|
+
if (!link.push) { this.#pushSays({ state: 'unsupported', relay: link.relay }); return; }
|
|
2537
|
+
await this.#throttle(link);
|
|
2538
|
+
const r = await this.#publish(link, PUSH_TOPIC, utf8ToBytes(bytes));
|
|
2539
|
+
if (r) { this.#emit({ type: 'notice', relay: link.relay, code: r.code, detail: r.detail }); this.#pushSays({ state: 'refused', relay: link.relay, code: r.code, detail: r.detail }); return; }
|
|
2540
|
+
this.#pushSays({ state: this.#push === null ? 'off' : 'registered', relay: link.relay, at: this.clock() });
|
|
2541
|
+
}
|
|
2542
|
+
#pushSays(x) { this.#pushState = x; this.#emit({ type: 'push', ...x }); }
|
|
2543
|
+
|
|
2544
|
+
/**
|
|
2545
|
+
* The phone's UnifiedPush registration for this agent's own relay (design/push.md, relay/push.mjs): { endpoint (https),
|
|
2546
|
+
* p256dh, auth (base64url) } to register, null to remove it there; sent at once when connected, else at the next login,
|
|
2547
|
+
* and again at every login. Never called: nothing is sent (a computer, the GTK app). → pushStatus().
|
|
2548
|
+
*/
|
|
2549
|
+
setPush(reg) {
|
|
2550
|
+
if (reg !== null) {
|
|
2551
|
+
const fine = reg && typeof reg === 'object' && Object.keys(reg).sort().join() === 'auth,endpoint,p256dh'
|
|
2552
|
+
&& typeof reg.endpoint === 'string' && /^https:\/\//.test(reg.endpoint) && reg.endpoint.length <= 1024 && [reg.p256dh, reg.auth].every((x) => typeof x === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(x));
|
|
2553
|
+
if (!fine) fail('push', 'a push registration is {endpoint: an https URL, p256dh, auth: base64url}, or null');
|
|
2554
|
+
reg = { endpoint: reg.endpoint, p256dh: reg.p256dh, auth: reg.auth };
|
|
2555
|
+
}
|
|
2556
|
+
const same = canonicalize(reg) === canonicalize(this.#push ?? null) && this.#push !== undefined;
|
|
2557
|
+
this.#push = reg;
|
|
2558
|
+
if (!same) {
|
|
2559
|
+
this.#pushState = { state: 'pending', relay: this.relay };
|
|
2560
|
+
if (this.#links.get(this.relay)?.up) this.#refreshSoon(this.relay);
|
|
2561
|
+
}
|
|
2562
|
+
return this.pushStatus();
|
|
2563
|
+
}
|
|
2564
|
+
|
|
2565
|
+
/** → { state: 'none' (never set) | 'pending' | 'registered' | 'off' | 'refused' | 'unsupported', relay?, at?, code?, detail? }. */
|
|
2566
|
+
pushStatus() { return { ...this.#pushState }; }
|
|
2567
|
+
|
|
2568
|
+
/**
|
|
2569
|
+
* A TURN server for a call or a transfer starting now (relay/turn.mjs): { urls, username, credential, exp } from this agent's
|
|
2570
|
+
* own relay, asked over its session (one publish, in the queue of the session's work: one request in flight), kept until
|
|
2571
|
+
* TURN_KEEP_S before exp. null where the relay gives none, the session is down, or no answer within TURN_WAIT_MS: the
|
|
2572
|
+
* caller goes on with STUN alone.
|
|
2573
|
+
*/
|
|
2574
|
+
async turnServer() {
|
|
2575
|
+
const t = this.#turn;
|
|
2576
|
+
if (t && t.exp - TURN_KEEP_S > this.clock()) return { ...t };
|
|
2577
|
+
const link = this.#links.get(this.relay);
|
|
2578
|
+
if (!link?.up || !link.turn) return null;
|
|
2579
|
+
const asked = new Promise((resolve) => {
|
|
2580
|
+
this.#later(async () => {
|
|
2581
|
+
if (!link.up) return resolve(null);
|
|
2582
|
+
link.turnGot = null;
|
|
2583
|
+
let r = null;
|
|
2584
|
+
try { r = await this.#publish(link, TURN_TOPIC, new Uint8Array(0)); } catch { return resolve(null); }
|
|
2585
|
+
const got = link.turnGot;
|
|
2586
|
+
link.turnGot = null;
|
|
2587
|
+
if (r) this.#emit({ type: 'notice', relay: link.relay, code: r.code, detail: r.detail });
|
|
2588
|
+
resolve(r ? null : got);
|
|
2589
|
+
});
|
|
2590
|
+
});
|
|
2591
|
+
const got = await Promise.race([asked, sleep(TURN_WAIT_MS).then(() => null)]);
|
|
2592
|
+
if (got) this.#turn = got;
|
|
2593
|
+
return got ? { ...got } : null;
|
|
2594
|
+
}
|
|
2595
|
+
|
|
2174
2596
|
// Presence at one relay (the header's "Presence"): each contact's marker toward this agent read
|
|
2175
2597
|
// (QoS 0: a marker is never queued); this agent's published toward those who may see it, once
|
|
2176
2598
|
// per connection, by a started carrier only (its CONNECT set the will); cleared toward any other.
|
|
@@ -2243,10 +2665,11 @@ export class Carrier {
|
|
|
2243
2665
|
}
|
|
2244
2666
|
|
|
2245
2667
|
// Until queued work is done and nothing has arrived for QUIET ms (and `until()` holds), or max ms.
|
|
2246
|
-
async #idle({ max = DRAIN, until = null } = {}) {
|
|
2668
|
+
async #idle({ max = DRAIN, until = null, down = null } = {}) {
|
|
2247
2669
|
const end = Date.now() + max;
|
|
2248
2670
|
for (;;) {
|
|
2249
2671
|
await this.#drain();
|
|
2672
|
+
if (down?.()) return;
|
|
2250
2673
|
const last = Math.max(this.#lastWork, ...[...this.#links.values()].map((l) => l.lastIn));
|
|
2251
2674
|
if (Date.now() - last >= QUIET && (!until || until())) return;
|
|
2252
2675
|
if (Date.now() >= end) return;
|
|
@@ -2257,9 +2680,15 @@ export class Carrier {
|
|
|
2257
2680
|
// ---- connections
|
|
2258
2681
|
|
|
2259
2682
|
async #credentials(relay, ep, started) {
|
|
2683
|
+
// A login with a proof of work that a busy relay turned away "rate" before spending its nonce
|
|
2684
|
+
// (#dial; relay/pow.mjs): sent again as it is while that nonce lives, no search spent twice.
|
|
2685
|
+
const spare = this.#spare.get(relay);
|
|
2686
|
+
this.#spare.delete(relay);
|
|
2687
|
+
if (spare && spare.until > Date.now()) return spare;
|
|
2260
2688
|
const { me, proven } = this.#read(({ me, st }) => ({ me, proven: st.relays[relay]?.proven === true }));
|
|
2261
2689
|
const powMax = relay === this.relay ? POW_MAX : POW_MAX_OTHER;
|
|
2262
|
-
const
|
|
2690
|
+
const issued = Date.now();
|
|
2691
|
+
const r = await http(this.platform, `${ep.http}/challenge?did=${encodeURIComponent(me.current_did)}${!proven && this.enrolHash ? `&enrol=${this.enrolHash}` : ''}`);
|
|
2263
2692
|
this.#clockFrom(relay, r);
|
|
2264
2693
|
if (r.status === 429) refuse('rate', `the relay ${relay} turned the login away: too many logins from this network (${relaySays(r.body?.error ?? r.body?.detail)}): ${retryIn(r, 'a minute')}, then try again`, r);
|
|
2265
2694
|
// Any other status is no answer about this agent (nginx says 502 while the relay restarts):
|
|
@@ -2288,6 +2717,14 @@ export class Carrier {
|
|
|
2288
2717
|
e.permanent = true;
|
|
2289
2718
|
throw e;
|
|
2290
2719
|
}
|
|
2720
|
+
// The function the relay states beside the bits: one this client does not compute is not
|
|
2721
|
+
// searched for (a relay of sigelo-relay-pow/0, SHA-256, or one asking more memory than POW_COST).
|
|
2722
|
+
const cost = bits === 0 ? POW_COST : powCost(r.body.pow);
|
|
2723
|
+
if (cost === null) {
|
|
2724
|
+
const e = new MsgError('pow', `the relay asks a proof of work this client does not compute (${JSON.stringify(r.body.pow ?? null).slice(0, 200)}); it computes {v: 1, alg: "argon2id"} at up to ${POW_COST.m} KiB, ${POW_COST.t} passes, 1 lane: update this client, or the relay`);
|
|
2725
|
+
e.permanent = true;
|
|
2726
|
+
throw e;
|
|
2727
|
+
}
|
|
2291
2728
|
// A search of 0 bits costs nothing and is not counted.
|
|
2292
2729
|
if (bits > 0) this.#locked(({ now, st }) => {
|
|
2293
2730
|
const at = (st.relays[relay] ??= { proven: false, claims: {} }), recent = (at.searches ?? []).filter((t) => t > now - DAY);
|
|
@@ -2305,12 +2742,14 @@ export class Carrier {
|
|
|
2305
2742
|
at.searches = [...recent, now];
|
|
2306
2743
|
});
|
|
2307
2744
|
const t0 = Date.now();
|
|
2308
|
-
if (bits > 0) this.#emit({ type: 'pow', relay, bits });
|
|
2309
|
-
pow = await solvePow(relay, me.did, ch.nonce, bits, t0 + POW_MS, this.platform.pow
|
|
2745
|
+
if (bits > 0) this.#emit({ type: 'pow', relay, bits, m: cost.m, t: cost.t });
|
|
2746
|
+
pow = await solvePow(relay, me.did, ch.nonce, bits, t0 + POW_MS, this.platform.pow, cost)
|
|
2747
|
+
?? fail('pow', `no ${bits}-bit proof of work found within ${POW_MS / 1000} s on this machine (${2 ** bits} Argon2id evaluations on average, ~${Math.round((2 ** bits * POW_EVAL_MS * cost.m * cost.t) / (POW_COST.m * POW_COST.t) / 1000)} s on a phone): try again, or later (the relay raises it under load)`);
|
|
2310
2748
|
if (bits > 0) this.#emit({ type: 'pow_done', relay, bits, ms: Date.now() - t0 });
|
|
2311
2749
|
}
|
|
2312
2750
|
const password = canonicalize({ v: LOGIN_V, nonce: ch.nonce, sig, bundle: loginBundle(me.bundle, relay), ...(pow !== undefined && { pow }) });
|
|
2313
|
-
|
|
2751
|
+
// until: this login's nonce is good till about then (#dial keeps it for a retry after "rate").
|
|
2752
|
+
return { username: me.current_did, clientId: clientIdOf(me.did), password, pow, until: issued + POW_MS, push: r.body?.push === PUSH_V, turn: r.body?.turn === TURN_V };
|
|
2314
2753
|
}
|
|
2315
2754
|
|
|
2316
2755
|
// How long this agent's own relay keeps a message on the free tier (relay.json, plan §11), when
|
|
@@ -2373,18 +2812,25 @@ export class Carrier {
|
|
|
2373
2812
|
if (n.accepted && creds.pow !== undefined) this.#locked(({ st }) => { (st.relays[relay] ??= { proven: false, claims: {} }).proven = true; });
|
|
2374
2813
|
return n;
|
|
2375
2814
|
};
|
|
2376
|
-
try {
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2815
|
+
try {
|
|
2816
|
+
try { await mqttConnect(this.platform, url, creds, link, onPacket, probe ? PROBE_MS : CONNECT_MS); } catch (e) {
|
|
2817
|
+
if (!probe || link.cut || typeof e.code === 'number') throw link.cut ?? await why(e);
|
|
2818
|
+
url = await wsEndpoint(this.platform, ep);
|
|
2819
|
+
try { await mqttConnect(this.platform, url, creds, link, onPacket); } catch (e2) { throw link.cut ?? await why(e2); }
|
|
2820
|
+
FELL_BACK.set(ep.mqtt, url);
|
|
2821
|
+
this.#emit({ type: 'transport', relay, transport: 'wss', detail: `${ep.mqtt} gave no CONNACK within ${PROBE_MS / 1000} s (${e.message}): MQTT over WebSocket at ${url} for the rest of this process` });
|
|
2822
|
+
}
|
|
2823
|
+
} catch (e) {
|
|
2824
|
+
// "rate" with a proof of work: the relay was checking as many proofs as it holds and refused
|
|
2825
|
+
// before spending the nonce (relay/pow.mjs), so this very login is good for the next try.
|
|
2826
|
+
if (e?.check === 'rate' && creds.pow !== undefined && creds.until > Date.now()) this.#spare.set(relay, creds);
|
|
2827
|
+
throw e;
|
|
2382
2828
|
}
|
|
2383
2829
|
// A close right after CONNACK (a cut in the same read) reached no listener of this connection.
|
|
2384
2830
|
if (!link.client.connected) throw link.cut ?? new MsgError('connect', 'the relay closed the connection');
|
|
2385
2831
|
// Deliveries are counted from here (quiet), not from before the login: a proof-of-work search
|
|
2386
2832
|
// of seconds would read as a drained queue, and give up stale claims before what they hold came.
|
|
2387
|
-
link.since = Date.now(); link.onlineAt = this.clock();
|
|
2833
|
+
link.since = Date.now(); link.onlineAt = this.clock(); link.push = creds.push === true; link.turn = creds.turn === true;
|
|
2388
2834
|
if (creds.pow !== undefined) this.#locked(({ st }) => { (st.relays[relay] ??= { proven: false, claims: {} }).proven = true; });
|
|
2389
2835
|
link.client.on('error', () => {}); // a close follows
|
|
2390
2836
|
link.client.on('close', () => this.#closed(link));
|
|
@@ -2420,6 +2866,8 @@ export class Carrier {
|
|
|
2420
2866
|
if (this.#links.get(link.relay) === link) this.#links.delete(link.relay);
|
|
2421
2867
|
this.#emit({ type: 'disconnected', relay: link.relay });
|
|
2422
2868
|
if (Date.now() - link.since >= STABLE_MS) this.#attempts.delete(link.relay);
|
|
2869
|
+
// Logged in, then closed: by this client (it hung up), or by the relay (its notice says why).
|
|
2870
|
+
if (link.onlineAt > 0) this.#ended(link.relay, link.closing ? null : { ms: Date.now() - link.since, ...(link.ended ?? { code: 'session_ended', detail: 'the relay closed the connection' }) });
|
|
2423
2871
|
if (!this.#started || this.#connecting.has(link.relay) || (link.closing && !link.pow)) return;
|
|
2424
2872
|
if (link.cut?.permanent) {
|
|
2425
2873
|
this.#emit({ type: 'error', relay: link.relay, check: link.cut.check, detail: link.cut.message, ...(link.cut.next !== undefined && { next: link.cut.next }) });
|
|
@@ -2427,6 +2875,28 @@ export class Carrier {
|
|
|
2427
2875
|
} else this.#retry(link.relay);
|
|
2428
2876
|
}
|
|
2429
2877
|
|
|
2878
|
+
// The relay ended a session (why: { ms it lasted, code, detail }) or refused a login (why: { code,
|
|
2879
|
+
// detail }), or this client ended one itself (why null): the pace of the next login (backoff).
|
|
2880
|
+
#ended(relay, why) {
|
|
2881
|
+
try {
|
|
2882
|
+
this.#locked(({ st }) => {
|
|
2883
|
+
const r = (st.relays[relay] ??= { proven: false, claims: {} });
|
|
2884
|
+
if (why === null || (why.ms ?? 0) >= ENDED_LASTS) { delete r.ended; if (why === null) return; }
|
|
2885
|
+
r.ended = { n: Math.min(32, (r.ended?.n ?? 0) + 1), at: Date.now(), code: String(why.code).slice(0, 64), detail: String(why.detail ?? '').slice(0, 200) };
|
|
2886
|
+
});
|
|
2887
|
+
} catch {}
|
|
2888
|
+
}
|
|
2889
|
+
// Before a login to `relay`: the wait the last early ends ask (backoff), but never past `end` (ms).
|
|
2890
|
+
async #pace(relay, end = null) {
|
|
2891
|
+
let e = null;
|
|
2892
|
+
try { e = this.#read(({ st }) => st.relays[relay]?.ended ?? null); } catch {}
|
|
2893
|
+
if (!e || !(e.n > 0) || !Number.isFinite(e.at)) return;
|
|
2894
|
+
const [first, most] = this.backoff;
|
|
2895
|
+
const due = e.at + Math.min(most, first * 2 ** (e.n - 1));
|
|
2896
|
+
const ms = Math.min(due, end ?? due) - Date.now();
|
|
2897
|
+
if (ms > 0) await sleep(Math.min(ms, most));
|
|
2898
|
+
}
|
|
2899
|
+
|
|
2430
2900
|
// Exponential backoff with jitter: first, 2 × first, … up to most. started: the first try's only
|
|
2431
2901
|
// (start({ started })); every later one is automatic.
|
|
2432
2902
|
#retry(relay, delay, started) {
|
|
@@ -2476,7 +2946,7 @@ export class Carrier {
|
|
|
2476
2946
|
this.#locked(({ now, store, st }) => {
|
|
2477
2947
|
const waiting = new Set(st.pending.filter((x) => x.relay === relay && x.control === 'answer').map((x) => x.topic));
|
|
2478
2948
|
for (const [id, p] of Object.entries(store.load().s.accepts)) {
|
|
2479
|
-
if (p.relay !== relay || !waiting.has(
|
|
2949
|
+
if (p.relay !== relay || !waiting.has(answerTopicOf(p))) continue;
|
|
2480
2950
|
store.take('accepts', id, now);
|
|
2481
2951
|
this.#emit(this.#note(st, now, { type: 'pairing_failed', did: p.code_did, name: p.name, code: e.check ?? 'connect', detail: `the code's relay refused this agent: ${e.message}` }));
|
|
2482
2952
|
}
|
|
@@ -2499,15 +2969,36 @@ export class Carrier {
|
|
|
2499
2969
|
|
|
2500
2970
|
// Connects (or refreshes) each relay, waits for the round to settle, and hangs up again unless
|
|
2501
2971
|
// started.
|
|
2972
|
+
// A wait (idle.max) is the caller's: a session the relay ends early, or a login it turns away
|
|
2973
|
+
// after the first, is tried again at the backoff pace until that time, never returned early
|
|
2974
|
+
// (0.1.17: `inbox --wait 300` said "no message came within 300 s" after ~20 s). this.ended: the
|
|
2975
|
+
// relay's last word on a session it ended during this one ({ code, detail, n }), or null.
|
|
2502
2976
|
async #session(relays, idle = {}, started) {
|
|
2503
2977
|
const opened = [];
|
|
2504
2978
|
this.#locked((ctx) => this.#expireKeys(ctx));
|
|
2979
|
+
const end = idle.max !== undefined && !this.#started ? Date.now() + idle.max : null;
|
|
2980
|
+
this.ended = null;
|
|
2505
2981
|
try {
|
|
2506
|
-
for (
|
|
2507
|
-
|
|
2508
|
-
|
|
2982
|
+
for (let round = 0; ; round++) {
|
|
2983
|
+
for (const r of relays) {
|
|
2984
|
+
if (this.#links.get(r)?.up) { this.#refreshSoon(r); continue; }
|
|
2985
|
+
await this.#pace(r, end);
|
|
2986
|
+
if (end !== null && round > 0 && Date.now() >= end) continue;
|
|
2987
|
+
try { opened.push(await this.#connect(r, started)); } catch (e) {
|
|
2988
|
+
if (ENDED_RETRY.has(e.check)) this.#ended(r, { code: e.check, detail: e.message });
|
|
2989
|
+
// The first login fails the verb as it always did; one after the relay ended a session waits again.
|
|
2990
|
+
if (end === null || round === 0 || !ENDED_RETRY.has(e.check)) throw e;
|
|
2991
|
+
this.ended = { code: e.check, detail: e.message, n: (this.ended?.n ?? 0) + 1 };
|
|
2992
|
+
}
|
|
2993
|
+
}
|
|
2994
|
+
const down = () => relays.some((r) => !this.#links.get(r)?.up);
|
|
2995
|
+
await this.#idle(end === null ? idle : { ...idle, max: Math.max(0, end - Date.now()), down });
|
|
2996
|
+
if (end === null || Date.now() >= end || !down() || opened.some((l) => l.cut)) break;
|
|
2997
|
+
if (idle.until?.()) break;
|
|
2998
|
+
// The relay ended it: why, then the same wait on a new login.
|
|
2999
|
+
const gone = opened.filter((l) => !l.up && l.ended).at(-1)?.ended ?? { code: 'session_ended', detail: 'the relay closed the connection' };
|
|
3000
|
+
this.ended = { ...gone, n: (this.ended?.n ?? 0) + 1 };
|
|
2509
3001
|
}
|
|
2510
|
-
await this.#idle(idle);
|
|
2511
3002
|
// One more round now that deliveries have stopped: claims past their time are given up
|
|
2512
3003
|
// only then (#refresh), and a frame that waited for a claim goes.
|
|
2513
3004
|
for (const r of relays) if (this.#links.get(r)?.up) this.#refreshSoon(r);
|
|
@@ -2525,16 +3016,32 @@ export class Carrier {
|
|
|
2525
3016
|
|
|
2526
3017
|
// short: the long code is parked at the relay (POST /park, relay/park.mjs) under a short code
|
|
2527
3018
|
// (short.mjs) for SHORT_TTL seconds, one fetch; refused, the invite is withdrawn as when its topic
|
|
2528
|
-
// is. A login of its own: the relay checks that the parked code is this agent's.
|
|
3019
|
+
// is. A login of its own: the relay checks that the parked code is this agent's. ttl with short:
|
|
3020
|
+
// SHORT_TTL_MIN to SHORT_TTL_MAX seconds, the life of both codes (a slow agent's operator).
|
|
2529
3021
|
// relay: the relay the code names (a company relay for colleagues, a public one for outsiders);
|
|
2530
3022
|
// the short code is parked there, and the pairing talks over it.
|
|
2531
3023
|
// local: no session: the code is made and kept only; its answer topic is claimed at this
|
|
2532
3024
|
// identity's next login (a device added offline, device.mjs), so connect once before it answers.
|
|
2533
|
-
|
|
3025
|
+
// renew: true begins a series of renewing codes (store.mjs renew); a series id continues one (#renewDue).
|
|
3026
|
+
// named: false when the caller made the name up (a placeholder): the contact takes the name the other side tells.
|
|
3027
|
+
// enrol: an enrolment code (enrol.mjs issue): parked with enrol: true (relay/park.mjs: up to ENROL_TTL_MAX,
|
|
3028
|
+
// fetched until the grant); an older relay that refuses the field gets a plain park, when ttl allows one.
|
|
3029
|
+
async invite({ name, ttl, short = false, relay, local = false, started, renew = false, named = name !== undefined, enrol = false } = {}) {
|
|
2534
3030
|
const at = relay === undefined ? this.relay : relayArg(relay);
|
|
3031
|
+
if (enrol && (!short || renew !== false || local)) fail('invite', 'an enrolment code is a short code, parked once: not long, renewing or local');
|
|
3032
|
+
if (enrol && ttl !== undefined && (!Number.isSafeInteger(ttl) || ttl < SHORT_TTL_MIN || ttl > ENROL_TTL_MAX)) {
|
|
3033
|
+
fail('ttl', `an enrolment code lives ${SHORT_TTL_MIN} s to a day (${ENROL_TTL_MAX} s), not ${JSON.stringify(ttl)}`);
|
|
3034
|
+
}
|
|
3035
|
+
if (short && !enrol && ttl !== undefined && (!Number.isSafeInteger(ttl) || ttl < SHORT_TTL_MIN || ttl > SHORT_TTL_MAX)) {
|
|
3036
|
+
fail('ttl', `a short code lives ${SHORT_TTL_MIN} to ${SHORT_TTL_MAX} seconds (default ${SHORT_TTL}), not ${JSON.stringify(ttl)}; longer: the long code (invite --long --ttl)`);
|
|
3037
|
+
}
|
|
3038
|
+
if (renew !== false && (!short || local)) fail('invite', 'a code that renews itself is a short one, parked at the relay: not with --long or local');
|
|
3039
|
+
const series = renew === true ? randomId() : typeof renew === 'string' ? renew : null;
|
|
2535
3040
|
const code = this.#locked(({ now, me, store }) => {
|
|
2536
3041
|
const code = makeInvite({ did: me.current_did, relay: at, now, ...(ttl !== undefined && { ttl }) });
|
|
2537
|
-
store.addInvite(code, name ?? `invite-${code.nonce.slice(1, 9)}`, now
|
|
3042
|
+
store.addInvite(code, name ?? `invite-${code.nonce.slice(1, 9)}`, now, null,
|
|
3043
|
+
series === null ? null : { id: series, ...(renew === true && { start: { name: name ?? null, ttl: ttl ?? null, relay: relay === undefined ? null : at } }) });
|
|
3044
|
+
if (!named) { store.load().s.invites[code.nonce].auto = true; store.save(); }
|
|
2538
3045
|
return code;
|
|
2539
3046
|
});
|
|
2540
3047
|
if (local) {
|
|
@@ -2551,26 +3058,66 @@ export class Carrier {
|
|
|
2551
3058
|
}
|
|
2552
3059
|
if (!short) return { code: code.text, did: code.did, relay: code.relay, exp: code.exp };
|
|
2553
3060
|
// Eight characters on the public relay; on any other, twelve: the last four its relay tag.
|
|
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);
|
|
2555
|
-
const
|
|
2556
|
-
|
|
3061
|
+
const s = makeShort(undefined, code.relay === this.shortRelay ? null : relayTag(code.relay)), exp = Math.min(checkNow(this.clock()) + (ttl ?? SHORT_TTL), code.exp), ep = endpointOf(code.relay, this.endpoints);
|
|
3062
|
+
const parkOnce = async (asEnrol) => {
|
|
3063
|
+
const creds = await this.#credentials(code.relay, ep, started);
|
|
3064
|
+
return 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, ...(asEnrol && { enrol: true }) }) });
|
|
3065
|
+
};
|
|
3066
|
+
let r = await parkOnce(enrol);
|
|
3067
|
+
// An older relay (no enrolment codes) answers 400 to the field: parked as an invite (fetched once), within its hour.
|
|
3068
|
+
if (enrol && r.status === 400) {
|
|
3069
|
+
if (exp - checkNow(this.clock()) > SHORT_TTL_MAX) refuse('park', `the relay ${code.relay} keeps no enrolment code longer than an hour (an older relay): --ttl 1h or less`, r);
|
|
3070
|
+
r = await parkOnce(false);
|
|
3071
|
+
}
|
|
2557
3072
|
const check = typeof r.body?.check === 'string' ? r.body.check : null;
|
|
2558
3073
|
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);
|
|
2559
3074
|
if ((r.status === 404 || r.status === 405) && check === null) refuse('park', `the relay ${code.relay} takes no short codes: use the long code (invite --long)`, r);
|
|
2560
3075
|
if (r.status !== 200) refuse('connect', `${code.relay}: ${statusWhy(r, 'POST /park')}`, r);
|
|
2561
3076
|
// exp is this machine's clock: one far off the relay's is refused (relay/park.mjs PARK_SKEW).
|
|
2562
|
-
|
|
3077
|
+
// A ttl past 10 minutes at an older relay (PARK_TTL 600) is refused the same way.
|
|
3078
|
+
const clock = typeof r.body?.detail === 'string' && r.body.detail.startsWith('exp:')
|
|
3079
|
+
? (ttl ?? SHORT_TTL) > SHORT_TTL ? `: this relay may keep short codes 10 minutes at most (an older relay): --ttl ${SHORT_TTL} or less, or the long code (invite --long --ttl ${ttl})`
|
|
3080
|
+
: ': this machine\'s clock may be off (date -u), or use the long code (invite --long)' : '';
|
|
2563
3081
|
if (r.body?.ok !== true) refuse(PARK_CHECKS.has(check) ? check : 'park', `the relay refused the short code (${relaySays(`${check}: ${r.body?.detail}`)})${clock}`, r);
|
|
2564
3082
|
// The relay keeps the code until its own exp (park.mjs: at most SHORT_TTL by its clock), not
|
|
2565
3083
|
// this machine's: that is the one shown. This machine's only when the relay names none.
|
|
2566
3084
|
const held = Number.isSafeInteger(r.body.exp) && r.body.exp > 0 ? r.body.exp : exp;
|
|
2567
|
-
|
|
3085
|
+
// Kept with the invite: a cancel by the short code finds it; a renewing series has its fresh code.
|
|
3086
|
+
this.#locked(({ store }) => { store.setShort(code.nonce, formatShort(s), held); if (series !== null && renew !== true) store.renewDone(series); });
|
|
3087
|
+
return { code: code.text, did: code.did, relay: code.relay, exp: code.exp, short: formatShort(s), short_exp: held, ...(series !== null && { renew: series }), ...(enrol && { enrol: r.body.enrol === true, short_hash: codeHash(s) }) };
|
|
2568
3088
|
} catch (e) {
|
|
2569
|
-
|
|
3089
|
+
// A renewal that failed leaves its series due (taken: store.mjs take), tried again (#renewDue).
|
|
3090
|
+
try { this.#locked(({ now, store }) => (series !== null && renew !== true ? store.take('invites', code.nonce, now) : store.cancelInvite(code.nonce))); } catch {}
|
|
2570
3091
|
throw e;
|
|
2571
3092
|
}
|
|
2572
3093
|
}
|
|
2573
3094
|
|
|
3095
|
+
// Renewing codes (store.mjs renew): a code of a series taken (answered) leaves it due, and a fresh
|
|
3096
|
+
// short code is parked for it here, with the series' name (numbered), ttl and relay. Claimed under
|
|
3097
|
+
// the lock, so two processes of one identity park one code; a failure is tried again RENEW_RETRY
|
|
3098
|
+
// seconds later, its reason kept for the state. Run after a session that may have taken one
|
|
3099
|
+
// (inbox, sync), at start, at a started carrier's answer and each round; never inside the work
|
|
3100
|
+
// queue (#later), whose drain the invite's own session waits for.
|
|
3101
|
+
async #renewDue(started) {
|
|
3102
|
+
if (this.#renewing) return;
|
|
3103
|
+
try { if (this.#read(({ now, store }) => store.renewClaim(now, true)).length === 0) return; } catch { return; }
|
|
3104
|
+
this.#renewing = true;
|
|
3105
|
+
try {
|
|
3106
|
+
const due = this.#locked(({ now, store }) => store.renewClaim(now));
|
|
3107
|
+
for (const x of due) {
|
|
3108
|
+
try {
|
|
3109
|
+
await this.invite({ name: x.name === null ? undefined : `${x.name}-${x.n + 1}`, short: true, renew: x.id, started,
|
|
3110
|
+
...(x.ttl !== null && { ttl: x.ttl }), ...(x.relay !== null && { relay: x.relay }) });
|
|
3111
|
+
} catch (e) { try { this.#locked(({ now, store }) => store.renewFailed(x.id, reason(e), now + RENEW_RETRY)); } catch {} }
|
|
3112
|
+
}
|
|
3113
|
+
} finally { this.#renewing = false; }
|
|
3114
|
+
}
|
|
3115
|
+
#renewSoon() {
|
|
3116
|
+
if (!this.#started || this.#renewing) return;
|
|
3117
|
+
const t = setTimeout(() => { if (this.#started) void this.#renewDue().catch(() => {}); }, 0);
|
|
3118
|
+
t.unref?.();
|
|
3119
|
+
}
|
|
3120
|
+
|
|
2574
3121
|
// Where a short code is parked → { relay, from }: `relay` when named (the inviter's --relay; a
|
|
2575
3122
|
// twelve-character code's tag must be its tag), else an eight-character code's shortRelay
|
|
2576
3123
|
// (relay.sigelo.ai), else the host its relay tag resolves to (relays.mjs resolveTag): this agent's
|
|
@@ -2630,17 +3177,38 @@ export class Carrier {
|
|
|
2630
3177
|
async unparkFrom(text, { relay } = {}) { return this.#unpark(text, relay); }
|
|
2631
3178
|
|
|
2632
3179
|
async #unpark(text, relay) {
|
|
3180
|
+
text = stripEnrol(text);
|
|
2633
3181
|
const { relay: at, from } = await this.relayForShort(text, { relay });
|
|
2634
3182
|
const shown = formatShort(normaliseShort(text)), ep = endpointOf(at, this.endpoints);
|
|
2635
3183
|
const r = await http(this.platform, `${ep.http}/park/${codeHash(text)}`);
|
|
2636
3184
|
if (r.status === 429) refuse('rate', `the relay ${at} looks up no more short codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to 10 minutes')}, or ask for the long code (invite --long)`, r);
|
|
2637
3185
|
if (r.status === 404 && r.body?.check === 'park_unknown') {
|
|
2638
|
-
refuse('park_unknown', `short code ${shown}: no invite waits under it at ${at}. It expired (a short code lives 10 minutes), was used already (once only), or is mistyped; ask the inviter for a new one. If the inviter made it on another relay (invite --relay) with an older sigelo, accept it with --relay <that relay>, or ask for the long code (invite --long)`, r);
|
|
3186
|
+
refuse('park_unknown', `short code ${shown}: no invite waits under it at ${at}. It expired (a short code lives 10 minutes unless its inviter chose up to an hour), was used already (once only), or is mistyped; ask the inviter for a new one. If the inviter made it on another relay (invite --relay) with an older sigelo, accept it with --relay <that relay>, or ask for the long code (invite --long)`, r);
|
|
2639
3187
|
}
|
|
2640
3188
|
if (r.status === 404 || r.status === 405) refuse('park', `the relay ${at} takes no short codes: ask the inviter for the long code (invite --long)`, r);
|
|
2641
3189
|
if (r.status !== 200) refuse('connect', `${at}: ${statusWhy(r, 'GET /park')}`, r);
|
|
2642
3190
|
if (r.body?.ok !== true || typeof r.body.invite !== 'string') refuse('connect', `${at}: GET /park answered 200 without a parked code: try again later; SIGELO_DEBUG=1 shows the answer`, r);
|
|
2643
3191
|
if (from === 'named' && tagOf(normaliseShort(text)) !== null) try { remember(this.relaysPath, at, this.platform.files); } catch {}
|
|
3192
|
+
// enrol: the relay parked it as an enrolment code (relay/park.mjs): init --enrol takes no other.
|
|
3193
|
+
return { invite: r.body.invite, relay: at, enrol: r.body.enrol === true };
|
|
3194
|
+
}
|
|
3195
|
+
|
|
3196
|
+
// The operator's grant has gone (enrol.mjs): its enrolment code spent at the relay that parks it
|
|
3197
|
+
// (DELETE /park/<hash>, the parker's login), so nobody fetches it again. Best effort → { unparked, … }.
|
|
3198
|
+
async unparkHash(hash, relay = this.relay) {
|
|
3199
|
+
if (typeof hash !== 'string' || !/^[0-9a-f]{64}$/.test(hash)) fail('park', 'a code hash: 64 hex');
|
|
3200
|
+
return this.#unparkCancel(relayArg(relay), hash);
|
|
3201
|
+
}
|
|
3202
|
+
|
|
3203
|
+
// A public code's long code: GET /park/<public hash> (relay/park.mjs), not spent there. → { invite, relay }.
|
|
3204
|
+
async #unparkPublic(text, relay) {
|
|
3205
|
+
const norm = normalisePub(text), shown = formatPub(norm);
|
|
3206
|
+
const { relay: at } = await this.relayForShort(norm, { relay });
|
|
3207
|
+
const r = await http(this.platform, `${endpointOf(at, this.endpoints).http}/park/${publicHash(text)}`);
|
|
3208
|
+
if (r.status === 429) refuse('rate', `the relay ${at} looks up no more public codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to 10 minutes')}, or use its sgl2 code`, r);
|
|
3209
|
+
if (r.status === 409 && r.body?.check === 'public_paused') refuse('public_paused', `${shown} is paused by its owner: try again later`, r);
|
|
3210
|
+
if (r.status === 404 && r.body?.check === 'park_unknown') refuse('park_unknown', `${shown}: no public code under it at ${at}: revoked, ended, or mistyped`, r);
|
|
3211
|
+
if (r.status !== 200 || r.body?.ok !== true || typeof r.body.invite !== 'string' || !r.body.invite.startsWith('sgl2')) refuse(r.status === 200 ? 'park' : 'connect', `${at}: ${r.status === 200 ? 'GET /park answered without a public code' : statusWhy(r, 'GET /park')}`, r);
|
|
2644
3212
|
return { invite: r.body.invite, relay: at };
|
|
2645
3213
|
}
|
|
2646
3214
|
|
|
@@ -2666,6 +3234,16 @@ export class Carrier {
|
|
|
2666
3234
|
// relay: the relay a short code was parked at (unpark), and the one a code must name (a long
|
|
2667
3235
|
// code names its own: one naming another is refused code_relay).
|
|
2668
3236
|
async accept(text, opts = {}) {
|
|
3237
|
+
// An enrolment code (ENROL-…, short.mjs) is for init --enrol on a new machine: refused here before any
|
|
3238
|
+
// fetch, so it is not spent and its operator is never made a contact of this identity by it.
|
|
3239
|
+
if (isEnrolCode(typeof text === 'string' ? text : '')) fail('enrol_code', 'that is an enrol code: run init --enrol CODE (sigelo-agent init --enrol, or sigelo_enrol), on a machine with no identity yet');
|
|
3240
|
+
// A public code's link carries its code and the four words to check (public.mjs readLink).
|
|
3241
|
+
const link = readLink(typeof text === 'string' ? text.trim() : text);
|
|
3242
|
+
if (link) { text = link.code; opts = { ...opts, words: opts.words ?? link.words ?? undefined }; }
|
|
3243
|
+
if (isPub(text)) {
|
|
3244
|
+
const { invite, relay: at } = await this.#unparkPublic(text, opts.relay);
|
|
3245
|
+
return this.#answer(invite, 'parked', { ...opts, relay: at });
|
|
3246
|
+
}
|
|
2669
3247
|
// Short or long by the input's shape, before either parser runs (short.mjs codeKind).
|
|
2670
3248
|
const how = codeKind(text) === 'short' ? 'parked' : 'long';
|
|
2671
3249
|
if (how !== 'parked') return this.#answer(text, how, opts);
|
|
@@ -2674,11 +3252,15 @@ export class Carrier {
|
|
|
2674
3252
|
try { return await this.#answer(long, how, { ...opts, relay: at }); } catch (e) { throw keepLong(e, long); }
|
|
2675
3253
|
}
|
|
2676
3254
|
|
|
2677
|
-
|
|
3255
|
+
// words (a public code's): the inviter's four words as its page published them, checked on the reply.
|
|
3256
|
+
async #answer(text, how, { name, wait = 10, tier, relay, started, words } = {}) {
|
|
2678
3257
|
if (tier !== undefined && !TIERS.includes(tier)) fail('tier', `a tier is ${TIERS.join(', ')}; not ${JSON.stringify(tier)}`);
|
|
2679
3258
|
const named = relay === undefined ? undefined : relayArg(relay);
|
|
2680
|
-
const
|
|
3259
|
+
const given = words === undefined || words === null ? null : normaliseWords(words);
|
|
3260
|
+
const { code, id, entry, reply, until } = this.#locked(({ now, me, store, st }) => {
|
|
2681
3261
|
const code = readCode(text, now, how);
|
|
3262
|
+
const pub = code.version === PUBLIC_VERSION;
|
|
3263
|
+
if (given !== null && !pub) fail('words', 'four words are checked with a public code (PUB-…) only; compare a one-time code\'s words after pairing');
|
|
2682
3264
|
if (named !== undefined && code.relay !== named) fail('code_relay', `the code names ${code.relay}, not ${named} (--relay): leave --relay out, or ask the inviter which relay it used`);
|
|
2683
3265
|
// This agent's own relay, those its operator configured, and one it named (--relay) are the operator's choice.
|
|
2684
3266
|
if (code.relay !== this.relay && code.relay !== named && !Object.hasOwn(this.endpoints ?? {}, code.relay) && !publicRelay(code.relay)) {
|
|
@@ -2690,16 +3272,19 @@ export class Carrier {
|
|
|
2690
3272
|
if (known?.revoked && !(known.relink?.until > now)) fail('revoked', `${known.did} was revoked by this owner${known.ended ? ` (link ${known.ended.id} ended): a new link needs both operators to ask again` : ''}`);
|
|
2691
3273
|
const k = kemKey();
|
|
2692
3274
|
try {
|
|
2693
|
-
const answer = buildAnswer({ code, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_pk: k.pk, prekeys: null });
|
|
2694
|
-
const keys = inviteKeys(code.secret), frame = seal(KIND.invite_answer, keys.key, keys.answer_topic, answer);
|
|
3275
|
+
const answer = buildAnswer({ code, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_pk: k.pk, prekeys: null, ...(pub && { iat: now }) });
|
|
3276
|
+
const keys = pub ? publicKeys(code.secret) : inviteKeys(code.secret), frame = seal(KIND.invite_answer, keys.key, keys.answer_topic, answer);
|
|
2695
3277
|
// Checked before anything is stored: the relay would refuse it (quota_storage).
|
|
2696
3278
|
if (frame.length > INVITE_BYTES) fail('too_large', `the answer is ${frame.length} bytes, more than an invite topic holds (${INVITE_BYTES}): this agent's chain is too long`);
|
|
2697
3279
|
const id = answerId(answer);
|
|
2698
3280
|
// Unnamed: the code's DID's first digits ("z5esAbCd"), as operators shorten a DID. Named, the
|
|
2699
3281
|
// name also replaces a known contact's on a re-pair (#onReply).
|
|
2700
|
-
|
|
2701
|
-
const
|
|
2702
|
-
|
|
3282
|
+
// A public code's request lives REQUEST_TTL at most (its reply topic's life), on its own topic.
|
|
3283
|
+
const until = pub ? Math.min(code.exp, now + REQUEST_TTL) : code.exp, reply = pub ? joinerKeys(code.secret, id).reply_topic : keys.reply_topic;
|
|
3284
|
+
store.addAccept(pub ? { ...code, exp: until } : code, id, name ?? code.did.slice('did:sigelo:'.length, 'did:sigelo:'.length + 8), now, hex(k.secretKey), me.current_did, name !== undefined, tier ?? null,
|
|
3285
|
+
pub ? { public: true, ...(given !== null && { words: given }) } : {});
|
|
3286
|
+
const entry = this.#queue(st, { relay: code.relay, topic: keys.answer_topic, bytes: frame, kind: KIND.invite_answer, control: 'answer', needs: [reply], exp: until });
|
|
3287
|
+
return { code, id, entry: entry.id, reply, until };
|
|
2703
3288
|
} finally { k.secretKey.fill(0); }
|
|
2704
3289
|
});
|
|
2705
3290
|
// Refused: the answer and the pending entry go, so no later connection sends or waits for them.
|
|
@@ -2709,9 +3294,8 @@ export class Carrier {
|
|
|
2709
3294
|
};
|
|
2710
3295
|
// Done early too once the reply topic or the answer is refused (a code answered before:
|
|
2711
3296
|
// mailbox_taken), not after the whole wait.
|
|
2712
|
-
const reply = inviteKeys(code.secret).reply_topic;
|
|
2713
3297
|
// And once the code expires (#lapse): the answer is dead, so --wait does not run out first.
|
|
2714
|
-
const settled = () => this.#handshakes.has(id) || this.#refusedTopics.has(reply) || Boolean(this.#results.get(entry)?.code) || this.clock() >=
|
|
3298
|
+
const settled = () => this.#handshakes.has(id) || this.#refusedTopics.has(reply) || Boolean(this.#results.get(entry)?.code) || this.clock() >= until;
|
|
2715
3299
|
try { await this.#session([code.relay], { max: wait * 1000, until: settled }, started); } catch (e) {
|
|
2716
3300
|
// A relay other than this agent's own that refuses it for good would be dialled again at
|
|
2717
3301
|
// every connection, until the code expires, for an answer it never takes: and a stranger's
|
|
@@ -2745,33 +3329,193 @@ export class Carrier {
|
|
|
2745
3329
|
// The code expired during the wait: #lapse emitted pairing_failed (onEvent); the refusal says
|
|
2746
3330
|
// it here, so the next inbox does not say it again. No long code to keep (keepLong): it is dead.
|
|
2747
3331
|
const lapsed = this.#locked(({ now, store, st }) => {
|
|
2748
|
-
if (now <
|
|
3332
|
+
if (now < until) return null;
|
|
2749
3333
|
st.pending = st.pending.filter((p) => p.id !== entry); store.take('accepts', id, now);
|
|
2750
|
-
const at = new Date(
|
|
3334
|
+
const at = new Date(until * 1000).toISOString().replace('.000', '');
|
|
2751
3335
|
const i = st.events.findIndex((e) => e.type === 'pairing_failed' && e.code === 'code_expired' && e.did === code.did && e.detail?.includes(at));
|
|
2752
3336
|
return i >= 0 ? st.events.splice(i, 1)[0].detail : `the code expired at ${at} before the inviter's agent replied: ask the inviter for a new code`;
|
|
2753
3337
|
});
|
|
2754
3338
|
if (lapsed) throw Object.assign(new MsgError('code_expired', lapsed), { lapsed: true });
|
|
3339
|
+
if (sent && code.version === PUBLIC_VERSION) return { status: 'waiting_approval', did: code.did, relay: code.relay, exp: until, words_given: given,
|
|
3340
|
+
detail: 'sent: the inviter accepts each new chat; if not within 7 days, this request ends (inbox then says so)' };
|
|
2755
3341
|
if (!sent) return { status: 'pending', did: code.did, relay: code.relay, detail: 'the answer has not reached the relay yet: it goes at the next connection' };
|
|
2756
3342
|
return { status: 'waiting', did: code.did, relay: code.relay, detail: 'answer delivered; the pairing completes when the inviter\'s agent next connects' };
|
|
2757
3343
|
}
|
|
2758
3344
|
|
|
3345
|
+
// A public code (sigelo-public/0, design/public-invite.md): a version 2 long code parked at the
|
|
3346
|
+
// relay under a PUB code, for months (ttl up to PUBLIC_TTL_MAX), by an identity on Pro (the relay
|
|
3347
|
+
// refuses public_pro otherwise). Its answer topic is claimed first. cap: new chats a day (the
|
|
3348
|
+
// relay's and this agent's: PUBLIC_CAP); open: approved at once, no request (an agent service
|
|
3349
|
+
// with its own doorman). → { id, name, code, short, words, link, exp, relay, cap, open, did }.
|
|
3350
|
+
async invitePublic({ name, ttl = 183 * DAY, cap = PUBLIC_CAP, open = false, relay, started } = {}) {
|
|
3351
|
+
const at = relay === undefined ? this.relay : relayArg(relay);
|
|
3352
|
+
checkCap(cap);
|
|
3353
|
+
if (!Number.isSafeInteger(ttl) || ttl < DAY || ttl > PUBLIC_TTL_MAX) fail('ttl', `a public code lives a day to a year (${PUBLIC_TTL_MAX} s), not ${JSON.stringify(ttl)}`);
|
|
3354
|
+
if (name !== undefined && typeof name !== 'string') fail('name', 'a string');
|
|
3355
|
+
const { code, words } = this.#locked(({ now, me, store }) => {
|
|
3356
|
+
const code = makeInvite({ did: me.current_did, relay: at, now, ttl, version: PUBLIC_VERSION }), words = didWords(me.did);
|
|
3357
|
+
store.addPublic(code, { name: name ?? `public-${code.nonce.slice(1, 7)}`, cap, open, words }, now);
|
|
3358
|
+
return { code, words };
|
|
3359
|
+
});
|
|
3360
|
+
const drop = () => { try { this.#locked(({ store }) => store.dropPublic(code.nonce)); } catch {} this.#routes = new Map(); };
|
|
3361
|
+
const t = publicKeys(code.secret).answer_topic;
|
|
3362
|
+
try {
|
|
3363
|
+
this.#routes = new Map();
|
|
3364
|
+
await this.#session([at], {}, started);
|
|
3365
|
+
if (!this.#claimed.has(t)) {
|
|
3366
|
+
const r = this.#refusedTopics.get(t);
|
|
3367
|
+
fail(r?.code ?? 'subscribe', `the relay did not let this agent claim the public code's answer topic${r ? ` (${relaySays(r.detail)})` : ''}`);
|
|
3368
|
+
}
|
|
3369
|
+
const pub = formatPub(makeShort(undefined, at === this.shortRelay ? null : relayTag(at))), ep = endpointOf(at, this.endpoints);
|
|
3370
|
+
const creds = await this.#credentials(at, ep, started);
|
|
3371
|
+
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: publicHash(pub), invite: code.text, exp: code.exp, cap }) });
|
|
3372
|
+
const check = typeof r.body?.check === 'string' ? r.body.check : null;
|
|
3373
|
+
if (r.status === 429) refuse('rate', `the relay ${at} parks no more codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to an hour')}`, r);
|
|
3374
|
+
if ((r.status === 404 || r.status === 405) && check === null) refuse('park', `the relay ${at} takes no public codes`, r);
|
|
3375
|
+
if (r.status !== 200) refuse('connect', `${at}: ${statusWhy(r, 'POST /park')}`, r);
|
|
3376
|
+
if (check === 'public_pro') refuse('public_pro', `a public code comes with Pro: one allowance for all your agents (sigelo.io/pro.html; relay: ${relaySays(r.body?.detail)})`, r);
|
|
3377
|
+
if (r.body?.ok !== true) refuse(PARK_CHECKS.has(check) ? check : 'park', `the relay refused the public code (${relaySays(`${check}: ${r.body?.detail}`)})${check === 'park' ? ': an older relay takes no public codes' : ''}`, r);
|
|
3378
|
+
const held = Number.isSafeInteger(r.body.exp) && r.body.exp > 0 ? r.body.exp : code.exp;
|
|
3379
|
+
this.#locked(({ store }) => { const p = store.load().s.publics[code.nonce]; p.short = pub; store.save(); });
|
|
3380
|
+
const n = this.#read(({ store }) => store.load().s.publics[code.nonce].name);
|
|
3381
|
+
return { id: code.nonce, name: n, code: code.text, short: pub, words, link: publicLink(pub, words), exp: held, relay: at, cap, open: open === true, did: code.did };
|
|
3382
|
+
} catch (e) { drop(); throw e; }
|
|
3383
|
+
}
|
|
3384
|
+
|
|
3385
|
+
/** This agent's public codes, with their requests waiting: contacts().publics. */
|
|
3386
|
+
publics() { return this.#read(({ now, store }) => Object.entries(store.load().s.publics ?? {}).map(([n, p]) => publicView(n, p, now))); }
|
|
3387
|
+
|
|
3388
|
+
// The owner approves a request (by its id: the answer id), at once: the reply goes at this
|
|
3389
|
+
// session (queued if the relay cannot be reached). → { approved: true, did, name, fingerprint, queued? }.
|
|
3390
|
+
async approvePublic(id, { started } = {}) {
|
|
3391
|
+
let out;
|
|
3392
|
+
try {
|
|
3393
|
+
out = this.#locked((ctx) => {
|
|
3394
|
+
const f = ctx.store.findRequest(id) ?? fail('challenge_unknown', `no request waits with id ${JSON.stringify(id)}: approved, refused or ended`);
|
|
3395
|
+
if (f[2].exp <= ctx.now) fail('challenge_expired', 'this request is older than 7 days: the joiner\'s agent has given it up');
|
|
3396
|
+
return { relay: f[1].relay, events: this.#approve(ctx, f[0], f[2]) };
|
|
3397
|
+
});
|
|
3398
|
+
} catch (e) {
|
|
3399
|
+
// A request that cannot be approved (revoked since, too old) goes.
|
|
3400
|
+
if (e instanceof MsgError && e.check !== 'challenge_unknown' && !INTERNAL.has(e.check)) {
|
|
3401
|
+
try { this.#locked(({ store }) => { const f = store.findRequest(id); if (f) { delete f[1].requests[id]; store.save(); } }); } catch {}
|
|
3402
|
+
}
|
|
3403
|
+
throw e;
|
|
3404
|
+
}
|
|
3405
|
+
for (const e of out.events) this.#emit(e);
|
|
3406
|
+
const paired = out.events.find((e) => e.type === 'paired');
|
|
3407
|
+
if (!paired) { const f = out.events[0]; fail(f?.code ?? 'pairing', f?.detail ?? 'not paired'); }
|
|
3408
|
+
const base = { approved: true, did: paired.did, name: paired.name, fingerprint: paired.fingerprint };
|
|
3409
|
+
try { await this.#session([out.relay], {}, started); } catch (e) { return { ...base, queued: true, detail: `${reason(e)}: the reply goes at the next connection` }; }
|
|
3410
|
+
return base;
|
|
3411
|
+
}
|
|
3412
|
+
|
|
3413
|
+
/** The owner refuses a request: dropped, the joiner told nothing (its request ends after 7 days). */
|
|
3414
|
+
refusePublic(id) {
|
|
3415
|
+
return this.#locked(({ store }) => {
|
|
3416
|
+
const f = store.findRequest(id) ?? fail('challenge_unknown', `no request waits with id ${JSON.stringify(id)}`);
|
|
3417
|
+
delete f[1].requests[id];
|
|
3418
|
+
store.save();
|
|
3419
|
+
return { refused: true, did: f[2].did };
|
|
3420
|
+
});
|
|
3421
|
+
}
|
|
3422
|
+
|
|
3423
|
+
// Pause, Resume and the cap of a public code (its id, or its PUB code), at the relay (POST
|
|
3424
|
+
// /park/<hash>) and here. → the code's view.
|
|
3425
|
+
async setPublic(key, { paused, cap } = {}, { started } = {}) {
|
|
3426
|
+
if (paused !== undefined && typeof paused !== 'boolean') fail('paused', 'true or false');
|
|
3427
|
+
if (cap !== undefined) checkCap(cap);
|
|
3428
|
+
if (paused === undefined && cap === undefined) fail('public', 'paused or cap');
|
|
3429
|
+
const k = typeof key === 'string' && isPub(key) ? formatPub(normalisePub(key)) : key;
|
|
3430
|
+
const [nonce, p] = this.#read(({ store }) => store.findPublic(k)) ?? fail('challenge_unknown', 'no public code of this agent with this id or code');
|
|
3431
|
+
if (p.short === null) fail('challenge_unknown', 'this public code was never parked');
|
|
3432
|
+
const ep = endpointOf(p.relay, this.endpoints), creds = await this.#credentials(p.relay, ep, started);
|
|
3433
|
+
const r = await http(this.platform, `${ep.http}/park/${publicHash(p.short)}`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password, ...(paused !== undefined && { paused }), ...(cap !== undefined && { cap }) }) });
|
|
3434
|
+
if (r.status === 429) refuse('rate', `the relay ${p.relay} takes no more requests from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to 10 minutes')}`, r);
|
|
3435
|
+
if (r.status === 404 && r.body?.check === 'park_unknown') refuse('park_unknown', `the relay ${p.relay} holds no such public code of yours (revoked or ended)`, r);
|
|
3436
|
+
if (r.status !== 200 || r.body?.ok !== true) refuse(typeof r.body?.check === 'string' ? r.body.check : 'connect', `${p.relay}: ${r.status === 200 ? relaySays(`${r.body?.check}: ${r.body?.detail}`) : statusWhy(r, 'POST /park/<hash>')}`, r);
|
|
3437
|
+
return this.#locked(({ now, store }) => {
|
|
3438
|
+
const q = store.load().s.publics[nonce];
|
|
3439
|
+
q.paused = r.body.paused === true; q.cap = r.body.cap ?? q.cap;
|
|
3440
|
+
store.save();
|
|
3441
|
+
return publicView(nonce, q, now);
|
|
3442
|
+
});
|
|
3443
|
+
}
|
|
3444
|
+
|
|
2759
3445
|
// An invite this agent made and nobody has answered, withdrawn: code, its long code (invite's
|
|
2760
|
-
// `code`)
|
|
2761
|
-
//
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
3446
|
+
// `code`), its short code, or the short code's hash (64 hex digits). Its answer topic is given up
|
|
3447
|
+
// at the next round; the short code parked for it is cancelled at the relay (DELETE /park/<hash>,
|
|
3448
|
+
// relay/park.mjs: a tombstone until its exp), at `relay` when named, else where it was parked. A
|
|
3449
|
+
// relay that cannot be told (older, offline, rate) leaves it to run out there: it leads to nothing,
|
|
3450
|
+
// the invite being gone here. A short code or hash this agent keeps no invite for (made on another
|
|
3451
|
+
// device of this identity) is cancelled at the relay only. A renewing code's series ends with it.
|
|
3452
|
+
// → { cancelled: true, name, short?, unparked?, detail? }.
|
|
3453
|
+
async cancelInvite(code, { relay: named, started } = {}) {
|
|
3454
|
+
const text = stripEnrol(typeof code === 'string' ? code.trim() : '');
|
|
3455
|
+
// A public code (its id, PUB code, sgl2 code or hash): Revoke for all (public.mjs).
|
|
3456
|
+
const pkey = isPub(text) ? formatPub(normalisePub(text)) : text.startsWith('sgl2') ? (() => { try { return parsePublicCode(text, checkNow(this.clock())).nonce; } catch { return null; } })() : text;
|
|
3457
|
+
const pub = pkey ? this.#read(({ store }) => store.findPublic(pkey, (sh) => publicHash(sh))) : null;
|
|
3458
|
+
if (pub) return this.#revokePublic(pub[0], pub[1], started);
|
|
3459
|
+
const hash = /^[0-9a-f]{64}$/.test(text) ? text : null, kind = hash !== null ? 'hash' : codeKind(text);
|
|
3460
|
+
const short = kind === 'short' ? formatShort(normaliseShort(text)) : null;
|
|
3461
|
+
const found = this.#locked(({ now, store }) => {
|
|
3462
|
+
const inv = store.load().s.invites;
|
|
3463
|
+
const nonce = kind === 'long' ? readCode(text, now).nonce
|
|
3464
|
+
: Object.keys(inv).find((n) => typeof inv[n].short === 'string' && (short !== null ? inv[n].short === short : codeHash(inv[n].short) === hash));
|
|
3465
|
+
if (nonce === undefined) return null;
|
|
3466
|
+
const p = inv[nonce] ?? fail('challenge_unknown', 'no pending invite with this nonce');
|
|
3467
|
+
store.cancelInvite(nonce);
|
|
3468
|
+
return { name: p.name, relay: p.relay, short: p.short ?? null, short_exp: p.short_exp ?? 0, now };
|
|
2767
3469
|
});
|
|
3470
|
+
if (found) {
|
|
3471
|
+
this.#routes = new Map();
|
|
3472
|
+
if (this.#links.get(found.relay)?.up) this.#refreshSoon(found.relay);
|
|
3473
|
+
}
|
|
3474
|
+
const shown = found?.short ?? short;
|
|
3475
|
+
if (shown === null && hash === null) return { cancelled: true, name: found.name };
|
|
3476
|
+
if (found && !(found.short_exp > found.now)) return { cancelled: true, name: found.name, short: found.short, unparked: true };
|
|
3477
|
+
const at = named !== undefined ? relayArg(named) : found ? found.relay : short !== null ? (await this.relayForShort(short)).relay : this.relay;
|
|
3478
|
+
const r = await this.#unparkCancel(at, hash ?? codeHash(shown), started);
|
|
3479
|
+
if (!found && !r.unparked) throw new MsgError(r.check ?? 'challenge_unknown', r.detail);
|
|
3480
|
+
if (!found && r.gone) fail('challenge_unknown', `${shown ?? 'that hash'}: no code of yours waits at ${at} (used, run out, or made elsewhere)`);
|
|
3481
|
+
return { cancelled: true, name: found?.name ?? null, ...(shown !== null && { short: shown }), unparked: r.unparked, ...(r.detail && { detail: r.detail }) };
|
|
3482
|
+
}
|
|
3483
|
+
|
|
3484
|
+
// Revoke for all: the relay's tombstone (DELETE /park/<hash>), then the code goes here with its
|
|
3485
|
+
// waiting requests, and its answer topic is given up at the next round. Pairings made stay.
|
|
3486
|
+
async #revokePublic(nonce, p, started) {
|
|
3487
|
+
const r = p.short !== null ? await this.#unparkCancel(p.relay, publicHash(p.short), started) : { unparked: true };
|
|
3488
|
+
this.#locked(({ store }) => store.dropPublic(nonce));
|
|
2768
3489
|
this.#routes = new Map();
|
|
2769
|
-
if (this.#links.get(relay)?.up) this.#refreshSoon(relay);
|
|
2770
|
-
return { cancelled: true, name };
|
|
3490
|
+
if (this.#links.get(p.relay)?.up) this.#refreshSoon(p.relay);
|
|
3491
|
+
return { cancelled: true, name: p.name, public: true, ...(p.short && { short: p.short }), unparked: r.unparked, ...(r.detail && { detail: r.detail }) };
|
|
3492
|
+
}
|
|
3493
|
+
|
|
3494
|
+
// DELETE /park/<hash> with a login of its own (as invite's POST /park). → { unparked, gone?, check?, detail? };
|
|
3495
|
+
// never throws: the invite is gone here whatever the relay says.
|
|
3496
|
+
async #unparkCancel(relay, hash, started) {
|
|
3497
|
+
try {
|
|
3498
|
+
const ep = endpointOf(relay, this.endpoints), creds = await this.#credentials(relay, ep, started);
|
|
3499
|
+
const r = await http(this.platform, `${ep.http}/park/${hash}`, { method: 'DELETE', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password }) });
|
|
3500
|
+
const check = typeof r.body?.check === 'string' ? r.body.check : null;
|
|
3501
|
+
if (r.status === 200 && r.body?.ok === true) return { unparked: true };
|
|
3502
|
+
// Nobody can fetch it there: run out, or used and run out.
|
|
3503
|
+
if (r.status === 404 && check === 'park_unknown') return { unparked: true, gone: true };
|
|
3504
|
+
const later = 'it runs out there by itself; any answer to it is refused here';
|
|
3505
|
+
if ((r.status === 404 || r.status === 405) && check === null) return { unparked: false, check: 'park', detail: `the relay ${relay} cannot cancel a short code (an older relay): ${later}` };
|
|
3506
|
+
if (r.status === 429) return { unparked: false, check: 'rate', detail: `the relay ${relay} takes no more short-code requests from this network for now (${relaySays(r.body?.detail)}): ${later}` };
|
|
3507
|
+
return { unparked: false, check: check ?? 'connect', detail: `the relay ${relay} did not cancel the short code (${r.status === 200 ? relaySays(`${check}: ${r.body?.detail}`) : statusWhy(r, 'DELETE /park')}): ${later}` };
|
|
3508
|
+
} catch (e) {
|
|
3509
|
+
return { unparked: false, check: e.check ?? 'connect', detail: `${reason(e)}: the short code runs out at the relay by itself; any answer to it is refused here` };
|
|
3510
|
+
}
|
|
2771
3511
|
}
|
|
2772
3512
|
|
|
2773
3513
|
/** The owner renames a contact (a name or any DID of its chain; store.mjs rename) → { did, name }. */
|
|
2774
3514
|
rename(who, name) { return this.#locked(({ store }) => store.rename(who, name)); }
|
|
3515
|
+
/** This side's display name as it is told to new contacts (the header's "Names"), or null. */
|
|
3516
|
+
selfName() { try { return theirName(this.#selfName()); } catch { return null; } }
|
|
3517
|
+
/** This side's kind as it is told to new contacts (the header's "Kinds"): "agent", "desk", or null. */
|
|
3518
|
+
selfKind() { try { const k = this.#selfKind(); return k === 'agent' || k === 'desk' ? k : null; } catch { return null; } }
|
|
2775
3519
|
|
|
2776
3520
|
contacts() {
|
|
2777
3521
|
return this.#read(({ now, store, st }) => {
|
|
@@ -2783,18 +3527,29 @@ export class Carrier {
|
|
|
2783
3527
|
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,
|
|
2784
3528
|
prekeys: pair !== null && theirPrekeys(c, e?.session, pair, now), waiting: e?.waiting ?? null, link: c.link ?? null,
|
|
2785
3529
|
// 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
|
|
3530
|
+
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,
|
|
3531
|
+
seen_upto: e?.seen_upto ?? null, seen_peer: e?.seen_peer === true,
|
|
3532
|
+
busy: (e?.busy_until ?? 0) > now, busy_n: (e?.busy_until ?? 0) > now ? (e?.busy_n ?? 1) : 0, busy_peer: e?.busy_peer === true, host_peer: e?.host_peer === true, via: c.via ?? null, name_from: c.name_from ?? null,
|
|
3533
|
+
kind_peer: e?.kind_peer ?? null };
|
|
2787
3534
|
}),
|
|
2788
|
-
invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay
|
|
3535
|
+
invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay,
|
|
3536
|
+
...(typeof p.short === 'string' && { short: p.short, short_exp: p.short_exp }), ...(p.renew && { renew: p.renew }) })),
|
|
3537
|
+
// Renewing codes (store.mjs renew): each series, its codes used, and why its last renewal failed (null: none).
|
|
3538
|
+
renewing: Object.entries(s.renew ?? {}).map(([id, x]) => ({ id, name: x.name, used: x.used, error: x.error ?? null })),
|
|
2789
3539
|
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 })),
|
|
3540
|
+
// Public codes of mine (public.mjs), with the requests waiting for approval.
|
|
3541
|
+
publics: Object.entries(s.publics ?? {}).filter(([, p]) => p.exp > now).map(([n, p]) => publicView(n, p, now)),
|
|
2790
3542
|
// Pairings that failed since the last inbox, which takes them as events.
|
|
2791
3543
|
failed: st.events.filter((e) => e.type === 'pairing_failed').map(({ name, did, code, detail, at }) => ({ name, did, code, detail, at })),
|
|
2792
3544
|
};
|
|
2793
3545
|
});
|
|
2794
3546
|
}
|
|
2795
3547
|
|
|
2796
|
-
|
|
2797
|
-
|
|
3548
|
+
// expires (unix seconds, optional): past it the message is dropped from the outbox unsent (refused
|
|
3549
|
+
// `expired`): a remote control's request or pushed state is worth minutes (apps/contact/control.mjs TTL).
|
|
3550
|
+
async send(to, content, { label = '', local = false, internal, expires } = {}) {
|
|
3551
|
+
if (expires !== undefined && !Number.isSafeInteger(expires)) fail('body', 'expires: unix seconds');
|
|
3552
|
+
const [r] = await this.#sendAll(to, [content], label, false, local, internal, expires);
|
|
2798
3553
|
// side: whose quota a quota_storage is (relay/allowance.mjs), on the error too.
|
|
2799
3554
|
if (r.status === 'refused') throw Object.assign(new MsgError(r.code, `refused (${r.detail})`), r.side && { side: r.side });
|
|
2800
3555
|
return r;
|
|
@@ -2805,14 +3560,63 @@ export class Carrier {
|
|
|
2805
3560
|
// the contact's claim on the topic; queued: it goes at the next connection.
|
|
2806
3561
|
async sendAll(to, contents, { label = '', local = false } = {}) { return this.#sendAll(to, contents, label, false, local); }
|
|
2807
3562
|
|
|
3563
|
+
// A seen receipt (the header's "Seen receipts"): every message of to's sealed at or before upto was shown.
|
|
3564
|
+
async seen(to, upto, { local = false } = {}) {
|
|
3565
|
+
if (!Number.isSafeInteger(upto) || upto < 0) fail('body', 'upto: unix seconds, 0 for none yet');
|
|
3566
|
+
return this.send(to, { seen: upto, busy: true, host: true }, { label: SEEN_LABEL, local, internal: SEEN_SEND });
|
|
3567
|
+
}
|
|
3568
|
+
|
|
3569
|
+
// A busy mark (the header's "Busy marks"): on, a turn runs for to; off, it ended. Only to a contact that
|
|
3570
|
+
// said it takes them (busy_peer), else { status: 'skipped' }; unsent past BUSY_TTL_S. n: agents running (sent when > 1).
|
|
3571
|
+
async busy(to, on, { local = false, n = 1 } = {}) {
|
|
3572
|
+
const peer = this.#read(({ store, st }) => st.peers[this.#resolve(store, to).did]?.busy_peer === true);
|
|
3573
|
+
if (!peer) return { status: 'skipped', to, detail: 'this contact never said it takes busy marks' };
|
|
3574
|
+
return this.send(to, { busy: on === true, ...(on === true && Number.isSafeInteger(n) && n > 1 && { n: Math.min(n, 99) }) }, { label: BUSY_LABEL, local, internal: BUSY_SEND, expires: this.clock() + BUSY_TTL_S });
|
|
3575
|
+
}
|
|
3576
|
+
|
|
3577
|
+
// Read marks (the header's "Seen receipts", 0.1.19): an agent's reader took these items (inbox, the MCP, a hook,
|
|
3578
|
+
// a host turn), so their senders get a seen receipt, by code, never the agent's own. Per contact the newest iat of
|
|
3579
|
+
// its direct messages (group items and ones without iat: none); once per message (the state's read_sent). An own
|
|
3580
|
+
// contact (its tier) always; anyone else as the app does: a first one, more only once theirs came (seen_peer).
|
|
3581
|
+
// → [{ to, upto, status | error }], one per receipt sent; local: queued for a started carrier elsewhere.
|
|
3582
|
+
async read(items, { local = false } = {}) {
|
|
3583
|
+
const due = this.#locked(({ now, store, st }) => {
|
|
3584
|
+
const tiers = store.tiers(now), newest = new Map(), out = [];
|
|
3585
|
+
for (const m of Array.isArray(items) ? items : []) {
|
|
3586
|
+
if (m === null || typeof m !== 'object' || typeof m.from !== 'string' || m.group !== undefined || !Number.isSafeInteger(m.iat) || m.iat <= 0) continue;
|
|
3587
|
+
newest.set(m.from, Math.max(newest.get(m.from) ?? 0, m.iat));
|
|
3588
|
+
}
|
|
3589
|
+
for (const [from, upto] of newest) {
|
|
3590
|
+
let c = null;
|
|
3591
|
+
try { c = store.lookup(from); } catch {}
|
|
3592
|
+
if (!c || c.revoked) continue;
|
|
3593
|
+
const e = this.#entry(st, c.did);
|
|
3594
|
+
if (upto <= (e.read_sent ?? 0)) continue;
|
|
3595
|
+
if (tiers.get(c.did) !== 'own' && !e.seen_peer && e.read_told) continue;
|
|
3596
|
+
e.read_sent = upto; e.read_told = true;
|
|
3597
|
+
out.push({ to: c.did, upto });
|
|
3598
|
+
}
|
|
3599
|
+
return out;
|
|
3600
|
+
});
|
|
3601
|
+
const r = [];
|
|
3602
|
+
for (const x of due) {
|
|
3603
|
+
try { r.push({ ...x, status: (await this.seen(x.to, x.upto, { local }))?.status ?? null }); } catch (e) { r.push({ ...x, error: e.message }); }
|
|
3604
|
+
}
|
|
3605
|
+
return r;
|
|
3606
|
+
}
|
|
3607
|
+
|
|
2808
3608
|
// spool: every content after the first waits on disk (#spool), as a file's chunks do. local: queued
|
|
2809
3609
|
// only, for the started carrier of this identity in another process (inbox's local, for sending).
|
|
2810
|
-
|
|
3610
|
+
// replyTo: the id of a message received (reply): its record keeps these ids, queued, in the same lock.
|
|
3611
|
+
async #sendAll(to, contents, label, spool, local = false, internal = null, expires = undefined, replyTo = null) {
|
|
2811
3612
|
if (typeof label !== 'string') fail('body', 'label must be a string');
|
|
2812
3613
|
if (label === LABEL_PREKEYS || label === OPERATOR_LABEL) fail('body', `the label ${JSON.stringify(label)} is the carrier's own`);
|
|
2813
3614
|
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
3615
|
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
3616
|
if (label.startsWith('sigelo-transfer/') && internal !== TRANSFER_SEND) fail('body', `the label ${JSON.stringify(label)} is the transfer engine's own (sigelo-agent transfer)`);
|
|
3617
|
+
if (label.startsWith('sigelo-call/') && internal !== CALL_SEND) fail('body', `the label ${JSON.stringify(label)} is the calls' own (the page's call screen)`);
|
|
3618
|
+
if (label.startsWith('sigelo-seen/') && internal !== SEEN_SEND) fail('body', `the label ${JSON.stringify(label)} is the seen receipts' own`);
|
|
3619
|
+
if (label.startsWith('sigelo-busy/') && internal !== BUSY_SEND) fail('body', `the label ${JSON.stringify(label)} is the busy marks' own`);
|
|
2816
3620
|
if (label.startsWith('sigelo-device/') && internal !== DEVICE_SEND) fail('body', `the label ${JSON.stringify(label)} is the device verbs' own (sigelo-agent device)`);
|
|
2817
3621
|
if (!Array.isArray(contents) || contents.length === 0) fail('body', 'at least one message');
|
|
2818
3622
|
for (const content of contents) {
|
|
@@ -2835,13 +3639,14 @@ export class Carrier {
|
|
|
2835
3639
|
}
|
|
2836
3640
|
});
|
|
2837
3641
|
}
|
|
2838
|
-
const { ids, c } = this.#locked(({ store, st }) => {
|
|
3642
|
+
const { ids, c } = this.#locked(({ now, store, st }) => {
|
|
2839
3643
|
const c = this.#resolve(store, to), outbox = this.#entry(st, c.did).outbox;
|
|
2840
3644
|
const ids = contents.map((content, i) => {
|
|
2841
3645
|
const id = randomId();
|
|
2842
|
-
if (spool && i > 0) { this.#spool(id, content); outbox.push({ id, label, spool: true }); } else outbox.push({ id, label, content });
|
|
3646
|
+
if (spool && i > 0) { this.#spool(id, content); outbox.push({ id, label, spool: true }); } else outbox.push({ id, label, content, ...(expires !== undefined && { exp: expires }) });
|
|
2843
3647
|
return id;
|
|
2844
3648
|
});
|
|
3649
|
+
if (replyTo !== null) received(st, replyTo, c.did, now).reply = { ids, wait: ids, status: 'queued', queued: now, label, ...(spool && { file: contents[0]?.name ?? null }) };
|
|
2845
3650
|
return { ids, c };
|
|
2846
3651
|
});
|
|
2847
3652
|
if (local) return ids.map((id) => ({ status: 'queued', id, to: c.did, name: c.name, detail: 'kept for the process that holds this identity\'s relay session: it sends it' }));
|
|
@@ -2863,7 +3668,8 @@ export class Carrier {
|
|
|
2863
3668
|
// refused, so a confused or misled agent cannot send its key (platform openPath). file: a path, or
|
|
2864
3669
|
// { bytes, name } (a page's file: no path to check). A refusal of any part throws as send does:
|
|
2865
3670
|
// the contact gets no file, and what came of it there goes at its retention.
|
|
2866
|
-
async sendFile(to, file, { local = false } = {}) {
|
|
3671
|
+
async sendFile(to, file, { local = false } = {}) { return this.#sendFile(to, file, local, null); }
|
|
3672
|
+
async #sendFile(to, file, local, replyTo) {
|
|
2867
3673
|
let bytes, leaf, what;
|
|
2868
3674
|
if (typeof file === 'string') {
|
|
2869
3675
|
if (file === '') fail('file', 'a file path is required');
|
|
@@ -2876,7 +3682,7 @@ export class Carrier {
|
|
|
2876
3682
|
} else fail('file', 'a file path is required');
|
|
2877
3683
|
if (bytes.length > MAX_FILE) fail('file_too_large', `${what} is ${bytes.length} bytes, at most ${MAX_FILE} (8 MiB) a file`);
|
|
2878
3684
|
const { manifest, chunks } = splitFile(bytes, leaf);
|
|
2879
|
-
const results = await this.#sendAll(to, [manifest, ...chunks], FILE_LABEL, true, local);
|
|
3685
|
+
const results = await this.#sendAll(to, [manifest, ...chunks], FILE_LABEL, true, local, null, undefined, replyTo);
|
|
2880
3686
|
const refused = results.find((x) => x.status === 'refused'), queued = results.find((x) => x.status === 'queued');
|
|
2881
3687
|
if (refused) fail(refused.code, `refused (${refused.detail}): ${manifest.name} did not go whole; send it again once that is settled`);
|
|
2882
3688
|
const { id, name, size, sha256: sum, chunks: n } = manifest;
|
|
@@ -2884,16 +3690,93 @@ export class Carrier {
|
|
|
2884
3690
|
...(queued && { detail: queued.detail }) };
|
|
2885
3691
|
}
|
|
2886
3692
|
|
|
3693
|
+
// ---- the agent task loop (apps/agent/WATCH.md "Accept now, reply later"): a message taken
|
|
3694
|
+
// now (a hook that spooled it, watch --spool) is answered later by its id (messageId), to its sender.
|
|
3695
|
+
|
|
3696
|
+
// The record of a message received, by id: the state's (RECEIVED_DAYS), else one still in the inbox
|
|
3697
|
+
// or in the log (an item kept by an earlier version, id derived), filed now. → the record, or throws msg_unknown.
|
|
3698
|
+
#receivedFor(id) {
|
|
3699
|
+
if (typeof id !== 'string' || !MSG_ID.test(id)) {
|
|
3700
|
+
fail(/^[0-9a-f]{16}\.[0-9a-f]{16}$/.test(String(id)) ? 'msg_group' : 'msg_id', /\./.test(String(id))
|
|
3701
|
+
? `${JSON.stringify(id)} is a group message's id: answer in the group (sigelo-agent group send <group> <text> --re <mid>)`
|
|
3702
|
+
: `a message id is 32 hex digits (SIGELO_MSG_ID, an inbox item's id), not ${JSON.stringify(id)}`);
|
|
3703
|
+
}
|
|
3704
|
+
const known = this.#read(({ st }) => st.received?.[id] ?? st.inbox.find((m) => messageId(m) === id) ?? null)
|
|
3705
|
+
?? this.history().messages.find((m) => messageId(m) === id) ?? null;
|
|
3706
|
+
if (known === null) fail('msg_unknown', `no message ${id} here: unknown, or received more than ${RECEIVED_DAYS} days ago`);
|
|
3707
|
+
return this.#locked(({ now, st }) => received(st, id, known.from, Number.isSafeInteger(known.ts) ? known.ts : known.received ?? now));
|
|
3708
|
+
}
|
|
3709
|
+
|
|
3710
|
+
/** A text (or any content send takes) to the sender of message `id` → send's result, with msg_id and delivery (replyStatus). */
|
|
3711
|
+
async reply(id, content, { label = 'reply', local = false } = {}) {
|
|
3712
|
+
const rec = this.#receivedFor(id);
|
|
3713
|
+
const [r] = await this.#sendAll(rec.from, [content], label, false, local, null, undefined, id);
|
|
3714
|
+
if (r.status === 'refused') throw Object.assign(new MsgError(r.code, `refused (${r.detail})`), r.side && { side: r.side });
|
|
3715
|
+
return { ...r, msg_id: id, delivery: this.replyStatus(id).reply };
|
|
3716
|
+
}
|
|
3717
|
+
|
|
3718
|
+
/** The label of a reply quoting received message `id` (a text): re/<h>/r (the header's "Replies"). */
|
|
3719
|
+
quote(id) {
|
|
3720
|
+
this.#receivedFor(id);
|
|
3721
|
+
const m = this.#read(({ st }) => st.inbox.find((x) => messageId(x) === id)) ?? this.history().messages.find((x) => messageId(x) === id);
|
|
3722
|
+
if (!m || typeof m.content !== 'string') fail('msg_unknown', `message ${id} is not a text here to quote (a file, or gone from the log)`);
|
|
3723
|
+
return reLabel(m.content, false);
|
|
3724
|
+
}
|
|
3725
|
+
|
|
3726
|
+
/** A file, as sendFile, to the sender of message `id` → sendFile's result, with msg_id and delivery. */
|
|
3727
|
+
async replyFile(id, file, { local = false } = {}) {
|
|
3728
|
+
const rec = this.#receivedFor(id);
|
|
3729
|
+
const r = await this.#sendFile(rec.from, file, local, id);
|
|
3730
|
+
return { ...r, msg_id: id, delivery: this.replyStatus(id).reply };
|
|
3731
|
+
}
|
|
3732
|
+
|
|
3733
|
+
/**
|
|
3734
|
+
* What is known of message `id` and the last reply to it → { msg_id, from, name, received, reply, fetched }.
|
|
3735
|
+
* reply: null, or { status: queued (here, not yet at the relay) | published (the relay holds it in the
|
|
3736
|
+
* contact's mailbox) | refused, queued_at, published_at, code, detail, parts, label, file? }. fetched:
|
|
3737
|
+
* always null: sigelo/0 has no read receipt, the relay does not tell the sender. contact: its presence
|
|
3738
|
+
* as this agent sees it ({online, last_seen}, when the contact lets it see), a hint only.
|
|
3739
|
+
*/
|
|
3740
|
+
replyStatus(id) {
|
|
3741
|
+
this.#receivedFor(id);
|
|
3742
|
+
return this.#read(({ store, st }) => {
|
|
3743
|
+
const rec = st.received[id], c = store.lookup(rec.from), r = rec.reply ?? null, p = st.presence?.[rec.from];
|
|
3744
|
+
return {
|
|
3745
|
+
msg_id: id, from: rec.from, name: c?.name ?? null, received: rec.ts,
|
|
3746
|
+
reply: r && { status: r.status, queued_at: r.queued, published_at: r.published ?? null, code: r.code ?? null, detail: r.detail ?? null, parts: r.ids.length, label: r.label,
|
|
3747
|
+
...(r.file !== undefined && { file: r.file }) },
|
|
3748
|
+
fetched: null,
|
|
3749
|
+
...(p && { contact: { online: p.online, last_seen: p.last_seen ?? null } }),
|
|
3750
|
+
};
|
|
3751
|
+
});
|
|
3752
|
+
}
|
|
3753
|
+
|
|
3754
|
+
// A reply's part `id` went (published), or the relay or this carrier refused it: its record says so.
|
|
3755
|
+
#replyMark(st, id, now, refused = null) {
|
|
3756
|
+
for (const rec of Object.values(st.received ?? {})) {
|
|
3757
|
+
const r = rec.reply;
|
|
3758
|
+
if (!r?.wait?.includes(id)) continue;
|
|
3759
|
+
if (refused) Object.assign(r, { status: 'refused', code: refused.code, detail: refused.detail, wait: [] });
|
|
3760
|
+
else {
|
|
3761
|
+
r.wait = r.wait.filter((x) => x !== id);
|
|
3762
|
+
if (r.wait.length === 0 && r.status === 'queued') Object.assign(r, { status: 'published', published: now });
|
|
3763
|
+
}
|
|
3764
|
+
return;
|
|
3765
|
+
}
|
|
3766
|
+
}
|
|
3767
|
+
|
|
2887
3768
|
// tiers: only messages from contacts of these tiers are taken (and waited for); the rest stay for a
|
|
2888
3769
|
// later inbox. Events are all taken. local: no session: what the state file holds, waited for by
|
|
2889
3770
|
// reading it again, for a reader beside a started carrier of the same identity (a watcher), which
|
|
2890
|
-
// a session here would disconnect.
|
|
2891
|
-
|
|
3771
|
+
// a session here would disconnect. from: only that contact's messages (its original DID), the
|
|
3772
|
+
// rest stay (MCP sigelo_wait_for_message).
|
|
3773
|
+
async inbox({ wait = 0, tiers, local = false, paired = false, from } = {}) {
|
|
2892
3774
|
const want = tiers === undefined ? null : new Set(tiers);
|
|
2893
3775
|
if (want && ![...want].every((t) => TIERS.includes(t))) fail('tier', `tiers: some of ${TIERS.join(', ')}`);
|
|
2894
|
-
|
|
3776
|
+
if (from !== undefined && typeof from !== 'string') fail('body', 'from: a contact\'s DID');
|
|
3777
|
+
const picks = (store, now) => { const t = want && store.tiers(now); return (m) => (from === undefined || m.from === from) && (!want || want.has(t.get(m.from) ?? 'friend')); };
|
|
2895
3778
|
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')));
|
|
2896
|
-
let offline = null;
|
|
3779
|
+
let offline = null, ended = null;
|
|
2897
3780
|
if (local) {
|
|
2898
3781
|
for (const end = Date.now() + wait * 1000; Date.now() < end && !ready();) await sleep(250);
|
|
2899
3782
|
} else {
|
|
@@ -2903,12 +3786,15 @@ export class Carrier {
|
|
|
2903
3786
|
try {
|
|
2904
3787
|
await this.#session(relays, wait > 0 ? { max: wait * 1000, until: ready } : {});
|
|
2905
3788
|
} catch (e) { this.lastError = e; offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
|
|
3789
|
+
ended = this.ended;
|
|
3790
|
+
// A renewing code this session took: its fresh one now, before the events go out.
|
|
3791
|
+
if (offline === null) await this.#renewDue();
|
|
2906
3792
|
}
|
|
2907
3793
|
return this.#locked(({ now, store, st }) => {
|
|
2908
3794
|
this.#sweepFiles(st, now);
|
|
2909
3795
|
const pick = picks(store, now), messages = st.inbox.filter(pick);
|
|
2910
3796
|
this.#logOut(messages);
|
|
2911
|
-
const out = { messages, events: st.events, dropped: st.dropped, ...(offline && { offline }) };
|
|
3797
|
+
const out = { messages: messages.map((m) => (reOf(m?.label) ? { ...m, re: reOf(m.label) } : m)), events: st.events, dropped: st.dropped, ...(offline && { offline }), ...(ended && { ended }) };
|
|
2912
3798
|
st.inbox = st.inbox.filter((m) => !pick(m)); st.events = []; st.dropped = {};
|
|
2913
3799
|
return out;
|
|
2914
3800
|
});
|
|
@@ -2958,6 +3844,7 @@ export class Carrier {
|
|
|
2958
3844
|
takeGroups() { return this.#locked(({ st }) => { const l = st.groups ?? []; st.groups = []; return l; }); }
|
|
2959
3845
|
takeDevices() { return this.#locked(({ st }) => { const l = st.devices ?? []; st.devices = []; return l; }); }
|
|
2960
3846
|
// pick(message) → take it (default all); the rest stay for a later take (an engine's).
|
|
3847
|
+
takeCalls(pick = () => true) { const took = this.#calls.filter((m) => pick(m)); this.#calls = this.#calls.filter((m) => !took.includes(m)); return took; }
|
|
2961
3848
|
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
3849
|
// A file a transfer saved whole (transfer-node.mjs): an inbox item as #onFile makes one, kept for
|
|
2963
3850
|
// inbox() (keep) and handed to onEvent. item: { type: 'file', from, contact, name, size, sha256, path, … }.
|
|
@@ -3042,11 +3929,13 @@ export class Carrier {
|
|
|
3042
3929
|
for (const r of this.#relaysInUse()) this.#retry(r, 0, started);
|
|
3043
3930
|
this.#tick = setInterval(() => this.#round(), this.tick);
|
|
3044
3931
|
this.#tick.unref?.();
|
|
3932
|
+
this.#renewSoon();
|
|
3045
3933
|
}
|
|
3046
3934
|
|
|
3047
3935
|
// force (sync, the caller's): a relay waiting for its next automatic try (#powWait) is tried now too.
|
|
3048
3936
|
#round(force = false) {
|
|
3049
3937
|
this.#later(() => this.#locked((ctx) => this.#expireKeys(ctx)));
|
|
3938
|
+
this.#renewSoon();
|
|
3050
3939
|
for (const l of this.#links.values()) l.absent.clear(); // an absent contact may be back: try once more
|
|
3051
3940
|
for (const r of this.#relaysInUse()) {
|
|
3052
3941
|
if (force) this.#unwait(r);
|
|
@@ -3057,8 +3946,9 @@ export class Carrier {
|
|
|
3057
3946
|
|
|
3058
3947
|
/** One round now (claims for a new week, queued messages), then wait as `inbox` does. */
|
|
3059
3948
|
async sync({ wait = 0 } = {}) {
|
|
3060
|
-
if (this.#started) { this.#round(true); await this.#idle({ max: Math.max(DRAIN, wait * 1000) }); return; }
|
|
3949
|
+
if (this.#started) { this.#round(true); await this.#idle({ max: Math.max(DRAIN, wait * 1000) }); await this.#renewDue(); return; }
|
|
3061
3950
|
await this.#session(this.#relaysInUse(), { max: Math.max(DRAIN, wait * 1000) });
|
|
3951
|
+
await this.#renewDue();
|
|
3062
3952
|
}
|
|
3063
3953
|
|
|
3064
3954
|
#unwait(relay) {
|
|
@@ -3067,6 +3957,17 @@ export class Carrier {
|
|
|
3067
3957
|
this.#timers.delete(relay);
|
|
3068
3958
|
}
|
|
3069
3959
|
|
|
3960
|
+
/** A nudge from outside (the phone woke): each relay in use down and not already waiting, a retry with the backoff; automatic (no proof-of-work confirmation). */
|
|
3961
|
+
// now (a push wake: mail waits at the relay): at once, past a backoff's wait already set.
|
|
3962
|
+
wake({ now = false } = {}) {
|
|
3963
|
+
if (!this.#started) return;
|
|
3964
|
+
for (const r of this.#relaysInUse()) {
|
|
3965
|
+
if (this.#links.get(r)?.up || this.#connecting.has(r)) continue;
|
|
3966
|
+
if (now && this.#timers.has(r) && !this.#powWaits.has(r)) { clearTimeout(this.#timers.get(r)); this.#timers.delete(r); }
|
|
3967
|
+
if (!this.#timers.has(r)) this.#retry(r, now ? 0 : undefined);
|
|
3968
|
+
}
|
|
3969
|
+
}
|
|
3970
|
+
|
|
3070
3971
|
/**
|
|
3071
3972
|
* The human's "Try now" (design/profiles.md §6): a login now at each relay in use that is not
|
|
3072
3973
|
* connected, as a search they started: past the day's POW_SEARCHES it throws pow_confirm, and
|