sigelo-contact 0.1.14 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +13 -10
  2. package/call.mjs +831 -0
  3. package/carrier.mjs +1013 -112
  4. package/control.mjs +81 -22
  5. package/device.mjs +1 -1
  6. package/enrol.mjs +214 -35
  7. package/gen-carrier.mjs +4 -4
  8. package/gen-device.mjs +2 -2
  9. package/gen-envelope.mjs +3 -3
  10. package/gen-invite.mjs +3 -3
  11. package/gen-short.mjs +3 -3
  12. package/group.mjs +28 -9
  13. package/invite.mjs +63 -13
  14. package/kdf.mjs +1 -1
  15. package/link.mjs +1 -1
  16. package/package.json +34 -7
  17. package/page.mjs +1018 -81
  18. package/photo.mjs +37 -0
  19. package/platform-node.mjs +110 -13
  20. package/prekeys.mjs +10 -2
  21. package/public.mjs +93 -0
  22. package/relays.mjs +1 -1
  23. package/restore.mjs +3 -3
  24. package/rtc-web.mjs +109 -0
  25. package/short.mjs +19 -3
  26. package/store.mjs +126 -10
  27. package/test-carrier.mjs +121 -18
  28. package/test-device.mjs +1 -1
  29. package/test-enrol.mjs +123 -8
  30. package/test-envelope.mjs +16 -3
  31. package/test-file.mjs +5 -5
  32. package/test-group.mjs +48 -7
  33. package/test-invite.mjs +15 -2
  34. package/test-link.mjs +6 -6
  35. package/test-platform.mjs +5 -5
  36. package/test-presence.mjs +5 -5
  37. package/test-push.mjs +136 -0
  38. package/test-relay-lane.mjs +323 -0
  39. package/test-short.mjs +35 -12
  40. package/test-tier.mjs +6 -6
  41. package/test-transfer-web.mjs +313 -0
  42. package/test-transfer.mjs +51 -11
  43. package/test-voice.mjs +161 -0
  44. package/test-ws.mjs +5 -5
  45. package/transfer-engine.mjs +858 -0
  46. package/transfer-node.mjs +254 -641
  47. package/transfer-web.mjs +80 -0
  48. package/transfer.mjs +25 -6
  49. package/voice-web.mjs +113 -0
  50. package/voice.mjs +70 -0
  51. package/words-lock.mjs +25 -10
package/control.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: MIT
2
- // Remote control over the relay (design/apps.md §6.3; adapters/moadim/UI-API.md "Remote"): an app
2
+ // Remote control over the relay (design/apps.md §6.3; apps/agent/UI-API.md "Remote"): an app
3
3
  // drives the page of `sigelo-agent ui` on a computer through the relay, holding no account key.
4
4
  //
5
5
  // The control identity: a random Ed25519 key made where the app runs (newControlIdentity), never
@@ -23,6 +23,16 @@
23
23
  // await ctl.call(method, path, body) → { status, body }: GET /api/state from the last pushed state
24
24
  // while the lease runs (no relay message), anything else one request
25
25
  // ctl.onChange(fn) fn() after each pushed state
26
+ // ctl.connected whether the computer's lease runs (an answer to a request within LEASE)
27
+ //
28
+ // Quiet without a lease (2026-11: an app left open four days against a computer whose page was gone
29
+ // published up to its relay day's cap, 3,000 a day, every poll a request nobody read): a request goes
30
+ // only while the computer's lease runs, renewed by its ANSWER, never by the request itself. Without one
31
+ // (never answered, an answer missed, refused words or seat) one call at a time is let through as a
32
+ // probe, PROBE_MIN seconds after the last one failed, doubling to PROBE_MAX; every other call is
33
+ // answered 503 not_connected here, no relay message. Each message carries exp (now + TTL, seconds):
34
+ // the carrier drops it unsent past it, the reader drops it late, so a backlog left at the relay by a
35
+ // control gone never runs on a computer that comes back.
26
36
  import { keygen } from 'sigelo';
27
37
  import { bytesToHex, randomBytes } from '@noble/hashes/utils.js';
28
38
  import { DEVICE_LABEL, DEVICE_SEND } from './carrier.mjs';
@@ -41,6 +51,15 @@ export const CALL_TIMEOUT = 30_000;
41
51
  export const PUSH_MAX = 64 * 1024, PUSH_KEEP = 20;
42
52
  // The computer's cap per control: a bucket of BURST requests, refilled at RATE a second.
43
53
  export const RATE = 1, BURST = 10;
54
+ // Without a lease: the first probe PROBE_MIN seconds after a failed one, the gap doubling to PROBE_MAX
55
+ // (an hour with nobody listening: 9 probes, then 3 an hour).
56
+ export const PROBE_MIN = 15, PROBE_MAX = 1200;
57
+ // A control message's life (seconds): past now + TTL it is dropped unsent (carrier) or unread.
58
+ export const TTL = 300;
59
+ // GETs the page polls every 2 s that the pushed state does not carry (the Agents view's list): answered
60
+ // from the last answer for KEEP_GET seconds, asked again at once after any POST (Enrol, revoke) or when a
61
+ // pushed state's seq moves. An open Agents view: 120 an hour, not 1,800 (LAN and local pages keep 2 s).
62
+ export const KEEP_GET = 30, KEPT = new Set(['/api/agents/workers']);
44
63
  const ID = /^[0-9a-f]{16}$/;
45
64
 
46
65
  /** The QR text: SIGELO:CTL:K7F3-Q9ZP, with :HOST (upper case) when the relay is not the default. */
@@ -90,9 +109,12 @@ export function capState(st, max = PUSH_MAX, keep = PUSH_KEEP) {
90
109
  }
91
110
  }
92
111
  export const newId = () => bytesToHex(randomBytes(8));
93
- export const requestMessage = ({ id, method, path, body }) => ({ v: CONTROL_V, typ: 'request', id, method, path, ...(body !== undefined && { body }) });
94
- export const responseMessage = ({ id, status, body }) => ({ v: CONTROL_V, typ: 'response', id, status, body });
95
- export const eventsMessage = ({ seq, since, state }) => ({ v: CONTROL_V, typ: 'events', seq, since, state });
112
+ const ttl = (exp) => (exp !== undefined && { exp });
113
+ export const requestMessage = ({ id, method, path, body, exp }) => ({ v: CONTROL_V, typ: 'request', id, method, path, ...(body !== undefined && { body }), ...ttl(exp) });
114
+ export const responseMessage = ({ id, status, body, exp }) => ({ v: CONTROL_V, typ: 'response', id, status, body, ...ttl(exp) });
115
+ export const eventsMessage = ({ seq, since, state, exp }) => ({ v: CONTROL_V, typ: 'events', seq, since, state, ...ttl(exp) });
116
+ /** A message's exp (unix seconds) passed: dropped, unanswered. None (an older sender): never stale. */
117
+ export const stale = (c, nowS) => Number.isSafeInteger(c?.exp) && c.exp <= nowS;
96
118
  /** A control message checked (request, response, events) → it; else throws control_message. */
97
119
  export function readControl(c) {
98
120
  if (!isObject(c) || c.v !== CONTROL_V) fail('control_message', `not a ${CONTROL_V} message`);
@@ -104,6 +126,7 @@ export function readControl(c) {
104
126
  } else if (c.typ === 'events') {
105
127
  if (!Number.isSafeInteger(c.seq) || !Number.isSafeInteger(c.since) || !isObject(c.state)) fail('control_message', 'events: seq, since, state');
106
128
  } else fail('control_message', `typ ${JSON.stringify(c.typ)}: request, response or events`);
129
+ if (c.exp !== undefined && !Number.isSafeInteger(c.exp)) fail('control_message', 'exp: unix seconds');
107
130
  return c;
108
131
  }
109
132
 
@@ -116,9 +139,20 @@ export function bucket({ rate = RATE, burst = BURST, now = () => Date.now() } =
116
139
  const err = (status, check, message) => ({ status, body: { error: { check, message } } });
117
140
 
118
141
  /** The app's side: requests out, responses matched by id, pushed states kept for GET /api/state. */
119
- export function makeControl({ operator, timeout = CALL_TIMEOUT, now = () => Date.now(), defer = (f) => setTimeout(f, 0) }) {
142
+ export function makeControl({ operator, timeout = CALL_TIMEOUT, now = () => Date.now(), defer = (f) => setTimeout(f, 0), after = (f, ms) => setTimeout(f, ms), cancel = (t) => clearTimeout(t) }) {
120
143
  let carrier = null, state = null, asked = -Infinity, taking = false;
121
- const waiting = new Map(), watchers = new Set(), events = new Map();
144
+ // lease: until when the computer's lease runs (ms), from the send time of the last request it answered
145
+ // (its answer renews it, never the request alone). Without one: probeAt, the earliest the next probe
146
+ // goes; gap, the back-off (s); probe, the one in flight, which the other calls wait for.
147
+ let lease = -Infinity, probeAt = -Infinity, gap = 0, probe = null;
148
+ const waiting = new Map(), watchers = new Set(), events = new Map(), kept = new Map();
149
+ const nowS = () => Math.floor(now() / 1000);
150
+ const quiet = () => {
151
+ lease = -Infinity;
152
+ if (now() < probeAt) return; // already backing off (several calls that failed together count once)
153
+ gap = gap ? Math.min(gap * 2, PROBE_MAX) : PROBE_MIN;
154
+ probeAt = now() + gap * 1000;
155
+ };
122
156
  const keep = (st) => {
123
157
  for (const e of st.events ?? []) events.set(e.n, e);
124
158
  for (const n of [...events.keys()].sort((a, b) => a - b).slice(0, Math.max(0, events.size - 200))) events.delete(n);
@@ -133,32 +167,51 @@ export function makeControl({ operator, timeout = CALL_TIMEOUT, now = () => Date
133
167
  if (m.from !== operator) continue;
134
168
  let c;
135
169
  try { c = readControl(m.content); } catch { continue; }
136
- if (c.typ === 'response') {
137
- const w = waiting.get(c.id);
138
- if (!w) continue;
139
- waiting.delete(c.id); clearTimeout(w.timer);
140
- w.ok({ status: c.status, body: c.body });
141
- } else if (c.typ === 'events') { keep(c.state); changed = true; }
170
+ if (stale(c, nowS())) continue;
171
+ const w = c.typ === 'response' ? waiting.get(c.id) : undefined;
172
+ // The computer is there (an answer come late, a push): the next call probes at once.
173
+ if (!w && now() >= lease) { probeAt = -Infinity; gap = 0; }
174
+ if (w) { waiting.delete(c.id); cancel(w.timer); w.ok({ status: c.status, body: c.body }); }
175
+ else if (c.typ === 'events') { if (c.state.seq !== state?.seq) kept.clear(); keep(c.state); changed = true; }
142
176
  }
143
177
  if (changed) for (const f of watchers) { try { f(); } catch {} }
144
178
  }
145
179
  const soon = () => { if (!taking) { taking = true; defer(take); } };
146
180
  async function request(method, path, body) {
147
- const id = newId();
148
- const answer = new Promise((ok) => { waiting.set(id, { ok, timer: setTimeout(() => { waiting.delete(id); ok(err(504, 'remote', `no answer from your computer within ${Math.round(timeout / 1000)} s: is sigelo-agent ui running there, and online?`)); }, timeout) }); });
149
- asked = now();
150
- try { await carrier.send(operator, requestMessage({ id, method, path, ...(body !== undefined && { body }) }), { label: DEVICE_LABEL, internal: DEVICE_SEND }); } catch (e) {
181
+ const id = newId(), sent = now(), exp = Math.floor(sent / 1000) + TTL;
182
+ let answered = false;
183
+ const answer = new Promise((ok) => { waiting.set(id, { ok: (r) => { answered = true; ok(r); }, end: ok, timer: after(() => { waiting.delete(id); ok(err(504, 'remote', `no answer from your computer within ${Math.round(timeout / 1000)} s: is sigelo-agent ui running there, and online?`)); }, timeout) }); });
184
+ try { await carrier.send(operator, requestMessage({ id, method, path, ...(body !== undefined && { body }), exp }), { label: DEVICE_LABEL, internal: DEVICE_SEND, expires: exp }); } catch (e) {
151
185
  const w = waiting.get(id);
152
- if (w) { waiting.delete(id); clearTimeout(w.timer); }
186
+ if (w) { waiting.delete(id); cancel(w.timer); }
187
+ quiet();
153
188
  return err(e.check === 'not_contact' ? 403 : 502, 'remote', e.check === 'not_contact' ? 'this app is no longer paired with your computer: pair it again' : `not sent to your computer (${e.message})`);
154
189
  }
155
190
  soon();
156
191
  const r = await answer;
157
- // The seat moved, or this control is refused: what was pushed no longer stands.
158
- if (r.status === 409 || r.status === 403) { const c = r.body?.error?.check; if (c === 'seat_elsewhere' || c === 'words') state = null; }
159
- if (method === 'GET' && r.status === 200 && new URL(path, 'http://app').pathname === '/api/state' && isObject(r.body)) keep(r.body);
192
+ if (!answered) { quiet(); return r; }
193
+ const c = r.body?.error?.check;
194
+ // The seat moved, or this control is refused: what was pushed no longer stands, and no lease runs.
195
+ if ((r.status === 409 && c === 'seat_elsewhere') || (r.status === 403 && c === 'words')) { state = null; quiet(); }
196
+ // Over the computer's rate cap: answered, the lease as it was.
197
+ else if (!(r.status === 429 && c === 'rate')) { lease = Math.max(lease, sent + LEASE * 1000); asked = Math.max(asked, sent); probeAt = -Infinity; gap = 0; }
198
+ if (method === 'GET' && r.status === 200 && new URL(path, 'http://app').pathname === '/api/state' && isObject(r.body)) { if (r.body.seq !== state?.seq) kept.clear(); keep(r.body); }
160
199
  return r;
161
200
  }
201
+ const notConnected = () => {
202
+ const s = Math.max(0, Math.ceil((probeAt - now()) / 1000));
203
+ return err(503, 'not_connected', `not connected to your computer: it has not answered (is sigelo-agent ui running there, and online?); trying again in ${s} s`);
204
+ };
205
+ // No lease: a call waits for the probe in flight; else it is the probe when one is due; else refused here.
206
+ async function ask(method, path, body) {
207
+ while (now() >= lease) {
208
+ if (probe !== null) { await probe; continue; }
209
+ if (now() < probeAt) return notConnected();
210
+ const p = probe = request(method, path, body);
211
+ try { return await p; } finally { if (probe === p) probe = null; }
212
+ }
213
+ return request(method, path, body);
214
+ }
162
215
  return {
163
216
  attach(c) { carrier = c; soon(); },
164
217
  onEvent(e) { if (e.type === 'device' || e.type === 'connected') soon(); },
@@ -173,10 +226,16 @@ export function makeControl({ operator, timeout = CALL_TIMEOUT, now = () => Date
173
226
  if (method === 'GET' && url.pathname === '/api/state' && state !== null && now() - asked < RENEW * 1000 && url.searchParams.get('full') !== '1') {
174
227
  return { status: 200, body: JSON.parse(JSON.stringify(local(Number(url.searchParams.get('since') ?? 0) || 0))) };
175
228
  }
176
- return request(method, path, body);
229
+ if (method === 'POST') kept.clear();
230
+ const hit = method === 'GET' && KEPT.has(url.pathname) ? kept.get(path) : undefined;
231
+ if (hit && now() - hit.at < KEEP_GET * 1000 && now() < lease) return JSON.parse(JSON.stringify(hit.r));
232
+ const r = await ask(method, path, body);
233
+ if (method === 'GET' && KEPT.has(url.pathname) && r.status === 200) kept.set(path, { at: now(), r: JSON.parse(JSON.stringify(r)) });
234
+ return r;
177
235
  },
178
236
  onChange(fn) { watchers.add(fn); return () => watchers.delete(fn); },
179
237
  get state() { return state; },
180
- stop() { for (const [, w] of waiting) { clearTimeout(w.timer); w.ok(err(503, 'remote', 'stopped')); } waiting.clear(); },
238
+ get connected() { return now() < lease; },
239
+ stop() { for (const [, w] of waiting) { cancel(w.timer); w.end(err(503, 'remote', 'stopped')); } waiting.clear(); },
181
240
  };
182
241
  }
package/device.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Devices, contract sigelo-device/1 (design/devices.md §5–§7): moving a device identity to a phone
3
3
  // or a second computer by QR. No network and no process here; sigelo-agent's `device` verbs drive
4
- // it (adapters/moadim/sigelo-agent-device.ts, DEVICES.md). Two ranks: SAFE, the device becomes
4
+ // it (apps/agent/sigelo-agent-device.ts, DEVICES.md). Two ranks: SAFE, the device becomes
5
5
  // worker i of the operator's keeper root, its own DID, tier own, revocable alone; FULL, it also
6
6
  // gets the operator identity and the keeper root K_j (the two files `keeper --from-words` writes).
7
7
  //
package/enrol.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Enrolment, contract sigelo-enrol/1: the operator places worker i, an identity DERIVED from its
3
3
  // keeper root K (MONERO.md §2, ts/src/keys.ts agentIdentitySeed(K, i, n)), on another machine, so
4
- // the 25 words bring the same DID back. THREAT-MODEL §2.11, adapters/moadim/ENROL.md.
4
+ // the 25 words bring the same DID back. THREAT-MODEL §2.11, apps/agent/ENROL.md.
5
5
  //
6
6
  // operatorIdentity(S, n) → the operator's own identity file: the root identity of S (keys.ts
7
7
  // identitySeed(S, n), genesis pinned the same way), marked `derived: {path, n}`
@@ -10,13 +10,13 @@
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, relay?, operatorName?, started? }) → a short
14
- // code (short.mjs, 10 minutes, once) for a normal invite (at `relay`, else the carrier's), and
13
+ // operator: issue({ carrier, file, i, n, name, keeper, relay?, operatorName?, started?, ttl? }) → a short
14
+ // code (short.mjs, 10 minutes or ttl: 60 s to an hour, once) for a normal invite (at `relay`, else the carrier's), and
15
15
  // a pending enrolment kept in `file` for 24 hours, with the operator attestation signed now
16
16
  // (`days`, ≤ 90; a device's 14). operatorName: how the worker files its operator (default
17
17
  // "operator"); started: the carrier's (a search the human started, carrier.mjs POW_SEARCHES);
18
18
  // confirmWords: kept with it, handed to confirm() as `ask` (the optional words switch)
19
- // machine: accept({ carrier, file, code, temp }) → `carrier` is a TEMPORARY identity (`temp`, its
19
+ // machine: accept({ carrier, file, code, temp, strict? }) → `carrier` is a TEMPORARY identity (`temp`, its
20
20
  // file): it fetches the code, pairs, and once paired sends a request, label LABEL_ENROL,
21
21
  // {v, typ: "enrol-request", proof}
22
22
  // both: complete({ carrier, file, wait, until, keeper | place, temp, confirm }) → one inbox or more:
@@ -57,9 +57,42 @@
57
57
  //
58
58
  // The pending file, 0600, beside the identity (x.json → x.enrol.json), under its own lock:
59
59
  // { v, issued: { invite nonce: { key, i, n, name, did, old_pair, relay, exp, attestation, issuer,
60
- // temp?, invite?, done? } },
61
- // joining: { invite nonce: { key, code_did, relay, exp, sent, temp } } }
60
+ // temp?, invite?, done?, sent_at?, needs_send?, short_hash?, unparked? } },
61
+ // joining: { invite nonce: { key, code_did, relay, exp, sent, temp, long?, short_hash?, answered? } } }
62
+ //
63
+ // The code is spent at the grant, not before (the agent-setup feedback, point 2). The operator parks its short
64
+ // code as an enrolment code (relay/park.mjs: fetched again until the grant) and spends it there once
65
+ // the worker's identity has gone (unparkHash, `unparked`). The machine keeps its joining entry from the
66
+ // fetch on: the long code, the short code's hash and its temporary identity, whether its answer went
67
+ // (`answered`); a refused proof of work or a crash leaves it, and init --enrol with the same code, or
68
+ // enrol --finish, takes it up again (resumeAnswer) instead of fetching the code or making another
69
+ // temporary identity.
70
+ //
71
+ // Who may enrol a machine (THREAT-MODEL §2.11a): only the identity that issued the code it fetched. The
72
+ // grant (LABEL_IDENTITY) is taken on the temporary identity only, from the contact holding the code's
73
+ // DID, for the code it names (`id`, the code's nonce: a grant for another code is refused enrol_replay),
74
+ // while its joining entry lives; a worker's own identity never takes one (no place() runs on it).
62
75
  // Entries go at exp, 24 hours after they were made, whatever their state.
76
+ //
77
+ // Neither side waits on one message (0.1.17: a lost identity left both sides waiting for the other).
78
+ // The machine sends its request again at most every RESEND_S while no identity has come (`sent`:
79
+ // the unix time of the last send; true, as an earlier version kept it, counts as long ago). The
80
+ // operator whose identity send was refused or failed marks the enrolment `needs_send` (the time of
81
+ // that try) and sends again at its next round, at most every RESEND_S, while the entry lives.
82
+ //
83
+ // The machine is told why (0.1.17: `enrol --finish` said "not done yet" for ever while the operator
84
+ // refused or held its request). The operator answers the temporary identity with a status, label
85
+ // LABEL_ENROL, {v, typ: "status", check, detail}: no key, no secret, no other DID; the check is the
86
+ // operator's (enrol_proof, enrol_unpaired, enrol_from, enrol_used, enrol_done, enrol_words while the
87
+ // words gate holds the key, device_words when they differed, or the failed send's check). Sent once
88
+ // per reason, again when the reason changes: the pending file's `told` { temp DID: { check, exp } }.
89
+ // The machine takes a status only from the contact it paired with through the code, keeps the last in
90
+ // its joining entry (`status`), and complete() hands it out (`status`).
91
+ //
92
+ // A request held (the words gate: confirm() said not yet) is kept in its issued entry (`held`: the message,
93
+ // proof only, no key), not only in the caller's memory: each complete() as the operator takes the held ones
94
+ // again first, so an app restarted, killed in the background or offline meanwhile still answers it once the
95
+ // words are confirmed, without the machine asking again (0.1.17: two real enrolments stalled this way).
63
96
  import { hkdf } from '@noble/hashes/hkdf.js';
64
97
  import { hmac } from '@noble/hashes/hmac.js';
65
98
  import { sha256 } from '@noble/hashes/sha2.js';
@@ -68,12 +101,12 @@ import { canonicalize, decodeKey, did as didOf, keygen, rotate, sign, structure,
68
101
  import { agentIdentitySeed, identitySeed, recoveryCommitment } from 'sigelo/dist/keys.js';
69
102
  import { keepLong, readCode } from './carrier.mjs';
70
103
  import { MsgError, checkNow, fail, pairId, signAs, unhex } from './kdf.mjs';
71
- import { codeKind, fingerprint } from './short.mjs';
104
+ import { codeHash, codeKind, fingerprint, formatEnrol, normaliseShort, stripEnrol } from './short.mjs';
72
105
  import { platform as nodePlatform } from './platform-node.mjs';
73
106
 
74
107
  export const ENROL_V = 'sigelo-enrol/1';
75
108
  export const LABEL_ENROL = 'sigelo-enrol/1', LABEL_IDENTITY = 'sigelo-identity/0';
76
- export const TYP_REQUEST = 'enrol-request', TYP_IDENTITY = 'enrol-identity';
109
+ export const TYP_REQUEST = 'enrol-request', TYP_IDENTITY = 'enrol-identity', TYP_STATUS = 'status';
77
110
  export const OPERATOR_CTX = 'sigelo-relay/operator', OPERATOR_DAYS = 90, DAY = 86400;
78
111
  // How long an enrolment stays pending, on either side: the invite's own default life.
79
112
  export const PENDING_TTL = DAY;
@@ -82,6 +115,10 @@ export const PENDING_TTL = DAY;
82
115
  export const PINNED_CREATED = '1970-01-01T00:00:00Z', ROTATION_IAT = 0, MAX_N = 64;
83
116
  const KEY_INFO = 'sigelo-enrol/0 key', PROOF_PREFIX = 'sigelo-enrol/0 request\n';
84
117
  const SKEW = 300, WAIT_STEP = 300;
118
+ /** The least time between two sends of the same request, or of the same identity after a failure (seconds). */
119
+ export const RESEND_S = 60;
120
+ // Due: never sent (false, undefined), sent by an earlier version (true: long ago), or RESEND_S since.
121
+ const due = (at, now) => at === undefined || at === null || at === false || at === true || !(now - at < RESEND_S);
85
122
 
86
123
  // ---------------------------------------------------------------- the worker's identity
87
124
 
@@ -161,8 +198,30 @@ export function matches(content, key, pair) {
161
198
  return d === 0;
162
199
  }
163
200
 
201
+ // What the machine is told for each check: for its human, never naming another DID (the operator's own
202
+ // detail may name the one that took the code).
203
+ const TOLD = {
204
+ enrol_proof: 'the request matches no enrolment code the operator issued in the last 24 hours (expired or cancelled): ask for a new code',
205
+ enrol_unpaired: 'the operator has not seen this machine pair through the code yet: it answers once the pairing completes',
206
+ enrol_from: 'another identity paired through this code first: ask the operator for a new code',
207
+ enrol_used: 'this code placed another worker already: ask the operator for a new code',
208
+ enrol_done: 'this worker was placed already: nothing more is sent',
209
+ enrol_words: 'the operator\'s app waits for its human to compare the four words: check that both sides show the same',
210
+ device_words: 'the operator said the four words differ: the key was not sent and the code is dropped; ask for a new code',
211
+ };
212
+ /** The operator's status for the machine: why its request is refused or held. No key, no DID. */
213
+ export const statusMessage = (check, detail) => ({ v: ENROL_V, typ: TYP_STATUS, check, detail });
214
+ /** The machine's reading of a status: { check, detail }, or null for any other shape. */
215
+ export function readStatus(content) {
216
+ if (!isObject(content) || content.v !== ENROL_V || content.typ !== TYP_STATUS || typeof content.check !== 'string' || !/^[a-z][a-z0-9_]{0,39}$/.test(content.check) || typeof content.detail !== 'string') return null;
217
+ return { check: content.check, detail: content.detail.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, ' ').slice(0, 300) };
218
+ }
219
+ /** The status the machine is sent for an operator's check (its own words for the known ones). */
220
+ export const toldFor = (check, detail) => TOLD[check] ?? `the operator could not send the key yet (${detail.replace(/ \(did:sigelo:[^)]*\)/g, '')}): it tries again within a minute`;
221
+
164
222
  /** The message that carries the worker: its identity file, a long invite to pair as it, and how it files its operator (optional). */
165
- export const identityMessage = (identity, invite, worker = null, operatorName = null) => ({ v: ENROL_V, typ: TYP_IDENTITY, identity, invite, worker, ...(operatorName !== null && { operator_name: operatorName }) });
223
+ // id: the code's nonce this grant is for (the machine refuses one for any other code: enrol_replay).
224
+ export const identityMessage = (identity, invite, worker = null, operatorName = null, id = null) => ({ v: ENROL_V, typ: TYP_IDENTITY, identity, invite, worker, ...(operatorName !== null && { operator_name: operatorName }), ...(id !== null && { id }) });
166
225
  // The operator's label for itself, as the worker files it: a contact name (1 to 64, no control or bidi characters).
167
226
  const LABEL_BAD = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/;
168
227
  export const operatorLabel = (v) => (typeof v === 'string' && v.trim() !== '' && [...v.trim()].length <= 64 && !LABEL_BAD.test(v) ? v.trim() : null);
@@ -172,9 +231,11 @@ export const operatorLabel = (v) => (typeof v === 'string' && v.trim() !== '' &&
172
231
  * with through the code), naming `relay`. → { identity, did, original, invite }, or a MsgError
173
232
  * naming the check.
174
233
  */
175
- export function checkIdentity(content, { operator, relay, now }) {
234
+ export function checkIdentity(content, { operator, relay, now, id }) {
176
235
  checkNow(now);
177
236
  if (!isObject(content) || content.v !== ENROL_V || content.typ !== TYP_IDENTITY || !isObject(content.identity) || typeof content.invite !== 'string') fail('enrol_message', `not a ${ENROL_V} ${TYP_IDENTITY}`);
237
+ // A grant names its code (0.1.19 on): one for another code than this enrolment's is an old or a misrouted one.
238
+ if (content.id !== undefined && id !== undefined && content.id !== id) fail('enrol_replay', 'a worker identity for another enrolment code than the one this machine answered: not taken');
178
239
  const x = content.identity, keys = ['v', 'secret', 'genesis', 'rotations', 'attestations', 'issuers'];
179
240
  if (Object.keys(x).sort().join() !== [...keys].sort().join() || typeof x.secret !== 'string' || !/^[0-9a-f]{64}$/.test(x.secret)) fail('enrol_message', `the identity must be exactly {${keys.join(', ')}}, secret 64 hex`);
180
241
  if (![x.rotations, x.attestations, x.issuers].every(Array.isArray) || x.attestations.length !== 1 || x.issuers.length !== 1) fail('enrol_message', 'the identity carries rotations, and exactly one attestation and one issuer');
@@ -219,7 +280,7 @@ export function pending(file, now, fn = () => undefined, platform = nodePlatform
219
280
  if (s?.v !== ENROL_V || !isObject(s.issued) || !isObject(s.joining)) fail('enrol_file', `${file} is not a ${ENROL_V} file: delete it to drop the pending enrolments`);
220
281
  }
221
282
  const before = canonicalize(s);
222
- for (const k of ['issued', 'joining']) for (const [id, e] of Object.entries(s[k])) if (!(e.exp > now)) delete s[k][id];
283
+ for (const k of ['issued', 'joining', 'told']) for (const [id, e] of Object.entries(s[k] ?? {})) if (!(e.exp > now)) delete s[k][id];
223
284
  const out = fn(s);
224
285
  if (canonicalize(s) !== before) platform.files.write(file, utf8ToBytes(JSON.stringify(s, null, 2)));
225
286
  return out;
@@ -254,20 +315,22 @@ const checkKeeper = (k) => {
254
315
  * stands for (24 hours). The operator attestation is signed here, at derivation time.
255
316
  * → { short, short_exp, code, id, did (the worker's current DID), original }.
256
317
  */
257
- export async function issue({ carrier, file, i, n, name, keeper, days = OPERATOR_DAYS, relay, operatorName, started, confirmWords = false }) {
318
+ export async function issue({ carrier, file, i, n, name, keeper, days = OPERATOR_DAYS, relay, operatorName, started, confirmWords = false, ttl }) {
258
319
  checkKeeper(keeper);
259
320
  if (operatorName !== undefined && operatorName !== null && operatorLabel(operatorName) === null) fail('enrol', 'operatorName: 1 to 64 characters, no control characters');
260
321
  const w = workerChain(keeper.K, i, n, keeper.recovery);
261
322
  // The temporary identity's contact, named apart from the worker's (forgotten once it has paired).
262
- const r = await carrier.invite({ name: `${name ?? `worker ${i}`} (enrolling)`, short: true, ...(relay !== undefined && relay !== carrier.relay && { relay }), ...(started !== undefined && { started }) });
323
+ const r = await carrier.invite({ name: `${name ?? `worker ${i}`} (enrolling)`, short: true, enrol: true, ...(relay !== undefined && relay !== carrier.relay && { relay }), ...(started !== undefined && { started }), ...(ttl !== undefined && { ttl }) });
263
324
  const now = nowOf(carrier), code = readCode(r.code, now), me = self(carrier, now);
264
325
  const attestation = operatorAttestation({ sign: me.sign, iss: me.did, sub: w.original, relay: code.relay, now, days });
265
326
  const old = liveHolding(carrier, w.original);
266
327
  pendingOf(carrier)(file, now, (s) => {
267
328
  s.issued[code.nonce] = { key: bytesToHex(enrolKey(code.secret)), i, n, name: name ?? null, did: w.did, original: w.original, old_pair: old ? pairOf(old) : null,
268
- relay: code.relay, exp: now + PENDING_TTL, attestation, issuer: me.genesis, ...(operatorLabel(operatorName) !== null && { operator_name: operatorLabel(operatorName) }), ...(confirmWords && { confirm_words: true }) };
329
+ relay: code.relay, exp: now + PENDING_TTL, attestation, issuer: me.genesis, ...(operatorLabel(operatorName) !== null && { operator_name: operatorLabel(operatorName) }), ...(confirmWords && { confirm_words: true }),
330
+ ...(r.short && { short_hash: codeHash(r.short) }) };
269
331
  });
270
- return { ...r, id: code.nonce, did: w.did, original: w.original };
332
+ // enrol_code: how it is shown to an agent (ENROL-K7F3-Q9ZP, short.mjs), never taken for a pairing code.
333
+ return { ...r, id: code.nonce, did: w.did, original: w.original, ...(r.short && { enrol_code: formatEnrol(normaliseShort(r.short)) }) };
271
334
  }
272
335
 
273
336
  /**
@@ -276,14 +339,47 @@ export async function issue({ carrier, file, i, n, name, keeper, days = OPERATOR
276
339
  * else at a later complete(). temp: the temporary identity's file, kept with the entry.
277
340
  * → { status, did: the operator's DID as the code names it, contact?, id, long? }.
278
341
  */
279
- export async function accept({ carrier, file, code: text, name, wait = 10, temp }) {
280
- const short = codeKind(text) === 'short', long = short ? await carrier.unpark(text) : text;
342
+ // strict: a short code must be one the relay parked as an enrolment code (relay/park.mjs isEnrol), and a
343
+ // long code is refused (it says nothing of what it is for): an agent's init --enrol, never a pairing code.
344
+ export async function accept({ carrier, file, code: given, name, wait = 10, temp, strict = false, relay }) {
345
+ const text = stripEnrol(given), short = codeKind(text) === 'short';
346
+ if (strict && !short) fail('enrol_not', 'init --enrol takes the enrol code your operator\'s app or sigelo-agent enrol gave (ENROL-K7F3-Q9ZP), not a long sgl1… code; a pairing code from a contact goes to accept CODE');
347
+ const got = short ? await carrier.unparkFrom(text, { ...(relay !== undefined && { relay }) }) : { invite: text, enrol: false }, long = got.invite;
348
+ if (strict && got.enrol !== true) fail('enrol_not', 'that is a pairing code, not an enrol code (the relay parked it as an invite; or your operator\'s app is older than 0.1.19): a pairing code goes to accept CODE; for enrolment ask your operator for a new enrol code');
349
+ const now = nowOf(carrier), code = readCode(long, now, short ? 'parked' : 'long');
350
+ pendingOf(carrier)(file, now, (s) => {
351
+ s.joining[code.nonce] = { key: bytesToHex(enrolKey(code.secret)), code_did: code.did, relay: code.relay, exp: now + PENDING_TTL, sent: false, temp: temp ?? null,
352
+ long, ...(short && { short_hash: codeHash(text) }), answered: false };
353
+ });
354
+ return answer(carrier, file, code.nonce, long, { name, wait, short, did: code.did });
355
+ }
356
+
357
+ // The machine's answer to the code of joining entry `id`, marked `answered` once it went or waits queued
358
+ // in the carrier (a refusal that withdrew it leaves it false: resumeAnswer sends it again).
359
+ async function answer(carrier, file, id, long, { name, wait, short, did }) {
360
+ const mark = () => pendingOf(carrier)(file, nowOf(carrier), (s) => { if (s.joining[id]) s.joining[id].answered = true; });
281
361
  try {
282
- const now = nowOf(carrier), code = readCode(long, now, short ? 'parked' : 'long');
283
- pendingOf(carrier)(file, now, (s) => { s.joining[code.nonce] = { key: bytesToHex(enrolKey(code.secret)), code_did: code.did, relay: code.relay, exp: now + PENDING_TTL, sent: false, temp: temp ?? null }; });
284
362
  const r = await carrier.accept(long, { name, wait });
285
- return { ...r, did: code.did, id: code.nonce, ...(short && { long }) };
286
- } catch (e) { throw short ? keepLong(e, long) : e; }
363
+ mark();
364
+ return { ...r, did, id, ...(short && { long }) };
365
+ } catch (e) {
366
+ if (e?.kept) mark();
367
+ // The entry stays: init --enrol with the same code, or enrol --finish, takes it up again.
368
+ throw Object.assign(short ? keepLong(e, long) : e, { pending: id });
369
+ }
370
+ }
371
+
372
+ /** The machine: each joining entry of `temp` whose answer did not go (a refused proof of work withdrew it)
373
+ * and whose code still lives is answered again. → how many were sent or queued again. */
374
+ export async function resumeAnswer({ carrier, file, temp, name = 'operator', wait = 30 }) {
375
+ const now = nowOf(carrier);
376
+ const todo = pendingOf(carrier)(file, now, (s) => Object.entries(s.joining).filter(([, j]) => j.temp === temp && j.answered === false && typeof j.long === 'string'));
377
+ let n = 0;
378
+ for (const [id, j] of todo) {
379
+ if (liveHolding(carrier, j.code_did)) { pendingOf(carrier)(file, nowOf(carrier), (s) => { if (s.joining[id]) s.joining[id].answered = true; }); continue; }
380
+ try { await answer(carrier, file, id, j.long, { name, wait, short: false, did: j.code_did }); n++; } catch (e) { if (!(e instanceof MsgError) && !e?.check) throw e; if (e.kept) n++; }
381
+ }
382
+ return n;
287
383
  }
288
384
 
289
385
  /**
@@ -294,45 +390,88 @@ export async function accept({ carrier, file, code: text, name, wait = 10, temp
294
390
  * machine: temp = the temporary identity's file this carrier runs on; place(checked, { operator })
295
391
  * writes the worker's file and pairs as it → { status, contact? }.
296
392
  * → { delivered: [{ id, name, temp, did }], placed: [{ id, name, did, original, … }], refused: [{ check, detail, from }],
393
+ * status (machine): [{ check, detail, at }] the operator's word on its request, told (operator): [{ to, check, detail }],
297
394
  * sent: [{ did }], rest: the batch without what was handled, offline? }
298
395
  */
299
396
  export async function complete({ carrier, file, wait = 0, until = () => false, keeper = null, place = null, temp = null, confirm = null }) {
300
397
  if (keeper) checkKeeper(keeper);
301
- const out = { delivered: [], placed: [], refused: [], sent: [], held: [], rest: { messages: [], events: [], dropped: {} } };
398
+ const out = { delivered: [], placed: [], refused: [], sent: [], held: [], status: [], told: [], rest: { messages: [], events: [], dropped: {} } };
302
399
  const end = Date.now() + wait * 1000;
400
+ // One request answered once per call, however it came (held before, and the same again from the inbox).
401
+ const done = new Set(), once = (m) => { const k = `${m?.from} ${m?.content?.proof}`; if (done.has(k)) return false; done.add(k); return true; };
303
402
  for (let first = true; ; first = false) {
304
- if (first && place) await sendRequests(carrier, file, temp, out, true);
403
+ if (first && place) await sendRequests(carrier, file, temp, out);
404
+ // The requests held before (the header's "A request held"): taken again first, once per complete().
405
+ if (first && keeper) {
406
+ const kept = pendingOf(carrier)(file, nowOf(carrier), (s) => Object.values(s.issued).filter((e) => e.held && !e.done).map((e) => e.held));
407
+ for (const m of kept) if (once(m)) await onRequest(carrier, file, keeper, m, out, confirm);
408
+ }
409
+ if (keeper) await resend(carrier, file, keeper, out);
305
410
  if (keeper) await settle(carrier, file, keeper, out);
306
411
  const left = Math.max(0, Math.ceil((end - Date.now()) / 1000));
307
412
  const batch = await carrier.inbox({ wait: Math.min(left, WAIT_STEP), paired: true });
308
413
  out.rest.events.push(...batch.events);
309
414
  for (const [k, n] of Object.entries(batch.dropped ?? {})) out.rest.dropped[k] = (out.rest.dropped[k] ?? 0) + n;
310
415
  for (const m of batch.messages) {
311
- if (m?.label === LABEL_ENROL && keeper) await onRequest(carrier, file, keeper, m, out, confirm);
416
+ if (m?.label === LABEL_ENROL && place && readStatus(m.content) && onStatus(carrier, file, temp, m, out)) continue;
417
+ if (m?.label === LABEL_ENROL && keeper && !readStatus(m.content)) { if (once(m)) await onRequest(carrier, file, keeper, m, out, confirm); }
312
418
  else if (m?.label === LABEL_IDENTITY && place && await onIdentity(carrier, file, temp, m, out, place)) continue;
313
419
  else out.rest.messages.push(m);
314
420
  }
315
421
  if (batch.offline !== undefined) { out.offline = batch.offline; out.lastError = carrier.lastError; break; }
316
422
  // A pairing this inbox completed sends its request now, not at the next run; a worker that
317
423
  // paired in this inbox is filed now.
318
- if (place && out.placed.length === 0) await sendRequests(carrier, file, temp, out, false);
424
+ if (place && out.placed.length === 0) await sendRequests(carrier, file, temp, out);
319
425
  if (keeper) await settle(carrier, file, keeper, out);
320
426
  if (until(out) || Date.now() >= end) break;
321
427
  }
428
+ // The machine: the operator's last word when none came in this run (an earlier run kept it).
429
+ if (place && out.status.length === 0 && out.placed.length === 0) {
430
+ const kept = pendingOf(carrier)(file, nowOf(carrier), (s) => Object.values(s.joining).filter((j) => j.temp === temp && j.status).map((j) => j.status));
431
+ out.status.push(...kept);
432
+ }
322
433
  return out;
323
434
  }
324
435
 
436
+ // The operator: tell the temporary DID `to` (a live contact) why its request is refused or held, once per
437
+ // check (the header's "The machine is told why"). Best effort: a send that fails is tried at the next reason.
438
+ async function tell(carrier, file, to, check, detail, out) {
439
+ const c = readStore(carrier).contacts[to];
440
+ if (!c || c.revoked || !c.pair_key) return;
441
+ const now = nowOf(carrier);
442
+ const fresh = pendingOf(carrier)(file, now, (s) => s.told?.[to]?.check !== check);
443
+ if (!fresh) return;
444
+ const words = toldFor(check, detail);
445
+ try {
446
+ await carrier.send(c.did, statusMessage(check, words), { label: LABEL_ENROL });
447
+ pendingOf(carrier)(file, nowOf(carrier), (s) => { (s.told ??= {})[to] = { check, detail: words, exp: now + PENDING_TTL }; });
448
+ out.told.push({ to, check, detail: words });
449
+ } catch (e) { if (!(e instanceof MsgError)) throw e; }
450
+ }
451
+
452
+ // The machine: the operator's status, from the contact it paired with through a code → true when taken.
453
+ function onStatus(carrier, file, temp, m, out) {
454
+ const c = readStore(carrier).contacts[m.from], st = readStatus(m.content);
455
+ const now = nowOf(carrier);
456
+ const id = c && !c.revoked ? pendingOf(carrier)(file, now, (s) => Object.entries(s.joining).find(([, j]) => j.temp === temp && c.chain.includes(j.code_did))?.[0]) : undefined;
457
+ if (!id) return false;
458
+ pendingOf(carrier)(file, now, (s) => { if (s.joining[id]) s.joining[id].status = { ...st, at: now }; });
459
+ out.status.push({ ...st, at: now, from: m.from });
460
+ return true;
461
+ }
462
+
325
463
  // The machine: a request for each enrolment of this temporary identity whose pairing is complete
326
- // and that has not sent one; at a first round, again for those sent before without an answer (the
327
- // operator's inbox may have gone to another reader).
328
- async function sendRequests(carrier, file, temp, out, first) {
329
- const todo = pendingOf(carrier)(file, nowOf(carrier), (s) => Object.entries(s.joining).filter(([, j]) => j.temp === temp && (!j.sent || first)));
464
+ // and that has not sent one, or sent it RESEND_S ago or more with no identity come since (it was
465
+ // lost, refused, or read elsewhere; the operator answers a request again until the worker paired).
466
+ async function sendRequests(carrier, file, temp, out) {
467
+ const now0 = nowOf(carrier);
468
+ const todo = pendingOf(carrier)(file, now0, (s) => Object.entries(s.joining).filter(([, j]) => j.temp === temp && due(j.sent, now0)));
330
469
  for (const [id, j] of todo) {
331
470
  const c = liveHolding(carrier, j.code_did);
332
471
  if (!c) continue;
333
472
  try {
334
473
  const r = await carrier.send(c.did, request(hexToBytes(j.key), pairOf(c)), { label: LABEL_ENROL });
335
- pendingOf(carrier)(file, nowOf(carrier), (s) => { if (s.joining[id]) s.joining[id].sent = true; });
474
+ pendingOf(carrier)(file, nowOf(carrier), (s) => { if (s.joining[id]) s.joining[id].sent = nowOf(carrier); });
336
475
  out.sent.push({ did: c.did, status: r.status });
337
476
  } catch (e) {
338
477
  out.refused.push({ check: e.check ?? 'error', detail: `the enrolment request to ${c.name} did not go (${e.message}): it goes at the next sigelo-agent enrol --finish`, from: c.did });
@@ -361,20 +500,33 @@ async function onRequest(carrier, file, keeper, m, out, confirm) {
361
500
  e.temp = c.did;
362
501
  return { id, e };
363
502
  });
364
- if (r.check) { out.refused.push({ ...r, from: m.from }); return; }
503
+ if (r.check) { out.refused.push({ ...r, from: m.from }); await tell(carrier, file, m.from, r.check, r.detail, out); return; }
365
504
  const { id, e } = r;
366
505
  // The words gate (devices.md §5.1): the human compares the pairing's four words on this side
367
506
  // before the key goes. Declined: the enrolment is dropped, nothing is ever sent for it.
368
507
  // An enrolment made with the switch on is never sent unasked: without a confirm() here, it waits.
369
508
  const said = e.confirmed ? true : confirm ? await confirm({ id, name: e.name, i: e.i, did: e.did, temp: c.did, words: fingerprint(pair), ask: e.confirm_words === true }) : e.confirm_words ? null : true;
370
509
  // Not yet (the page waits for the human's tap): the request is kept, nothing goes.
371
- if (said === null || said === undefined) { out.held.push(m); return; }
510
+ if (said === null || said === undefined) {
511
+ const kept = { from: m.from, name: m.name ?? null, label: LABEL_ENROL, content: m.content };
512
+ pendingOf(carrier)(file, nowOf(carrier), (s) => { if (s.issued[id]) s.issued[id].held = kept; });
513
+ out.held.push(m); await tell(carrier, file, c.did, 'enrol_words', '', out); return;
514
+ }
515
+ pendingOf(carrier)(file, nowOf(carrier), (s) => { if (s.issued[id]) delete s.issued[id].held; });
372
516
  if (!said) {
373
517
  pendingOf(carrier)(file, nowOf(carrier), (s) => { delete s.issued[id]; });
374
518
  out.refused.push({ check: 'device_words', detail: `the four words of ${who} were not confirmed: worker ${e.i} not sent, the code is dropped; make a new one`, from: m.from });
519
+ await tell(carrier, file, c.did, 'device_words', '', out);
375
520
  return;
376
521
  }
377
522
  if (confirm || e.confirm_words) pendingOf(carrier)(file, nowOf(carrier), (s) => { if (s.issued[id]) s.issued[id].confirmed = true; });
523
+ await sendIdentity(carrier, file, keeper, id, e, c, out);
524
+ }
525
+
526
+ // The operator: worker e.i's identity to the temporary DID c, with its own invite. Refused or failed:
527
+ // marked needs_send (resend tries again), never left to a request that may not come again.
528
+ async function sendIdentity(carrier, file, keeper, id, e, c, out) {
529
+ const now = nowOf(carrier), who = `${c.name ?? c.did} (${c.did})`;
378
530
  try {
379
531
  // The worker's own invite, made once per enrolment: a repeated request gets the same.
380
532
  let invite = e.invite;
@@ -384,11 +536,38 @@ async function onRequest(carrier, file, keeper, m, out, confirm) {
384
536
  }
385
537
  const identity = workerIdentity({ K: keeper.K, i: e.i, n: e.n, recovery: keeper.recovery, attestation: e.attestation, issuer: e.issuer });
386
538
  if (didOf([identity.genesis, ...identity.rotations.map((x) => x.next_genesis)].at(-1)) !== e.did) fail('keeper', `worker ${e.i} derives to another DID than at enrol: the keeper root changed since (sigelo-agent keeper)`);
387
- const sent = await carrier.send(c.did, identityMessage(identity, invite, e.i, e.operator_name ?? null), { label: LABEL_IDENTITY });
539
+ const sent = await carrier.send(c.did, identityMessage(identity, invite, e.i, e.operator_name ?? null, id), { label: LABEL_IDENTITY });
540
+ pendingOf(carrier)(file, nowOf(carrier), (s) => { if (s.issued[id]) { s.issued[id].sent_at = nowOf(carrier); delete s.issued[id].needs_send; } });
388
541
  out.delivered.push({ id, name: e.name, temp: c.did, did: e.did, status: sent.status });
542
+ await spend(carrier, file, id, e);
389
543
  } catch (x) {
390
544
  if (!(x instanceof MsgError)) throw x;
391
- out.refused.push({ check: x.check, detail: `worker ${e.i} did not go to ${who} (${x.message}): it goes when the machine asks again (sigelo-agent enrol --finish there)`, from: m.from });
545
+ if (x.check !== 'keeper') pendingOf(carrier)(file, nowOf(carrier), (s) => { if (s.issued[id]) s.issued[id].needs_send = nowOf(carrier); });
546
+ out.refused.push({ check: x.check, detail: `worker ${e.i} did not go to ${who} (${x.message}): it goes again at the next round, or when the machine asks again (sigelo-agent enrol --finish there)`, from: c.did, needs_send: id });
547
+ if (x.check !== 'keeper') await tell(carrier, file, c.did, x.check, x.message, out);
548
+ }
549
+ }
550
+
551
+ // The operator: the grant went, so the enrolment code is spent at the relay (relay/park.mjs: until now it
552
+ // could be fetched again). Best effort: one not spent runs out there by itself, and its pairing is taken.
553
+ async function spend(carrier, file, id, e) {
554
+ if (!e.short_hash || e.unparked || typeof carrier.unparkHash !== 'function') return;
555
+ try {
556
+ const r = await carrier.unparkHash(e.short_hash, e.relay);
557
+ if (r.unparked) pendingOf(carrier)(file, nowOf(carrier), (s) => { if (s.issued[id]) s.issued[id].unparked = true; });
558
+ } catch {}
559
+ }
560
+
561
+ // The operator: each enrolment whose identity send failed (needs_send), sent again once RESEND_S
562
+ // passed, while the entry lives, its worker has not paired, and its temporary DID is still a live
563
+ // contact. Only what onRequest already let go (its proof checked, its words confirmed when asked).
564
+ async function resend(carrier, file, keeper, out) {
565
+ const now = nowOf(carrier);
566
+ const todo = pendingOf(carrier)(file, now, (s) => Object.entries(s.issued).filter(([, e]) => e.needs_send !== undefined && e.temp && !e.done && due(e.needs_send, now) && (e.confirmed || !e.confirm_words)));
567
+ for (const [id, e] of todo) {
568
+ const c = readStore(carrier).contacts[e.temp];
569
+ if (!c || c.revoked || !c.pair_key) continue;
570
+ await sendIdentity(carrier, file, keeper, id, e, c, out);
392
571
  }
393
572
  }
394
573
 
@@ -424,7 +603,7 @@ async function onIdentity(carrier, file, temp, m, out, place) {
424
603
  }
425
604
  const [id, j] = hit;
426
605
  try {
427
- const x = checkIdentity(m.content, { operator: c, relay: j.relay, now }), tempDid = self(carrier, now).original;
606
+ const x = checkIdentity(m.content, { operator: c, relay: j.relay, now, id }), tempDid = self(carrier, now).original;
428
607
  const r = await place(x, { operator: c, id });
429
608
  // The temporary identity is done: the operator is forgotten on it, its mailboxes given up.
430
609
  let released = false, offline;