sigelo-contact 0.1.10 → 0.1.12

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
@@ -13,6 +13,7 @@
13
13
  // await c.relayForShort(short, { relay }) → { relay, from }: where a short code is parked: 8 characters, shortRelay
14
14
  // (relay.sigelo.ai); 12, the relay its tag resolves to (relays.mjs), or relay_tag
15
15
  // await c.registryRelays() → [{ tag, host, did?, tier?, note? }]: the signed registry's relays, verified (relays.mjs)
16
+ // await c.probeRelay(host) → { relay, ok, ms, retention_days, detail? }: does it answer (GET /relay.json, else /challenge)
16
17
  // await c.redeemGift(code) → { exp, months }: a gift code (PRO-K7F3-Q9ZP) redeemed at this agent's relay;
17
18
  // this identity is the operator whose pool is Pro until exp (relay/gifts.mjs)
18
19
  // await c.accept(code, { name, wait, relay }) → { status: 'connected' | 'waiting' | 'pending', … } a long code or a short one
@@ -312,12 +313,12 @@ const TICK = 3600 * 1000, BACKOFF = [1000, 60000];
312
313
  // relay that accepts and closes at once is dialled ever more slowly, as one that refuses is.
313
314
  const STABLE_MS = 60000;
314
315
  // Login refusals no retry can fix.
315
- const PERMANENT = new Set(['password', 'bundle', 'sig', 'client_id', 'closed', 'challenge', 'relay', 'identity']);
316
+ const PERMANENT = new Set(['password', 'bundle', 'sig', 'retired_recovery', 'client_id', 'closed', 'challenge', 'relay', 'identity']);
316
317
  // A refusal by one of these is this process failing, not a message: the delivery is not acknowledged.
317
318
  const INTERNAL = new Set(['lock', 'state', 'store', 'identity', 'time']);
318
319
  // The login checks relay/auth.mjs names on POST /check. Any other word from the relay is `connect`:
319
320
  // a check name decides what this client does next, so a relay cannot pick one.
320
- const LOGIN_CHECKS = new Set(['rate', 'password', 'challenge_unknown', 'challenge_expired', 'bundle', 'sig', 'client_id', 'closed', 'pow', 'relay_full']);
321
+ const LOGIN_CHECKS = new Set(['rate', 'password', 'challenge_unknown', 'challenge_expired', 'bundle', 'sig', 'retired_recovery', 'client_id', 'closed', 'pow', 'relay_full']);
321
322
  // Refusals of an invite reply that a later round may get past: the reply stays queued.
322
323
  const REPLY_RETRY = new Set(['rate', 'relay_full', 'quota_messages']);
323
324
  // $sigelo/notice codes that refuse the publish, or the SUBSCRIBE, in flight (relay-plan §3 "Errors").
@@ -767,6 +768,8 @@ const LOGIN_NEXT = {
767
768
  relay_full: 'the relay is full: try again later',
768
769
  challenge_expired: 'the login took longer than its challenge lives (a slow proof of work): try again',
769
770
  challenge_unknown: 'try again',
771
+ // relay/auth.mjs: a recovery by a recovery key the chain kept there retired (THREAT-MODEL §2.5a).
772
+ retired_recovery: 'the relay keeps a chain that retired the recovery key this one recovers with: send the chain with the newest recovery',
770
773
  // A closed relay (relay/closed.mjs) admits its operators and the identities they attest for it.
771
774
  closed: 'this relay admits only identities its operator vouches for: ask that operator for an attestation for this relay (sigelo-agent add-attestation), or pair through an open relay',
772
775
  connect: 'try again later',
@@ -2376,6 +2379,7 @@ export class Carrier {
2376
2379
  // (relay.sigelo.ai), else the host its relay tag resolves to (relays.mjs resolveTag): this agent's
2377
2380
  // own relay, its contacts' relays, the relay its operator attestation names,
2378
2381
  // the local table; then the registry; else the person is asked (relay_tag). Nothing else asks.
2382
+ // A contact's relay is checked against the registry first (resolveTag).
2379
2383
  async relayForShort(text, { relay } = {}) {
2380
2384
  const norm = normaliseShort(text), tag = tagOf(norm), shown = formatShort(norm);
2381
2385
  if (relay !== undefined) {
@@ -2402,6 +2406,22 @@ export class Carrier {
2402
2406
  async registryRelays() {
2403
2407
  return [...(await this.#registry())].map(([tag, e]) => ({ tag, ...e }));
2404
2408
  }
2409
+ /**
2410
+ * Does a relay answer here? GET /relay.json at its HTTP endpoint (endpointOf), else GET /challenge (a
2411
+ * relay without the site's relay.json still answers it, 400 without a DID): the page's relay picker,
2412
+ * before a host is used. Nothing is sent but these two GETs. → { relay, ok, ms, retention_days, detail? }.
2413
+ */
2414
+ async probeRelay(host) {
2415
+ relayArg(host);
2416
+ const base = endpointOf(host, this.endpoints).http, t0 = Date.now(), ms = () => Date.now() - t0;
2417
+ try {
2418
+ const r = await http(this.platform, `${base}/relay.json`);
2419
+ if (r.status === 200 && r.body?.limits !== undefined) return { relay: host, ok: true, ms: ms(), retention_days: retentionOf(r.body) };
2420
+ const c = await http(this.platform, `${base}/challenge`);
2421
+ if ((c.status === 400 || c.status === 200) && c.body !== null) return { relay: host, ok: true, ms: ms(), retention_days: null };
2422
+ return { relay: host, ok: false, ms: ms(), retention_days: null, detail: `${host} answered ${c.status}: not a sigelo relay` };
2423
+ } catch (e) { return { relay: host, ok: false, ms: ms(), retention_days: null, detail: e.message }; }
2424
+ }
2405
2425
 
2406
2426
  // The long code parked under a short one: GET /park/<code hash>, which the relay answers once,
2407
2427
  // at the relay relayForShort names. Whatever it answers is a code to parse like any other
@@ -2467,6 +2487,10 @@ export class Carrier {
2467
2487
  if (code.relay !== this.relay && code.relay !== named && !Object.hasOwn(this.endpoints ?? {}, code.relay) && !publicRelay(code.relay)) {
2468
2488
  fail('code_relay', `the code names ${code.relay}, an address or a local name, not a public relay: allow it in SIGELO_RELAY_ENDPOINTS if it is yours`);
2469
2489
  }
2490
+ // A contact revoked here: refused before anything goes (its reply would be refused, the inviter
2491
+ // left paired alone), unless a new link permits it (store.mjs relink).
2492
+ const known = store.lookup(code.did);
2493
+ 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` : ''}`);
2470
2494
  const k = kemKey();
2471
2495
  try {
2472
2496
  const answer = buildAnswer({ code, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_pk: k.pk, prekeys: null });
@@ -2752,6 +2776,8 @@ export class Carrier {
2752
2776
  });
2753
2777
  }
2754
2778
  setLink(who, link) { return this.#locked(({ now, store }) => store.setLink(who, link, now)); }
2779
+ // A new link with a contact an ended link revoked: a one-use permit for its pairing (store.mjs relink).
2780
+ relink(did, id, until) { return this.#locked(({ now, store }) => store.relink(did, id, until, now)); }
2755
2781
  // The original DID that paired through this agent's code `nonce` (its inviteNonce, readCode().nonce),
2756
2782
  // or null: none yet, or the code's life plus a day is over (enrol.mjs answers only that DID).
2757
2783
  answeredBy(nonce) { return this.#read(({ now, st }) => { const a = Object.hasOwn(st.answered, nonce) ? st.answered[nonce] : null; return a && a.exp > now ? a.did : null; }); }
@@ -2769,9 +2795,10 @@ export class Carrier {
2769
2795
  });
2770
2796
  }
2771
2797
 
2772
- async forget(did) {
2798
+ // ended: {id, by, at} when a link's end forgets it (link.mjs), so a new link may pair it again.
2799
+ async forget(did, { ended = null } = {}) {
2773
2800
  const c = this.#locked(({ store, st }) => {
2774
- const c = store.revoke(did);
2801
+ const c = store.revoke(did, ended);
2775
2802
  delete st.peers[c.did];
2776
2803
  st.pending = st.pending.filter((p) => p.peer !== c.did);
2777
2804
  this.#sweepSpool(st);
package/control.mjs CHANGED
@@ -15,7 +15,8 @@
15
15
  // local listener answers it ({status, body} of the LAN path)
16
16
  // events operator → control { v, typ: "events", seq, since, state } GET /api/state?since=<since>,
17
17
  // pushed on change while the control holds a lease (LEASE, renewed by
18
- // any request), never polled
18
+ // any request), never polled; past PUSH_MAX a summary (capState:
19
+ // truncated), and the app pulls the rest (GET /api/state?full=1)
19
20
  //
20
21
  // const ctl = makeControl({ operator, timeout }) the client: its carrier is attached after
21
22
  // carrier = new Carrier({ ..., onEvent: (e) => ctl.onEvent(e) }); ctl.attach(carrier)
@@ -35,6 +36,9 @@ export const LEASE = 600, RENEW = 300;
35
36
  // An answer longer than this is refused too_large (a free reader's message cap is 256 KiB).
36
37
  export const ANSWER_MAX = 192 * 1024;
37
38
  export const CALL_TIMEOUT = 30_000;
39
+ // A pushed state longer than this goes as a summary (capState): the newest PUSH_KEEP contacts of each
40
+ // group and events, the counts, truncated; the app shows it and pulls the whole on demand (a request).
41
+ export const PUSH_MAX = 64 * 1024, PUSH_KEEP = 20;
38
42
  // The computer's cap per control: a bucket of BURST requests, refilled at RATE a second.
39
43
  export const RATE = 1, BURST = 10;
40
44
  const ID = /^[0-9a-f]{16}$/;
@@ -67,6 +71,24 @@ export function newControlIdentity() {
67
71
  }
68
72
 
69
73
  const isObject = (x) => typeof x === 'object' && x !== null && !Array.isArray(x);
74
+
75
+ /**
76
+ * A state to push: itself while its JSON is at most max; else a summary that fits: each group's
77
+ * newest keep contacts (by their last message), the newest keep events, every other field as it
78
+ * was, and truncated: { contacts: {group: count}, events: count, kept } (the counts of the whole).
79
+ * keep halves until it fits (0: the groups and events empty).
80
+ */
81
+ export function capState(st, max = PUSH_MAX, keep = PUSH_KEEP) {
82
+ if (!isObject(st) || JSON.stringify(st).length <= max) return st;
83
+ const groups = isObject(st.groups) ? st.groups : {}, events = Array.isArray(st.events) ? st.events : [];
84
+ const newest = (xs, n) => [...xs].sort((a, b) => (b?.last?.at ?? 0) - (a?.last?.at ?? 0)).slice(0, n);
85
+ const counts = Object.fromEntries(Object.entries(groups).map(([g, xs]) => [g, Array.isArray(xs) ? xs.length : 0]));
86
+ for (let n = keep; ; n = n > 1 ? Math.floor(n / 2) : 0) {
87
+ const out = { ...st, groups: Object.fromEntries(Object.entries(groups).map(([g, xs]) => [g, Array.isArray(xs) ? newest(xs, n) : xs])),
88
+ events: events.slice(-n), truncated: { contacts: counts, events: events.length, kept: n } };
89
+ if (n === 0 || JSON.stringify(out).length <= max) return out;
90
+ }
91
+ }
70
92
  export const newId = () => bytesToHex(randomBytes(8));
71
93
  export const requestMessage = ({ id, method, path, body }) => ({ v: CONTROL_V, typ: 'request', id, method, path, ...(body !== undefined && { body }) });
72
94
  export const responseMessage = ({ id, status, body }) => ({ v: CONTROL_V, typ: 'response', id, status, body });
@@ -144,8 +166,11 @@ export function makeControl({ operator, timeout = CALL_TIMEOUT, now = () => Date
144
166
  if (carrier === null) return err(503, 'remote', 'not connected yet');
145
167
  let url;
146
168
  try { url = new URL(path, 'http://app'); } catch { return err(404, 'route', 'not a route'); }
147
- // The pushed state stands for GET /api/state while the lease runs: no relay message.
148
- if (method === 'GET' && url.pathname === '/api/state' && state !== null && now() - asked < RENEW * 1000) {
169
+ // A control's four words are confirmed on the computer only: never asked, no relay message.
170
+ if (url.pathname === '/api/controls' || url.pathname.startsWith('/api/controls/')) return err(403, 'remote', 'controls are confirmed on the computer\'s own page only');
171
+ // The pushed state stands for GET /api/state while the lease runs: no relay message. full=1
172
+ // (a pushed summary's "pull the rest") always asks the computer.
173
+ if (method === 'GET' && url.pathname === '/api/state' && state !== null && now() - asked < RENEW * 1000 && url.searchParams.get('full') !== '1') {
149
174
  return { status: 200, body: JSON.parse(JSON.stringify(local(Number(url.searchParams.get('since') ?? 0) || 0))) };
150
175
  }
151
176
  return request(method, path, body);
package/create.mjs ADDED
@@ -0,0 +1,76 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // A new identity made on the device (design/apps-seed.md §7, pass A10a; Monerujo's create and seed
3
+ // review as the model). The root S is drawn here, as `newRoot()` draws it (keys.ts: 253 random bits from
4
+ // crypto.getRandomValues, redrawn until 0 < S < l), and held as bytes. Its 25 words exist only while the
5
+ // review screen shows them; the identity's files are made only after the human has typed three of them
6
+ // back, then S is zeroed. No network, no storage and no clock here: the page (apps/web/create.mjs) seals
7
+ // what `commit` returns, as a restore's.
8
+ //
9
+ // newSeed(net) → a session:
10
+ // .net, .vault the network, and the primary address of S's own Monero wallet (the vault,
11
+ // MONERO.md §2): a Monero wallet app restored from the words shows the same
12
+ // .words() the 25 words, ['w1', …, 'w25']: for the review screen only; refused once spent
13
+ // .quiz() QUIZ (3) positions, 1 to 25, drawn afresh each time, ascending
14
+ // .check(answers) the words typed for the last quiz's positions (in that order) → { ok, wrong: [positions] };
15
+ // a wrong answer ends the quiz: back to the words, then a new quiz
16
+ // .commit(o) after a check that passed: restoreFromRoot(S, o) with created today and the wallet's
17
+ // birth as today's date (restore_date: a new wallet has nothing older), the keeper
18
+ // marked made: "here" (as keeper --from-words --made-here), then S zeroed
19
+ // → { identity, keeper, device, list, notes, did, worker, vault }
20
+ // .discard() S zeroed; every call after it refused (create_spent)
21
+ // QUIZ how many words the human types back
22
+ //
23
+ // Words are compared as the wallet's own decoder reads them: case and blanks ignored, the whole word or
24
+ // its first three letters.
25
+ import { encodeMoneroWords, newRootBytes, vaultFromRoot } from 'sigelo/dist/keys.js';
26
+ import { fail } from './kdf.mjs';
27
+ import { NETS, WORD_COUNT, restoreFromRoot } from './restore.mjs';
28
+
29
+ export const QUIZ = 3;
30
+ const day = (now) => new Date(now * 1000).toISOString().slice(0, 10);
31
+ const norm = (w) => String(w ?? '').trim().toLowerCase();
32
+ /** An unbiased index in [0, n) from crypto.getRandomValues. */
33
+ function draw(n) {
34
+ const lim = Math.floor(0x100000000 / n) * n, b = new Uint32Array(1);
35
+ for (;;) { globalThis.crypto.getRandomValues(b); if (b[0] < lim) return b[0] % n; }
36
+ }
37
+
38
+ /** A fresh root for a new identity on `net` (mainnet | stagenet): see the header. */
39
+ export function newSeed(net) {
40
+ if (!NETS.includes(net)) fail('create_net', `net: ${NETS.join(' or ')}`);
41
+ let S = newRootBytes(), asked = null, passed = false;
42
+ const live = () => { if (S === null) fail('create_spent', 'these words are gone: start again'); return S; };
43
+ const v = vaultFromRoot(S, net), vault = v.address;
44
+ v.b.fill(0); v.a.fill(0);
45
+ return Object.freeze({
46
+ net, vault,
47
+ words: () => encodeMoneroWords(live()).split(' '),
48
+ quiz() {
49
+ live();
50
+ const at = new Set();
51
+ while (at.size < QUIZ) at.add(draw(WORD_COUNT) + 1);
52
+ asked = [...at].sort((a, b) => a - b);
53
+ passed = false;
54
+ return [...asked];
55
+ },
56
+ check(answers) {
57
+ const w = encodeMoneroWords(live()).split(' ');
58
+ if (asked === null) fail('create_quiz', 'no words asked yet');
59
+ if (!Array.isArray(answers) || answers.length !== asked.length) fail('create_quiz', `${asked.length} words, in the order asked`);
60
+ const same = (typed, word) => { const t = norm(typed); return t === word || (t.length === 3 && t === word.slice(0, 3)); };
61
+ const wrong = asked.filter((pos, i) => !same(answers[i], w[pos - 1]));
62
+ passed = wrong.length === 0;
63
+ if (!passed) asked = null;
64
+ return { ok: passed, wrong };
65
+ },
66
+ commit({ name, relay, now, j } = {}) {
67
+ live();
68
+ if (!passed) fail('create_unchecked', 'type the three words from your paper first');
69
+ const r = restoreFromRoot(S, { name, relay, net, restore: { restore_date: day(now) }, seat: 'here', now, ...(j !== undefined && { j }) });
70
+ S.fill(0); S = null;
71
+ r.keeper.made = 'here'; // as keeper --from-words --made-here: Me says "Created on"
72
+ return { ...r, vault };
73
+ },
74
+ discard() { S?.fill(0); S = null; },
75
+ });
76
+ }
package/enrol.mjs CHANGED
@@ -10,9 +10,10 @@
10
10
  // bytes at every call: `created` pinned, the nonce from the key (SPEC §4 `nonce`),
11
11
  // rotations m → m+1 voluntary with iat 0. A second copy of a rotation is the same
12
12
  // rotation, never a fork.
13
- // operator: issue({ carrier, file, i, n, name, keeper }) → a short code (short.mjs, 10 minutes,
14
- // once) for a normal invite, and a pending enrolment kept in `file` for 24 hours, with
15
- // the operator attestation signed now (`days`, ≤ 90; a device's 14)
13
+ // operator: issue({ carrier, file, i, n, name, keeper, relay? }) → a short code (short.mjs, 10
14
+ // minutes, once) for a normal invite (at `relay`, else the carrier's), and a pending
15
+ // enrolment kept in `file` for 24 hours, with the operator attestation signed now (`days`,
16
+ // ≤ 90; a device's 14)
16
17
  // machine: accept({ carrier, file, code, temp }) → `carrier` is a TEMPORARY identity (`temp`, its
17
18
  // file): it fetches the code, pairs, and once paired sends a request, label LABEL_ENROL,
18
19
  // {v, typ: "enrol-request", proof}
@@ -243,11 +244,11 @@ const checkKeeper = (k) => {
243
244
  * stands for (24 hours). The operator attestation is signed here, at derivation time.
244
245
  * → { short, short_exp, code, id, did (the worker's current DID), original }.
245
246
  */
246
- export async function issue({ carrier, file, i, n, name, keeper, days = OPERATOR_DAYS }) {
247
+ export async function issue({ carrier, file, i, n, name, keeper, days = OPERATOR_DAYS, relay }) {
247
248
  checkKeeper(keeper);
248
249
  const w = workerChain(keeper.K, i, n, keeper.recovery);
249
250
  // The temporary identity's contact, named apart from the worker's (forgotten once it has paired).
250
- const r = await carrier.invite({ name: `${name ?? `worker ${i}`} (enrolling)`, short: true });
251
+ const r = await carrier.invite({ name: `${name ?? `worker ${i}`} (enrolling)`, short: true, ...(relay !== undefined && relay !== carrier.relay && { relay }) });
251
252
  const now = nowOf(carrier), code = readCode(r.code, now), me = self(carrier, now);
252
253
  const attestation = operatorAttestation({ sign: me.sign, iss: me.did, sub: w.original, relay: code.relay, now, days });
253
254
  const old = liveHolding(carrier, w.original);
package/invite.mjs CHANGED
@@ -256,7 +256,7 @@ function agreed(agree, value, secret, store, r, kem_sk) {
256
256
  * order and under its names (each marked "pair:"), plus the invite's own:
257
257
  * card, challenge_unknown, challenge_expired, bundle, card_did, challenge_did (re-key codes),
258
258
  * challenge_body, transcript (own), sig, self (own), kem (own),
259
- * revoked, not_contact, bundle, stale_chain, original_did (own), revoked
259
+ * revoked, not_contact, retired_recovery (own), bundle, stale_chain, original_did (own), revoked
260
260
  * Returns { did, current_did, current_key, attestations, rejected, rekeyed, pair_key, secret,
261
261
  * answer_id } or throws MsgError. secret (hex) is gone from the store; the caller needs it for
262
262
  * the reply's topic and key, and answer_id for buildReply. rekeyed: an existing contact's pairing
@@ -285,7 +285,7 @@ export function checkAnswer(answer, store, now, agree) {
285
285
  * Bob: check Alice's reply and store her under her ORIGINAL DID. The same order; code_did stands
286
286
  * where sigelo-pair has challenge_did: Bob accepts only if the code's DID is in Alice's chain.
287
287
  * card, challenge_unknown, challenge_expired, bundle, card_did, code_did, challenge_body,
288
- * transcript, sig, self, kem, revoked, not_contact, bundle, stale_chain, original_did, revoked
288
+ * transcript, sig, self, kem, revoked, not_contact, retired_recovery, bundle, stale_chain, original_did, revoked
289
289
  * Returns { did, current_did, current_key, attestations, rejected, rekeyed, pair_key } or throws MsgError.
290
290
  */
291
291
  export function checkReply(reply, store, now, agree) {
package/link.mjs CHANGED
@@ -31,6 +31,8 @@
31
31
  // link past its ttl refused (link_expired). Run by inbox, watch and the MCP server before
32
32
  // they return messages; never by the model.
33
33
  // list({ carrier, file }) → { links: this agent's linked contacts, made: the operator's }
34
+ // labelled(carrier, messages) → the messages, each from a linked contact carrying
35
+ // link: {id, purpose} (design/links.md §8.4: the inbox shows why; data, never instructions)
34
36
  //
35
37
  // The messages: label LINK_LABEL on sigelo-msg/0, content {v, typ, id, iat, …}, id 8 characters of
36
38
  // short.mjs's alphabet:
@@ -50,7 +52,10 @@
50
52
  // other shape). Checks on an introduction (an offer not from X's operator) are never told back.
51
53
  //
52
54
  // Already paired: the purpose is attached to the pairing (link.prior: the tier before); its end
53
- // restores that tier and keeps the contact. Otherwise an end forgets the contact on both sides.
55
+ // restores that tier and keeps the contact. Otherwise an end forgets the contact on both sides, as
56
+ // ended (store.mjs): a NEW link between the same two pairs again only when each side is asked afresh
57
+ // (an ask, its operator's offer, or X's operator's accept; never an allow rule), each leaving a
58
+ // one-use permit (carrier.relink); the ended id never again (link_stale). design/links.md §7.1a.
54
59
  //
55
60
  // The file, 0600, beside the identity (x.json → x.links.json), under its own lock:
56
61
  // { v, links: { id: operator records }, pending: { "<by> <id>": an agent's step in progress },
@@ -176,6 +181,10 @@ const nowOf = (carrier) => checkNow(carrier.clock());
176
181
  const readStore = (carrier) => { const raw = platformOf(carrier).files.read(carrier.storePath); return raw === null ? { contacts: {} } : JSON.parse(textOf(raw)); };
177
182
  const exists = (carrier, file) => platformOf(carrier).files.read(file) !== null;
178
183
  const live = (c) => c && !c.revoked && c.pair_key ? c : null;
184
+ // The contact an ended link (or a forget) revoked whose chain holds `did`, or null.
185
+ const gone = (carrier, did) => Object.values(readStore(carrier).contacts).find((c) => c.revoked && c.chain.includes(did)) ?? null;
186
+ // After an end, a new link pairs again only through a permit left by this fresh step (store.mjs relink).
187
+ const relink = (carrier, did, id, until) => (gone(carrier, did) ? carrier.relink(did, id, until) : null);
179
188
  // The live contact whose chain holds `did`, or null.
180
189
  const holding = (carrier, did) => live(Object.values(readStore(carrier).contacts).find((c) => !c.revoked && c.chain.includes(did)));
181
190
  // This agent: its original DID, its chain, and its operators (issuers of the unexpired operator
@@ -278,6 +287,20 @@ export function list({ carrier, file }) {
278
287
  }), platformOf(carrier));
279
288
  }
280
289
 
290
+ /**
291
+ * Messages as an inbox returns them, each from a contact that came by a link labelled with it:
292
+ * link: {id, purpose} (a copy; others as they were). What a linked contact writes is read knowing
293
+ * why it is a contact; the purpose is the operator's text, data, never instructions.
294
+ */
295
+ export function labelled(carrier, messages) {
296
+ if (!Array.isArray(messages) || messages.length === 0) return messages;
297
+ const cs = readStore(carrier).contacts ?? {};
298
+ return messages.map((m) => {
299
+ const c = typeof m?.from === 'string' && Object.hasOwn(cs, m.from) ? cs[m.from] : null;
300
+ return live(c) && c.link ? { ...m, link: { id: c.link.id, purpose: c.link.purpose } } : m;
301
+ });
302
+ }
303
+
281
304
  // ---------------------------------------------------------------- handle
282
305
 
283
306
  /**
@@ -286,7 +309,7 @@ export function list({ carrier, file }) {
286
309
  */
287
310
  export async function handle({ carrier, file, batch = null, local = false, wait = 5 }) {
288
311
  const out = { linked: [], refused: [], ended: [], received: [], ignored: 0 };
289
- const rest = batch && { ...batch, messages: batch.messages.filter((m) => !isLink(m)) };
312
+ const rest = batch && { ...batch, messages: labelled(carrier, batch.messages.filter((m) => !isLink(m))) };
290
313
  if (local) return { ...out, batch: rest };
291
314
  const messages = [...carrier.takeLinks(), ...(batch?.messages.filter(isLink) ?? [])];
292
315
  for (const m of messages) {
@@ -331,6 +354,12 @@ async function onMessage(carrier, file, m, out, wait) {
331
354
  const had = holding(carrier, peer);
332
355
  if (had?.link) return refuse(carrier, out, m.from, x.id, had.link.id === x.id ? 'link_stale' : 'link_exists', `${had.name} is linked already (${had.link.id})`);
333
356
  if (x.typ === 'offer' && x.paired && !had) return refuse(carrier, out, m.from, x.id, 'link_peer', `the offer says this agent is paired with ${x.from}; it is not`);
357
+ if (!had) {
358
+ try { relink(carrier, peer, x.id, x.iat + x.ttl + 3600); } catch (e) {
359
+ if (!(e instanceof MsgError)) throw e;
360
+ return refuse(carrier, out, m.from, x.id, e.check, e.message);
361
+ }
362
+ }
334
363
  if (had && (x.typ === 'ask' || x.paired)) {
335
364
  // Paired already: the purpose attached to the pairing, its tier kept to restore at the end.
336
365
  if (x.tier) carrier.setTier(had.did, x.tier);
@@ -420,7 +449,7 @@ async function endHere(carrier, file, c, reason, tell, out) {
420
449
  const now = nowOf(carrier), l = c.link;
421
450
  if (tell.peer) { try { await send(carrier, c.did, msg('end', l.id, now, { reason })); } catch (e) { if (!(e instanceof MsgError)) throw e; } }
422
451
  if (l.prior) carrier.setLink(c.did, null);
423
- else await carrier.forget(c.did);
452
+ else await carrier.forget(c.did, { ended: { id: l.id, by: l.linked_by, at: now } });
424
453
  out.ended.push({ id: l.id, contact: c.did, name: c.name, reason, forgot: !l.prior });
425
454
  if (tell.operator && l.linked_by !== c.did && holding(carrier, l.linked_by)) {
426
455
  try { await send(carrier, l.linked_by, msg('status', l.id, now, { status: 'ended', check: `link_${reason === 'unlink' ? 'unlinked' : reason}` })); } catch (e) { if (!(e instanceof MsgError)) throw e; }
@@ -440,6 +469,10 @@ async function introduced(carrier, file, m, x, mine, out, wait) {
440
469
  const had = holding(carrier, x.from);
441
470
  if (had?.link) return quietly('link_exists', `${had.name} is linked already (${had.link.id})`);
442
471
  if (x.paired && !had) return quietly('link_peer', `it says this agent is paired with ${x.from}; it is not`);
472
+ // After an end: forgotten by hand, never; that link's own id, stale; a new one waits for the operator (never a rule).
473
+ const was = had ? null : gone(carrier, x.from);
474
+ if (was && !was.ended) return quietly('revoked', `${was.name} was forgotten here: never linked again`);
475
+ if (was && was.ended.id === x.id) return quietly('link_stale', `link ${x.id} ended already`);
443
476
  let exp = x.iat + x.ttl;
444
477
  if (x.code !== undefined) {
445
478
  let code;
@@ -454,7 +487,7 @@ async function introduced(carrier, file, m, x, mine, out, wait) {
454
487
  // One contact cannot crowd out the others: at most a quarter of the places each.
455
488
  const all = Object.values(s.received);
456
489
  if (all.length >= RECEIVED_MAX || all.filter((r) => r.from === m.from).length >= RECEIVED_MAX / 4) return 'full';
457
- const rule = s.allow[m.from];
490
+ const rule = was ? null : s.allow[m.from];
458
491
  s.received[key] = rule ? { ...rec, answer: { accept: true, tier: rule.tier, by: 'allow' } } : rec;
459
492
  return rule ? 'allowed' : 'kept';
460
493
  }, platformOf(carrier));
@@ -485,6 +518,18 @@ async function answered(carrier, file, key, r, out, wait) {
485
518
  try { await send(carrier, r.from, msg('status', r.id, now, { status: 'linked' })); } catch (e) { if (!(e instanceof MsgError)) throw e; }
486
519
  return;
487
520
  }
521
+ // After an end: only the operator's own accept relinks (its permit, store.mjs relink), never a rule.
522
+ if (gone(carrier, r.peer) && r.answer.by !== 'operator') {
523
+ drop();
524
+ out.refused.push({ id: r.id, check: 'revoked', detail: `the introduction from ${r.from}: a link with it ended; only your operator links it again (not told)`, from: r.from, silent: true });
525
+ return;
526
+ }
527
+ try { relink(carrier, r.peer, r.id, r.exp + 3600); } catch (e) {
528
+ if (!(e instanceof MsgError)) throw e;
529
+ drop();
530
+ out.refused.push({ id: r.id, check: e.check, detail: `the introduction from ${r.from}: ${e.message} (not told)`, from: r.from, silent: true });
531
+ return;
532
+ }
488
533
  state(file, now, (s) => { delete s.received[key]; s.pending[key] = { ...base, role: 'b', peer: r.peer, code_did: r.did, exp: r.exp + 3600 }; }, platformOf(carrier));
489
534
  try { await carrier.accept(r.code, { ...(r.name && { name: r.name }), wait, tier }); } catch (e) {
490
535
  if (!(e instanceof MsgError)) throw e;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sigelo-contact",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "private": false,
5
5
  "description": "Agent contacts for sigelo identities: invite codes, a contact store, end-to-end encrypted envelopes with hybrid post-quantum key agreement, and an MQTT carrier. Client code (MIT); the relay server is csigelo/sigelo-relay (AGPL-3.0).",
6
6
  "keywords": [
@@ -12,7 +12,11 @@
12
12
  "ml-kem",
13
13
  "mqtt",
14
14
  "did",
15
- "sigelo"
15
+ "sigelo",
16
+ "agent-to-agent",
17
+ "agent-communication",
18
+ "pairing-code",
19
+ "mcp"
16
20
  ],
17
21
  "homepage": "https://sigelo.io/",
18
22
  "repository": {
@@ -62,6 +66,8 @@
62
66
  "./qr-decode.mjs": "./qr-decode.mjs",
63
67
  "./restore": "./restore.mjs",
64
68
  "./restore.mjs": "./restore.mjs",
69
+ "./create": "./create.mjs",
70
+ "./create.mjs": "./create.mjs",
65
71
  "./package.json": "./package.json"
66
72
  },
67
73
  "files": [
@@ -69,6 +75,7 @@
69
75
  "bip39-english.mjs",
70
76
  "carrier.mjs",
71
77
  "control.mjs",
78
+ "create.mjs",
72
79
  "device.mjs",
73
80
  "enrol.mjs",
74
81
  "envelope.mjs",
@@ -122,6 +129,6 @@
122
129
  "@noble/hashes": "^2.4.0",
123
130
  "@noble/post-quantum": "^0.7.1",
124
131
  "mqtt": "^5.16.0",
125
- "sigelo": "^0.1.10"
132
+ "sigelo": "^0.1.12"
126
133
  }
127
134
  }
package/page.mjs CHANGED
@@ -17,11 +17,22 @@
17
17
  // line and "\n"), clearHistory(), readData() → text | null, writeData(text). The history is every
18
18
  // message and pairing event the carrier's inbox() hands over; data is the page's own (tags, words
19
19
  // checked, read marks, the host's controls). hooks: me() → { did, original, chain }, meInfo() →
20
- // { identity_file, recovery, key, erase, restored? } (restored: the app's restore from seed, { on, keeper, seat }), agents() → the agents' directory as the state shows it
20
+ // { identity_file, recovery, key, erase, restored? } (restored: the app's restore from seed, { on, keeper, seat, created? }), agents() → the agents' directory as the state shows it
21
21
  // ([] where there is none), seat() → the seat or null, deviceRound() → { gave? } after each drain
22
22
  // (or none), note(line), defer(fn) (setImmediate on Node), every(fn, ms) → a timer, hidden({ did, name })
23
23
  // → true for what the page never shows nor names (the computer's relay controls: their contacts, their
24
- // pairing, their codes waiting; design/apps.md §6.3).
24
+ // pairing, their codes waiting; design/apps.md §6.3), controls: { pending() → [{name, scope, words}],
25
+ // confirm(name, match) → whether one was pending } (relay controls whose four words wait: the
26
+ // Controls card; routes in no remote scope, so never asked over the relay or the LAN).
27
+ //
28
+ // Agents (ENROL.md, the app's main list): hooks.keeper, where the host has the operator's keeper root:
29
+ // { read() → the keeper file as JSON (workers, …) | null, root(k) → { K, recovery } (K zeroed after use),
30
+ // update(fn) → fn(keeper) applied and kept }. enrolFile: the pending enrolments (enrol.mjs enrolPath). The
31
+ // page issues a one-time code for worker i on its own session (enrol.mjs issue, the operator side of
32
+ // `sigelo-agent enrol --name`, which refuses busy beside a page), takes the requests that come through
33
+ // it (kept apart from the devices'), answers them with the worker's identity and files the worker
34
+ // when it pairs (complete). Worker indices are allocated at the seat only (DEVICES.md): a page whose
35
+ // seat is on another device refuses seat_elsewhere.
25
36
  //
26
37
  // The relay setting (UI-API.md "Settings"): the relay new codes name, kept in data.settings.relay.
27
38
  // Precedence: relayFixed (the host's environment: SIGELO_RELAY, or a relay the host was given) wins,
@@ -31,20 +42,25 @@
31
42
  // relay.sigelo.ai's (the carrier's relayForShort).
32
43
  import { bytesToHex, randomBytes } from '@noble/hashes/utils.js';
33
44
  import { DEFAULT_RELAY } from './carrier.mjs';
45
+ import * as E from './enrol.mjs';
34
46
  import { checkRelay } from './invite.mjs';
35
47
 
36
48
  const DAY = 86400, TAG_MAX = 20, NAME_MAX = 64, TEXT_MAX = 100_000;
49
+ // An agent's name: a contact name and, placed here, a file name (sigelo.<name>.local.json), as `enrol --name` takes it.
50
+ const AGENT_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
37
51
  const goodRelay = (h) => { try { checkRelay(h); return true; } catch { return false; } };
38
52
  const nowS = () => Math.floor(Date.now() / 1000);
39
53
  const hexOf = (n) => bytesToHex(randomBytes(n));
40
54
  export const refuse = (status, check, message) => { throw Object.assign(new Error(message), { check, status }); };
41
55
 
42
- export function makePage({ makeCarrier, link: L, linksFile, codeKind, unlogged, store, hooks = {}, relayFixed = null }) {
56
+ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, codeKind, unlogged, store, hooks = {}, relayFixed = null }) {
43
57
  const defer = hooks.defer ?? ((f) => setTimeout(f, 0));
44
58
  const every = hooks.every ?? ((f, ms) => { const t = setInterval(f, ms); t.unref?.(); return t; });
45
59
  const watchers = new Set();
46
60
  const changed = () => { for (const f of watchers) { try { f(); } catch {} } };
47
- const hidden = (x) => { try { return hooks.hidden?.(x) === true; } catch { return false; } };
61
+ // What the page never shows: the host's (relay controls), and an enrolment's temporary pairing (its code's
62
+ // invite, the temporary DID): the worker shows in Agents, then as itself once it has paired.
63
+ const hidden = (x) => { try { return enrolHidden(x) || hooks.hidden?.(x) === true; } catch { return false; } };
48
64
 
49
65
  // ---- history: every message and pairing event, one JSON line each; status lines fold into their message
50
66
  const recs = [], outById = new Map();
@@ -78,17 +94,23 @@ export function makePage({ makeCarrier, link: L, linksFile, codeKind, unlogged,
78
94
  const serial = (f0) => { const fn = gone(f0); const p = chain.then(fn, fn); chain = p.catch(() => {}); return p; };
79
95
  const invites = new Map();
80
96
  let devices = null;
97
+ // Enrolments this page issued (agents, below): id (the code's nonce) → { id, worker, name, short, code, exp, relay, tier,
98
+ // state: code | words | sending | enrolled | expired | failed, words, temp, did, original, check?, detail? }.
99
+ const enrolling = new Map();
100
+ let agentHeld = [];
81
101
  // What the carrier's inbox() hands over, as every client takes it: messages and the events it
82
102
  // keeps (pairings, failures, rotations), into the history. Taken at once after any event, and
83
103
  // every minute for what no event announced.
84
104
  let draining = null, again = false;
85
105
  function take(b) {
86
- for (const m of b.messages) {
106
+ // A linked contact's messages carry the link (id, purpose): data, shown beside them.
107
+ for (const m of (L.labelled ? L.labelled(carrier, b.messages) : b.messages)) {
87
108
  // Enrolment and device messages carry keys or codes: never in the history (the device rounds take them).
88
- if (typeof m['label'] === 'string' && unlogged.test(m['label'])) { devices?.hold(m); continue; }
109
+ if (typeof m['label'] === 'string' && unlogged.test(m['label'])) { if (!holdAgent(m)) devices?.hold(m); continue; }
89
110
  if (hidden({ did: m['from'], name: m['name'] })) continue;
90
- if (m['type'] === 'file') record({ kind: 'in', did: m['from'], name: m['contact'], label: m['label'], text: `file ${String(m['name'])} (${String(m['size'])} bytes), saved at ${String(m['path'])}` });
91
- else record({ kind: 'in', did: m['from'], name: m['name'], text: m['content'], label: m['label'] });
111
+ const link = m['link'] ? { link: m['link'] } : {};
112
+ if (m['type'] === 'file') record({ kind: 'in', did: m['from'], name: m['contact'], label: m['label'], text: `file ${String(m['name'])} (${String(m['size'])} bytes), saved at ${String(m['path'])}`, ...link });
113
+ else record({ kind: 'in', did: m['from'], name: m['name'], text: m['content'], label: m['label'], ...link });
92
114
  }
93
115
  const named = new Set();
94
116
  for (const e of b.events) {
@@ -124,6 +146,7 @@ export function makePage({ makeCarrier, link: L, linksFile, codeKind, unlogged,
124
146
  } catch (err) { live.error = `inbox: ${err.message}`; }
125
147
  finally { draining = null; }
126
148
  if (live.seatGone === null && devices?.busy()) void serial(() => devices.round()).catch((err) => { live.error = `devices: ${err.message}`; });
149
+ if (live.seatGone === null && agentsBusy()) void serial(() => agentRound()).catch((err) => { live.error = `agents: ${err.message}`; });
127
150
  })();
128
151
  return draining;
129
152
  }
@@ -184,6 +207,96 @@ export function makePage({ makeCarrier, link: L, linksFile, codeKind, unlogged,
184
207
  await linking.catch(() => {});
185
208
  }
186
209
 
210
+
211
+ // ---- agents: the operator's workers (keeper `workers`), enrolled by a one-time code from this page
212
+ const K = hooks.keeper ?? null;
213
+ const pend = (fn) => E.pending(enrolFile, nowS(), fn, carrier.platform);
214
+ const LIVE = new Set(['code', 'words', 'sending']);
215
+ function enrolHidden(x) {
216
+ for (const e of enrolling.values()) {
217
+ if (x.did !== undefined && x.did !== null && (x.did === e.temp || (LIVE.has(e.state) && carrier.answeredBy(e.id) === x.did))) return true;
218
+ if (x.name === `${e.name} (enrolling)` && LIVE.has(e.state)) return true;
219
+ }
220
+ return false;
221
+ }
222
+ // An enrolment request from the DID that answered one of this page's codes: kept for agentRound, not the devices'.
223
+ function holdAgent(m) {
224
+ if (m['label'] !== E.LABEL_ENROL) return false;
225
+ for (const e of enrolling.values()) {
226
+ if (LIVE.has(e.state) && (e.temp === m['from'] || carrier.answeredBy(e.id) === m['from'])) { agentHeld.push(m); return true; }
227
+ }
228
+ return false;
229
+ }
230
+ const agentsBusy = () => agentHeld.length > 0 || [...enrolling.values()].some((e) => LIVE.has(e.state));
231
+ const keeperOr = async () => (K ? await K.read() : null) ?? refuse(400, 'keeper', 'no keeper root here: your 25 words make it (sigelo-agent keeper --from-words on a computer; in the app, Create or Restore from seed)');
232
+ const seatHere = () => { const st = hooks.seat?.(); if (st && st.here === false) refuse(409, 'seat_elsewhere', `the seat is with ${st.holder}: agents are enrolled there (DEVICES.md)`); };
233
+ const pub = (e) => ({ id: e.id, state: e.state, code: e.state === 'code' ? e.short : null, exp: e.exp, relay: e.relay, words: e.words ?? null,
234
+ command: e.state === 'code' ? `${e.relay !== DEFAULT_RELAY ? `SIGELO_RELAY=${e.relay} ` : ''}sigelo-agent init --enrol ${e.short}` : null, ...(e.check !== undefined && { check: e.check, detail: e.detail ?? null }) });
235
+ // Who answered each code (its four words), codes dead unanswered (the index free again), enrolments done.
236
+ async function look() {
237
+ if (!enrolFile) return;
238
+ const t = nowS(), issued = pend((st) => Object.fromEntries(Object.entries(st.issued).map(([id, e]) => [id, { done: e.done ?? null }])));
239
+ for (const e of enrolling.values()) {
240
+ if (!LIVE.has(e.state)) continue;
241
+ const f = issued[e.id];
242
+ if (f?.done) { e.state = 'enrolled'; e.at = f.done; changed(); continue; }
243
+ if (!f) { e.state = 'expired'; changed(); continue; }
244
+ if (e.state !== 'code') continue;
245
+ const by = carrier.answeredBy(e.id);
246
+ if (by) {
247
+ e.temp = by; e.state = 'words';
248
+ e.words = carrier.contacts().contacts.find((x) => x.did === by)?.fingerprint ?? null;
249
+ changed();
250
+ } else if (t > e.exp + 30) {
251
+ e.state = 'expired';
252
+ pend((st) => { delete st.issued[e.id]; });
253
+ try { await carrier.cancelInvite(e.code); } catch {}
254
+ await K?.update((k) => { if (k.workers[e.worker]?.name === e.name && k.workers[e.worker].placed === 'remote') delete k.workers[e.worker]; });
255
+ changed();
256
+ }
257
+ }
258
+ }
259
+ // The requests kept apart, answered with the worker's identity; a worker that paired is filed (enrol.mjs complete).
260
+ async function agentRound() {
261
+ await look();
262
+ const pass = agentHeld.splice(0);
263
+ if (!pass.length && ![...enrolling.values()].some((e) => e.state === 'words' || e.state === 'sending')) return;
264
+ const k = await K?.read();
265
+ if (!k) return;
266
+ const root = await K.root(k);
267
+ // The carrier as enrolment sees it: its inbox is what the page kept apart.
268
+ const proxy = new Proxy(carrier, { get: (x, p) => (p === 'inbox' ? async () => ({ messages: pass.splice(0), events: [], dropped: {} }) : typeof x[p] === 'function' ? x[p].bind(x) : x[p]) });
269
+ let res;
270
+ try { res = await E.complete({ carrier: proxy, file: enrolFile, keeper: root, wait: 0 }); } finally { root.K.fill(0); }
271
+ for (const d of res.delivered) { const e = enrolling.get(d.id); if (e) e.state = 'sending'; }
272
+ for (const x of res.refused) {
273
+ const e = [...enrolling.values()].find((y) => y.temp !== undefined && y.temp === x.from);
274
+ if (e) Object.assign(e, { check: x.check, detail: x.detail });
275
+ }
276
+ for (const p of res.placed) { const e = enrolling.get(p.id); if (e) Object.assign(e, { state: 'enrolled', at: nowS(), did: p.did }); }
277
+ changed();
278
+ }
279
+ const workerOf = (k, v) => {
280
+ if (!Number.isSafeInteger(v) || v < 0) refuse(400, 'body', 'worker: its index (0, 1, 2…)');
281
+ return k.workers[v] ?? refuse(404, 'worker', `no worker ${v} in the keeper's roster`);
282
+ };
283
+ // The contact holding a worker's original DID, live, or null.
284
+ const contactOfWorker = (w) => carrier.contacts().contacts.find((x) => !x.revoked && x.chain.includes(w.original)) ?? null;
285
+ async function workers() {
286
+ const k = K ? await K.read() : null, st = hooks.seat?.() ?? null, seat = st ? (st.here ? 'here' : 'elsewhere') : null;
287
+ if (!k) return { keeper: false, seat, workers: [] };
288
+ await look();
289
+ const local = hooks.agents?.() ?? [], waiting = enrolFile ? pend((x) => Object.values(x.issued).filter((e) => !e.done).map((e) => e.i)) : [];
290
+ const rows = Object.entries(k.workers).map(([i, w]) => {
291
+ const n = Number(i), c = contactOfWorker(w), here = local.find((a) => a.did === w.original), e = [...enrolling.values()].filter((x) => x.worker === n).at(-1);
292
+ const status = w.revoked !== undefined ? 'revoked' : c || here ? 'enrolled' : (e && LIVE.has(e.state)) || waiting.includes(n) ? 'pending' : 'unplaced';
293
+ return { worker: n, name: w.name, did: c?.current_did ?? w.did, original: w.original, rank: w.rank ?? null, placed: w.placed, at: w.at, status, revoked: w.revoked ?? null,
294
+ seen: c ? seen(c.did) : null, tier: c?.tier ?? null, contact: c?.did ?? null, local: here?.name ?? null,
295
+ attested_until: here?.mine?.exp ?? w.until ?? w.attestation?.body?.exp ?? null, enrolling: e && e.state !== 'expired' ? pub(e) : null };
296
+ }).sort((a, b) => a.worker - b.worker);
297
+ return { keeper: true, seat, workers: rows };
298
+ }
299
+
187
300
  // ---- reads
188
301
  const textOf = (v) => (typeof v === 'string' ? v : JSON.stringify(v));
189
302
  function state(since) {
@@ -339,7 +452,7 @@ export function makePage({ makeCarrier, link: L, linksFile, codeKind, unlogged,
339
452
  const msgs = recs.filter((r) => (r.kind === 'in' || r.kind === 'out') && r.did === d && r.n > since).slice(-200);
340
453
  // Read: the page has shown them.
341
454
  if ((data.read[d] ?? 0) < seq) { data.read[d] = seq; saveData(); }
342
- return { seq, messages: msgs.map((r) => ({ n: r.n, dir: r.kind, at: r.at, text: textOf(r.text), label: r.label ?? '', status: r.status ?? null, code: r.code ?? null, detail: r.detail ?? null })) };
455
+ return { seq, messages: msgs.map((r) => ({ n: r.n, dir: r.kind, at: r.at, text: textOf(r.text), label: r.label ?? '', status: r.status ?? null, code: r.code ?? null, detail: r.detail ?? null, link: r.link ?? null })) };
343
456
  },
344
457
  'POST /api/sync': () => serial(async () => { await carrier.sync(); return { synced: true }; }),
345
458
  'POST /api/history/clear': () => serial(async () => {
@@ -360,6 +473,72 @@ export function makePage({ makeCarrier, link: L, linksFile, codeKind, unlogged,
360
473
  }),
361
474
  // The signed registry's relays (sigelo.ai/relays.json, verified; fetched at most once a day): the page's picker.
362
475
  'GET /api/relays': async () => ({ relays: await carrier.registryRelays() }),
476
+ // The relay picker's Test (UI-API.md): does this host answer as a relay, before it is used.
477
+ 'POST /api/relays/test': async (b) => {
478
+ const v = typeof b['relay'] === 'string' ? b['relay'].trim().toLowerCase() : '';
479
+ if (!goodRelay(v)) refuse(400, 'body', 'relay: a host name, as relay.example.org (a port after a colon if not the usual)');
480
+ return carrier.probeRelay(v);
481
+ },
482
+ // Agents (ENROL.md): the keeper's workers; a one-time code for worker i (the next free); revoke; rename.
483
+ 'GET /api/agents/workers': () => workers(),
484
+ 'POST /api/agents/enrol-code': (b) => serial(async () => {
485
+ seatHere();
486
+ if (!enrolFile) refuse(404, 'route', 'no enrolment here');
487
+ const name = b['name'], tier = b['tier'], relay = b['relay'];
488
+ if (typeof name !== 'string' || !AGENT_NAME.test(name)) refuse(400, 'body', 'name: lowercase letters, digits, _ and -, at most 64');
489
+ if (tier !== undefined && tier !== 'own' && tier !== 'friend' && tier !== 'quiet') refuse(400, 'body', 'tier: own (the default), friend or quiet');
490
+ if (relay !== undefined && relay !== null && relay !== '' && !(typeof relay === 'string' && goodRelay(relay.trim().toLowerCase()))) refuse(400, 'body', 'relay: a host name, as relay.example.org');
491
+ const at = relayFixed ?? (typeof relay === 'string' && relay !== '' ? relay.trim().toLowerCase() : newCodes());
492
+ const k = await keeperOr();
493
+ const same = Object.entries(k.workers).find(([, w]) => w.name === name && w.revoked === undefined);
494
+ if (same) refuse(409, 'name_taken', `${name} is worker ${same[0]} already: another name`);
495
+ const used = Object.keys(k.workers).map(Number), i = used.length ? Math.max(...used) + 1 : 0;
496
+ const root = await K.root(k);
497
+ let r;
498
+ try { r = await E.issue({ carrier, file: enrolFile, i, n: 0, name, keeper: root, relay: at }); } finally { root.K.fill(0); }
499
+ const until = pend((x) => x.issued[r.id]?.attestation?.body?.exp ?? null);
500
+ await K.update((x) => { x.workers[i] = { name, n: 0, did: r.did, original: r.original, placed: 'remote', at: nowS(), ...(until && { until }) }; });
501
+ if (tier === 'friend' || tier === 'quiet') carrier.presetTier(r.original, tier);
502
+ const e = { id: r.id, worker: i, name, short: r.short, code: r.code, exp: r.short_exp, relay: r.relay, tier: tier ?? 'own', state: 'code', did: r.did, original: r.original };
503
+ enrolling.set(e.id, e);
504
+ changed();
505
+ return { worker: i, name, did: r.did, original: r.original, tier: e.tier, ...pub(e) };
506
+ }),
507
+ 'POST /api/agents/revoke': (b) => serial(async () => {
508
+ seatHere();
509
+ const k = await keeperOr(), i = b['worker'], w = workerOf(k, i);
510
+ if (w.revoked !== undefined) refuse(409, 'revoked', `worker ${i} (${w.name}) is revoked already`);
511
+ if (w.placed === 'device') refuse(409, 'device', `${w.name} is a device: revoke it under Devices (it is told to delete its keys)`);
512
+ const e = [...enrolling.values()].filter((x) => x.worker === i).at(-1);
513
+ // A code nobody answered: cancelled, the index free again. Anything further: the worker may hold its key: revoked.
514
+ if (e?.state === 'code') {
515
+ try { await carrier.cancelInvite(e.code); } catch {}
516
+ pend((x) => { delete x.issued[e.id]; });
517
+ await K.update((x) => { delete x.workers[i]; });
518
+ e.state = 'expired';
519
+ changed();
520
+ return { worker: i, name: w.name, cancelled: true, revoked: null, forgot: null };
521
+ }
522
+ if (e && LIVE.has(e.state)) { pend((x) => { delete x.issued[e.id]; }); e.state = 'failed'; e.check = 'revoked'; if (e.temp) { try { await carrier.forget(e.temp); } catch {} } }
523
+ const c = contactOfWorker(w);
524
+ if (c) await carrier.forget(c.did);
525
+ const t = nowS();
526
+ await K.update((x) => { if (x.workers[i]) x.workers[i].revoked = t; });
527
+ changed();
528
+ return { worker: i, name: w.name, cancelled: false, revoked: t, forgot: c?.did ?? null, attested_until: w.until ?? w.attestation?.body?.exp ?? null };
529
+ }),
530
+ 'POST /api/agents/rename': (b) => serial(async () => {
531
+ seatHere();
532
+ const k = await keeperOr(), i = b['worker'], w = workerOf(k, i), name = b['name'];
533
+ if (typeof name !== 'string' || !AGENT_NAME.test(name)) refuse(400, 'body', 'name: lowercase letters, digits, _ and -, at most 64');
534
+ const same = Object.entries(k.workers).find(([j, x]) => Number(j) !== i && x.name === name && x.revoked === undefined);
535
+ if (same) refuse(409, 'name_taken', `${name} is worker ${same[0]} already: another name`);
536
+ const c = contactOfWorker(w);
537
+ if (c && c.name !== name) carrier.rename(c.did, name);
538
+ await K.update((x) => { if (x.workers[i]) x.workers[i].name = name; });
539
+ changed();
540
+ return { worker: i, name };
541
+ }),
363
542
  // Links (LINKS.md). The operator's: link, unlink, the list. This identity's introductions: answer, allow.
364
543
  'GET /api/links': () => linkCall(() => {
365
544
  const r = L.list({ carrier, file: linksFile }), cs = carrier.contacts().contacts;
@@ -404,6 +583,15 @@ export function makePage({ makeCarrier, link: L, linksFile, codeKind, unlogged,
404
583
  return allow ? L.allow({ carrier, file: linksFile, contact, ...(typeof tier === 'string' && { tier }), ...(typeof days === 'number' && { days }) })
405
584
  : L.deny({ carrier, file: linksFile, contact });
406
585
  })),
586
+ // Relay controls paired, their four words not confirmed (the terminal's y/N, here on the page).
587
+ 'GET /api/controls': () => ({ pending: hooks.controls?.pending() ?? [] }),
588
+ // Not serial: a refusal forgets the control's contact through serial itself.
589
+ 'POST /api/controls/confirm': async (b) => {
590
+ const name = b['name'], match = b['match'];
591
+ if (typeof name !== 'string' || name === '' || typeof match !== 'boolean') refuse(400, 'body', 'name: a control\'s name; match: true (the app shows the same four words) or false');
592
+ if (!hooks.controls || !(await hooks.controls.confirm(name, match))) refuse(404, 'control_unknown', `no control ${JSON.stringify(name)} waits for its four words`);
593
+ return { name, confirmed: match, ...(!match && { forgotten: true }) };
594
+ },
407
595
  };
408
596
  // One handler for every listener: the route's answer as [status, JSON value].
409
597
  async function dispatch(method, url, b) {
package/relays.mjs CHANGED
@@ -9,6 +9,10 @@
9
9
  // 3. none: the person is asked once (accept --relay <host>), and the host goes into the table.
10
10
  // Two known hosts with one tag (20 bits collide, by chance or on purpose): neither is guessed, the
11
11
  // person is asked. The registry lists a tag once (first host keeps it), so it cannot collide.
12
+ // A contact's relay comes from the code that contact paired with, so its tag can be ground to equal
13
+ // any registered relay's in seconds: such a host wins only when the registry has no other host for
14
+ // the tag; one it names otherwise is a collision, asked (review 2026-10-28, MEDIUM 4). The own,
15
+ // operator and table hosts rank above both and never consult the registry.
12
16
  //
13
17
  // The local table: relays.local.json beside the identity, {"relays": ["corp.example.com", …]}, hosts
14
18
  // as a long code names them (host[:port]); the tag is computed, never stored. The registry cache:
@@ -108,18 +112,26 @@ export async function loadRegistry({ file, url = REGISTRY_URL, now, get, pin = R
108
112
  }
109
113
 
110
114
  /**
111
- * The host for `tag`. known: [{ host, from }] (step 1, any order; duplicates of a host are one);
112
- * registry: () => Promise<Map> (step 2, called only when step 1 has no host for the tag).
113
- * → { host, from }; throws relay_tag when two known hosts share the tag, or nothing has it.
115
+ * The host for `tag`. known: [{ host, from }] (step 1, any order; duplicates of a host are one, the
116
+ * trusted `from` kept over 'contact'); registry: () => Promise<Map> (step 2, called when step 1 has no
117
+ * host for the tag, or only a contact's). → { host, from }; throws relay_tag when two known hosts
118
+ * share the tag, when the registry names another host than the one contact's, or nothing has it.
114
119
  */
115
120
  export async function resolveTag(tag, { known, registry, shown }) {
116
121
  const hits = new Map();
117
- for (const k of known) if (goodRelay(k.host) && relayTag(k.host) === tag && !hits.has(k.host)) hits.set(k.host, k.from);
122
+ for (const k of known) if (goodRelay(k.host) && relayTag(k.host) === tag && (!hits.has(k.host) || hits.get(k.host) === 'contact')) hits.set(k.host, k.from);
118
123
  if (hits.size > 1) {
119
124
  fail('relay_tag', `short code ${shown}: its relay tag ${tag} fits ${[...hits.keys()].join(' and ')}, relays this agent knows: it does not guess. Ask the inviter which relay it used, then accept it with --relay <host>`);
120
125
  }
121
- if (hits.size === 1) { const [[host, from]] = hits; return { host, from }; }
126
+ const [[host, from] = []] = hits;
127
+ if (host !== undefined && from !== 'contact') return { host, from };
122
128
  const e = (await registry()).get(tag);
129
+ if (host !== undefined) {
130
+ if (e && e.host !== host) {
131
+ fail('relay_tag', `short code ${shown}: its relay tag ${tag} fits ${host}, a contact's relay, and ${e.host} in the registry: it does not guess. Ask the inviter which relay it used, then accept it with --relay <host>`);
132
+ }
133
+ return { host, from };
134
+ }
123
135
  if (e) return { host: e.host, from: 'registry' };
124
136
  return fail('relay_tag', `short code ${shown} was made on a relay this agent does not know (relay tag ${tag}): ask the inviter which relay, then accept it with --relay <host> (remembered for its next code); or ask for the long code (invite --long)`);
125
137
  }
package/restore.mjs CHANGED
@@ -19,6 +19,7 @@
19
19
  // seat "elsewhere": null (the seat's list is on the other device)
20
20
  // notes me.local.seat.json: { v, here: {name, did, worker}, imported: 1 } or, elsewhere,
21
21
  // { v, here, elsewhere: true, entry } (the list entry `takeSeat` signs later)
22
+ // restoreFromRoot(S, o) the same from the 32-byte root (a new identity, contact/create.mjs); S stays the caller's
22
23
  // takeSeat(notes, identity, now) → { list, notes } standby → seat: the list naming this device
23
24
  // (epoch 1: the other device's list is not known here, so this is
24
25
  // `seat take --force` semantics; the caller warns first)
@@ -29,6 +30,7 @@ import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js';
29
30
  import { did as didOf, sign as signWith } from 'sigelo';
30
31
  import { keeperRoot, recoveryCommitment, rootFromMnemonic } from 'sigelo/dist/keys.js';
31
32
  import { MONERO_WORDS } from 'sigelo/dist/monero-words.js';
33
+ import { scReduce32 } from 'sigelo/dist/monero.js';
32
34
  import { DEVICE_DAYS, KEEPER_V, checkName, nextSeat, signList } from './device.mjs';
33
35
  import { operatorAttestation, operatorIdentity, workerChain, workerIdentity } from './enrol.mjs';
34
36
  import { checkRelay } from './invite.mjs';
@@ -86,16 +88,49 @@ function checkMeta(restore) {
86
88
  * relay (the host its attestation names), net, restore ({} | {restore_height} | {restore_date}),
87
89
  * seat ("here" | "elsewhere"), now (unix seconds), j (the keeper index, 1; never 0) }.
88
90
  */
89
- export function restoreFromWords(text, { name, relay, net = 'mainnet', restore = {}, seat = 'here', now, j = KEEPER_J } = {}) {
91
+ export function restoreFromWords(text, o = {}) {
92
+ checkOptions(o);
93
+ const c = checkWords(text);
94
+ if (!c.ok) fail('restore_words', c.error ?? `${c.count} of ${WORD_COUNT} words`);
95
+ let S = null;
96
+ try {
97
+ S = rootFromMnemonic(split(text).join(' '));
98
+ return derive(S, o);
99
+ } catch (e) {
100
+ // Never a message that could carry a word: the words were checked above, anything else is ours.
101
+ if (e?.check) throw e;
102
+ return fail('restore', `the restore failed (${e?.constructor?.name ?? 'error'})`);
103
+ } finally { S?.fill(0); }
104
+ }
105
+
106
+ /**
107
+ * The same files from the root S itself (32 bytes, canonical), for a new identity made on the device
108
+ * (contact/create.mjs): S is the caller's to zero. o as restoreFromWords.
109
+ */
110
+ export function restoreFromRoot(S, o = {}) {
111
+ checkOptions(o);
112
+ if (!(S instanceof Uint8Array) || S.length !== 32 || !canonical(S)) fail('restore', 'a canonical root of 32 bytes (0 < S < l)');
113
+ try { return derive(S, o); } catch (e) {
114
+ if (e?.check) throw e;
115
+ return fail('restore', `the derivation failed (${e?.constructor?.name ?? 'error'})`);
116
+ }
117
+ }
118
+
119
+ // 0 < S < l, as keys.ts: only then is a wallet's spend key S itself, so the words a wallet shows are S's.
120
+ const canonical = (S) => { const r = scReduce32(S); try { return r.every((x, i) => x === S[i]) && S.some((x) => x !== 0); } finally { r.fill(0); } };
121
+
122
+ function checkOptions({ name, relay, net = 'mainnet', restore = {}, seat = 'here', now, j = KEEPER_J } = {}) {
90
123
  checkNow(now); checkName(name); checkRelay(relay);
91
124
  if (!NETS.includes(net)) fail('restore_net', `net: ${NETS.join(' or ')}`);
92
125
  if (!SEATS.includes(seat)) fail('restore_seat', `seat: ${SEATS.join(' or ')}`);
93
126
  if (!Number.isSafeInteger(j) || j < 1) fail('restore', 'keeper: 1 or more (K_0 is the ceremony\'s agents\' keeper)');
94
- const meta = checkMeta(restore), c = checkWords(text);
95
- if (!c.ok) fail('restore_words', c.error ?? `${c.count} of ${WORD_COUNT} words`);
96
- let S = null, K = null, secret = null;
127
+ checkMeta(restore);
128
+ }
129
+
130
+ function derive(S, { name, relay, net = 'mainnet', restore = {}, seat = 'here', now, j = KEEPER_J }) {
131
+ const meta = restore ?? {};
132
+ let K = null, secret = null;
97
133
  try {
98
- S = rootFromMnemonic(split(text).join(' '));
99
134
  const identity = operatorIdentity(S, 0), original = didOf(identity.genesis), recovery = recoveryCommitment(S);
100
135
  K = keeperRoot(S, j);
101
136
  secret = hexToBytes(identity.secret);
@@ -110,11 +145,7 @@ export function restoreFromWords(text, { name, relay, net = 'mainnet', restore =
110
145
  const list = seat === 'here' ? signList({ operator: original, seq: 1, iat: now, devices: [entry], seat: nextSeat(undefined, w.original, now) }, (b) => signWith(secret, b)) : null;
111
146
  const notes = list ? { v: SEAT_LOCAL_V, here, imported: 1 } : { v: SEAT_LOCAL_V, here, elsewhere: true, entry };
112
147
  return { identity, keeper, device, list, notes, did: original, worker: w.original };
113
- } catch (e) {
114
- // Never a message that could carry a word: the words were checked above, anything else is ours.
115
- if (e?.check) throw e;
116
- return fail('restore', `the restore failed (${e?.constructor?.name ?? 'error'})`);
117
- } finally { S?.fill(0); K?.fill(0); secret?.fill(0); }
148
+ } finally { K?.fill(0); secret?.fill(0); }
118
149
  }
119
150
 
120
151
  /** A standby restored device takes the seat: the list naming it, signed by the operator key in `identity`. */
package/store.mjs CHANGED
@@ -26,12 +26,14 @@
26
26
  // introduction this contact came with (prior: {tier, tier_by}, the pairing was there before: an end
27
27
  // restores them instead of forgetting). Kept by a re-pair, a merge and a rename; gone with revoke. A
28
28
  // link never writes operator_exp, so never ours; while it lasts a contact that is not ours cannot be
29
- // set own (link_tier).
29
+ // set own (link_tier). ended: {id, by, at} on a contact a link's end revoked (revoke(did, ended)), and
30
+ // relink: {id, until}, the one-use permit a NEW link leaves on it (design/links.md §7.1a): the pairing
31
+ // through that link's code is admitted, the record written afresh. Forgotten by hand: no ended, never.
30
32
  // The file holds one-time secrets, Bob's one-time key and
31
33
  // pairing keys, so it is written 0600. Two simultaneous writers still need the integrator's lock.
32
34
  import { utf8ToBytes } from '@noble/hashes/utils.js';
33
35
  import { files as nodeFiles } from './platform-node.mjs';
34
- import { canonicalize, verify } from 'sigelo';
36
+ import { canonicalize, commitmentOf, verify, verifySig } from 'sigelo';
35
37
  import { SKEW, TTL_MAX, V, attempt, checkTime, fail, hex, keyOf } from './invite.mjs';
36
38
 
37
39
  export const TIERS = ['own', 'friend', 'quiet'];
@@ -42,6 +44,21 @@ export const OPERATOR_CTX = 'sigelo-relay/operator';
42
44
  export const NAME_MAX = 64;
43
45
  // What a record keeps of its tier through admit (a re-pair, a merged notice).
44
46
  const TIER_KEYS = ['tier', 'tier_by', 'operator_exp', 'link'];
47
+ // A recovery key used and replaced still governs every node up to its retirement (SPEC §7.2), and
48
+ // no offline verifier tells its thief from its owner (THREAT-MODEL §2.5a). A known contact's record
49
+ // remembers: its chain holds the recovery rotation that retired the key. → commitment → JCS of that
50
+ // rotation, for the rotations on the chain's edges (signed by the key hashing to the commitment,
51
+ // into a genesis with another one or none).
52
+ const commitOrNull = (k) => { try { return commitmentOf(k); } catch { return null; } };
53
+ const jcsOrNull = (x) => { try { return canonicalize(x); } catch { return null; } };
54
+ function retiredBy(record) {
55
+ const edges = new Set(record.chain.slice(1).map((d, i) => `${record.chain[i]} ${d}`)), out = new Map();
56
+ for (const r of record.rotations) {
57
+ const c = r.body.reason === 'recovery' && edges.has(`${r.body.id} ${r.body.next}`) ? commitOrNull(r.body.recovery_key) : null;
58
+ if (c !== null && r.next_genesis.recovery !== c) out.set(c, canonicalize(r));
59
+ }
60
+ return out;
61
+ }
45
62
 
46
63
  export class Contacts {
47
64
  /**
@@ -306,17 +323,41 @@ export class Contacts {
306
323
  return found[0] ?? null;
307
324
  }
308
325
 
309
- /** Local and final for this store: the pairing key goes, and pending codes to or from the contact die with it. */
310
- revoke(did) {
326
+ /**
327
+ * Local and final for this store: the pairing key goes, and pending codes to or from the contact die
328
+ * with it. ended: {id, by, at} when a link's end revokes it (relink may then permit a new link); a
329
+ * revoke without it (forgotten by hand) is for good.
330
+ */
331
+ revoke(did, ended = null) {
311
332
  const c = this.lookup(did) ?? fail('not_contact', `${did} is not a contact`);
312
- c.revoked = true; c.pair_key = null; delete c.link;
333
+ c.revoked = true; c.pair_key = null; delete c.link; delete c.relink;
334
+ if (ended) c.ended = ended; else delete c.ended;
313
335
  for (const [n, p] of Object.entries(this.s.accepts)) if (c.chain.includes(p.code_did)) delete this.s.accepts[n];
314
336
  for (const [n, p] of Object.entries(this.s.invites)) if (p.peer === c.did) delete this.s.invites[n];
315
337
  this.save(); return c;
316
338
  }
317
339
 
318
340
  /**
319
- * sigelo-pair's last checks, in its order and under its names: revoked, not_contact, then every
341
+ * A NEW link with a contact an ended link revoked (design/links.md §7.1a): a one-use permit, until
342
+ * `until`, for the pairing through that link's code (admit). → true; null when `did` is no revoked
343
+ * contact here (nothing to permit). Forgotten by hand: revoked; the ended link's own id: link_stale.
344
+ */
345
+ relink(did, id, until, now) {
346
+ checkTime(now);
347
+ const c = this.load().lookup(did);
348
+ if (!c || !c.revoked) return null;
349
+ if (!c.ended) fail('revoked', `${c.did} was revoked by this owner (forgotten, not by a link's end): never linked again`);
350
+ if (c.ended.id === id) fail('link_stale', `link ${id} ended with ${c.name}: a new link has a new id`);
351
+ if (!Number.isSafeInteger(until) || until <= now) fail('link_expired', 'a relink permit ends in the future');
352
+ c.relink = { id, until };
353
+ this.save();
354
+ return true;
355
+ }
356
+
357
+ /**
358
+ * sigelo-pair's last checks, in its order and under its names: revoked, not_contact, then
359
+ * retired_recovery (own: a recovery rotation sent by a recovery key the known chain retired,
360
+ * retiredBy), then every
320
361
  * rotation this store has seen is merged in and §7.3 picks again (bundle, stale_chain): a peer
321
362
  * cannot hide a rotation, so a recovery seen once keeps beating the thief. Then original_did
322
363
  * (own), and revoked once more, just before writing. r: verify(bundle) already checked by the caller.
@@ -329,21 +370,35 @@ export class Contacts {
329
370
  */
330
371
  admit(bundle, r, name, fields, now) {
331
372
  const held = this.#holders(r.chain), gone = held.find((c) => c.revoked);
332
- if (gone) fail('revoked', `${gone.did} was revoked by this owner`);
373
+ // A relink (design/links.md §7.1a): a pairing (named) of a contact an ended link revoked, with a
374
+ // live permit; written afresh, its rotations seen kept.
375
+ const relinking = gone && name !== null && held.length === 1 && gone.relink && gone.relink.until > now ? gone : null;
376
+ if (gone && !relinking) fail('revoked', `${gone.did} was revoked by this owner`);
333
377
  if (held.length > 1) fail('original_did', `the chain runs through ${held.length} contacts: ${held.map((c) => c.did).join(', ')}`);
334
- const old = held[0];
378
+ const prior = held[0], old = relinking ? undefined : prior;
335
379
  if (!old && name === null) fail('not_contact', `${r.chain[0]} is not a contact; this code was for a known contact only`);
336
380
  let rotations = bundle.rotations;
337
- if (old) {
381
+ if (prior) {
382
+ // A thief with an old copy of a retired recovery key signs a recovery from a node before its
383
+ // retirement (G0 → T, or the retiring node with a later iat): offline it verifies and §7.3
384
+ // follows it. This store saw the retirement, so any other recovery by that key is a fork by a
385
+ // retired key, refused. A store that first met the thief's chain cannot tell (the limit).
386
+ const retired = retiredBy(prior);
387
+ for (const x of retired.size > 0 ? rotations : []) {
388
+ const c = x?.body?.reason === 'recovery' ? commitOrNull(x.body.recovery_key) : null;
389
+ if (c !== null && retired.has(c) && jcsOrNull(x) !== retired.get(c) && verifySig(x.body.recovery_key, x.body, x.sig)) {
390
+ fail('retired_recovery', `a recovery rotation from ${x.body.id} signed by a recovery key ${prior.did} has retired (a later recovery replaced it)`);
391
+ }
392
+ }
338
393
  const claimed = r.did, seen = new Set(rotations.map(canonicalize));
339
- rotations = [...rotations, ...old.rotations.filter((x) => !seen.has(canonicalize(x)))];
394
+ rotations = [...rotations, ...prior.rotations.filter((x) => !seen.has(canonicalize(x)))];
340
395
  r = attempt('bundle', () => verify({ ...bundle, rotations }, now));
341
396
  if (r.did !== claimed) fail('stale_chain', `the rotations already seen resolve to ${r.did}, not ${claimed}`);
342
- if (r.chain[0] !== old.did) fail('original_did', `the chain starts at ${r.chain[0]}; this store knows the peer from ${old.did}`);
397
+ if (r.chain[0] !== prior.did) fail('original_did', `the chain starts at ${r.chain[0]}; this store knows the peer from ${prior.did}`);
343
398
  }
344
399
  const heldNow = this.#holders(r.chain);
345
- if (heldNow.some((c) => c.revoked)) fail('revoked', `${r.chain[0]} was revoked during this pairing`);
346
- if (heldNow.some((c) => c.did !== old?.did)) fail('original_did', `another contact took ${r.chain[0]}'s chain during this pairing`);
400
+ if (heldNow.some((c) => c.revoked && c.did !== relinking?.did)) fail('revoked', `${r.chain[0]} was revoked during this pairing`);
401
+ if (heldNow.some((c) => c.did !== prior?.did)) fail('original_did', `another contact took ${r.chain[0]}'s chain during this pairing`);
347
402
  const kept = old ? Object.fromEntries(TIER_KEYS.filter((k) => Object.hasOwn(old, k)).map((k) => [k, old[k]])) : {};
348
403
  const pre = !old && TIERS.includes(this.s.preset?.[r.chain[0]]) ? { tier: this.s.preset[r.chain[0]], tier_by: 'owner' } : {};
349
404
  if (this.s.preset) delete this.s.preset[r.chain[0]];
package/test-device.mjs CHANGED
@@ -15,13 +15,14 @@ import { tmpdir } from 'node:os';
15
15
  import { delimiter, dirname, join } from 'node:path';
16
16
  import { fileURLToPath } from 'node:url';
17
17
  import { canonicalize, did, sign, verifySig } from 'sigelo';
18
- import { keeperRoot, mnemonicFromRoot, recoveryCommitment, rootFromMnemonic } from 'sigelo/dist/keys.js';
18
+ import { keeperRoot, mnemonicFromRoot, recoveryCommitment, rootFromMnemonic, vaultFromRoot } from 'sigelo/dist/keys.js';
19
19
  import { UNLOGGED } from './carrier.mjs';
20
20
  import * as C from './control.mjs';
21
21
  import * as D from './device.mjs';
22
22
  import { operatorAttestation, operatorIdentity, workerIdentity } from './enrol.mjs';
23
23
  import { makeInvite } from './invite.mjs';
24
24
  import * as RS from './restore.mjs';
25
+ import * as CR from './create.mjs';
25
26
  import { alnumCapacity, encode, toPng, toTerminal } from './qr.mjs';
26
27
  import { jsQR, readPng, scanPng } from './qr-decode.mjs';
27
28
 
@@ -411,5 +412,33 @@ ok(UNLOGGED.test('sigelo-device/1') && UNLOGGED.test('sigelo-identity/0') && UNL
411
412
  S.fill(0); K.fill(0);
412
413
  }
413
414
 
415
+ // ---- a new identity made in the apps (create.mjs, pass A10a): S drawn here, three words typed back, then the restore's files
416
+ {
417
+ const now = 1761400000, ck = (f) => checkOf(f);
418
+ const s = CR.newSeed('stagenet'), w = s.words(), words = w.join(' '), S = rootFromMnemonic(words);
419
+ ok(w.length === 25 && RS.checkWords(words).ok && s.vault === vaultFromRoot(S, 'stagenet').address && s.vault.startsWith('5') && CR.newSeed('mainnet').vault.startsWith('4'),
420
+ 'newSeed: 25 words with a valid checksum, a canonical root; vault = the words\' own Monero wallet (stagenet 5…, mainnet 4…)');
421
+ ok(ck(() => s.commit({ name: 'phone', relay: 'relay.sigelo.ai', now })) === 'create_unchecked' && ck(() => s.check(['a', 'b', 'c'])) === 'create_quiz', 'newSeed: no commit before three words are checked; no check before a quiz');
422
+ const q = s.quiz();
423
+ ok(q.length === CR.QUIZ && new Set(q).size === 3 && q.every((x, i) => Number.isInteger(x) && x >= 1 && x <= 25 && (i === 0 || q[i - 1] < x)), `quiz: three distinct positions 1..25, ascending (${q})`);
424
+ const bad = s.check(q.map((x, i) => (i === 1 ? w[x % 25] === w[x - 1] ? 'zzz' : w[x % 25] : w[x - 1])));
425
+ ok(bad.ok === false && bad.wrong.join() === String(q[1]) && ck(() => s.commit({ name: 'phone', relay: 'relay.sigelo.ai', now })) === 'create_unchecked' && ck(() => s.check(q.map((x) => w[x - 1]))) === 'create_quiz',
426
+ 'check: a wrong word named by its position; the quiz ends (back to the words), no commit');
427
+ const q2 = s.quiz(), good = s.check(q2.map((x, i) => (i === 0 ? ` ${w[x - 1].toUpperCase()} ` : i === 1 ? w[x - 1].slice(0, 3) : w[x - 1])));
428
+ ok(good.ok === true && good.wrong.length === 0, 'check: the right words pass, as the wallet reads them (capitals, blanks, the first three letters)');
429
+ const r = s.commit({ name: 'phone', relay: 'relay.sigelo.ai', now }), ref = RS.restoreFromWords(words, { name: 'phone', relay: 'relay.sigelo.ai', net: 'stagenet', restore: { restore_date: '2025-10-25' }, now });
430
+ ok(JSON.stringify({ ...r, vault: undefined }) === JSON.stringify({ ...ref, keeper: { ...ref.keeper, made: 'here' } }) && r.vault === s.vault,
431
+ 'commit: exactly the files a restore from the same 25 words makes (identity, keeper, device, list, notes), the keeper marked made here');
432
+ ok(r.keeper.created === '2025-10-25' && r.keeper.restore_date === '2025-10-25' && r.keeper.net === 'stagenet' && r.list.seat.epoch === 1 && r.list.devices[0].rank === 'full' && r.list.seat.holder === r.list.devices[0].did,
433
+ 'commit: created today, the wallet\'s birth today (restore_date), stagenet; the first FULL device holding the seat (epoch 1)');
434
+ ok(ck(() => s.words()) === 'create_spent' && ck(() => s.quiz()) === 'create_spent' && ck(() => s.commit({ name: 'phone', relay: 'relay.sigelo.ai', now })) === 'create_spent',
435
+ 'commit: S zeroed; the words are never given again (create_spent)');
436
+ const d = CR.newSeed('mainnet'); d.discard();
437
+ ok(ck(() => d.words()) === 'create_spent' && ck(() => CR.newSeed('testnet')) === 'create_net' && CR.newSeed('mainnet').words().join(' ') !== words, 'discard: S zeroed, refused after; testnet refused; a fresh root each time');
438
+ ok(ck(() => RS.restoreFromRoot(new Uint8Array(32), { name: 'phone', relay: 'relay.sigelo.ai', now })) === 'restore' && ck(() => RS.restoreFromRoot(new Uint8Array(32).fill(0xff), { name: 'phone', relay: 'relay.sigelo.ai', now })) === 'restore',
439
+ 'restoreFromRoot: zero and S >= l refused (not canonical: a wallet would show other words)');
440
+ S.fill(0);
441
+ }
442
+
414
443
  report();
415
444
  console.log(`ALL PASS (${count})`);
package/test-invite.mjs CHANGED
@@ -8,7 +8,8 @@ import { tmpdir } from 'node:os';
8
8
  import { dirname, join } from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { hexToBytes } from '@noble/hashes/utils.js';
11
- import { canonicalize } from 'sigelo';
11
+ import { createHash } from 'node:crypto';
12
+ import { canonicalize, keygen, rotate, verify } from 'sigelo';
12
13
  import { MsgError } from './kdf.mjs';
13
14
  import { SKEW, TTL_MAX, answerId, buildAnswer, buildReply, checkAnswer, checkReply, hex, inviteKeys, makeInvite, parseInvite } from './invite.mjs';
14
15
  import { Contacts } from './store.mjs';
@@ -149,6 +150,35 @@ try {
149
150
  ok(readFileSync(target, 'utf8') === 'untouched' && (statSync(join(sub, 'Z.json')).mode & 0o777) === 0o600, 'save() ignores a planted .tmp symlink and writes 0600');
150
151
  ok(readdirSync(sub).sort().join(' ') === 'Z.json Z.json.tmp target', 'save() leaves no temporary file behind');
151
152
 
153
+ // A retired recovery key (SPEC §7.2, THREAT-MODEL §2.5a), against a known contact: wren's chain
154
+ // G0 → G1 → recovery with R1 into G2 under a new key R2. A thief holding only R1 signs a recovery
155
+ // G0 → T, or G1 → T with a later iat: offline both verify and §7.3 follows them, so the merge used
156
+ // to take the thief's chain. The record remembers the retirement: retired_recovery; wren stays.
157
+ {
158
+ const sd = (l) => new Uint8Array(createHash('sha256').update(`sigelo-retired-test/0 ${l}`).digest());
159
+ const pub = (l) => keygen({ seed: sd(l), recovery: 'sha256:' + '0'.repeat(64), created: '2026-10-01T00:00:00Z', nonce: new Uint8Array(16) }).key;
160
+ const gen = (l, rec) => keygen({ seed: sd(l), recovery: pub(`${rec} recovery`), created: '2026-10-01T00:00:00Z', nonce: sd(`${l} nonce`).slice(0, 16) });
161
+ const step = (from, to, reason, iat, rec) => rotate({ genesis: from.genesis, next_genesis: to.genesis, iat, reason, secret: reason === 'recovery' ? sd(`${rec} recovery`) : from.secret, next_secret: to.secret });
162
+ const T = 1761000000, bundleOf = (g, rotations) => ({ v: 'sigelo/0', typ: 'bundle', genesis: g.genesis, rotations, bindings: [], attestations: [], issuers: [] });
163
+ const scenario = (l) => {
164
+ const g0 = gen(l, l), g1 = gen(`${l} 1`, l), g2 = gen(`${l} 2`, `${l} 2`), ta = gen(`${l} thief A`, `${l} thief`), tb = gen(`${l} thief B`, `${l} thief`);
165
+ const v = step(g0, g1, 'voluntary', T), rec = step(g1, g2, 'recovery', T + 100, l);
166
+ return { g0, honest: bundleOf(g0, [v, rec]), thiefA: bundleOf(g0, [step(g0, ta, 'recovery', T + 200, l)]), thiefB: bundleOf(g0, [v, step(g1, tb, 'recovery', T + 300, l)]), g2, ta, tb };
167
+ };
168
+ const now = T + 1000, fields = (n) => ({ relay: 'relay.test', pair_key: n.toString(16).padStart(64, '0') });
169
+ const ws = new Contacts(join(dir, 'retired.json'), F.dids.A0), w = scenario('wren');
170
+ ok(verify(w.thiefA, now).did === w.ta.did && verify(w.thiefB, now).did === w.tb.did, 'retired recovery: offline, both thief chains verify (G0 → T, and G1 → T with a later iat)');
171
+ run('retired recovery: wren known with her chain', {}, () => ws.admit(w.honest, verify(w.honest, now), 'wren', fields(1), now));
172
+ run('retired recovery: the thief with G0 and his recovery by the retired key', { error: 'retired_recovery' }, () => ws.admit(w.thiefA, verify(w.thiefA, now), null, fields(1), now));
173
+ run('retired recovery: the thief from G1 with a later iat than hers', { error: 'retired_recovery' }, () => ws.admit(w.thiefB, verify(w.thiefB, now), null, fields(1), now));
174
+ const again = run('retired recovery: her next bundle is admitted', {}, () => ws.admit(w.honest, verify(w.honest, now), null, fields(1), now));
175
+ ok(again?.current_did === w.g2.did && ws.lookup(w.g0.did).current_did === w.g2.did, 'retired recovery: she stays: the record ends at her G2, none of the thief\'s');
176
+ // The limit: a store that met the thief's chain first cannot tell; first seen wins.
177
+ const x = scenario('xena');
178
+ run('retired recovery, the limit: the thief\'s chain known first', {}, () => ws.admit(x.thiefA, verify(x.thiefA, now), 'xena', fields(2), now));
179
+ run('retired recovery, the limit: then her chain is refused', { error: 'retired_recovery' }, () => ws.admit(x.honest, verify(x.honest, now), null, fields(2), now));
180
+ }
181
+
152
182
  let thrown;
153
183
  try { parseInvite('sgl2', c.now); } catch (e) { thrown = e; }
154
184
  ok(thrown?.constructor === MsgError && thrown.check === 'code_version', 'invite refusals are MsgError, the one error class of contact/, with .check');
package/test-link.mjs CHANGED
@@ -118,6 +118,20 @@ const D0 = 'did:sigelo:z' + '1'.repeat(44);
118
118
  ok(a1.link === undefined && a1.tier === 'friend' && a1.tier_by === 'owner', 'setLink null with prior: the tier before restored');
119
119
  hs.revoke(F.did);
120
120
  ok(hs.load().s.contacts[F.did].link === undefined, 'revoke drops the link');
121
+ // Relink (design/links.md §7.1a): a link's end is remembered (ended); a new link pairs only with a permit.
122
+ ok(hs.load().s.contacts[F.did].ended === undefined && checkOf(() => hs.relink(F.did, 'DDDDDDDD', now + 60, now)) === 'revoked', 'forgotten by hand: no ended; relink refused (revoked)');
123
+ ok(hs.relink(A.did, 'DDDDDDDD', now + 60, now) === null && hs.relink(D0, 'DDDDDDDD', now + 60, now) === null, 'relink of a live contact, or of no contact: nothing to permit (null)');
124
+ const X2 = agent('store relink');
125
+ hs.admit(chainOnly(X2), verify(chainOnly(X2), now), 'x2', { relay: 'relay.test', pair_key: key(4) }, now);
126
+ hs.revoke(X2.did, { id: 'K7F3Q9ZQ', by: H.did, at: now });
127
+ const x2 = () => hs.load().s.contacts[X2.did];
128
+ ok(x2().revoked && x2().ended?.id === 'K7F3Q9ZQ' && x2().pair_key === null, 'revoked by a link\'s end: ended {id, by, at} kept');
129
+ const again = (pk, name = 'x2', t = now) => checkOf(() => hs.admit(chainOnly(X2), verify(chainOnly(X2), t), name, { relay: 'relay.test', pair_key: key(pk) }, t));
130
+ ok(again(5) === 'revoked', 'a pairing without a permit: revoked');
131
+ ok(checkOf(() => hs.relink(X2.did, 'K7F3Q9ZQ', now + 60, now)) === 'link_stale' && checkOf(() => hs.relink(X2.did, 'EEEEEEEE', now, now)) === 'link_expired', 'a permit for the ended id: link_stale; one already over: link_expired');
132
+ ok(hs.relink(X2.did, 'EEEEEEEE', now + 60, now) === true && x2().relink?.id === 'EEEEEEEE', 'a new link\'s permit: relink {id, until}');
133
+ ok(again(6, null) === 'revoked' && again(6, 'x2', now + 61) === 'revoked', 'a notice (no name) is no pairing, and a permit past its until: revoked still');
134
+ ok(again(7) === 'accepted' && !x2().revoked && x2().ended === undefined && x2().relink === undefined && x2().pair_key === key(7) && x2().link === undefined, 'with the permit: admitted, the record written afresh (no ended, no permit)', JSON.stringify(x2()));
121
135
  } finally { rmSync(dir, { recursive: true, force: true }); }
122
136
  }
123
137
 
@@ -209,6 +223,11 @@ try {
209
223
  'list on the agent: {id, contact, tier, purpose, linked_by, expires}', JSON.stringify(la));
210
224
  ok(lh.made.some((x) => x.id === L.id && x.status === 'linked' && x.tier_a === 'friend' && x.tier_b === 'quiet') && !JSON.stringify(lh).includes('sgl1'), 'list on the operator: the link made, no code', JSON.stringify(lh.made));
211
225
  ok(A.c.contacts().contacts.find((c) => c.did === B.did)?.link?.purpose === L.purpose, 'contacts() shows the purpose');
226
+ // The inbox labels a linked contact's messages with the link (id, purpose); others carry none.
227
+ await B.c.send(A.did, 'the PR is ready'); await F.c.send(A.did, 'lunch?');
228
+ await turn(A);
229
+ const lm = A.seen.find((m) => m.content === 'the PR is ready'), fm = A.seen.find((m) => m.content === 'lunch?');
230
+ ok(JSON.stringify(lm?.link) === JSON.stringify({ id: L.id, purpose: L.purpose }) && fm && fm.link === undefined, 'inbox: review\'s message carries link {id, purpose}; a friend\'s, unlinked, none', JSON.stringify([lm, fm]));
212
231
 
213
232
  // An end from a contact that is no party to the link: ignored.
214
233
  await sendLink(F, A, { v: LINK_V, typ: 'end', id: L.id, iat: now, reason: 'unlink' });
@@ -275,6 +294,24 @@ try {
275
294
  ok(A.out.some((r) => r.ended.some((x) => x.id === L.id && x.forgot)) && B.out.some((r) => r.ended.some((x) => x.id === L.id)), 'handle reports the end on both');
276
295
  ok(await failure(() => unlink({ carrier: H.c, file: H.f, id: 'ZZZZZZZZ' })) === 'link_unknown', 'unlink of no link: link_unknown');
277
296
 
297
+ // ---- relink (design/links.md §7.1a): the end remembered on both sides; one side's ask alone is
298
+ // refused; the ended id never again; both asked afresh: linked again under a new id.
299
+ ok(contactOf(A, B.did).ended?.id === L.id && contactOf(B, A.did).ended?.id === L.id, 'the end remembered on both revoked records (ended: the link id)');
300
+ const R1 = await link({ carrier: H.c, file: H.f, a: 'project', b: 'review', purpose: 'review again' });
301
+ await turn(A);
302
+ await H.c.inbox({ wait: 1 });
303
+ const inv1 = H.c.takeLinks().find((m) => m.content.id === R1.id && m.content.typ === 'invite');
304
+ ok(typeof inv1?.content.code === 'string' && contactOf(A, B.did).relink?.id === R1.id, 'project, asked afresh: a permit for review and a code (taken here, never forwarded)', JSON.stringify(contactOf(A, B.did)));
305
+ ok(await failure(() => B.c.accept(inv1.content.code, { name: 'project', wait: 0 })) === 'revoked' && contactOf(B, A.did).revoked && contactOf(A, B.did).revoked,
306
+ 'that code accepted by review, which was not asked (one side alone): refused revoked before anything went; nothing paired');
307
+ await sendLink(H, A, { v: LINK_V, typ: 'ask', id: L.id, iat: now, peer: B.did, kind: 'own', purpose: 'p', ttl: DAY }); await turn(A);
308
+ ok(A.out.at(-1).refused.some((x) => x.id === L.id && x.check === 'link_stale'), 'an ask carrying the ended link\'s id: link_stale', JSON.stringify(A.out.at(-1).refused));
309
+ const R2 = await link({ carrier: H.c, file: H.f, a: 'project', b: 'review', purpose: 'review again' });
310
+ for (let i = 0; i < 4 && recOf(H, R2.id)?.status === 'pending'; i++) await rounds(1, A, H, B, A, B, H);
311
+ const ab2 = contactOf(A, B.did), ba2 = contactOf(B, A.did);
312
+ ok(recOf(H, R2.id).status === 'linked' && R2.id !== L.id && ab2?.link?.id === R2.id && !ab2.revoked && ab2.ended === undefined && ba2?.link?.id === R2.id && !ba2.revoked && ba2.ended === undefined,
313
+ 'both asked afresh (project\'s ask, review\'s offer from its operator): linked again under a new id, the records fresh', JSON.stringify([recOf(H, R2.id)?.status, ab2, ba2]));
314
+
278
315
  // ---- expiry: a day and more later, each side ends by itself.
279
316
  now += DAY + 60;
280
317
  await rounds(1, Dd, C);
package/test-short.mjs CHANGED
@@ -117,7 +117,7 @@ const collide = (() => { const seen = new Map(); for (let i = 0; ; i++) { const
117
117
  let asked = 0;
118
118
  const registry = async () => { asked++; return new Map([[relayTag('reg.test'), { host: 'reg.test' }], [relayTag('corp.test'), { host: 'other-corp.test' }]]); };
119
119
  const known = [{ host: 'relay.test', from: 'own' }, { host: 'corp.test', from: 'contact' }];
120
- ok((await resolveTag(relayTag('corp.test'), { known, registry, shown: 'x' })).host === 'corp.test' && asked === 0, 'resolveTag: a known relay, the registry not consulted');
120
+ ok((await resolveTag(relayTag('corp.test'), { known: [{ host: 'relay.test', from: 'own' }, { host: 'corp.test', from: 'table' }], registry, shown: 'x' })).host === 'corp.test' && asked === 0, 'resolveTag: a relay of its own table, the registry not consulted');
121
121
  ok((await resolveTag(relayTag('reg.test'), { known, registry, shown: 'x' })).from === 'registry' && asked === 1, 'resolveTag: none known, the registry');
122
122
  const unknown = await failure(() => resolveTag(relayTag('nobody.test'), { known, registry, shown: 'AAAA-AAAA-' + relayTag('nobody.test') }));
123
123
  ok(unknown.check === 'relay_tag' && unknown.message.includes('accept it with --relay <host>') && unknown.message.includes(relayTag('nobody.test')), `resolveTag: nothing has it: relay_tag, asked for --relay (${unknown.message})`);
@@ -125,6 +125,19 @@ const collide = (() => { const seen = new Map(); for (let i = 0; ; i++) { const
125
125
  const both = await failure(() => resolveTag(tag, { known: [{ host: h1, from: 'contact' }, { host: h2, from: 'table' }], registry, shown: 'x' }));
126
126
  ok(both.check === 'relay_tag' && both.message.includes(`${h1} and ${h2}`) && both.message.includes('it does not guess') && asked === 2, `two known hosts, one tag (${h1}, ${h2}: ${tag}): refused, both named, asked (${both.message})`);
127
127
  ok((await resolveTag(tag, { known: [{ host: h1, from: 'contact' }, { host: h1, from: 'table' }], registry, shown: 'x' })).host === h1, 'one host known twice: no collision');
128
+ // Review 2026-10-28, MEDIUM 4: a contact's relay (from the inviter's code) whose tag was ground to
129
+ // equal a registered relay's won over the registry. A contact-sourced host is checked against the
130
+ // registry: an entry for the tag naming another host is a collision, asked; own, operator and
131
+ // table hosts rank above both and never consult it.
132
+ const reg2 = async () => new Map([[tag, { host: h2 }]]);
133
+ const evil = await failure(() => resolveTag(tag, { known: [{ host: 'relay.test', from: 'own' }, { host: h1, from: 'contact' }], registry: reg2, shown: 'x' }));
134
+ ok(evil.check === 'relay_tag' && evil.message.includes(h1) && evil.message.includes(h2), `a contact's relay whose tag the registry gives another host: relay_tag, both named, neither dialled (${evil.message})`);
135
+ const agree = await resolveTag(tag, { known: [{ host: h2, from: 'contact' }], registry: reg2, shown: 'x' });
136
+ const alone = await resolveTag(tag, { known: [{ host: h1, from: 'contact' }], registry: async () => new Map(), shown: 'x' });
137
+ ok(agree.host === h2 && agree.from === 'contact' && alone.host === h1 && alone.from === 'contact', 'a contact\'s relay the registry agrees with, or does not list: that relay');
138
+ const ranked = await Promise.all(['own', 'operator', 'table'].map((from) => resolveTag(tag, { known: [{ host: h1, from }], registry: async () => { throw new Error('consulted'); }, shown: 'x' })));
139
+ const both2 = await resolveTag(tag, { known: [{ host: h1, from: 'contact' }, { host: h1, from: 'table' }], registry: async () => { throw new Error('consulted'); }, shown: 'x' });
140
+ ok(ranked.every((r) => r.host === h1) && both2.from === 'table', 'own, operator and table hosts resolve without the registry; a host both a contact\'s and the table\'s counts as the table\'s');
128
141
  rmSync(d, { recursive: true, force: true });
129
142
  }
130
143
 
@@ -437,6 +450,14 @@ try {
437
450
  ok(d5.check === 'closed' && hits === 1 && d5.long === c5.code, `accept by the registry's host: fetched at ${CORP} (closed to dora), the registry not fetched again the same day (${hits}; ${d5.check})`);
438
451
  const listed = await cdora.registryRelays();
439
452
  ok(listed.length === 1 && listed[0].host === CORP && listed[0].tag === relayTag(CORP) && listed[0].tier === 'enterprise' && hits === 1, `registryRelays (the apps' picker): the verified list from the cache, not fetched again (${JSON.stringify(listed)}; ${hits})`);
453
+ // Review 2026-10-28, MEDIUM 4, the carrier's path: a contact paired in from a code naming a
454
+ // host whose tag was ground to equal CORP's (twin-812718.test) no longer wins over the registry.
455
+ const TWIN = 'twin-812718.test', contactsOf = cdora.contacts;
456
+ cdora.contacts = () => ({ ...contactsOf.call(cdora), contacts: [{ name: 'mallory', relay: TWIN }] });
457
+ try {
458
+ const tw = await failure(() => cdora.relayForShort(c5.short));
459
+ ok(relayTag(TWIN) === relayTag(CORP) && tw.check === 'relay_tag' && tw.message.includes(TWIN) && tw.message.includes(CORP), `relayForShort: a contact's relay sharing the registry's tag for ${CORP}: relay_tag, asked, not dialled (${tw.message})`);
460
+ } finally { cdora.contacts = contactsOf; }
440
461
  } finally { await cdora.stop(); reg.close(); rmSync(elsewhere, { recursive: true, force: true }); }
441
462
  for (const c of [cn, cbn, co]) await c.stop();
442
463
  } finally { await corp.close(); }