sigelo-contact 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/carrier.mjs CHANGED
@@ -4,9 +4,11 @@
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 })
7
- // await c.invite({ name, ttl }) → { code, did, relay, exp } the answer topic is claimed first
8
- // await c.accept(code, { name, wait }) → { status: 'connected' | 'waiting' | 'pending', … }
9
- // c.contacts() → { contacts, invites, answers }
7
+ // await c.invite({ name, ttl, short }) → { code, did, relay, exp, short?, short_exp? } the answer topic is claimed first;
8
+ // short: the long code is also parked at the relay under a short one
9
+ // await c.unpark(short) → the long code parked under a short one, taken from the relay (one use)
10
+ // await c.accept(code, { name, wait }) → { status: 'connected' | 'waiting' | 'pending', … } a long code or a short one
11
+ // c.contacts() → { contacts, invites, answers } each contact with its four words (fingerprint)
10
12
  // await c.send(to, content, { label }) → { status: 'sent' | 'queued', … }, or throws the relay's code
11
13
  // await c.sendAll(to, contents, { label }) → one result each ('refused' with its code), one login
12
14
  // await c.inbox({ wait }) → { messages, events, dropped, offline? }: all are taken (messages: those kept)
@@ -103,15 +105,32 @@
103
105
  // invite and accept replace K and clear the mark (store.admit writes the record afresh). A
104
106
  // contact on sigelo-contact 0.1.2 follows the recovery but marks nothing and keeps writing
105
107
  // under K, to weeks nobody may read but a thief: the recovered side pairs again at once.
108
+ // - Recovery beats key, for messages too: a contact's envelope signed by a DID that a recovery
109
+ // this agent follows has overruled (any DID of the contact's chain up to the node recovered
110
+ // from, or on a fork the recovery left) is refused, and noted (`refused`, code re_pair, `from`
111
+ // the contact): it may be the thief's. The relay delivers in the order written, so a thief's
112
+ // messages written before the owner recovered arrive before the recovery's notice, and were
113
+ // taken as the contact's. So a notice that brings a recovery checks again every message of
114
+ // that contact still waiting for inbox() against the chain it ends at (the recovery is not
115
+ // taken first: the relay alone decides what comes when), and one that arrives after it fails
116
+ // `from`, reported as re_pair. A message signed by the recovered-from key before the theft
117
+ // cannot be told from the thief's: refused alike; the owner writes again once paired again.
118
+ // What an earlier inbox() returned, or onEvent got, cannot be taken back: the `rotated` event
119
+ // of such a notice lists the DIDs it overruled (`overruled`).
106
120
  // - Mailboxes: an agent holds the topics of every ISO week from `retention` ago to AHEAD (7 days,
107
121
  // or its retention if shorter) ahead. The relay drops a publish to a topic nobody claimed (and
108
122
  // says no_reader), so next week's topic must be claimed before a contact writes in it while
109
- // this agent is offline. A no_reader refuses that message, and everything else to that contact
110
- // until the next round, unsealed: no epoch is begun, and no prekey spent, for a contact away
111
- // that long. Free tier: 7 days, 3 weeks (4 within 5 minutes of Monday 00:00 UTC), so 3 or 4
112
- // mailboxes per contact; Pro's 90 days: 14 or 15 (relay/allowance.mjs counts 15). A Pro
113
- // reader away longer than a week is told nothing of contacts writing in a week it did not
114
- // claim: they get no_reader and send later. A Pro reader must say its 90 days
123
+ // this agent is offline. An invitee's mailbox cannot be claimed before it reads the inviter's
124
+ // reply (the topic needs K, which the reply carries), so the inviter's first frames to it meet
125
+ // no_reader until the invitee next connects. A no_reader never loses a message: it stays queued
126
+ // here, unsealed (its epoch restarted when it began one, its prekey given back), with
127
+ // everything else to that contact until the next round, and goes at the next connection that
128
+ // finds the mailbox held (`queued`, the reason in its detail). Free tier: 14 days, 4 weeks
129
+ // (5 within 5 minutes of Monday 00:00 UTC), so 4 or 5 mailboxes per contact; Pro's 90 days:
130
+ // 14 or 15 (relay/allowance.mjs counts 15). A reader away longer than a week is told nothing of
131
+ // contacts writing in a week it did not claim: their messages wait on their side (no_reader).
132
+ // The retention: the constructor's, else relay.json's free tier at this agent's own relay
133
+ // (read once, at the first login), else RETENTION_DAYS. A Pro reader must say its 90 days
115
134
  // (SIGELO_RELAY_RETENTION_DAYS): nothing tells the carrier its tier. A claim past its time is
116
135
  // given up only once deliveries have stopped, so what is queued on it is read first. The relay
117
136
  // brakes new claims (relay/allowance.mjs RATE.claim: 128 at once per identity, then 2 a second):
@@ -132,6 +151,7 @@ import { answerId, buildAnswer, buildReply, checkAnswer, checkReply, inviteKeys,
132
151
  import { MsgError, checkNow, fail, hex, isoWeek, pairId, topic } from './kdf.mjs';
133
152
  import { Prekeys, exact, kemDecapsulate, kemEncapsulate, kemKey } from './prekeys.mjs';
134
153
  import { Contacts } from './store.mjs';
154
+ import { SHORT_TTL, codeHash, fingerprint, formatShort, isShort, makeShort } from './short.mjs';
135
155
 
136
156
  export const V = 'sigelo-carrier/0';
137
157
  export const DEFAULT_RELAY = 'relay.sigelo.ai', MQTT_PORT = 8883, NOTICE = '$sigelo/notice';
@@ -140,7 +160,8 @@ export const LABEL_PREKEYS = 'sigelo-msg/0 prekeys', KIND_NOTICE = 4, KIND_PREKE
140
160
  // type of its own, never a SPEC §5.2 challenge: a world that passed the relay's nonce on as its own
141
161
  // challenge would get the agent's relay login back from sign-challenge.
142
162
  export const LOGIN_V = 'sigelo-relay/0', TYP_LOGIN = 'relay-login';
143
- export const RETENTION_DAYS = 7, RETENTION_MAX_DAYS = 90, DAY = 86400, SKEW = 300, AHEAD = 7 * DAY;
163
+ // RETENTION_DAYS: the relay's free tier (relay/allowance.mjs TIERS.free), when relay.json says nothing.
164
+ export const RETENTION_DAYS = 14, RETENTION_MAX_DAYS = 90, DAY = 86400, SKEW = 300, AHEAD = 7 * DAY;
144
165
  // The relay closes a connection whose SUBSCRIBE holds more topics (relay/mailbox.mjs MAX_TOPICS).
145
166
  const MAX_TOPICS = 128;
146
167
  // An invite topic holds 4 messages and 64 KB (relay/mailbox.mjs INVITE_BYTES); a bundle at most 64
@@ -238,6 +259,10 @@ const b64 = (b) => Buffer.from(b).toString('base64');
238
259
  const unb64 = (s) => new Uint8Array(Buffer.from(s, 'base64'));
239
260
  const randomId = () => hex(randomBytes(8));
240
261
  const clientIdOf = (original) => 's' + createHash('sha256').update(original, 'utf8').digest('hex').slice(0, 24);
262
+ // The four words of a pairing (short.mjs), from its pairing key as the store holds it (hex), or null.
263
+ const wordsOf = (pairKey) => (typeof pairKey === 'string' ? fingerprint(pairId(hexToBytes(pairKey))) : null);
264
+ // The refusals of POST /park this client names (relay/park.mjs, and the login's: auth.mjs).
265
+ const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', ...LOGIN_CHECKS]);
241
266
 
242
267
  // ---------------------------------------------------------------- configuration
243
268
 
@@ -281,6 +306,14 @@ export function publicRelay(relay) {
281
306
  return host.includes('.') && !IPV4_LIKE.test(host) && !LOCAL_NAME.test(host);
282
307
  }
283
308
 
309
+ const retentionOk = (n) => Number.isSafeInteger(n) && n >= 1 && n <= RETENTION_MAX_DAYS;
310
+
311
+ /** The free tier's retention in days that a relay's relay.json states (limits.free.retention_days), or null. */
312
+ export function retentionOf(info) {
313
+ const n = info?.limits?.free?.retention_days;
314
+ return retentionOk(n) ? n : null;
315
+ }
316
+
284
317
  /** SIGELO_RELAY (the relay new invites name), SIGELO_RELAY_ENDPOINTS (JSON, as endpointOf), SIGELO_RELAY_RETENTION_DAYS. */
285
318
  export function optionsFromEnv(env = process.env) {
286
319
  const o = {};
@@ -290,7 +323,7 @@ export function optionsFromEnv(env = process.env) {
290
323
  }
291
324
  if (env.SIGELO_RELAY_RETENTION_DAYS) {
292
325
  const n = Number(env.SIGELO_RELAY_RETENTION_DAYS);
293
- if (!Number.isSafeInteger(n) || n < 1 || n > RETENTION_MAX_DAYS) fail('relay', `SIGELO_RELAY_RETENTION_DAYS: whole days, 1 to ${RETENTION_MAX_DAYS} (the reader's tier)`);
326
+ if (!retentionOk(n)) fail('relay', `SIGELO_RELAY_RETENTION_DAYS: whole days, 1 to ${RETENTION_MAX_DAYS} (the reader's tier)`);
294
327
  o.retentionDays = n;
295
328
  }
296
329
  return o;
@@ -529,6 +562,18 @@ const rePairWhy = (c) => (c.re_pair === 'contact_recovery'
529
562
  ? `${c.name} recovered its identity after a theft: the pairing key may be the thief's; pair again (invite, accept) before writing`
530
563
  : `this agent recovered its identity: the pairing key with ${c.name} may be the thief's; pair again (invite, and ${c.name}'s operator accepts the code) before writing`);
531
564
 
565
+ // A re-pair keeps a known contact's name (store.admit), unless the owner named the answer
566
+ // (`accept --name`): then that name. The inviter's `invite --name` names a new contact only: the
567
+ // code may be answered by anyone, and a re-key code's name is the contact's own. → the contact.
568
+ function renamed(store, c, entry) {
569
+ if (entry.named === true && c.name !== entry.name) { c.name = entry.name; store.save(); }
570
+ return c;
571
+ }
572
+
573
+ // Why messages to a contact wait after a no_reader (the header's "Mailboxes"): its agent has not
574
+ // claimed the mailbox they go to, not this one.
575
+ const noReader = (name) => `${name}'s agent does not hold its mailbox for this pairing yet (it has not run inbox since the pairing, or has been away longer than a week): kept here, it goes at your next inbox or send once ${name}'s agent has connected`;
576
+
532
577
  // MQTT 3.1.1 says only "bad user name or password": POST /check with the same credentials names
533
578
  // the failing check (relay/auth.mjs).
534
579
  async function named(ep, creds, err) {
@@ -622,13 +667,16 @@ class Link {
622
667
  export class Carrier {
623
668
  #links = new Map(); #work = Promise.resolve(); #busy = 0; #lastWork = 0; #routes = new Map(); #results = new Map();
624
669
  #claimed = new Set(); #refusedTopics = new Map(); #handshakes = new Map(); #soon = new Set();
625
- #started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map();
670
+ #started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map(); #ask = false;
626
671
 
627
- constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays = RETENTION_DAYS, clock = () => Math.floor(Date.now() / 1000),
672
+ constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays, clock = () => Math.floor(Date.now() / 1000),
628
673
  onEvent, keep, backoff = BACKOFF, tick = TICK }) {
629
674
  if (typeof identity !== 'function') throw new TypeError('identity: a function returning { secret, bundle }');
630
675
  if (typeof store !== 'string' || typeof state !== 'string') throw new TypeError('store, state: file paths (pathsFor(identityFile))');
631
- if (!Number.isSafeInteger(retentionDays) || retentionDays < 1 || retentionDays > RETENTION_MAX_DAYS) throw new TypeError(`retentionDays: 1 to ${RETENTION_MAX_DAYS}`);
676
+ if (retentionDays !== undefined && !retentionOk(retentionDays)) throw new TypeError(`retentionDays: 1 to ${RETENTION_MAX_DAYS}`);
677
+ // Not given: relay.json's at the first login to this agent's own relay may set it (#relayInfo).
678
+ this.#ask = retentionDays === undefined;
679
+ retentionDays ??= RETENTION_DAYS;
632
680
  if (onEvent !== undefined && typeof onEvent !== 'function') throw new TypeError('onEvent: a function');
633
681
  if (keep !== undefined && typeof keep !== 'boolean') throw new TypeError('keep: true or false');
634
682
  Object.assign(this, { identity, storePath: store, statePath: state, relay, endpoints, retention: retentionDays * DAY, clock, onEvent: onEvent ?? (() => {}),
@@ -917,7 +965,18 @@ export class Carrier {
917
965
  const s = this.#restore(st, store, me, did) ?? fail('not_contact', 'no live pairing with the writer of this topic');
918
966
  // Bytes 2 to 18 are the epoch id (envelope.mjs "Layout"); a frame too short fails open() below.
919
967
  const begins = !s.in.epochs.has(hex(bytes.subarray(2, 18)));
920
- const r = open(s, bytes, t, now); // checks by name; the session is unchanged when one fails
968
+ let r;
969
+ try { r = open(s, bytes, t, now); } catch (e) { // checks by name; the session is unchanged when one fails
970
+ // Not signed as the contact's current DID, after a recovery of the contact's this agent
971
+ // followed: a key the recovery overruled, maybe the thief's (the header's "Recovery beats
972
+ // key"). Refused and noted, and no bundle is owed for it (`from`'s known_due): nothing goes
973
+ // under this K. The claimed DID is unverified: not echoed.
974
+ if (e instanceof MsgError && e.check === 'from' && s.peer.re_pair === 'contact_recovery') {
975
+ return [this.#note(st, now, { type: 'refused', from: s.peer.did, name: s.peer.name, code: 're_pair',
976
+ detail: `a message not signed by ${s.peer.name}'s key after its recovery: maybe the thief's, not delivered` })];
977
+ }
978
+ throw e;
979
+ }
921
980
  const c = s.peer, events = [];
922
981
  // The writer's epochs begin here again: a bundle owed for one that could not (RESYNC) is not.
923
982
  if (begins) this.#entry(st, did).resync_due = false;
@@ -1064,13 +1123,31 @@ export class Carrier {
1064
1123
  const recovered = kept.some((x) => x.body.reason === 'recovery' && !held.has(canonicalize(x)));
1065
1124
  if (recovered) merged.re_pair ??= 'contact_recovery';
1066
1125
  store.save();
1126
+ const overruled = recovered ? this.#overrule(st, now, merged, kept, before.chain) : [];
1067
1127
  if (a.current_did === c.current_did) return [];
1068
1128
  // The contact's old key, and perhaps its state with the prekeys we listed, may be a thief's:
1069
1129
  // list fresh ones only. retire() keeps the old secrets until they expire, for epochs begun.
1070
1130
  const s = this.#restore(st, store, me, c.did);
1071
1131
  if (s) { s.in.prekeys.retire(now); this.#persist(st, s); }
1072
1132
  this.#entry(st, c.did).prekeys_resend = true;
1073
- return [this.#note(st, now, { type: 'rotated', did: c.did, name: c.name, current_did: a.current_did, ...(recovered && { re_pair: merged.re_pair }) })];
1133
+ return [this.#note(st, now, { type: 'rotated', did: c.did, name: c.name, current_did: a.current_did, ...(recovered && { re_pair: merged.re_pair, overruled }) })];
1134
+ }
1135
+
1136
+ // A recovery of contact c was merged (kept: the rotation followed on each edge of c.chain). The
1137
+ // DIDs it overrules: those of the chain up to the last recovery's node, and those of the chain
1138
+ // held before that it left. Messages of c's still waiting for inbox() signed by one of them are
1139
+ // taken out and noted refused (the header's "Recovery beats key"). → the DIDs overruled.
1140
+ #overrule(st, now, c, kept, before) {
1141
+ const last = kept.findLastIndex((x) => x.body.reason === 'recovery'), honest = new Set(c.chain.slice(last + 1));
1142
+ const overruled = [...new Set([...c.chain, ...before])].filter((d) => !honest.has(d));
1143
+ const out = st.inbox.filter((m) => m.from === c.did && !honest.has(m.current_did));
1144
+ if (out.length === 0) return overruled;
1145
+ st.inbox = st.inbox.filter((m) => !out.includes(m));
1146
+ for (const m of out) {
1147
+ this.#note(st, now, { type: 'refused', from: c.did, name: c.name, current_did: m.current_did, iat: m.iat, code: 're_pair',
1148
+ detail: `signed by ${m.current_did}, a key ${c.name}'s recovery overruled: maybe the thief's, not delivered` });
1149
+ }
1150
+ return overruled;
1074
1151
  }
1075
1152
 
1076
1153
  // Alice: an answer to one of her codes. checkAnswer runs sigelo-pair's checks in its order and
@@ -1120,7 +1197,7 @@ export class Carrier {
1120
1197
  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 };
1121
1198
  this.#queue(st, { ...entry, bytes: frame });
1122
1199
  this.#routes = new Map();
1123
- return [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed })];
1200
+ 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) })];
1124
1201
  }
1125
1202
 
1126
1203
  // Alice: her reply will never reach the answerer (refused, too large, or its code expired while
@@ -1182,16 +1259,16 @@ export class Carrier {
1182
1259
  }
1183
1260
  spend(id);
1184
1261
  // An entry written before `as` was kept: unknown, so the notice goes (#next `first`).
1185
- const held = waiting.find(([x]) => x === id)[1].as ?? null;
1186
- const c = store.lookup(res.did);
1262
+ const answered = waiting.find(([x]) => x === id)[1], held = answered.as ?? null;
1263
+ const c = renamed(store, store.lookup(res.did), answered);
1187
1264
  const s = session({ me: { did: me.did, current_did: me.current_did, secret: me.secret }, peer: c, K: hexToBytes(res.pair_key) });
1188
- const events = [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed })];
1265
+ 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) })];
1189
1266
  try { acceptPrekeys(s, reply.prekeys, now); } catch (e) {
1190
1267
  if (!(e instanceof MsgError)) throw e;
1191
1268
  events.push({ type: 'dropped', check: e.check, detail: `the reply's prekeys: ${e.message}` });
1192
1269
  }
1193
1270
  st.peers[c.did] = { session: dumpSession(s), announced: held, known: held, outbox: st.peers[c.did]?.outbox ?? [], prekeys_resend: false, prekeys_iat: 0 };
1194
- for (const [x] of waiting) this.#handshakes.set(x, { contact: { name: c.name, did: c.did, current_did: c.current_did } });
1271
+ 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) } });
1195
1272
  this.#routes = new Map();
1196
1273
  return events;
1197
1274
  }
@@ -1210,8 +1287,8 @@ export class Carrier {
1210
1287
  }
1211
1288
  st.pending = st.pending.filter((p) => p.exp === undefined || p.exp > now);
1212
1289
  // Nothing goes to a contact whose mailbox nobody held at this round's last publish to it
1213
- // (no_reader): it would be refused alike. Its control frames wait for the next round; its
1214
- // messages are refused here, unsealed, so no epoch is begun (and no prekey spent) for nothing.
1290
+ // (no_reader): it would be refused alike. Its frames wait for the next round, its messages
1291
+ // unsealed in its outbox, so no epoch is begun (and no prekey spent) for nothing.
1215
1292
  const absent = (did) => did !== undefined && link.absent.has(did);
1216
1293
  const queued = st.pending.find((p) => p.relay === link.relay && (p.control === 'reply' || !absent(p.peer)) && (p.needs ?? []).every((t) => link.subscribed.has(t)));
1217
1294
  if (queued) return queued;
@@ -1220,11 +1297,10 @@ export class Carrier {
1220
1297
  const e = st.peers[c.did];
1221
1298
  if (!e) continue;
1222
1299
  if (absent(c.did)) {
1223
- const detail = `nobody holds ${c.name}'s mailbox now: it has been away longer than it claims ahead, or no longer reads this pairing; send again later`;
1224
- for (const item of e.outbox.splice(0)) {
1225
- this.#results.set(item.id, { code: 'no_reader', detail, local: true });
1226
- this.#emit({ type: 'refused', id: item.id, peer: c.did, code: 'no_reader', detail });
1227
- }
1300
+ const detail = noReader(c.name);
1301
+ for (const item of e.outbox) this.#results.set(item.id, { code: null, queued: detail });
1302
+ // Said once while it lasts (a CLI agent reads it in inbox()).
1303
+ if (e.outbox.length > 0 && e.waiting !== detail) { e.waiting = detail; this.#emit(this.#note(st, now, { type: 'waiting', did: c.did, name: c.name, detail })); }
1228
1304
  continue;
1229
1305
  }
1230
1306
  const K = hexToBytes(c.pair_key), t = topic(K, me.did, c.did, isoWeek(now));
@@ -1291,8 +1367,11 @@ export class Carrier {
1291
1367
  try {
1292
1368
  const m = send(s, { label: item.label, content: item.content }, now);
1293
1369
  e.outbox.shift();
1370
+ if (e.waiting === noReader(c.name)) e.waiting = null;
1294
1371
  this.#persist(st, s);
1295
- return this.#queue(st, { id: item.id, relay, topic: m.topic, bytes: m.bytes, kind: KIND.message, n: m.n, peer: c.did });
1372
+ // item: put back in the outbox if the relay says no_reader (#refused). Plaintext at rest
1373
+ // only as long as the outbox already kept it, until the PUBACK.
1374
+ return this.#queue(st, { id: item.id, relay, topic: m.topic, bytes: m.bytes, kind: KIND.message, n: m.n, peer: c.did, item });
1296
1375
  } catch (err) {
1297
1376
  if (!(err instanceof MsgError)) throw err;
1298
1377
  if (err.check === 'prekeys') {
@@ -1338,9 +1417,16 @@ export class Carrier {
1338
1417
  const s = this.#restore(st, store, me, e.peer);
1339
1418
  if (s) { restartEpoch(s, unb64(e.bytes)); this.#persist(st, s); }
1340
1419
  }
1420
+ // Nobody holds the contact's mailbox: the message goes back to the front of its outbox, to be
1421
+ // sealed again for the week it then goes in (the header's "Mailboxes"). Sealed bytes kept for
1422
+ // later could name a week whose mailbox the reader never claims again. An entry written by an
1423
+ // earlier version has no item: refused, as it was.
1424
+ if (e.kind === KIND.message && r.code === 'no_reader' && e.item) p.outbox.unshift(e.item);
1341
1425
  return false;
1342
1426
  }
1343
1427
 
1428
+ #nameOf(did) { try { return this.#read(({ store }) => store.lookup(did)?.name) ?? 'the contact'; } catch { return 'the contact'; } }
1429
+
1344
1430
  async #throttle(link) {
1345
1431
  for (;;) {
1346
1432
  const t = Date.now();
@@ -1380,8 +1466,11 @@ export class Carrier {
1380
1466
  this.#locked((ctx) => { if (!(r && this.#refused(ctx, e, r))) ctx.st.pending = ctx.st.pending.filter((p) => p.id !== e.id); });
1381
1467
  if (r?.code === 'pow') { link.pow = true; link.closing = true; link.client.end(true); return; } // log in again, with the proof (#connect, #closed)
1382
1468
  if (r?.code === 'no_reader' && e.peer !== undefined && e.control !== 'reply') link.absent.add(e.peer);
1383
- if (e.control === undefined || e.control === 'answer') this.#results.set(e.id, r ?? { code: null }); // what a verb waits for
1384
- this.#emit(r ? { type: 'refused', id: e.id, peer: e.peer, control: e.control, code: r.code, detail: r.detail } : { type: 'sent', id: e.id, peer: e.peer, control: e.control });
1469
+ // A message the relay had no reader for is back in its outbox (#refused): queued, not refused.
1470
+ const back = r?.code === 'no_reader' && e.kind === KIND.message && e.item !== undefined;
1471
+ 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
1472
+ this.#emit(back ? { type: 'queued', id: e.id, peer: e.peer, code: r.code, detail: r.detail }
1473
+ : r ? { type: 'refused', id: e.id, peer: e.peer, control: e.control, code: r.code, detail: r.detail } : { type: 'sent', id: e.id, peer: e.peer, control: e.control });
1385
1474
  // A refusal stops this round: what follows would be refused alike (a quota, the rate brake),
1386
1475
  // and a control frame would be queued again at once. The next round retries. A mailbox
1387
1476
  // nobody holds stops only what goes to that contact (absent, #next).
@@ -1549,8 +1638,26 @@ export class Carrier {
1549
1638
  return { username: me.current_did, clientId: clientIdOf(me.did), password, pow };
1550
1639
  }
1551
1640
 
1641
+ // How long this agent's own relay keeps a message on the free tier (relay.json, plan §11), when
1642
+ // the constructor was not told: asked once, beside the first login's challenge. Any failure (no
1643
+ // such file, a relay on loopback, a value out of range) keeps RETENTION_DAYS. Before the first
1644
+ // claim, so the weeks claimed behind (#weeks) follow it.
1645
+ async #relayInfo(ep) {
1646
+ this.#ask = false;
1647
+ try {
1648
+ const r = await http(`${ep.http}/relay.json`);
1649
+ const n = r.status === 200 ? retentionOf(r.body) : null;
1650
+ if (n !== null) this.retention = n * DAY;
1651
+ } catch {}
1652
+ }
1653
+
1654
+ get retentionDays() { return this.retention / DAY; }
1655
+
1552
1656
  async #dial(relay) {
1553
- const ep = endpointOf(relay, this.endpoints), link = new Link(relay, relay === this.relay), creds = await this.#credentials(relay, ep);
1657
+ const ep = endpointOf(relay, this.endpoints), link = new Link(relay, relay === this.relay);
1658
+ const info = link.own && this.#ask ? this.#relayInfo(ep) : null;
1659
+ const creds = await this.#credentials(relay, ep);
1660
+ await info;
1554
1661
  // A cut connection is this client's own refusal: no POST /check may rename it.
1555
1662
  try { await mqttConnect(ep.mqtt, creds, link, (packet) => this.#onPacket(link, packet)); } catch (e) { throw link.cut ?? await named(ep, creds, e); }
1556
1663
  // A close right after CONNACK (a cut in the same read) reached no listener of this connection.
@@ -1678,7 +1785,10 @@ export class Carrier {
1678
1785
 
1679
1786
  // ---- the verbs
1680
1787
 
1681
- async invite({ name, ttl } = {}) {
1788
+ // short: the long code is parked at the relay (POST /park, relay/park.mjs) under a short code
1789
+ // (short.mjs) for SHORT_TTL seconds, one fetch; refused, the invite is withdrawn as when its topic
1790
+ // is. A login of its own: the relay checks that the parked code is this agent's.
1791
+ async invite({ name, ttl, short = false } = {}) {
1682
1792
  const code = this.#locked(({ now, me, store }) => {
1683
1793
  const code = makeInvite({ did: me.current_did, relay: this.relay, now, ...(ttl !== undefined && { ttl }) });
1684
1794
  store.addInvite(code, name ?? `invite-${code.nonce.slice(1, 9)}`, now);
@@ -1692,14 +1802,39 @@ export class Carrier {
1692
1802
  const r = this.#refusedTopics.get(t);
1693
1803
  fail(r?.code ?? 'subscribe', `the relay did not let this agent claim the invite's topic${r ? ` (${relaySays(r.detail)})` : ''}`);
1694
1804
  }
1805
+ if (!short) return { code: code.text, did: code.did, relay: code.relay, exp: code.exp };
1806
+ const s = makeShort(), exp = Math.min(checkNow(this.clock()) + SHORT_TTL, code.exp), ep = endpointOf(code.relay, this.endpoints);
1807
+ const creds = await this.#credentials(code.relay, ep);
1808
+ const r = await http(`${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 }) });
1809
+ const check = typeof r.body?.check === 'string' ? r.body.check : null;
1810
+ if (r.status === 429) fail('rate', `POST /park: ${relaySays(r.body?.detail)}`);
1811
+ if ((r.status === 404 || r.status === 405) && check === null) fail('park', `${code.relay} takes no short codes: use the long code (invite --long)`);
1812
+ if (r.status !== 200) fail('connect', `POST /park answered ${r.status}`);
1813
+ if (r.body?.ok !== true) fail(PARK_CHECKS.has(check) ? check : 'park', `the relay refused the short code (${relaySays(`${check}: ${r.body?.detail}`)})`);
1814
+ return { code: code.text, did: code.did, relay: code.relay, exp: code.exp, short: formatShort(s), short_exp: exp };
1695
1815
  } catch (e) {
1696
1816
  try { this.#locked(({ store }) => store.cancelInvite(code.nonce)); } catch {}
1697
1817
  throw e;
1698
1818
  }
1699
- return { code: code.text, did: code.did, relay: code.relay, exp: code.exp };
1819
+ }
1820
+
1821
+ // The long code parked under a short one, at this agent's own relay (a short code names none):
1822
+ // GET /park/<code hash>, which the relay answers once. Whatever it answers is a code to parse
1823
+ // like any other (accept); the four words show whether the pairing is the inviter's.
1824
+ async unpark(text) {
1825
+ const ep = endpointOf(this.relay, this.endpoints);
1826
+ const r = await http(`${ep.http}/park/${codeHash(text)}`);
1827
+ if (r.status === 429) fail('rate', `GET /park: ${relaySays(r.body?.detail)}`);
1828
+ if (r.status === 404 && r.body?.check === 'park_unknown') {
1829
+ fail('park_unknown', `no invite waits under this short code at ${this.relay}: mistyped, used already, or older than 10 minutes. Ask for a new one (a code made at another relay works only as the long code: invite --long)`);
1830
+ }
1831
+ if (r.status === 404 || r.status === 405) fail('park', `${this.relay} takes no short codes: ask for the long code (invite --long)`);
1832
+ if (r.status !== 200 || r.body?.ok !== true || typeof r.body.invite !== 'string') fail('connect', `GET /park answered ${r.status}`);
1833
+ return r.body.invite;
1700
1834
  }
1701
1835
 
1702
1836
  async accept(text, { name, wait = 10 } = {}) {
1837
+ if (isShort(text)) text = await this.unpark(text);
1703
1838
  const { code, id, entry } = this.#locked(({ now, me, store, st }) => {
1704
1839
  const code = parseInvite(text, now);
1705
1840
  // This agent's own relay, and those its operator configured, are the operator's choice.
@@ -1713,7 +1848,9 @@ export class Carrier {
1713
1848
  // Checked before anything is stored: the relay would refuse it (quota_storage).
1714
1849
  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`);
1715
1850
  const id = answerId(answer);
1716
- store.addAccept(code, id, name ?? `contact-${code.did.slice(-8)}`, now, hex(k.secretKey), me.current_did);
1851
+ // Unnamed: the code's DID's first digits ("z5esAbCd"), as operators shorten a DID. Named, the
1852
+ // name also replaces a known contact's on a re-pair (#onReply).
1853
+ store.addAccept(code, id, name ?? code.did.slice('did:sigelo:'.length, 'did:sigelo:'.length + 8), now, hex(k.secretKey), me.current_did, name !== undefined);
1717
1854
  const entry = this.#queue(st, { relay: code.relay, topic: keys.answer_topic, bytes: frame, kind: KIND.invite_answer, control: 'answer', needs: [keys.reply_topic], exp: code.exp });
1718
1855
  return { code, id, entry: entry.id };
1719
1856
  } finally { k.secretKey.fill(0); }
@@ -1723,7 +1860,11 @@ export class Carrier {
1723
1860
  this.#locked(({ now, store, st }) => { st.pending = st.pending.filter((p) => p.id !== entry); store.take('accepts', id, now); });
1724
1861
  fail(check, why);
1725
1862
  };
1726
- try { await this.#session([code.relay], { max: wait * 1000, until: () => this.#handshakes.has(id) }); } catch (e) {
1863
+ // Done early too once the reply topic or the answer is refused (a code answered before:
1864
+ // mailbox_taken), not after the whole wait.
1865
+ const reply = inviteKeys(code.secret).reply_topic;
1866
+ const settled = () => this.#handshakes.has(id) || this.#refusedTopics.has(reply) || Boolean(this.#results.get(entry)?.code);
1867
+ try { await this.#session([code.relay], { max: wait * 1000, until: settled }); } catch (e) {
1727
1868
  // A relay other than this agent's own that refuses it for good would be dialled again at
1728
1869
  // every connection, until the code expires, for an answer it never takes: and a stranger's
1729
1870
  // code names it. Withdrawn only while it waits to go: an answer the relay holds keeps its
@@ -1740,7 +1881,7 @@ export class Carrier {
1740
1881
  const why = { withdrawn: 'the answer is withdrawn', queued: 'the answer stays queued: it goes at the next connection', delivered: 'the relay holds the answer: the reply is read at a later connection' }[left];
1741
1882
  throw new MsgError(e.check ?? 'connect', `${reason(e)} (${why})`);
1742
1883
  }
1743
- const h = this.#handshakes.get(id), sent = this.#results.get(entry), reply = inviteKeys(code.secret).reply_topic;
1884
+ const h = this.#handshakes.get(id), sent = this.#results.get(entry);
1744
1885
  this.#handshakes.delete(id); this.#results.delete(entry);
1745
1886
  if (h?.check) fail(h.check, h.detail);
1746
1887
  if (h) return { status: 'connected', contact: h.contact };
@@ -1755,7 +1896,7 @@ export class Carrier {
1755
1896
  const s = store.load().s;
1756
1897
  return {
1757
1898
  contacts: Object.values(s.contacts).map((c) => ({ name: c.name, did: c.did, current_did: c.current_did, revoked: c.revoked, relay: c.relay, queued: st.peers[c.did]?.outbox.length ?? 0,
1758
- re_pair: c.re_pair ?? null })),
1899
+ re_pair: c.re_pair ?? null, fingerprint: c.revoked ? null : wordsOf(c.pair_key) })),
1759
1900
  invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay })),
1760
1901
  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 })),
1761
1902
  };
@@ -1779,6 +1920,22 @@ export class Carrier {
1779
1920
  if (content === undefined) fail('body', 'content is required');
1780
1921
  try { canonicalize({ label, content }); } catch (e) { fail('body', `content is not canonical JSON (no floats): ${e.message}`); }
1781
1922
  }
1923
+ // An answer of ours to `to`'s code waits for its reply (accept said `waiting`): the reply may be
1924
+ // at the relay now. One session reads it first, so `send` right after `accept` pairs (or, to a
1925
+ // contact already, re-pairs) and goes under the key the reply brings.
1926
+ const answered = this.#read(({ now, store }) => [...new Set(Object.values(store.load().s.accepts)
1927
+ .filter((p) => p.exp > now && (p.name === to || p.code_did === to)).map((p) => p.relay))]);
1928
+ if (answered.length > 0) {
1929
+ try { await this.#session(answered); } catch {}
1930
+ this.#routes = new Map();
1931
+ this.#read(({ now, store }) => {
1932
+ const s = store.load().s;
1933
+ if (!Object.values(s.contacts).some((c) => !c.revoked && c.pair_key && (c.name === to || c.chain.includes(to)))
1934
+ && Object.values(s.accepts).some((p) => p.exp > now && (p.name === to || p.code_did === to))) {
1935
+ fail('not_paired', `${JSON.stringify(to)} is not paired yet: your answer to its code waits for the inviter's agent to connect and reply; send again once inbox reports "paired"`);
1936
+ }
1937
+ });
1938
+ }
1782
1939
  const { ids, c } = this.#locked(({ store, st }) => {
1783
1940
  const c = this.#resolve(store, to), outbox = this.#entry(st, c.did).outbox;
1784
1941
  const ids = contents.map((content) => { const id = randomId(); outbox.push({ id, label, content }); return id; });
@@ -0,0 +1,167 @@
1
+ {
2
+ "contract": "sigelo-park/0",
3
+ "alphabet": "0123456789ABCDEFGHJKMNPQRSTVWXYZ",
4
+ "rules": {
5
+ "code": "8 characters of the alphabet from 5 random bytes, 5 bits each, most significant first; shown as XXXX-XXXX; lives 600 s, one fetch",
6
+ "normalise": "drop whitespace and dashes (U+002D, U+2010 to U+2015, U+2212); uppercase; I and L → 1, O → 0; then exactly 8 characters of the alphabet, else short_code",
7
+ "code_hash": "hex(SHA-256(UTF-8 \"sigelo-park/0\" ‖ UTF-8 normalised code))",
8
+ "fingerprint": "HKDF-SHA256(16 bytes of the pair id, salt \"sigelo-fingerprint/0\", empty info, 6 bytes); the first 44 bits, 11 at a time, index the BIP-39 English list (sha256 of the list one word a line: 2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda)",
9
+ "rng": "rng(label) = first 5 bytes of SHA-256(UTF-8 \"sigelo-park/0 \" + label)"
10
+ },
11
+ "codes": [
12
+ {
13
+ "label": "a",
14
+ "rng": "7c330786cc",
15
+ "code": "FGSG-F1PC",
16
+ "normalised": "FGSGF1PC",
17
+ "code_hash": "629f5c50434574b583aae6fa4664a7ace329e2a0a62ef29140dcbdc21424a443"
18
+ },
19
+ {
20
+ "label": "b",
21
+ "rng": "ebac845f43",
22
+ "code": "XEP8-8QT3",
23
+ "normalised": "XEP88QT3",
24
+ "code_hash": "0778a95c3785446e88f6df877abcc6793787a6d53825af7f01fac2d6b23da66a"
25
+ },
26
+ {
27
+ "label": "c",
28
+ "rng": "29efe35974",
29
+ "code": "57QY-6PBM",
30
+ "normalised": "57QY6PBM",
31
+ "code_hash": "f31675864983beeadd2f46fe62891864f87071011d5a5c719208d241a027f263"
32
+ },
33
+ {
34
+ "label": "d",
35
+ "rng": "3b9f02b509",
36
+ "code": "7EFG-5D89",
37
+ "normalised": "7EFG5D89",
38
+ "code_hash": "529f4d2fe1fcacf4e51f84b6859a668dadf2dff69ff107a159e794000642af2d"
39
+ },
40
+ {
41
+ "label": "zeros",
42
+ "rng": "0000000000",
43
+ "code": "0000-0000",
44
+ "normalised": "00000000",
45
+ "code_hash": "e90299d03e123d1c92eb28b8e5ca42b7a719fe6b2cd25503fd94eba3a67511ee"
46
+ },
47
+ {
48
+ "label": "ones",
49
+ "rng": "ffffffffff",
50
+ "code": "ZZZZ-ZZZZ",
51
+ "normalised": "ZZZZZZZZ",
52
+ "code_hash": "d64ebd4f29ed60b23dc016c34c92a9ad0dd43f134ae3578206d6e06894938898"
53
+ }
54
+ ],
55
+ "normalise": [
56
+ {
57
+ "case": "as shown",
58
+ "input": "FGSG-F1PC",
59
+ "normalised": "FGSGF1PC"
60
+ },
61
+ {
62
+ "case": "without the dash",
63
+ "input": "FGSGF1PC",
64
+ "normalised": "FGSGF1PC"
65
+ },
66
+ {
67
+ "case": "lowercase",
68
+ "input": "fgsg-f1pc",
69
+ "normalised": "FGSGF1PC"
70
+ },
71
+ {
72
+ "case": "spoken in groups",
73
+ "input": " fg sg f1 pc ",
74
+ "normalised": "FGSGF1PC"
75
+ },
76
+ {
77
+ "case": "an en dash from a phone",
78
+ "input": "FGSG–F1PC",
79
+ "normalised": "FGSGF1PC"
80
+ },
81
+ {
82
+ "case": "I, i, L and l read as 1",
83
+ "input": "IiLl-2345",
84
+ "normalised": "11112345"
85
+ },
86
+ {
87
+ "case": "O and o read as 0",
88
+ "input": "Oo00-ABCD",
89
+ "normalised": "0000ABCD"
90
+ },
91
+ {
92
+ "case": "U is no digit",
93
+ "input": "U000-0000",
94
+ "error": "short_code"
95
+ },
96
+ {
97
+ "case": "seven characters",
98
+ "input": "FGSG-F1P",
99
+ "error": "short_code"
100
+ },
101
+ {
102
+ "case": "nine characters",
103
+ "input": "FGSGF1PC0",
104
+ "error": "short_code"
105
+ },
106
+ {
107
+ "case": "a symbol",
108
+ "input": "K7F3_Q9ZP",
109
+ "error": "short_code"
110
+ },
111
+ {
112
+ "case": "a long code",
113
+ "input": "sgl122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222",
114
+ "error": "short_code"
115
+ }
116
+ ],
117
+ "fingerprints": [
118
+ {
119
+ "case": "carrier-v0.json derived.pair",
120
+ "pair": "a2cf45bd3d6aee6d6e3f14ffd2751924",
121
+ "okm": "d6a99a189c6c",
122
+ "indices": [
123
+ 1717,
124
+ 614,
125
+ 1073,
126
+ 454
127
+ ],
128
+ "words": "stove error mail decide"
129
+ },
130
+ {
131
+ "case": "zero pair",
132
+ "pair": "00000000000000000000000000000000",
133
+ "okm": "06cbb8ea02e1",
134
+ "indices": [
135
+ 54,
136
+ 750,
137
+ 468,
138
+ 46
139
+ ],
140
+ "words": "almost fruit dentist alarm"
141
+ },
142
+ {
143
+ "case": "ones pair",
144
+ "pair": "ffffffffffffffffffffffffffffffff",
145
+ "okm": "a11ec15d70ec",
146
+ "indices": [
147
+ 1288,
148
+ 1968,
149
+ 698,
150
+ 1806
151
+ ],
152
+ "words": "patient voyage firm tide"
153
+ },
154
+ {
155
+ "case": "pair of rng(\"pair\")",
156
+ "pair": "41068cf691662c20931f820952ac3ddf",
157
+ "okm": "3f11eb6818b3",
158
+ "indices": [
159
+ 504,
160
+ 1146,
161
+ 1744,
162
+ 395
163
+ ],
164
+ "words": "disease monster sure cousin"
165
+ }
166
+ ]
167
+ }