sigelo-contact 0.1.13 → 0.1.20

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 +727 -0
  3. package/carrier.mjs +1204 -137
  4. package/control.mjs +81 -22
  5. package/device.mjs +1 -1
  6. package/enrol.mjs +239 -43
  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 +616 -0
  13. package/invite.mjs +63 -13
  14. package/kdf.mjs +1 -1
  15. package/link.mjs +24 -16
  16. package/package.json +49 -7
  17. package/page.mjs +1172 -70
  18. package/photo.mjs +37 -0
  19. package/platform-node.mjs +125 -18
  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 +95 -0
  25. package/short.mjs +31 -3
  26. package/store.mjs +147 -12
  27. package/test-carrier.mjs +138 -21
  28. package/test-device.mjs +1 -1
  29. package/test-enrol.mjs +157 -8
  30. package/test-envelope.mjs +16 -3
  31. package/test-file.mjs +5 -5
  32. package/test-group.mjs +413 -0
  33. package/test-invite.mjs +15 -2
  34. package/test-link.mjs +11 -8
  35. package/test-platform.mjs +5 -5
  36. package/test-presence.mjs +169 -0
  37. package/test-push.mjs +136 -0
  38. package/test-relay-lane.mjs +248 -0
  39. package/test-short.mjs +38 -12
  40. package/test-tier.mjs +6 -6
  41. package/test-transfer-web.mjs +246 -0
  42. package/test-transfer.mjs +463 -0
  43. package/test-voice.mjs +158 -0
  44. package/test-ws.mjs +5 -5
  45. package/transfer-engine.mjs +800 -0
  46. package/transfer-node.mjs +449 -0
  47. package/transfer-web.mjs +80 -0
  48. package/transfer.mjs +388 -0
  49. package/voice-web.mjs +113 -0
  50. package/voice.mjs +65 -0
  51. package/words-lock.mjs +115 -0
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
  //