sigelo-contact 0.1.13 → 0.1.14

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/page.mjs CHANGED
@@ -25,6 +25,12 @@
25
25
  // confirm(name, match) → whether one was pending } (relay controls whose four words wait: the
26
26
  // Controls card; routes in no remote scope, so never asked over the relay or the LAN).
27
27
  //
28
+ // Groups (adapters/moadim/GROUPS.md, design/groups.md §5): groups: group.mjs (the module) and groupsFile
29
+ // (groupsPath of the identity). Each drain hands the carrier's group messages to group.mjs handle(), here
30
+ // in code: without it the page never takes a roster, carries a copy on or files a message. The page's
31
+ // own marks in data: gread (gid → the newest item shown: {mid, at}), gnotices (a stranger added, the
32
+ // creator gone, a refusal: until dismissed). /api/groups/* (UI-API.md "Groups").
33
+ //
28
34
  // Agents (ENROL.md, the app's main list): hooks.keeper, where the host has the operator's keeper root:
29
35
  // { read() → the keeper file as JSON (workers, …) | null, root(k) → { K, recovery } (K zeroed after use),
30
36
  // update(fn) → fn(keeper) applied and kept }. enrolFile: the pending enrolments (enrol.mjs enrolPath). The
@@ -32,7 +38,19 @@
32
38
  // `sigelo-agent enrol --name`, which refuses busy beside a page), takes the requests that come through
33
39
  // it (kept apart from the devices'), answers them with the worker's identity and files the worker
34
40
  // 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.
41
+ // seat is on another device refuses seat_elsewhere. No four words to tap: a worker that pairs as the DID
42
+ // derived from K (enrol.mjs `verified`) is words-checked here at once; the words stay to see, and the
43
+ // optional switch (`confirm_words`) holds the key until "They match" (POST /api/agents/enrol-words).
44
+ //
45
+ // Transfers (adapters/moadim/TRANSFER.md, contact/transfer-node.mjs): hooks.transfers, where the host
46
+ // moves big files ({ lib: transfer-node.mjs, make(carrier, onEvent) → its Engine }; Node only, until the
47
+ // WebView's platform.rtc): the page owns the session, so its engine answers offers and moves the bytes;
48
+ // the /api/transfers* routes; none without the hook (404 route).
49
+ //
50
+ // Proof of work (design/profiles.md §6): what the human starts here (the page's start, a code, an
51
+ // answer, "Try now") passes the carrier's `started: 'user'`; past the day's three the route answers
52
+ // 409 pow_confirm, and the same call with `pow_confirmed: true` goes on. The carrier's automatic
53
+ // retries stay capped: state's me.pow_capped {relay, next} says when the next one is.
36
54
  //
37
55
  // The relay setting (UI-API.md "Settings"): the relay new codes name, kept in data.settings.relay.
38
56
  // Precedence: relayFixed (the host's environment: SIGELO_RELAY, or a relay the host was given) wins,
@@ -44,6 +62,7 @@ import { bytesToHex, randomBytes } from '@noble/hashes/utils.js';
44
62
  import { DEFAULT_RELAY } from './carrier.mjs';
45
63
  import * as E from './enrol.mjs';
46
64
  import { checkRelay } from './invite.mjs';
65
+ import { didWords } from './short.mjs';
47
66
 
48
67
  const DAY = 86400, TAG_MAX = 20, NAME_MAX = 64, TEXT_MAX = 100_000;
49
68
  // An agent's name: a contact name and, placed here, a file name (sigelo.<name>.local.json), as `enrol --name` takes it.
@@ -51,9 +70,11 @@ const AGENT_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
51
70
  const goodRelay = (h) => { try { checkRelay(h); return true; } catch { return false; } };
52
71
  const nowS = () => Math.floor(Date.now() / 1000);
53
72
  const hexOf = (n) => bytesToHex(randomBytes(n));
73
+ // A short change mark of a string (FNV-1a, 32 bits): not a check of anything, only "something changed".
74
+ const hashOf = (t) => { let x = 0x811c9dc5; for (let i = 0; i < t.length; i++) { x ^= t.charCodeAt(i); x = Math.imul(x, 0x01000193) >>> 0; } return x.toString(36); };
54
75
  export const refuse = (status, check, message) => { throw Object.assign(new Error(message), { check, status }); };
55
76
 
56
- export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, codeKind, unlogged, store, hooks = {}, relayFixed = null }) {
77
+ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, groupsFile = null, enrolFile = null, codeKind, unlogged, store, hooks = {}, relayFixed = null }) {
57
78
  const defer = hooks.defer ?? ((f) => setTimeout(f, 0));
58
79
  const every = hooks.every ?? ((f, ms) => { const t = setInterval(f, ms); t.unref?.(); return t; });
59
80
  const watchers = new Set();
@@ -82,12 +103,15 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
82
103
  };
83
104
  let data;
84
105
  try { data = JSON.parse(store.readData() ?? 'null') ?? {}; } catch { data = {}; }
85
- for (const k of ['tags', 'checked', 'read', 'controls', 'settings']) data[k] ??= {};
106
+ for (const k of ['tags', 'checked', 'read', 'controls', 'settings', 'gread']) data[k] ??= {};
107
+ data.gnotices ??= [];
86
108
  delete data.waiting; // kept by an earlier page; the carrier says it now (contacts: prekeys, waiting)
87
109
  const saveData = () => store.writeData(JSON.stringify(data));
88
110
 
89
111
  // ---- live status, not kept
90
- const live = { online: new Set(), pow: null, powDone: null, error: null, seatGone: null };
112
+ const live = { online: new Set(), pow: null, powDone: null, error: null, seatGone: null, powCapped: null, powConfirm: null };
113
+ // A call the human made: past the day's searches it asks (pow_confirm) unless they said go on.
114
+ const startedBy = (b) => (b?.['pow_confirmed'] === true ? 'confirmed' : 'user');
91
115
  // Writes, one at a time. Once the seat went to another device, every write is refused.
92
116
  let chain = Promise.resolve();
93
117
  const gone = (fn) => () => (live.seatGone !== null ? refuse(409, 'seat_elsewhere', `the seat went to ${live.seatGone}: this page no longer logs in as you`) : fn());
@@ -137,7 +161,7 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
137
161
  if (draining) { again = true; return draining; }
138
162
  draining = (async () => {
139
163
  try {
140
- do { again = false; take(await carrier.inbox({ local: true })); } while (again);
164
+ do { again = false; take(await carrier.inbox({ local: true })); await groupRound(); } while (again);
141
165
  // Device messages: wiped answers, a standby asking for the seat (it goes, and this page stops logging in as you).
142
166
  if (live.seatGone === null && hooks.deviceRound) {
143
167
  const r = await hooks.deviceRound();
@@ -161,6 +185,7 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
161
185
  return linking;
162
186
  };
163
187
  const onEvent = (e) => {
188
+ if (e.type === 'transfer') defer(() => void transfers?.engine.kick());
164
189
  if (e.type === 'link' || e.type === 'paired') defer(() => void linkRound());
165
190
  try {
166
191
  const d = e['did'] ?? e['from'] ?? e['peer'];
@@ -178,10 +203,19 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
178
203
  }
179
204
  case 'pow': live.pow = { bits: Number(e['bits']), since: Date.now() }; break;
180
205
  case 'pow_done': live.pow = null; live.powDone = Number(e['ms']); break;
181
- case 'connected': live.online.add(String(e['relay'])); live.error = null; void checkClock(); break;
206
+ case 'connected':
207
+ live.online.add(String(e['relay'])); live.error = null; void checkClock();
208
+ if (live.powCapped?.relay === e['relay']) live.powCapped = null;
209
+ if (live.powConfirm?.relay === e['relay']) live.powConfirm = null;
210
+ break;
182
211
  case 'disconnected': live.online.delete(String(e['relay'])); break;
183
- case 'error': live.error = `${e['check']}: ${e['detail']}`; break;
184
- case 'notice': break;
212
+ case 'error':
213
+ live.error = `${e['check']}: ${e['detail']}`;
214
+ // The day's searches spent: when the next automatic try is, and "Try now" (POST /api/pow/try).
215
+ if (e['check'] === 'pow' && Number.isSafeInteger(e['next'])) live.powCapped = { relay: String(e['relay']), next: e['next'] };
216
+ if (e['check'] === 'pow_confirm') live.powConfirm = { relay: String(e['relay']), detail: String(e['detail']).replace(/^pow_confirm: /, '') };
217
+ break;
218
+ case 'notice': case 'presence': case 'group_tier': break; // presence, the group tier: the state says it, nothing to take
185
219
  default: soon();
186
220
  }
187
221
  } catch (err) { live.error = `history: ${err.message}`; }
@@ -189,6 +223,14 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
189
223
  };
190
224
  const kept = () => (typeof data.settings.relay === 'string' && goodRelay(data.settings.relay) ? data.settings.relay : null);
191
225
  const carrier = makeCarrier(onEvent, kept() !== null ? { relay: kept() } : {});
226
+ // The engine's events: a file offered, done, failed (into the history as events; the view reads GET /api/transfers).
227
+ const onTransfer = (e) => {
228
+ if (['asked', 'done', 'failed', 'declined', 'cancelled'].includes(e.what)) {
229
+ try { record({ kind: 'event', type: 'transfer', what: e.what, id: e.id, did: e.from ?? null, name: e.contact ?? null, code: e.reason ?? null, detail: e.what === 'asked' ? `${e.name} (${e.size} bytes)` : e.path ?? null }); } catch {}
230
+ }
231
+ changed();
232
+ };
233
+ const transfers = hooks.transfers ? { lib: hooks.transfers.lib, engine: hooks.transfers.make(carrier, onTransfer) } : null;
192
234
  // The relay new codes name, as the precedence says.
193
235
  const newCodes = () => relayFixed ?? kept() ?? DEFAULT_RELAY;
194
236
  const settings = () => ({ relay: kept() ?? DEFAULT_RELAY, default: DEFAULT_RELAY, fixed: relayFixed, in_use: carrier.relay });
@@ -198,13 +240,15 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
198
240
  async function start() {
199
241
  void checkClock();
200
242
  timers = [every(() => void checkClock(), 600_000), every(() => void drain().then(() => linkRound()), 60_000)];
201
- await carrier.start();
243
+ await carrier.start({ started: 'user' });
202
244
  await drain();
203
245
  void linkRound();
246
+ void transfers?.engine.kick();
204
247
  }
205
248
  async function halt() {
206
249
  for (const t of timers) clearInterval(t);
207
250
  await linking.catch(() => {});
251
+ await transfers?.engine.close().catch(() => {});
208
252
  }
209
253
 
210
254
 
@@ -231,6 +275,7 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
231
275
  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
276
  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
277
  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,
278
+ confirm_words: e.confirmWords === true, words_ok: e.wordsOk ?? null, verified: e.verified === true,
234
279
  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
280
  // Who answered each code (its four words), codes dead unanswered (the index free again), enrolments done.
236
281
  async function look() {
@@ -266,14 +311,23 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
266
311
  const root = await K.root(k);
267
312
  // The carrier as enrolment sees it: its inbox is what the page kept apart.
268
313
  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]) });
314
+ // The optional switch: the key waits for "They match" (null: not yet, the request kept for the next round).
315
+ const confirm = async (o) => { if (!o.ask) return true; const e = enrolling.get(o.id); if (e && !e.words) e.words = o.words; return e?.wordsOk ?? null; };
269
316
  let res;
270
- try { res = await E.complete({ carrier: proxy, file: enrolFile, keeper: root, wait: 0 }); } finally { root.K.fill(0); }
317
+ try { res = await E.complete({ carrier: proxy, file: enrolFile, keeper: root, wait: 0, confirm }); } finally { root.K.fill(0); }
318
+ agentHeld.push(...(res.held ?? []));
271
319
  for (const d of res.delivered) { const e = enrolling.get(d.id); if (e) e.state = 'sending'; }
272
320
  for (const x of res.refused) {
273
321
  const e = [...enrolling.values()].find((y) => y.temp !== undefined && y.temp === x.from);
274
322
  if (e) Object.assign(e, { check: x.check, detail: x.detail });
275
323
  }
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 }); }
324
+ for (const p of res.placed) {
325
+ const e = enrolling.get(p.id);
326
+ if (e) Object.assign(e, { state: 'enrolled', at: nowS(), did: p.did, verified: p.verified === true });
327
+ // Worker i of these words, derived here: checked as "They match" checks a contact (no tap).
328
+ const c = p.verified ? carrier.contacts().contacts.find((x) => x.did === p.original && !x.revoked) : null;
329
+ if (c) { data.checked[c.did] = c.pair ?? ''; saveData(); }
330
+ }
277
331
  changed();
278
332
  }
279
333
  const workerOf = (k, v) => {
@@ -292,6 +346,7 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
292
346
  const status = w.revoked !== undefined ? 'revoked' : c || here ? 'enrolled' : (e && LIVE.has(e.state)) || waiting.includes(n) ? 'pending' : 'unplaced';
293
347
  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
348
  seen: c ? seen(c.did) : null, tier: c?.tier ?? null, contact: c?.did ?? null, local: here?.name ?? null,
349
+ online: c?.online ?? null, last_seen: c?.last_seen ?? null,
295
350
  attested_until: here?.mine?.exp ?? w.until ?? w.attestation?.body?.exp ?? null, enrolling: e && e.state !== 'expired' ? pub(e) : null };
296
351
  }).sort((a, b) => a.worker - b.worker);
297
352
  return { keeper: true, seat, workers: rows };
@@ -320,6 +375,8 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
320
375
  waiting, not_collected: queued.length, queued: x.queued,
321
376
  status: x.re_pair ? 'pair_again' : waiting ? 'waiting' : queued.length ? 'not_collected' : 'ok', ours: x.ours === true || mine !== null, tier,
322
377
  link: x.link ? { id: x.link.id, purpose: x.link.purpose, linked_by: x.link.linked_by, expires: x.link.expires ?? null } : null,
378
+ // Presence (carrier.mjs): theirs as read now (online true, false, null: not known), and what they see of mine.
379
+ online: x.online ?? null, online_since: x.online_since ?? null, last_seen: x.last_seen ?? null, presence: x.presence ?? 'deny',
323
380
  };
324
381
  });
325
382
  // Mine: ours by key, whatever the tier (an own agent set to friend is still mine), or tier own.
@@ -340,10 +397,14 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
340
397
  // The seat (DEVICES.md): null without one; here false = another device logs in as you: the page shows a banner.
341
398
  seat: hooks.seat?.() ?? null,
342
399
  pow: live.pow && { bits: live.pow.bits, elapsed_s: Math.round((Date.now() - live.pow.since) / 1000), expected_s: Math.ceil(2 ** live.pow.bits / 180000) },
400
+ pow_capped: live.powCapped, pow_confirm: live.powConfirm,
343
401
  },
344
402
  groups: { mine: mineGroup, contacts: rest },
403
+ // Chat groups (GROUPS.md): the tab's badge and its notices; the list is GET /api/groups.
404
+ chats: chatsState(),
345
405
  pending: { invites: pendingInvites, paired, answers: c.answers, failed },
346
406
  introductions: introductions(c.contacts),
407
+ transfers: transferCounts(),
347
408
  events: recs.filter((r) => r.kind === 'event' && r.n > since).slice(-50),
348
409
  };
349
410
  }
@@ -357,6 +418,122 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
357
418
  } catch { return []; }
358
419
  }
359
420
 
421
+ // Files offered and waiting for a yes, and those moving: the page's badge (GET /api/transfers has the rest).
422
+ function transferCounts() {
423
+ if (!transfers) return null;
424
+ try {
425
+ const l = transfers.lib.list({ carrier, identity: hooks.transfers.identity });
426
+ return { asked: l.in.filter((r) => r.state === 'asked').length, active: [...l.in, ...l.out].filter((r) => ['accepted', 'offering', 'active'].includes(r.state)).length };
427
+ } catch { return null; }
428
+ }
429
+ // ---- groups (GROUPS.md): the inbox side by code at each drain; the lists and the verbs below
430
+ const GROUP_NOTICES = 20;
431
+ const gfile = () => groupsFile ?? refuse(404, 'route', 'no groups here');
432
+ // A notice for the operator, kept until dismissed (data.gnotices): a stranger added, the creator gone, refusals.
433
+ const gnote = (n) => { data.gnotices.push({ id: hexOf(4), at: nowS(), ...n }); if (data.gnotices.length > GROUP_NOTICES) data.gnotices.splice(0, data.gnotices.length - GROUP_NOTICES); };
434
+ // The carrier's group messages checked and filed (handle), copies carried on and sent; every item is the
435
+ // page's to show (taken: no inbox beside a page). Invitations wait as status pending in the list.
436
+ async function groupRound() {
437
+ if (!G || !groupsFile) return;
438
+ try {
439
+ const r = await G.handle({ carrier, file: groupsFile });
440
+ let noted = false;
441
+ for (const n of r.notices) if (n.why !== 'invited') { gnote(n); noted = true; }
442
+ const by = new Map();
443
+ for (const x of r.refused) by.set(x.check, (by.get(x.check) ?? 0) + 1);
444
+ for (const [check, n] of by) { gnote({ type: 'group', why: 'refused', check, count: n }); noted = true; }
445
+ if (noted) saveData();
446
+ if (noted || r.filed || r.notices.length || r.joined.length || r.removed.length) changed();
447
+ } catch (err) { live.error = `groups: ${err.message}`; }
448
+ }
449
+ // Unread in a group: the items after the newest shown (data.gread), none of mine.
450
+ const unreadIn = (gid, items) => {
451
+ const m = data.gread[gid];
452
+ if (!m) return items.filter((i) => !i.mine).length;
453
+ const at = items.findIndex((i) => i.mid === m.mid);
454
+ return (at >= 0 ? items.slice(at + 1) : items.filter((i) => (i.received ?? 0) > m.at)).filter((i) => !i.mine).length;
455
+ };
456
+ const brakeQuiet = (g) => g.brake !== 'off' && g.run >= g.brake;
457
+ function groupsList() {
458
+ if (!G || !groupsFile) return [];
459
+ const gs = G.list({ carrier, file: groupsFile });
460
+ return gs.map((g) => {
461
+ const items = ['member', 'frozen'].includes(g.status) ? G.history({ carrier, file: groupsFile, group: g.gid }) : [];
462
+ const last = items.at(-1);
463
+ return { ...g, unread: unreadIn(g.gid, items), quiet: brakeQuiet(g),
464
+ last: last ? { name: last.mine ? null : last.name, text: textOf(last.content).slice(0, 200), at: last.received ?? last.iat, mine: last.mine === true } : null };
465
+ });
466
+ }
467
+ function groupTier() {
468
+ const told = carrier.groupTier ?? null, { lim, tier } = G.limitsFor(carrier);
469
+ return { tier, groups: lim.groups, members: lim.members, told: told !== null };
470
+ }
471
+ // /api/state's chats: the badge (unread in all), invitations waiting, notices. Never fails the state.
472
+ function chatsState() {
473
+ if (!G || !groupsFile || carrier.platform.files.read(groupsFile) === null) return { unread: 0, invited: 0, notices: data.gnotices.length, rev: `0.${data.gnotices.length}` };
474
+ try {
475
+ const gs = groupsList();
476
+ // rev: changes with any group's roster, status, run or newest item (the page fetches a chat again on it).
477
+ const rev = gs.map((g) => `${g.gid.slice(0, 8)}.${g.ver}.${g.status}.${g.run}.${g.last?.at ?? 0}.${g.unread}`).join(' ');
478
+ return { unread: gs.reduce((a, g) => a + g.unread, 0), invited: gs.filter((g) => g.status === 'pending').length, notices: data.gnotices.length, rev: `${hashOf(rev)}.${data.gnotices.length}` };
479
+ } catch { return { unread: 0, invited: 0, notices: data.gnotices.length, rev: '' }; }
480
+ }
481
+ // group.mjs refusals by check: unknown → 404, usage → 400, any other (group_*, not_contact, name) → 409.
482
+ async function groupCall(fn) {
483
+ gfile();
484
+ try { return await fn(); } catch (e) {
485
+ if (e.check !== undefined && e.status === undefined) e.status = ['group_unknown', 'not_contact'].includes(e.check) ? 404 : ['group_message', 'group_text', 'group_members'].includes(e.check) ? 400 : 409;
486
+ throw e;
487
+ }
488
+ }
489
+ const gid = (b) => (typeof b['group'] === 'string' && b['group'] !== '' ? b['group'] : refuse(400, 'body', 'group: its gid'));
490
+ const dids = (v, what, need = true) => {
491
+ if (v === undefined && !need) return [];
492
+ if (!Array.isArray(v) || (need && v.length === 0) || v.length > 64 || v.some((x) => typeof x !== 'string' || x === '')) refuse(400, 'body', `${what}: a list of contact DIDs`);
493
+ return v;
494
+ };
495
+ // A write's answer: the group as the list shows it, and how its copies went.
496
+ const gout = (r) => ({ ...(r.group && { group: r.group }), copies: r.copies ?? [], ...(r.offline !== undefined && { offline: r.offline }) });
497
+ const groupRoutes = {
498
+ 'GET /api/groups': () => groupCall(() => ({ tier: groupTier(), groups: groupsList(), notices: data.gnotices.slice() })),
499
+ 'GET /api/groups/history': (_, q) => groupCall(() => {
500
+ const g = q.get('group') ?? refuse(400, 'body', 'group: its gid'), one = groupsList().find((x) => x.gid === g) ?? refuse(404, 'group_unknown', `no group ${g} here`);
501
+ const items = G.history({ carrier, file: groupsFile, group: g }), last = items.at(-1);
502
+ // Read: the page has shown them.
503
+ if (last && data.gread[g]?.mid !== last.mid) { data.gread[g] = { mid: last.mid, at: last.received ?? last.iat }; saveData(); }
504
+ return { group: { ...one, unread: 0 }, messages: items.slice(-200).map((i) => ({ mid: i.mid, re: i.re ?? null, from: i.from, name: i.name, role: i.role, tier: i.tier ?? null, mine: i.mine === true,
505
+ operator: i.operator === true, note: i.note ?? null, text: textOf(i.content), mentions: i.mentions ?? [], mentioned: i.mentioned === true, via: i.via ?? null, at: i.received ?? i.iat })) };
506
+ }),
507
+ 'POST /api/groups/create': (b) => serial(() => groupCall(async () => {
508
+ const brake = b['brake'];
509
+ return gout(await G.create({ carrier, file: groupsFile, name: b['name'], members: dids(b['members'], 'members'), humans: dids(b['humans'], 'humans', false), ...(brake !== undefined && brake !== null && { brake }),
510
+ ...(typeof b['role'] === 'string' && { role: b['role'] }) }));
511
+ })),
512
+ 'POST /api/groups/add': (b) => serial(() => groupCall(async () => gout(await G.add({ carrier, file: groupsFile, group: gid(b), members: dids(b['members'], 'members'), humans: dids(b['humans'], 'humans', false) })))),
513
+ 'POST /api/groups/remove': (b) => serial(() => groupCall(async () => gout(await G.remove({ carrier, file: groupsFile, group: gid(b), members: dids(b['members'], 'members') })))),
514
+ 'POST /api/groups/rename': (b) => serial(() => groupCall(async () => gout(await G.rename({ carrier, file: groupsFile, group: gid(b), name: b['name'] })))),
515
+ 'POST /api/groups/brake': (b) => serial(() => groupCall(async () => gout(await G.setBrake({ carrier, file: groupsFile, group: gid(b), brake: b['brake'] })))),
516
+ 'POST /api/groups/role': (b) => serial(() => groupCall(async () => gout(await G.setRole({ carrier, file: groupsFile, group: gid(b), member: b['member'], role: b['role'] })))),
517
+ 'POST /api/groups/share': (b) => serial(() => groupCall(async () => gout(await G.share({ carrier, file: groupsFile, group: gid(b), member: b['member'] })))),
518
+ 'POST /api/groups/leave': (b) => serial(() => groupCall(async () => { const r = await G.leave({ carrier, file: groupsFile, group: gid(b) }); changed(); return { ...gout(r), told: r.told }; })),
519
+ 'POST /api/groups/join': (b) => serial(() => groupCall(async () => { const r = G.join({ carrier, file: groupsFile, group: gid(b) }); changed(); return gout(r); })),
520
+ 'POST /api/groups/send': (b) => serial(() => groupCall(async () => {
521
+ const text = b['text'], re = b['re'], mentions = b['mentions'];
522
+ if (typeof text !== 'string' || text.trim() === '') refuse(400, 'body', 'text: the message');
523
+ if (mentions !== undefined && (!Array.isArray(mentions) || mentions.some((x) => typeof x !== 'string'))) refuse(400, 'body', 'mentions: member DIDs or names');
524
+ const r = await G.send({ carrier, file: groupsFile, group: gid(b), text, ...(typeof re === 'string' && re !== '' && { re }), ...(mentions && { mentions }) });
525
+ changed();
526
+ return { gid: r.gid, mid: r.mid, copies: r.copies, via_creator: r.via_creator, unreached: r.unreached, ...(r.offline !== undefined && { offline: r.offline }) };
527
+ })),
528
+ 'POST /api/groups/dismiss': (b) => serial(async () => {
529
+ const id = b['id'], before = data.gnotices.length;
530
+ data.gnotices = id === 'all' ? [] : data.gnotices.filter((n) => n.id !== id);
531
+ if (data.gnotices.length === before && id !== 'all') refuse(404, 'notice', 'no such notice');
532
+ saveData(); changed();
533
+ return { dismissed: before - data.gnotices.length };
534
+ }),
535
+ };
536
+
360
537
  // ---- writes
361
538
  const contactOf = (d) => {
362
539
  if (typeof d !== 'string') refuse(400, 'body', 'contact: a DID');
@@ -382,13 +559,13 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
382
559
  'GET /api/state': async (_, q) => { if (draining) await draining; return state(Number(q.get('since') ?? 0) || 0); },
383
560
  'GET /api/me': () => {
384
561
  const m = hooks.me(), i = hooks.meInfo();
385
- return { did: m.did, original: m.original, chain: m.chain, identity_file: i.identity_file, recovery: i.recovery, key: i.key, relay: carrier.relay, retention_days: carrier.retentionDays, erase: i.erase,
562
+ return { did: m.did, original: m.original, words: didWords(m.original), chain: m.chain, identity_file: i.identity_file, recovery: i.recovery, key: i.key, relay: carrier.relay, retention_days: carrier.retentionDays, erase: i.erase,
386
563
  ...(i.restored && { restored: i.restored }) };
387
564
  },
388
565
  'POST /api/invite': (b) => serial(async () => {
389
566
  const name = b['name'] === undefined || b['name'] === '' ? `contact-${hexOf(2)}` : cleanName(b['name'], 'name');
390
567
  const at = newCodes();
391
- const r = await carrier.invite({ name, short: b['long'] !== true, ...(at !== carrier.relay && { relay: at }) });
568
+ const r = await carrier.invite({ name, short: b['long'] !== true, ...(at !== carrier.relay && { relay: at }), started: startedBy(b) });
392
569
  const inv = { id: hexOf(6), name, code: r.code, exp: r.exp, ...(r.short !== undefined && { short: r.short, short_exp: r.short_exp }) };
393
570
  invites.set(inv.id, inv);
394
571
  changed();
@@ -407,7 +584,7 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
407
584
  // friend or quiet, the human's choice; own is detected, never asked (store.mjs tiers).
408
585
  const tier = b['tier'];
409
586
  if (tier !== undefined && tier !== 'friend' && tier !== 'quiet') refuse(400, 'body', 'tier: friend or quiet');
410
- const r = await carrier.accept(code, { ...(name !== undefined && { name }), wait: 10, ...(tier !== undefined && { tier }) });
587
+ const r = await carrier.accept(code, { ...(name !== undefined && { name }), wait: 10, ...(tier !== undefined && { tier }), started: startedBy(b) });
411
588
  const now = r.contact ? carrier.contacts().contacts.find((x) => x.did === r.contact.did) : undefined;
412
589
  return r.contact ? { status: r.status, contact: { ...r.contact, pair: now?.pair ?? null, tier: now?.tier ?? null } }
413
590
  : { ...r, exp: carrier.contacts().answers.find((x) => x.did === r.did)?.exp ?? null };
@@ -427,6 +604,11 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
427
604
  if (tier !== 'own' && tier !== 'friend' && tier !== 'quiet') refuse(400, 'body', 'tier: own, friend or quiet');
428
605
  return carrier.setTier(c.did, tier);
429
606
  }),
607
+ 'POST /api/presence': (b) => serial(async () => {
608
+ const c = contactOf(b['contact']), allow = b['allow'];
609
+ if (typeof allow !== 'boolean') refuse(400, 'body', 'allow: true or false');
610
+ try { return carrier.setPresence(c.did, allow); } catch (e) { if (e.check === 'presence_own') e.status = 409; throw e; }
611
+ }),
430
612
  'POST /api/tag': (b) => serial(async () => {
431
613
  const c = contactOf(b['contact']), tags = b['tags'];
432
614
  if (!Array.isArray(tags) || tags.length > 8) refuse(400, 'body', 'tags: a list of at most 8');
@@ -484,8 +666,10 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
484
666
  'POST /api/agents/enrol-code': (b) => serial(async () => {
485
667
  seatHere();
486
668
  if (!enrolFile) refuse(404, 'route', 'no enrolment here');
487
- const name = b['name'], tier = b['tier'], relay = b['relay'];
669
+ const name = b['name'], tier = b['tier'], relay = b['relay'], words = b['confirm_words'], label = b['operator_name'];
488
670
  if (typeof name !== 'string' || !AGENT_NAME.test(name)) refuse(400, 'body', 'name: lowercase letters, digits, _ and -, at most 64');
671
+ if (words !== undefined && typeof words !== 'boolean') refuse(400, 'body', 'confirm_words: true or false (default false: checked by its DID)');
672
+ if (label !== undefined && label !== null && label !== '' && E.operatorLabel(label) === null) refuse(400, 'body', 'operator_name: how the agent files you, 1 to 64 characters');
489
673
  if (tier !== undefined && tier !== 'own' && tier !== 'friend' && tier !== 'quiet') refuse(400, 'body', 'tier: own (the default), friend or quiet');
490
674
  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
675
  const at = relayFixed ?? (typeof relay === 'string' && relay !== '' ? relay.trim().toLowerCase() : newCodes());
@@ -495,15 +679,40 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
495
679
  const used = Object.keys(k.workers).map(Number), i = used.length ? Math.max(...used) + 1 : 0;
496
680
  const root = await K.root(k);
497
681
  let r;
498
- try { r = await E.issue({ carrier, file: enrolFile, i, n: 0, name, keeper: root, relay: at }); } finally { root.K.fill(0); }
682
+ try {
683
+ r = await E.issue({ carrier, file: enrolFile, i, n: 0, name, keeper: root, relay: at, started: startedBy(b), confirmWords: words === true,
684
+ ...(typeof label === 'string' && label !== '' && { operatorName: label }) });
685
+ } finally { root.K.fill(0); }
499
686
  const until = pend((x) => x.issued[r.id]?.attestation?.body?.exp ?? null);
500
687
  await K.update((x) => { x.workers[i] = { name, n: 0, did: r.did, original: r.original, placed: 'remote', at: nowS(), ...(until && { until }) }; });
501
688
  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 };
689
+ 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, confirmWords: words === true };
503
690
  enrolling.set(e.id, e);
504
691
  changed();
505
692
  return { worker: i, name, did: r.did, original: r.original, tier: e.tier, ...pub(e) };
506
693
  }),
694
+ // The optional words switch: the human's answer for an enrolment that holds its key until it.
695
+ 'POST /api/agents/enrol-words': (b) => serial(async () => {
696
+ const e = enrolling.get(String(b['id'])) ?? refuse(404, 'enrol', 'no such enrolment on this page');
697
+ if (typeof b['match'] !== 'boolean') refuse(400, 'body', 'match: true (the agent\'s machine shows the same four words) or false');
698
+ if (!LIVE.has(e.state)) refuse(409, 'enrol_state', `this enrolment is ${e.state}`);
699
+ e.wordsOk = b['match'];
700
+ await agentRound();
701
+ if (!b['match']) {
702
+ pend((x) => { delete x.issued[e.id]; });
703
+ await K?.update((k) => { if (k.workers[e.worker]?.name === e.name && k.workers[e.worker].placed === 'remote') delete k.workers[e.worker]; });
704
+ if (e.temp) { try { await carrier.forget(e.temp); } catch {} }
705
+ Object.assign(e, { state: 'failed', check: 'device_words', detail: 'The four words differed: its key was not sent, and the code is dropped. Make a new one.' });
706
+ }
707
+ changed();
708
+ return pub(e);
709
+ }),
710
+ // "Try now" (design/profiles.md §6): the automatic tries paused for the day; the human's goes now.
711
+ 'POST /api/pow/try': (b) => serial(async () => {
712
+ const r = await carrier.tryNow({ confirmed: b['pow_confirmed'] === true });
713
+ live.powCapped = null; live.powConfirm = null; changed();
714
+ return r;
715
+ }),
507
716
  'POST /api/agents/revoke': (b) => serial(async () => {
508
717
  seatHere();
509
718
  const k = await keeperOr(), i = b['worker'], w = workerOf(k, i);
@@ -552,8 +761,8 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
552
761
  };
553
762
  const days = b['days'];
554
763
  if (days !== undefined && days !== null && !Number.isSafeInteger(days)) refuse(400, 'body', 'days: whole days, 1 to 365');
555
- const tierA = str('tier_a'), tierB = str('tier_b'), note_ = str('note'), relay = str('relay');
556
- const rec = await L.link({ carrier, file: linksFile, a: str('a', true), b: str('b', true), purpose: str('purpose', true), ...(tierA && { tierA }), ...(tierB && { tierB }),
764
+ const tierA = str('tier_a'), tierB = str('tier_b'), note_ = str('note'), relay = str('relay'), nameA = str('name_a'), nameB = str('name_b');
765
+ const rec = await L.link({ carrier, file: linksFile, a: str('a', true), b: str('b', true), purpose: str('purpose', true), ...(tierA && { tierA }), ...(tierB && { tierB }), ...(nameA && { nameA }), ...(nameB && { nameB }),
557
766
  ...(typeof days === 'number' && { days }), ...(note_ && { note: note_ }), ...(relay && { relay }) });
558
767
  const { code: _c, steps: _s, exp: _e, ttl: _t, ...out } = rec;
559
768
  return out;
@@ -593,6 +802,9 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
593
802
  return { name, confirmed: match, ...(!match && { forgotten: true }) };
594
803
  },
595
804
  };
805
+ // Transfers: the routes exist only where the host moves files (hooks.transfers).
806
+ if (transfers) Object.assign(routes, transferRoutes({ X: transfers.lib, engine: transfers.engine, carrier, identity: hooks.transfers.identity, serial, contactOf, changed }));
807
+ if (G) Object.assign(routes, groupRoutes);
596
808
  // One handler for every listener: the route's answer as [status, JSON value].
597
809
  async function dispatch(method, url, b) {
598
810
  const route = routes[`${method} ${url.pathname}`];
@@ -607,3 +819,50 @@ export function makePage({ makeCarrier, link: L, linksFile, enrolFile = null, co
607
819
  onChange: (f) => { watchers.add(f); return () => watchers.delete(f); },
608
820
  };
609
821
  }
822
+
823
+ // ---- transfers (UI-API.md "Transfers"): the verbs of contact/transfer-node.mjs over the page's session.
824
+ // Refusals by check: unknown → 404; usage → 400; direct_ask, disk_full, transfer_state and the rest → 409.
825
+ function transferRoutes({ X, engine, carrier, identity, serial, contactOf, changed }) {
826
+ const call = async (fn) => {
827
+ try { const r = await fn(); changed(); return r; } catch (e) {
828
+ if (e.check !== undefined && e.status === undefined) e.status = ['transfer_unknown', 'not_contact'].includes(e.check) ? 404 : ['usage', 'body'].includes(e.check) ? 400 : 409;
829
+ throw e;
830
+ }
831
+ };
832
+ const idOf = (b) => (typeof b['id'] === 'string' && /^[0-9a-f]{32}$/.test(b['id']) ? b['id'] : refuse(400, 'body', 'id: a transfer id (32 hex digits)'));
833
+ const directOf = (b) => (b['direct'] === undefined ? undefined : typeof b['direct'] === 'boolean' ? b['direct'] : refuse(400, 'body', 'direct: true or false'));
834
+ const viaOf = (b) => (b['via'] === undefined || b['via'] === 'auto' || b['via'] === 'tor' ? b['via'] : refuse(400, 'body', 'via: auto or tor'));
835
+ const strip = ({ file: _f, ...r }) => r;
836
+ const settings = async () => ({ ...X.settings({ identity }), tor_daemon: await X.torCaps(X.torConfig()), direct_available: (await X.loadRtc()) !== null });
837
+ return {
838
+ 'GET /api/transfers': () => X.list({ carrier, identity, engine }),
839
+ 'POST /api/transfers/send': (b) => serial(() => call(async () => {
840
+ if (typeof b['path'] !== 'string' || b['path'] === '') refuse(400, 'body', 'path: a file on this computer');
841
+ const c = contactOf(b['to']), d = directOf(b), via = viaOf(b);
842
+ const r = await X.send({ carrier, identity, to: c.did, path: b['path'], ...(via && { via }), ...(d !== undefined && { direct: d }) });
843
+ void engine.kick();
844
+ return strip(r);
845
+ })),
846
+ 'POST /api/transfers/accept': (b) => serial(() => call(async () => {
847
+ const d = directOf(b), via = viaOf(b), r = X.accept({ carrier, identity, id: idOf(b), ...(via && { via }), ...(d !== undefined && { direct: d }) });
848
+ void engine.kick();
849
+ return r;
850
+ })),
851
+ 'POST /api/transfers/resume': (b) => serial(() => call(async () => { const r = X.accept({ carrier, identity, id: idOf(b), ...(directOf(b) !== undefined && { direct: directOf(b) }) }); void engine.kick(); return r; })),
852
+ 'POST /api/transfers/decline': (b) => serial(() => call(async () => X.decline({ carrier, identity, id: idOf(b) }))),
853
+ 'POST /api/transfers/cancel': (b) => serial(() => call(async () => strip(await X.cancel({ carrier, identity, id: idOf(b), engine })))),
854
+ 'POST /api/transfers/forget': (b) => serial(() => call(async () => strip(X.forget({ carrier, identity, id: idOf(b), engine })))),
855
+ 'POST /api/transfers/direct': (b) => serial(() => call(async () => {
856
+ if (typeof b['on'] !== 'boolean') refuse(400, 'body', 'on: true or false');
857
+ return X.setDirect({ carrier, identity, contact: contactOf(b['contact']).did, on: b['on'] });
858
+ })),
859
+ 'GET /api/transfers/settings': () => settings(),
860
+ 'POST /api/transfers/settings': (b) => serial(() => call(async () => {
861
+ const patch = {};
862
+ if (b['tor'] !== undefined) { if (typeof b['tor'] !== 'boolean') refuse(400, 'body', 'tor: true or false'); patch.tor = b['tor']; }
863
+ if (b['prefer'] !== undefined) { if (b['prefer'] !== 'fast' && b['prefer'] !== 'private') refuse(400, 'body', 'prefer: fast or private'); patch.prefer = b['prefer']; }
864
+ X.settings({ identity, patch });
865
+ return settings();
866
+ })),
867
+ };
868
+ }
package/platform-node.mjs CHANGED
@@ -222,12 +222,23 @@ export async function pow(prefix, bits, { deadline = Infinity, signal } = {}) {
222
222
  * → { bytes, name }.
223
223
  */
224
224
  export function openPath(file, own) {
225
- let real, bytes;
225
+ const { real } = sendable(file, own, MAX_FILE);
226
+ let bytes;
227
+ try { bytes = readFileSync(real); } catch (e) { fail('file', `cannot read ${file}: ${e.code ?? e.message}`, { cause: e }); }
228
+ return { bytes, name: basename(real) };
229
+ }
230
+
231
+ /**
232
+ * The checks of openPath without the read (a transfer's file is read in place, chunk by chunk):
233
+ * a regular file of at most max bytes, none of this identity's own. → { real, name, size, mtimeMs }.
234
+ */
235
+ export function sendable(file, own, max) {
236
+ let real, s;
226
237
  try {
227
238
  real = realpathSync(file);
228
- const s = statSync(real);
239
+ s = statSync(real);
229
240
  if (!s.isFile()) fail('file', `${file} is not a regular file`);
230
- if (s.size > MAX_FILE) fail('file_too_large', `${file} is ${s.size} bytes, at most ${MAX_FILE} (8 MiB) a file`);
241
+ if (s.size > max) fail('file_too_large', `${file} is ${s.size} bytes, at most ${max}${max === MAX_FILE ? ' (8 MiB)' : ''} a file`);
231
242
  } catch (e) {
232
243
  if (e instanceof MsgError) throw e;
233
244
  fail('file', `cannot read ${file}: ${e.code === 'ENOENT' ? 'no such file' : e.code ?? e.message}`, { cause: e });
@@ -240,8 +251,7 @@ export function openPath(file, own) {
240
251
  if (real.startsWith(received + sep) || real === own.log || (dirname(real) === ownDir && (leaf.startsWith(`${basename(base)}.`) || leaf.includes('.local.')))) {
241
252
  fail('file', `${file} is one of this agent's identity files (key, contacts, state, files received, inbox log): not sent`);
242
253
  }
243
- try { bytes = readFileSync(real); } catch (e) { fail('file', `cannot read ${file}: ${e.code ?? e.message}`, { cause: e }); }
244
- return { bytes, name: basename(real) };
254
+ return { real, name: basename(real), size: s.size, mtimeMs: s.mtimeMs };
245
255
  }
246
256
 
247
257
  // ---------------------------------------------------------------- the platform
package/short.mjs CHANGED
@@ -145,6 +145,18 @@ export const formatGift = (norm) => `${GIFT_PREFIX}-${formatShort(norm)}`;
145
145
  /** The key the relay holds a gift under: hex SHA-256("sigelo-gift/0" ‖ the normalised code). */
146
146
  export const giftHash = (text) => bytesToHex(sha256(concatBytes(utf8ToBytes(GIFT_V), utf8ToBytes(normaliseGift(text)))));
147
147
 
148
+ /**
149
+ * Four words naming a DID on a screen (an app's profile list): HKDF-SHA-256 of the DID's text under
150
+ * "sigelo-did-words/0", 44 bits as four BIP-39 words. A label to tell profiles apart, not a check:
151
+ * a pairing's own four words (fingerprint) are what two sides compare.
152
+ */
153
+ export function didWords(did) {
154
+ if (typeof did !== 'string' || !/^did:sigelo:z[1-9A-HJ-NP-Za-km-z]{1,100}$/.test(did)) fail('did', 'not a did:sigelo DID');
155
+ const b = hkdf(sha256, utf8ToBytes(did), utf8ToBytes('sigelo-did-words/0'), new Uint8Array(0), 6);
156
+ let x = 0n;
157
+ for (const v of b) x = (x << 8n) | BigInt(v);
158
+ return [0, 1, 2, 3].map((i) => WORDS[Number((x >> BigInt(48 - 11 * (i + 1))) & 2047n)]).join(' ');
159
+ }
148
160
  /** The four words of a pairing, from its pair id (32 lowercase hex digits, kdf.pairId). */
149
161
  export function fingerprint(pair) {
150
162
  const b = hkdf(sha256, unhex(pair, 16, 'pair'), utf8ToBytes(FINGERPRINT_LABEL), new Uint8Array(0), 6);
package/store.mjs CHANGED
@@ -5,7 +5,7 @@
5
5
  // { v, self, invites: { nonce: { secret, exp, name, peer, relay } },
6
6
  // accepts: { answer id: { secret, code_did, exp, name, relay, kem_sk, as, named?, tier? } },
7
7
  // contacts: { original DID: { name, did, current_did, current_key, revoked, chain, rotations, relay, pair_key, re_pair?,
8
- // tier, tier_by, operator_exp?, link? } },
8
+ // tier, tier_by, operator_exp?, link?, presence? } },
9
9
  // preset?: { original DID: tier } }
10
10
  // invites: codes this owner handed out, keyed by inviteNonce(code bytes); peer: the original DID of
11
11
  // the contact a re-key code is for, null on a new contact's code. accepts: codes this owner
@@ -29,6 +29,9 @@
29
29
  // set own (link_tier). ended: {id, by, at} on a contact a link's end revoked (revoke(did, ended)), and
30
30
  // relink: {id, until}, the one-use permit a NEW link leaves on it (design/links.md §7.1a): the pairing
31
31
  // through that link's code is admitted, the record written afresh. Forgotten by hand: no ended, never.
32
+ // presence: true when the owner lets this contact see whether this agent is online (setPresence; off
33
+ // by default, design/transfer.md §8 T0). An own agent (ours, or tier own) always sees it: presenceOf.
34
+ // Kept by a re-pair, a merge and a rename, as the tier is.
32
35
  // The file holds one-time secrets, Bob's one-time key and
33
36
  // pairing keys, so it is written 0600. Two simultaneous writers still need the integrator's lock.
34
37
  import { utf8ToBytes } from '@noble/hashes/utils.js';
@@ -43,7 +46,7 @@ export const OPERATOR_CTX = 'sigelo-relay/operator';
43
46
  // The longest name rename() gives a contact, in characters.
44
47
  export const NAME_MAX = 64;
45
48
  // What a record keeps of its tier through admit (a re-pair, a merged notice).
46
- const TIER_KEYS = ['tier', 'tier_by', 'operator_exp', 'link'];
49
+ const TIER_KEYS = ['tier', 'tier_by', 'operator_exp', 'link', 'presence'];
47
50
  // A recovery key used and replaced still governs every node up to its retirement (SPEC §7.2), and
48
51
  // no offline verifier tells its thief from its owner (THREAT-MODEL §2.5a). A known contact's record
49
52
  // remembers: its chain holds the recovery rotation that retired the key. → commitment → JCS of that
@@ -125,6 +128,22 @@ export class Contacts {
125
128
  return { did: c.did, name: c.name, tier: this.tierOf(c, now), ours: this.oursOf(c, now) };
126
129
  }
127
130
 
131
+ /** What contact c sees of this agent's presence: "own" (an own agent: always), "allow" (the owner's choice), or "deny" (the default). */
132
+ presenceOf(c, now) { return this.oursOf(c, now) || this.tierOf(c, now) === 'own' ? 'own' : c.presence === true ? 'allow' : 'deny'; }
133
+
134
+ /**
135
+ * The owner's choice for a contact (a name or any DID of its chain): may it see whether this agent
136
+ * is online. An own agent always may (presence_own). → { did, name, presence: presenceOf }.
137
+ */
138
+ setPresence(who, allow, now) {
139
+ if (typeof allow !== 'boolean') fail('presence', 'allow: true or false');
140
+ const c = this.#find(who);
141
+ if (!allow && this.presenceOf(c, now) === 'own') fail('presence_own', `${c.name} is your own agent (${this.oursOf(c, now) ? 'yours by key' : 'tier own'}): own agents always see each other's presence`);
142
+ if (allow) c.presence = true; else delete c.presence;
143
+ this.save();
144
+ return { did: c.did, name: c.name, presence: this.presenceOf(c, now) };
145
+ }
146
+
128
147
  /**
129
148
  * The link record of a contact (who: a name or any DID of its chain), link.mjs's: an object
130
149
  * {id, purpose, linked_by, expires, tier, prior?}, or null to drop it (prior: its tier and tier_by