sigelo-contact 0.1.21 → 0.1.23

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 (69) hide show
  1. package/GROUPS-REFERENCE.md +165 -0
  2. package/GROUPS.md +53 -0
  3. package/LICENSE +235 -21
  4. package/README.md +4 -5
  5. package/call.mjs +89 -28
  6. package/carrier.mjs +230 -51
  7. package/control.mjs +2 -2
  8. package/create.mjs +2 -2
  9. package/device.mjs +2 -2
  10. package/enrol.mjs +2 -2
  11. package/envelope.mjs +6 -6
  12. package/file.mjs +2 -2
  13. package/fixtures/carrier-v0.json +1 -1
  14. package/fixtures/envelope-v0.json +1 -1
  15. package/fixtures/group-v2.json +2999 -0
  16. package/gen-carrier.mjs +2 -2
  17. package/gen-device.mjs +1 -1
  18. package/gen-envelope.mjs +2 -2
  19. package/gen-group2.mjs +291 -0
  20. package/gen-invite.mjs +2 -2
  21. package/gen-short.mjs +1 -1
  22. package/group.mjs +116 -17
  23. package/group2.mjs +1534 -0
  24. package/home-wire.mjs +812 -0
  25. package/invite.mjs +3 -3
  26. package/kdf.mjs +2 -2
  27. package/kin.mjs +62 -0
  28. package/link.mjs +6 -6
  29. package/package.json +25 -8
  30. package/page.mjs +542 -63
  31. package/photo.mjs +2 -2
  32. package/platform-node.mjs +6 -6
  33. package/prekeys.mjs +3 -3
  34. package/public.mjs +2 -2
  35. package/qr-decode.mjs +1 -1
  36. package/qr.mjs +2 -2
  37. package/relays.mjs +2 -2
  38. package/restore.mjs +2 -2
  39. package/rtc-web.mjs +3 -3
  40. package/short.mjs +2 -2
  41. package/store.mjs +22 -9
  42. package/test-carrier.mjs +32 -11
  43. package/test-device.mjs +3 -3
  44. package/test-enrol.mjs +9 -4
  45. package/test-envelope.mjs +2 -2
  46. package/test-file.mjs +2 -2
  47. package/test-group-move.mjs +225 -0
  48. package/test-group.mjs +1 -1
  49. package/test-group2.mjs +202 -0
  50. package/test-home.mjs +225 -0
  51. package/test-invite.mjs +1 -1
  52. package/test-link.mjs +3 -3
  53. package/test-platform.mjs +2 -2
  54. package/test-presence.mjs +2 -2
  55. package/test-push.mjs +5 -5
  56. package/test-relay-lane.mjs +3 -3
  57. package/test-short.mjs +1 -1
  58. package/test-tier.mjs +8 -2
  59. package/test-transfer-web.mjs +15 -7
  60. package/test-transfer.mjs +24 -6
  61. package/test-voice.mjs +2 -2
  62. package/test-ws.mjs +1 -1
  63. package/transfer-engine.mjs +46 -16
  64. package/transfer-node.mjs +9 -7
  65. package/transfer-web.mjs +4 -4
  66. package/transfer.mjs +8 -8
  67. package/voice-web.mjs +2 -2
  68. package/voice.mjs +7 -3
  69. package/words-lock.mjs +2 -2
package/page.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // SPDX-License-Identifier: MIT
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
2
  // The page's routes over one carrier (apps/agent/UI-API.md), shared by `sigelo-agent ui`
3
3
  // (apps/agent/sigelo-agent-ui.ts: HTTP on 127.0.0.1) and the self-contained app (apps/web/router.mjs:
4
4
  // in the page). One route table, one JSON: what is the same everywhere is here; what one host has
@@ -22,15 +22,20 @@
22
22
  // ([] where there is none), seat() → the seat or null, deviceRound() → { gave? } after each drain
23
23
  // (or none), note(line), defer(fn) (setImmediate on Node), every(fn, ms) → a timer, hidden({ did, name })
24
24
  // → true for what the page never shows nor names (the computer's relay controls: their contacts, their
25
- // pairing, their codes waiting; design/apps.md §6.3), controls: { pending() → [{name, scope, words}],
25
+ // pairing, their codes waiting; apps/agent/UI-API.md "Remote"), controls: { pending() → [{name, scope, words}],
26
26
  // confirm(name, match) → whether one was pending } (relay controls whose four words wait: the
27
27
  // Controls card; routes in no remote scope, so never asked over the relay or the LAN).
28
28
  //
29
- // Groups (apps/agent/GROUPS.md, design/groups.md §5): groups: group.mjs (the module) and groupsFile
29
+ // Groups (apps/agent/GROUPS.md): groups: group.mjs (the module) and groupsFile
30
30
  // (groupsPath of the identity). Each drain hands the carrier's group messages to group.mjs handle(), here
31
31
  // in code: without it the page never takes a roster, carries a copy on or files a message. The page's
32
32
  // own marks in data: gread (gid → the newest item shown: {mid, at}), gnotices (a stranger added, the
33
33
  // creator gone, a refusal: until dismissed). /api/groups/* (UI-API.md "Groups").
34
+ // Home groups (design/groups-build.md step 5): groups2: group2.mjs and groups2File (groups2Path of the identity). The
35
+ // carrier stays at their home relays (setHomes: push registered there too) and says `home` when it connects there or a
36
+ // row comes; the page then syncs them (group2.mjs sync, one at a time; a join waiting: every 5 s). Step 6: GET /api/groups
37
+ // lists them beside the groups (v: 2), the chat reads the groups file's history, and the shared routes (create without
38
+ // members, join by a code, any route naming a home group's gid) go to group2.mjs (UI-API.md "Home groups").
34
39
  //
35
40
  // Agents (ENROL.md, the app's main list): hooks.keeper, where the host has the operator's keeper root:
36
41
  // { read() → the keeper file as JSON (workers, …) | null, root(k) → { K, recovery } (K zeroed after use),
@@ -47,7 +52,7 @@
47
52
  // { name() → its name, call(method, path, body?) → { status, body } }. /api/keeper* go there; a limit is a
48
53
  // policy-change signed here with this identity (the computer relays it, POST /api/keeper/policy). None: elsewhere.
49
54
  //
50
- // Transfers (apps/agent/TRANSFER.md, design/transfer.md §10): hooks.transfers, where the host moves big
55
+ // Transfers (apps/agent/TRANSFER.md): hooks.transfers, where the host moves big
51
56
  // files ({ lib, identity, make(carrier, onEvent, { compared }) → its Engine; lib: transfer-node.mjs on a
52
57
  // computer (a file by its path), transfer-web.mjs's in the phone app (a file picked: doc), which also gives
53
58
  // pick(), photo({ keepLocation }), open(saved) and url(doc) }): the page owns the session, so its engine
@@ -58,18 +63,22 @@
58
63
  // voice.mjs) goes the same way, its fields as the message and the recording as the file, where the host records
59
64
  // (hooks.transfers.rec: write(rec, offset, bytes), keep(rec, name) → { doc } | { path }, read(saved) → bytes).
60
65
  //
61
- // Calls (UI-API.md "Calls", design/calls.md, call.mjs): one Line over this carrier, always; the media is the page's (ui.js's
66
+ // Calls (UI-API.md "Calls", call.mjs): one Line over this carrier, always; the media is the page's (ui.js's
62
67
  // Phone), which reaches it by /api/calls*. hooks.calls, where the host has a shell: { alert({on, id, did, name}) the ring
63
- // (the phone app: ringtone, vibration, a heads-up; the seam the push build wires to a full-screen ring), audio({on, id,
64
- // name}) the call's audio mode (CallService), speaker(on), mic(), micSettings() }. "Can call me" (decision 2026-11-17):
65
- // data.calls[did] true | false, else the default: off for a quiet contact, else data.settings.calls (default on).
68
+ // (the phone app: ringtone, vibration, a heads-up; the seam the push build wires to a full-screen ring; it may answer
69
+ // { busy }: another app's call, the Line answers busy), audio({on, id, name}) the call's audio mode (CallService),
70
+ // speaker(on), route(to?) the audio output (→ { current, available, held }), missed({did, name}) a missed call's
71
+ // notification at once (tag chat:<did>, as the page's poll raises it, which then replaces it: a page started by a push
72
+ // wake tells nothing at its first look), mic(), micSettings() }. "Can call me" (decision 2026-11-17):
73
+ // data.calls[did] true, else off (2026-11-27, the Owner: calls are switched on per contact, by hand; no default for all,
74
+ // and an old data.settings.calls is ignored).
66
75
  // A call's chat line is a history record { kind: in | out, label CALL_LABEL, text "Call · 3:12" | "Missed call" | …,
67
76
  // call: { id, state, secs } }; only a missed one counts as unread (a call taken or made here was seen).
68
- // "Always relay my media" (design/calls.md §6, UI-API.md "Settings"): data.settings.relay_media, per profile (default
77
+ // "Always relay my media" (UI-API.md "Settings"): data.settings.relay_media, per profile (default
69
78
  // off); SIGELO_ICE_POLICY=relay in the host's environment says the same. On: GET /api/calls/turn answers policy
70
79
  // "relay" and the transfer engine is given it (relayMedia): every WebRTC lane only through the relay's TURN.
71
80
  //
72
- // Proof of work (design/profiles.md §6): what the human starts here (the page's start, a code, an
81
+ // Proof of work: what the human starts here (the page's start, a code, an
73
82
  // answer, "Try now") passes the carrier's `started: 'user'`; past the day's three the route answers
74
83
  // 409 pow_confirm, and the same call with `pow_confirmed: true` goes on. The carrier's automatic
75
84
  // retries stay capped: state's me.pow_capped {relay, next} says when the next one is.
@@ -80,15 +89,18 @@
80
89
  // them), or a first one to a contact not known to (an earlier version takes it as a message once, then hears no more;
81
90
  // never to my own agents, which read none);
82
91
  // the first receipt from a contact is answered once (a 0 when receipts are off), so both sides know. data.seen: each
83
- // contact's {sent, told}. Chat defaults (data.settings): new_tier and new_presence, given to a contact at its pairing;
84
- // notify (all chats) and data.notify (a chat: contact DID or gid → false) for the notifications.
92
+ // contact's {sent, told}. Chat defaults (data.settings): new_tier and new_presence, given to a contact at its pairing.
93
+ // Alerts (Settings → Notifications, "Alert me about", 2026-11-27): data.settings.alerts all | people | none, read by the
94
+ // page's notifications and its banner alike; an older data.settings.notify maps (false → none, else all). A chat's
95
+ // Mute: data.notify (a contact DID or gid → false). A person is normal or muted: quiet is an agent's tier (trust); a
96
+ // person on quiet before is muted and filed friend, once (settlePeople, data.settings.people).
85
97
  //
86
- // The Wallet settings (UI-API.md "Wallet", design/ux1/notes.md "Decided"): per profile, in data.settings: wallet (the
98
+ // The Wallet settings (UI-API.md "Wallet"): per profile, in data.settings: wallet (the
87
99
  // switch, default off), prices (a local price, opt-in, default off) and currency (one of CURRENCIES). Read in state's
88
100
  // me.wallet by every form of the page. This page holds no wallet: GET /api/wallet answers where: "none", its other
89
101
  // wallet routes 409 wallet_none ("This phone has no wallet yet"); `sigelo-agent ui` answers them with the computer's.
90
102
  //
91
- // Pictures (UI-API.md "Pictures", design/ux1/notes.md "Decided"): store.readPicture(name) → bytes | null and
103
+ // Pictures (UI-API.md "Pictures"): store.readPicture(name) → bytes | null and
92
104
  // store.writePicture(name, bytes | null), the host's (beside the page's data, 0600, on a computer; the profile's storage
93
105
  // on the phone). data.pics: key → {type, rev, at} for 'me' (this identity's own), 'l:<did or gid>' (a local one for a
94
106
  // contact or a group: wins) and 't:<did>' (the one a contact sent). Mine travels as one more body inside the
@@ -110,11 +122,20 @@
110
122
  //
111
123
  // A hosted agent's settings (UI-API.md "Agent settings"; sigelo-agent-host.ts): HOST_CAPS_LABEL {fields: [{key, value,
112
124
  // options: [{value, label}], off?, next?}], note?}, sent only to a page whose receipts said host: true (carrier.mjs
113
- // host_peer); checked (capsOf: keys model, effort, permissionMode; others dropped), kept as data.host[did], never in the
125
+ // host_peer); checked (capsOf: keys model, effort, permissionMode; others dropped; commands [{name, args?, help}], the chat
126
+ // commands it takes, a malformed row dropped), kept as data.host[did], never in the
114
127
  // history; the contact's `host`. POST /api/host/set sends HOST_SET_LABEL {key, value} (a choice it offered) and marks it
115
- // next until the agent says again. A HOST_SET_LABEL that reaches a page: dropped (a page hosts nothing).
128
+ // next until the agent says again. POST /api/host/ask sends HOST_SET_LABEL {ask: "caps"}: the host sends its caps again (the
129
+ // agent page's Ask again). A rename of an own agent that sent its caps (POST /api/rename, /api/agents/rename) also sends
130
+ // HOST_SET_LABEL {name}: the host says that name in its own lines and keeps it (hostName). A HOST_SET_LABEL that reaches a
131
+ // page: dropped (a page hosts nothing).
132
+ // The Session card (2026-11-28): the caps' `session` {folder, home, root, started, resumed, login: {state, account?, here},
133
+ // waits?} (sessionOf; malformed: dropped, the fields kept). POST /api/host/dirs, /api/host/session, /api/host/login send
134
+ // HOST_DIRS_LABEL {path, into?, id}, HOST_SESSION_LABEL {do, path?}, HOST_LOGIN_LABEL {do, code?}; the agent's answers on the
135
+ // same labels are kept beside its caps (host.dirs, host.session_ev, host.login_ev; checked by dirsOf, sessionEvOf,
136
+ // loginEvOf), never in the history; the code a person pastes is sent, never kept.
116
137
  //
117
- // The public invite (UI-API.md "Public invite"): a public code (sigelo-public/0, carrier.mjs invitePublic), PUB-…
138
+ // The public invite (UI-API.md "Public code"): a public code (sigelo-public/0, carrier.mjs invitePublic), PUB-…
118
139
  // with the four words and a link, for 1, 6 or 12 months, Pro only, kept in the contact store; each use a request to
119
140
  // approve (/api/public/approve, /refuse) unless open; Pause and the cap: /api/public/set; Stop for good (Revoke for
120
141
  // all): /api/invite/cancel {id}. An earlier version's 7-day long code (data.public) runs out as an ordinary invite.
@@ -197,7 +218,41 @@ export function promptOf(label, c) {
197
218
  return null;
198
219
  }
199
220
  export const HOST_CAPS_LABEL = 'sigelo-host-caps/0', HOST_SET_LABEL = 'sigelo-host-set/0';
221
+ export const HOST_DIRS_LABEL = 'sigelo-host-dirs/0', HOST_SESSION_LABEL = 'sigelo-host-session/0', HOST_LOGIN_LABEL = 'sigelo-host-login/0';
200
222
  const HOST_KEYS = new Set(['model', 'effort', 'permissionMode']);
223
+ const LOGIN_STATES = new Set(['signed_in', 'signed_out', 'unknown', 'signing_in']);
224
+ const isStr = (v, max) => typeof v === 'string' && v.length <= max;
225
+ const isObj = (c) => typeof c === 'object' && c !== null && !Array.isArray(c);
226
+ /** The caps' session (the Session card) → it, or null (malformed). */
227
+ export function sessionOf(s) {
228
+ if (!isObj(s) || !isStr(s.folder, 4096) || !isStr(s.home, 4096) || !isStr(s.root, 4096) || !Number.isSafeInteger(s.started) || s.started < 0 || typeof s.resumed !== 'boolean') return null;
229
+ const l = s.login;
230
+ if (!isObj(l) || !LOGIN_STATES.has(l.state) || typeof l.here !== 'boolean' || (l.account !== undefined && !isStr(l.account, 120)) || (s.waits !== undefined && s.waits !== 'new' && s.waits !== 'folder')) return null;
231
+ return { folder: s.folder, home: s.home, root: s.root, started: s.started, resumed: s.resumed, login: { state: l.state, ...(l.account !== undefined && { account: l.account }), here: l.here }, ...(s.waits !== undefined && { waits: s.waits }) };
232
+ }
233
+ /** A folder listing (HOST_DIRS_LABEL from the agent) → it, or null. */
234
+ export function dirsOf(c) {
235
+ if (!isObj(c) || (c.id !== undefined && !(isStr(c.id, 32) && /^[\w-]+$/.test(c.id))) || !isStr(c.root, 4096)) return null;
236
+ const id = c.id !== undefined ? { id: c.id } : {};
237
+ if (c.error !== undefined) return isStr(c.error, 40) && isStr(c.detail, 200) ? { ...id, root: c.root, error: c.error, detail: c.detail } : null;
238
+ if (!isStr(c.path, 4096) || !isStr(c.parent, 4096) || !Array.isArray(c.dirs) || c.dirs.length > 200 || !c.dirs.every((d) => isStr(d, 255) && d !== '' && !/[\\/]/.test(d))
239
+ || !Number.isSafeInteger(c.hidden) || c.hidden < 0 || !Number.isSafeInteger(c.more) || c.more < 0) return null;
240
+ return { ...id, path: c.path, parent: c.parent, root: c.root, dirs: [...c.dirs], hidden: c.hidden, more: c.more };
241
+ }
242
+ /** A session event (HOST_SESSION_LABEL from the agent: new, waiting, set, refused) → it, or null. */
243
+ export function sessionEvOf(c) {
244
+ if (!isObj(c) || !['new', 'waiting', 'set', 'refused'].includes(c.event) || (c.why !== undefined && !isStr(c.why, 16)) || (c.folder !== undefined && !isStr(c.folder, 4096))
245
+ || (c.started !== undefined && !(Number.isSafeInteger(c.started) && c.started >= 0)) || (c.reason !== undefined && !isStr(c.reason, 40)) || (c.detail !== undefined && !isStr(c.detail, 200))) return null;
246
+ return Object.fromEntries(['event', 'why', 'folder', 'started', 'reason', 'detail'].filter((k) => c[k] !== undefined).map((k) => [k, c[k]]));
247
+ }
248
+ /** A login event (HOST_LOGIN_LABEL from the agent: link {url}, code_sent, bad_code, done {account?}, failed {reason}, cancelled) → it, or null. */
249
+ export function loginEvOf(c) {
250
+ if (!isObj(c) || !['link', 'code_sent', 'bad_code', 'done', 'failed', 'cancelled'].includes(c.state) || (c.state === 'link' && !(isStr(c.url, 4096) && /^https:\/\/\S+$/.test(c.url)))
251
+ || (c.account !== undefined && !isStr(c.account, 120)) || (c.reason !== undefined && !isStr(c.reason, 200))) return null;
252
+ return Object.fromEntries(['state', 'url', 'account', 'reason'].filter((k) => c[k] !== undefined && (k !== 'url' || c.state === 'link')).map((k) => [k, c[k]]));
253
+ }
254
+ /** The login code the sign-in page shows (sigelo-agent-host.ts LOGIN_CODE), spaces taken out. */
255
+ export const HOST_LOGIN_CODE = /^[A-Za-z0-9._~-]{8,1000}#[A-Za-z0-9._~-]{8,1000}$/;
201
256
  /** A hosted agent's settings as it announced them → {fields, note?} (a key not known here dropped), or null (malformed). */
202
257
  export function capsOf(c) {
203
258
  if (typeof c !== 'object' || c === null || Array.isArray(c) || !Array.isArray(c.fields) || c.fields.length > 16) return null;
@@ -210,7 +265,11 @@ export function capsOf(c) {
210
265
  fields.push({ key: f.key, value: f.value, options: f.options.map((o) => ({ value: o.value, label: o.label })), ...(f.off !== undefined && { off: f.off }), ...(f.next !== undefined && { next: f.next }) });
211
266
  }
212
267
  if (c.note !== undefined && !str(c.note, 120)) return null;
213
- return { fields, ...(c.note !== undefined && { note: c.note }) };
268
+ if (c.commands !== undefined && (!Array.isArray(c.commands) || c.commands.length > 32)) return null;
269
+ const commands = (c.commands ?? []).filter((x) => typeof x === 'object' && x !== null && typeof x.name === 'string' && /^[a-z][a-z0-9_-]{0,31}$/.test(x.name) && str(x.help, 120)
270
+ && (x.args === undefined || str(x.args, 40))).map((x) => ({ name: x.name, ...(x.args !== undefined && { args: x.args }), help: x.help }));
271
+ const session = c.session === undefined ? null : sessionOf(c.session);
272
+ return { fields, ...(c.note !== undefined && { note: c.note }), ...(commands.length > 0 && { commands }), ...(session !== null && { session }) };
214
273
  }
215
274
  const chainOnly = (b) => ({ v: 'sigelo/0', typ: 'bundle', genesis: b.genesis, rotations: b.rotations ?? [], bindings: [], attestations: [], issuers: [] });
216
275
  const SIGNED_LINE = /\n-- Signed with sigelo by [a-z]+ [a-z]+ [a-z]+ [a-z]+\. Check it in the sigelo app\.\s*$/;
@@ -284,7 +343,7 @@ export function matchIn(t, want) {
284
343
  return { snippet: pre + body + (to < t.length ? '…' : ''), mark: [s - from + pre.length, Math.min(e, to) - from + pre.length] };
285
344
  }
286
345
 
287
- export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, groupsFile = null, enrolFile = null, codeKind, unlogged, store, hooks = {}, relayFixed = null }) {
346
+ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, groupsFile = null, groups2: G2 = null, groups2File = null, enrolFile = null, codeKind, unlogged, store, hooks = {}, relayFixed = null }) {
288
347
  const defer = hooks.defer ?? ((f) => setTimeout(f, 0));
289
348
  const every = hooks.every ?? ((f, ms) => { const t = setInterval(f, ms); t.unref?.(); return t; });
290
349
  const watchers = new Set();
@@ -357,8 +416,30 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
357
416
  // A contact's own picture (the header's "Pictures"): kept apart, never in the history.
358
417
  if (m['label'] === PICTURE_LABEL) { takePicture(m); continue; }
359
418
  // A hosted agent's settings (the header's): kept apart, never in the history; a setting sent here, dropped.
360
- if (m['label'] === HOST_CAPS_LABEL) { const h = capsOf(m['content']); if (h) { data.host[String(m['from'])] = { ...h, at: nowS() }; saveData(); changed(); } continue; }
419
+ if (m['label'] === HOST_CAPS_LABEL) {
420
+ const h = capsOf(m['content']), was = data.host[String(m['from'])];
421
+ // The Session card's answers stay beside the caps that replace these.
422
+ if (h) { data.host[String(m['from'])] = { ...h, at: nowS(), ...Object.fromEntries(['dirs', 'dirs_ask', 'session_ev', 'login_ev'].filter((k) => was?.[k] !== undefined).map((k) => [k, was[k]])) }; saveData(); changed(); }
423
+ continue;
424
+ }
361
425
  if (m['label'] === HOST_SET_LABEL) continue;
426
+ // The Session card's answers (the header's): beside the agent's caps (none: dropped), never in the history.
427
+ if (m['label'] === HOST_DIRS_LABEL || m['label'] === HOST_SESSION_LABEL || m['label'] === HOST_LOGIN_LABEL) {
428
+ const h = data.host[String(m['from'])], l = m['label'];
429
+ const v = l === HOST_DIRS_LABEL ? dirsOf(m['content']) : l === HOST_SESSION_LABEL ? sessionEvOf(m['content']) : loginEvOf(m['content']);
430
+ if (!h || !v) continue;
431
+ if (l === HOST_DIRS_LABEL) h.dirs = { ...v, at: nowS() };
432
+ else if (l === HOST_SESSION_LABEL) {
433
+ h.session_ev = { ...v, at: nowS() };
434
+ if (h.session && (v.event === 'new' || v.event === 'set')) { if (v.folder !== undefined) h.session.folder = v.folder; if (v.started !== undefined) h.session.started = v.started; h.session.resumed = false; delete h.session.waits; }
435
+ if (h.session && v.event === 'refused') delete h.session.waits;
436
+ } else {
437
+ h.login_ev = { ...v, at: nowS() };
438
+ if (h.session && v.state === 'done') h.session.login = { state: 'signed_in', ...(v.account !== undefined && { account: v.account }), here: true };
439
+ }
440
+ saveData(); changed();
441
+ continue;
442
+ }
362
443
  // A photo's preview (photo.mjs): into the chat at once, the full file by its transfer.
363
444
  if (m['label'] === PHOTO_LABEL) {
364
445
  let ph = null;
@@ -480,6 +561,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
480
561
  if (e['check'] === 'pow_confirm') live.powConfirm = { relay: String(e['relay']), detail: String(e['detail']).replace(/^pow_confirm: /, '') };
481
562
  keepOffline();
482
563
  break;
564
+ case 'home': defer(homeRound); break;
483
565
  case 'notice': case 'presence': case 'group_tier': case 'busy': break; // presence, the group tier, a busy mark: the state says it, nothing to take
484
566
  case 'seen': defer(() => { receipt(String(e['from']), true); picturesDue(); }); break;
485
567
  // A new contact told its name (carrier.mjs "Names"): my groups that list it under the made-up one are sent again.
@@ -491,6 +573,19 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
491
573
  };
492
574
  const kept = () => (typeof data.settings.relay === 'string' && goodRelay(data.settings.relay) ? data.settings.relay : null);
493
575
  const carrier = makeCarrier(onEvent, kept() !== null ? { relay: kept() } : {});
576
+ // Home groups: the carrier's sessions at their home relays, and a sync at each `home` it says (the header's "Home groups").
577
+ let homing = null, homeAgain = false;
578
+ function homeRound() {
579
+ if (!G2 || !groups2File) return;
580
+ if (homing) { homeAgain = true; return; }
581
+ homing = (async () => {
582
+ // The items are taken (the page reads the chat from the groups file's history, step 6): nothing piles up in the file.
583
+ do { homeAgain = false; try { await serial(() => G2.sync({ carrier, file: groups2File, take: true })); } catch (err) { live.error = `home groups: ${err.message}`; } } while (homeAgain);
584
+ homing = null;
585
+ changed();
586
+ })();
587
+ }
588
+ if (G2 && groups2File && typeof carrier.setHomes === 'function') carrier.setHomes(() => G2.homes({ carrier, file: groups2File }));
494
589
  // The engine's events: a file offered, done, failed (into the history as events; the view reads GET /api/transfers).
495
590
  const onTransfer = (e) => {
496
591
  if (['asked', 'done', 'failed', 'declined', 'cancelled'].includes(e.what)) {
@@ -506,8 +601,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
506
601
  // ---- calls (the header's): the Line, its messages taken from the carrier at each `call` event and each drain.
507
602
  data.calls ??= {};
508
603
  const liveContact = (d) => carrier.contacts().contacts.find((c) => c.did === d && !c.revoked) ?? null;
509
- const canCall = (c) => (typeof data.calls[c.did] === 'boolean' ? data.calls[c.did] : c.tier === 'quiet' ? false : data.settings.calls !== false);
510
- // Calls are between people (design/calls.md §1): a contact this page takes for an agent (its kind, as the chat list
604
+ const canCall = (c) => data.calls[c.did] === true;
605
+ // Calls are between people: a contact this page takes for an agent (its kind, as the chat list
511
606
  // shows it: the human's choice, else my agent, a worker, a group's agent) is never rung from here and never rings here.
512
607
  const personOf = (c) => {
513
608
  const agent = (hooks.agents?.() ?? []).find((a) => a.did !== undefined && c.chain?.includes(a.did));
@@ -519,11 +614,18 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
519
614
  contact: liveContact, allowed: canCall, person: personOf,
520
615
  refused: ({ did, check }) => record({ kind: 'event', type: 'dropped', did, name: liveContact(did)?.name ?? null, code: check, detail: 'a call from an agent: refused (calls are between people)' }),
521
616
  shares: (c) => c.presence === 'allow' || c.presence === 'own', me: () => hooks.me().original,
522
- line: ({ did, dir, text, call }) => { record({ kind: dir, did, name: liveContact(did)?.name ?? null, text, label: CALL_LABEL, call }); },
523
- alert: (x) => { try { CH.alert?.(x); } catch {} },
617
+ line: ({ did, dir, text, call }) => { record({ kind: dir, did, name: liveContact(did)?.name ?? null, text, label: CALL_LABEL, call }); if (call?.state === 'missed') missedNote(did); },
618
+ alert: (x) => { try { return CH.alert?.(x); } catch { return undefined; } },
524
619
  audio: (x) => { try { void Promise.resolve(CH.audio?.(x)).catch(() => {}); } catch {} },
525
620
  changed: () => changed(),
526
621
  });
622
+ // A missed call told at once (CH.missed), not only by the page's poll: as the poll would (alerts for people, the chat
623
+ // not muted, not a quiet contact); the poll's own notification has the same tag (chat:<did>) and replaces it.
624
+ function missedNote(did) {
625
+ const c = liveContact(did);
626
+ if (typeof CH.missed !== 'function' || !c || alertsOf() === 'none' || data.notify?.[did] === false || c.tier === 'quiet') return;
627
+ try { void Promise.resolve(CH.missed({ did, name: c.name })).catch(() => {}); } catch {}
628
+ }
527
629
  const callRound = () => { try { for (const m of carrier.takeCalls()) line.receive(m); } catch (err) { live.error = `calls: ${err.message}`; } };
528
630
  // The relay new codes name, as the precedence says.
529
631
  const newCodes = () => relayFixed ?? kept() ?? DEFAULT_RELAY;
@@ -569,11 +671,14 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
569
671
  }
570
672
  }
571
673
  const notifyOf = (chat) => data.notify[chat] !== false;
674
+ const ALERTS = ['all', 'people', 'none'];
675
+ const alertsOf = () => (ALERTS.includes(data.settings.alerts) ? data.settings.alerts : data.settings.notify === false ? 'none' : 'all');
572
676
  // The public invite as the state shows it (carrier.mjs publicView): the first public code of mine, or null.
573
677
  const publicInvite = (c) => c.publics?.[0] ?? null;
574
678
  const walletSet = () => ({ wallet: data.settings.wallet === true, prices: data.settings.prices === true, currency: CURRENCIES.includes(data.settings.currency) ? data.settings.currency : null });
575
- const settingsAll = () => ({ ...settings(), seen_receipts: receiptsOn(), notify: data.settings.notify !== false,
576
- new_tier: TIER_NEW.has(data.settings.new_tier) ? data.settings.new_tier : 'friend', new_presence: data.settings.new_presence === true, calls: data.settings.calls !== false,
679
+ // notify: alerts not none, for a page from before "Alert me about".
680
+ const settingsAll = () => ({ ...settings(), seen_receipts: receiptsOn(), alerts: alertsOf(), notify: alertsOf() !== 'none',
681
+ new_tier: TIER_NEW.has(data.settings.new_tier) ? data.settings.new_tier : 'friend', new_presence: data.settings.new_presence === true,
577
682
  relay_media: relayMedia() === 'relay', ...walletSet() });
578
683
 
579
684
  // ---- pictures (the header's): mine to the contacts that read them, theirs kept, a local one beside
@@ -613,18 +718,45 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
613
718
  } catch (e) { record({ kind: 'event', type: 'dropped', did: d, name: m['name'], code: 'picture', detail: e.message }); }
614
719
  }
615
720
 
616
- let timers = [];
721
+ let timers = [], homeTicks = 0;
617
722
  async function start() {
618
723
  void checkClock();
619
- timers = [every(() => void checkClock(), 600_000), every(() => void drain().then(() => linkRound()), 60_000)];
724
+ timers = [every(() => void checkClock(), 600_000), every(() => void drain().then(() => linkRound()), 60_000),
725
+ // A join of mine waiting: its answer comes on a reply topic no row announces, so the home is read again: every 5 s for
726
+ // the first 2 minutes of the newest join, then every minute for an hour, then every 10 minutes (a refused one waits on).
727
+ every(() => {
728
+ if (!G2 || !groups2File) return;
729
+ const js = homeList().filter((g) => g.status === 'joining');
730
+ if (!js.length) return;
731
+ const age = nowS() - Math.max(...js.map((g) => g.joining?.at ?? 0)), step = age < 120 ? 1 : age < 3600 ? 12 : 120;
732
+ if (++homeTicks % step === 0) homeRound();
733
+ }, 5000)];
620
734
  // The enrolments from before this start (the pending file): their requests held, a failed identity sent again.
621
735
  try { await look(); } catch {}
736
+ await settlePeople();
622
737
  await carrier.start({ started: 'user' });
623
738
  await drain();
624
739
  void linkRound();
625
740
  picturesDue();
626
741
  void transfers?.engine.kick();
627
742
  }
743
+ // A person is normal or muted (the header's): one on quiet from before is muted and filed friend, once a profile. Its kind
744
+ // as the chat list takes it (the human's, the contact's word, my agent, a worker, a group's agent): an agent keeps quiet.
745
+ async function settlePeople() {
746
+ if (data.settings.people === 1) return;
747
+ try {
748
+ if (K) await workers().catch(() => null);
749
+ const local = hooks.agents?.() ?? [], roles = rosterAgents();
750
+ for (const x of carrier.contacts().contacts) {
751
+ if (x.revoked || x.tier !== 'quiet') continue;
752
+ const agent = local.find((a) => a.did !== undefined && x.chain.includes(a.did));
753
+ if (kindOf(x, agent?.mine ?? null, roles).kind !== 'person') continue;
754
+ data.notify[x.did] = false;
755
+ carrier.setTier(x.did, 'friend');
756
+ }
757
+ data.settings.people = 1; saveData();
758
+ } catch {}
759
+ }
628
760
  async function halt() {
629
761
  for (const t of timers) clearInterval(t);
630
762
  await linking.catch(() => {});
@@ -635,7 +767,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
635
767
 
636
768
  // ---- agents: the operator's workers (keeper `workers`), enrolled by a one-time code from this page
637
769
  const K = hooks.keeper ?? null;
638
- // The computer this profile is paired to, for the keeper (design/agent-wallet-page.md §4): { name() → its name,
770
+ // The computer this profile is paired to, for the keeper (UI-API.md "Computers"): { name() → its name,
639
771
  // call(method, path, body?) → { status, body } } (its page over the control, scope all), or none.
640
772
  const PC = hooks.computer ?? null;
641
773
  const viaPc = async (method, path, body) => {
@@ -754,6 +886,14 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
754
886
  };
755
887
  // The contact holding a worker's original DID, live, or null.
756
888
  const contactOfWorker = (w) => carrier.contacts().contacts.find((x) => !x.revoked && x.chain.includes(w.original)) ?? null;
889
+ // A rename told to the agent's host (UX review A): an own agent that sent its caps (a host) gets HOST_SET_LABEL {name}; it
890
+ // says that name in its own lines and keeps it. Not sent (offline, refused): the rename stands here, the host keeps its own.
891
+ const hostName = async (c, name) => {
892
+ if (!c || !data.host?.[c.did] || typeof name !== 'string' || !(c.ours === true || c.tier === 'own' || c.chain?.some((d) => workerDids.has(d)))) return;
893
+ // Kept before anything else goes or is acknowledged (the flush rule), as every route that sends does.
894
+ try { await carrier.send(c.did, { name }, { label: HOST_SET_LABEL }); } catch {}
895
+ saveData();
896
+ };
757
897
  // A contact's kind (UI-API.md "Kinds"): person, agent or desk (a support desk). The human's choice (POST /api/kind,
758
898
  // data.kind) wins; else what the contact said of itself once paired (carrier.mjs "Kinds": kind_peer agent or desk);
759
899
  // else an agent when the page knows it is one (my agent: ours by its operator attestation, on this machine, or a
@@ -810,7 +950,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
810
950
  const queued = msgs.filter((r) => r.kind === 'out' && r.status === 'queued');
811
951
  return {
812
952
  did: x.did, name: x.name, name_from: x.name_from ?? null, current_did: x.current_did, relay: x.relay, re_pair: x.re_pair, words: x.fingerprint, pair,
813
- words_checked: pair !== null && data.checked[x.did] === pair, tags: data.tags[x.did] ?? [],
953
+ // A sibling proven by its operator attestation and my commitment (kin.mjs) needs no words, as an enrolled worker does not.
954
+ words_checked: pair !== null && (data.checked[x.did] === pair || Boolean(x.kin)), kin: x.kin ?? null, tags: data.tags[x.did] ?? [],
814
955
  // Came by a public code (carrier.mjs via): mine ({public: id}, nobody compared) or theirs ({public: true, words}).
815
956
  via: x.via ?? null,
816
957
  local: agent?.name ?? null, mine, unread: msgs.filter((r) => r.kind === 'in' && r.n > read && (!r.call || r.call.state === 'missed')).length,
@@ -901,7 +1042,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
901
1042
  async function groupRound() {
902
1043
  if (!G || !groupsFile) return;
903
1044
  try {
904
- const r = await G.handle({ carrier, file: groupsFile });
1045
+ const r = await G.handle({ carrier, file: groupsFile, ...(groups2File && { file2: groups2File }) });
905
1046
  let noted = false;
906
1047
  for (const n of r.notices) if (n.why !== 'invited') { gnote(n); noted = true; }
907
1048
  const by = new Map();
@@ -926,7 +1067,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
926
1067
  const items = ['member', 'frozen'].includes(g.status) ? G.history({ carrier, file: groupsFile, group: g.gid }) : [];
927
1068
  const last = items.at(-1);
928
1069
  return { ...g, unread: unreadIn(g.gid, items), quiet: brakeQuiet(g), notify: notifyOf(g.gid), picture: picRev(`l:${g.gid}`),
929
- 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 };
1070
+ last: last ? { name: last.mine ? null : last.name, role: last.role ?? null, text: textOf(last.content).slice(0, 200), at: last.received ?? last.iat, mine: last.mine === true } : null };
930
1071
  });
931
1072
  }
932
1073
  function groupTier() {
@@ -935,12 +1076,14 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
935
1076
  }
936
1077
  // /api/state's chats: the badge (unread in all), invitations waiting, notices. Never fails the state.
937
1078
  function chatsState() {
938
- if (!G || !groupsFile || carrier.platform.files.read(groupsFile) === null) return { unread: 0, invited: 0, notices: data.gnotices.length, rev: `0.${data.gnotices.length}` };
1079
+ const g1 = Boolean(G && groupsFile && carrier.platform.files.read(groupsFile) !== null);
1080
+ if (!g1 && !(G2 && groups2File && carrier.platform.files.read(groups2File) !== null)) return { unread: 0, invited: 0, notices: data.gnotices.length, rev: `0.${data.gnotices.length}` };
939
1081
  try {
940
- const gs = groupsList();
1082
+ // Home groups too (design/groups-build.md step 6): a sync that brought a row changes rev, so the page reads the list again.
1083
+ const gs = [...(g1 ? groupsList() : []), ...homeList()];
941
1084
  // rev: changes with any group's roster, status, run or newest item (the page fetches a chat again on it).
942
1085
  const rev = gs.map((g) => `${g.gid.slice(0, 8)}.${g.ver}.${g.status}.${g.run}.${g.last?.at ?? 0}.${g.unread}`).join(' ');
943
- 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}` };
1086
+ return { unread: gs.reduce((a, g) => a + g.unread, 0), invited: gs.filter((g) => g.status === 'pending' || g.status === 'invited').length, notices: data.gnotices.length, rev: `${hashOf(rev)}.${data.gnotices.length}` };
944
1087
  } catch { return { unread: 0, invited: 0, notices: data.gnotices.length, rev: '' }; }
945
1088
  }
946
1089
  // group.mjs refusals by check: unknown → 404, usage → 400, any other (group_*, not_contact, name) → 409.
@@ -952,7 +1095,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
952
1095
  }
953
1096
  }
954
1097
  const gid = (b) => (typeof b['group'] === 'string' && b['group'] !== '' ? b['group'] : refuse(400, 'body', 'group: its gid'));
955
- const isGroup = (x) => { try { return typeof x === 'string' && /^[0-9a-f]{32}$/.test(x) && Boolean(G && groupsFile && carrier.platform.files.read(groupsFile) !== null && G.list({ carrier, file: groupsFile }).some((g) => g.gid === x)); } catch { return false; } };
1098
+ const isGroup = (x) => { try { return typeof x === 'string' && /^[0-9a-f]{32}$/.test(x) && (Boolean(G && groupsFile && carrier.platform.files.read(groupsFile) !== null && G.list({ carrier, file: groupsFile }).some((g) => g.gid === x)) || isHome(x)); } catch { return false; } };
956
1099
  const dids = (v, what, need = true) => {
957
1100
  if (v === undefined && !need) return [];
958
1101
  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`);
@@ -965,16 +1108,21 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
965
1108
  'GET /api/groups/history': (_, q) => groupCall(() => {
966
1109
  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`);
967
1110
  const items = G.history({ carrier, file: groupsFile, group: g }), last = items.at(-1);
1111
+ // The first item new to this look (as unreadIn counts: after the newest shown, not mine), before the mark moves.
1112
+ const m0 = data.gread[g], at0 = m0 ? items.findIndex((i) => i.mid === m0.mid) : -1;
1113
+ const unreadFrom = (!m0 ? items : at0 >= 0 ? items.slice(at0 + 1) : items.filter((i) => (i.received ?? 0) > m0.at)).find((i) => !i.mine)?.mid ?? null;
968
1114
  // Read: the page has shown them.
969
1115
  if (last && data.gread[g]?.mid !== last.mid) { data.gread[g] = { mid: last.mid, at: last.received ?? last.iat }; saveData(); }
970
- 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,
1116
+ return { group: { ...one, unread: 0 }, unread_from: unreadFrom, 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,
971
1117
  operator: i.operator === true, note: i.note ?? null, text: textOf(i.content), mentions: i.mentions ?? [], mentioned: i.mentioned === true, via: i.via ?? null, photo: i.photo ?? null, ...(i.voice && { voice: i.voice }), at: i.received ?? i.iat })) };
972
1118
  }),
973
- 'POST /api/groups/create': (b) => serial(() => groupCall(async () => {
974
- const brake = b['brake'];
975
- 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 }),
976
- ...(carrier.selfName() !== null && { selfName: carrier.selfName() }),
977
- ...(typeof b['role'] === 'string' && { role: b['role'] }) }));
1119
+ // A group of contacts of mine to a home group (design/groups-build.md §5): its members invited over the pairings.
1120
+ 'POST /api/groups/move': (b) => serial(() => groupCall(async () => {
1121
+ const home = b['home'] === undefined || b['home'] === null || b['home'] === '' ? undefined : String(b['home']).trim().toLowerCase();
1122
+ if (home !== undefined) checkRelay(home);
1123
+ const r = await G.move({ carrier, file: groupsFile, file2: groups2File, group: gid(b), ...(home && { home }) });
1124
+ carrier.wake?.({ now: true });
1125
+ return { ...gout({ ...r, copies: [...r.invited, ...r.line] }), home: homeOne(r.home.gid) ?? r.home, unreached: r.unreached };
978
1126
  })),
979
1127
  '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) })))),
980
1128
  'POST /api/groups/remove': (b) => serial(() => groupCall(async () => gout(await G.remove({ carrier, file: groupsFile, group: gid(b), members: dids(b['members'], 'members') })))),
@@ -1001,11 +1149,269 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1001
1149
  }),
1002
1150
  };
1003
1151
 
1152
+ // ---- home groups (design/groups-build.md step 6; UI-API.md "Home groups"): group2.mjs over groups2File. The list and
1153
+ // the chat read the file only, never the relay; every action is a session at the group's home relay, one at a time
1154
+ // (serial). The page's own marks in data: gread as for groups; gjoin (gid → {approve, at}: a join of mine waiting);
1155
+ // gnames (DID → the name a member had when removed here: the Banned list names it).
1156
+ const JOIN_LINK = 'https://sigelo.io/join#';
1157
+ const HOME_KEYS = ['name', 'about', 'channel', 'join', 'history', 'agents', 'brake'];
1158
+ let homeMemo = null;
1159
+ // The groups file's view (G2.list, local, show), kept while the file is the same and for 30 s at most (links run out).
1160
+ function homeBase() {
1161
+ const raw = carrier.platform.files.read(groups2File);
1162
+ if (raw === null) return [];
1163
+ const t = new TextDecoder().decode(raw), key = `${t.length}.${hashOf(t)}`;
1164
+ if (homeMemo?.key === key && nowS() - homeMemo.at < 30) return homeMemo.base;
1165
+ const gs = G2.list({ carrier, file: groups2File }), facts = G2.local({ carrier, file: groups2File });
1166
+ const base = gs.map((g) => ({ g, f: facts[g.gid] ?? {}, msgs: g.status === 'joining' ? [] : G2.show({ carrier, file: groups2File, group: g.gid }).messages }));
1167
+ homeMemo = { key, at: nowS(), base };
1168
+ return base;
1169
+ }
1170
+ // A message of the log as the chat and the unread count read it (a poll by its question; a deleted one by its mark).
1171
+ const homeText = (m) => (m.deleted ? '' : m.text ?? (m.poll ? `Poll: ${m.poll.question}` : m.file ? `File: ${m.file.name}` : ''));
1172
+ const homeItems = (msgs) => msgs.map((m) => ({ mid: m.mid, mine: m.mine === true, received: m.iat }));
1173
+ function homeList() {
1174
+ if (!G2 || !groups2File) return [];
1175
+ let base;
1176
+ try { base = homeBase(); } catch (e) { live.error = `home groups: ${e.message}`; return []; }
1177
+ const cs = new Map(carrier.contacts().contacts.filter((c) => !c.revoked && !hidden(c)).map((c) => [c.did, c])), me = hooks.me().original;
1178
+ const nameOf = (d, n) => cs.get(d)?.name ?? n;
1179
+ return base.map(({ g, f, msgs }) => {
1180
+ const items = homeItems(msgs), lastM = msgs.at(-1);
1181
+ const members = g.members.map((m) => ({ did: m.did, name: m.me ? m.name : nameOf(m.did, m.name), kind: m.kind, role: m.role, me: m.me, contact: !m.me && cs.has(m.did) }));
1182
+ const owner = members.find((m) => m.role === 'owner');
1183
+ return { gid: g.gid, name: g.name, v: 2, home: g.home, home_own: g.home === carrier.relay, status: g.status,
1184
+ ended: g.status === 'closed' ? f.closed ?? 'end' : null, banned: g.status === 'removed' && (f.barred ?? []).includes(me),
1185
+ role: g.role, mine: g.role === 'owner', owner: f.owner ?? null, owner_words: f.owner ? didWords(f.owner) : null, owner_name: owner ? (owner.me ? null : owner.name) : f.owner ? nameOf(f.owner, null) : null,
1186
+ settings: g.settings ?? {}, brake: g.settings?.brake ?? 20, pins: g.pins ?? [], requests: g.requests,
1187
+ links: (g.links ?? []).map((l) => ({ id: l.id, exp: l.exp, approve: l.approve, code: l.code ?? null, link: l.code ? JOIN_LINK + l.code : null })),
1188
+ members, barred: (f.barred ?? []).map((d) => ({ did: d, name: nameOf(d, data.gnames?.[d] ?? null), words: didWords(d) })),
1189
+ joining: g.status === 'joining' ? { at: f.joining?.at ?? null, approve: data.gjoin?.[g.gid]?.approve ?? null } : null,
1190
+ // An invitation over a pairing, waiting (design/groups-build.md §1.6): who sent it, until when; a move names the old group.
1191
+ invited: g.status === 'invited' && f.invited ? { by: f.invited.by, name: nameOf(f.invited.by, f.invited.name), at: f.invited.at, exp: f.invited.exp } : null, moved_from: f.moved_from ?? null,
1192
+ run: 0, quiet: false, ver: `${f.seq ?? 0}.${g.requests}.${g.role}.${members.length}.${g.epoch}.${(g.links ?? []).length}`,
1193
+ // The picture: one set on this device, else the group's (an admin's, in the log: step 7).
1194
+ unread: unreadIn(g.gid, items), notify: notifyOf(g.gid), picture: picRev(`l:${g.gid}`) ?? (g.settings?.avatar ? `a${g.settings.avatar.sha256.slice(0, 16)}` : null),
1195
+ last: lastM ? { name: lastM.mine ? null : nameOf(lastM.from, lastM.name), role: lastM.role, kind: lastM.kind, text: homeText(lastM).slice(0, 200), at: lastM.iat, mine: lastM.mine === true } : null };
1196
+ });
1197
+ }
1198
+ const homeOne = (gid) => homeList().find((g) => g.gid === gid) ?? null;
1199
+ const isHome = (x) => typeof x === 'string' && /^[0-9a-f]{32}$/.test(x) && homeOne(x) !== null;
1200
+ // group2.mjs refusals by check: unknown → 404; a code, a link's terms, a setting or a text that is wrong → 400; the rest (a role
1201
+ // missing, a member, the relay's home_*) → 409.
1202
+ // read: a read of the file only (events), which changes nothing to push.
1203
+ async function homeCall(fn, read = false) {
1204
+ if (!G2 || !groups2File) refuse(404, 'route', 'no home groups here');
1205
+ try { const r = await fn(); if (!read) changed(); return r; } catch (e) {
1206
+ if (e.check !== undefined && e.status === undefined) e.status = ['group_unknown', 'group_name', 'group_file_gone'].includes(e.check) ? 404 : ['group_code', 'group_link', 'group_settings', 'group_text', 'group_message', 'group_file', 'group_file_size', 'group_events', 'code_relay', 'body'].includes(e.check) ? 400 : 409;
1207
+ throw e;
1208
+ }
1209
+ }
1210
+ const hgid = (b) => { const g = gid(b); if (!isHome(g)) refuse(404, 'group_unknown', `no home group ${g} here`); return g; };
1211
+ const hfile = () => ({ carrier, file: groups2File });
1212
+ // A write's answer: what group2.mjs said, and the group as the list shows it now.
1213
+ const homeOut = (r, g) => ({ ...r, group: homeOne(g) ?? r?.group ?? null });
1214
+ const memberArg = (b) => (typeof b['member'] === 'string' && b['member'] !== '' ? b['member'] : refuse(400, 'body', 'member: a member\'s DID'));
1215
+ const homeRoutes = {
1216
+ 'POST /api/groups/create': (b) => serial(() => homeCall(async () => {
1217
+ const name = typeof b['name'] === 'string' ? b['name'].trim() : refuse(400, 'body', 'name: the group\'s name');
1218
+ const home = b['home'] === undefined || b['home'] === null || b['home'] === '' ? carrier.relay : String(b['home']).trim().toLowerCase();
1219
+ checkRelay(home);
1220
+ // Contacts picked (New group): invited over the pairings once it is made.
1221
+ const members = dids(b['members'], 'members', false);
1222
+ const r = await G2.create({ ...hfile(), name, home, kind: 'human', selfName: carrier.selfName() ?? 'owner', ...(members.length && { members }) });
1223
+ carrier.wake?.({ now: true });
1224
+ return { group: homeOne(r.group.gid) ?? r.group, copies: r.invited?.copies ?? [] };
1225
+ })),
1226
+ 'POST /api/groups/add': (b) => serial(() => homeCall(async () => {
1227
+ const r = await G2.add({ ...hfile(), group: hgid(b), members: dids(b['members'], 'members') });
1228
+ return { group: homeOne(r.gid), copies: r.copies, ...(r.offline !== undefined && { offline: r.offline }) };
1229
+ })),
1230
+ 'POST /api/groups/preview': (b) => homeCall(async () => {
1231
+ const code = typeof b['code'] === 'string' && b['code'].trim() !== '' ? b['code'] : refuse(400, 'body', 'code: a GRP code or its link');
1232
+ // A supergroup's address (name@relay, design/groups-build.md §3.7): its card, checked offline; private: join needs `with`.
1233
+ const at = G2.parseAddress(code), c = at ? await G2.card({ carrier, address: code }) : null;
1234
+ const p = c ? { gid: c.gid, name: c.name, home: c.relay, owner: c.owner, words: c.words, approve: c.approve, exp: c.link_exp ?? c.slot.exp,
1235
+ supergroup: { address: c.address, public: c.public, about: c.about, pinned: c.pinned, operator_words: c.operator_words } } : await G2.peek({ carrier, code });
1236
+ return { ...p, owner_name: carrier.contacts().contacts.find((c) => c.did === p.owner && !c.revoked)?.name ?? null, status: homeOne(p.gid)?.status ?? null };
1237
+ }),
1238
+ 'POST /api/groups/join': (b) => serial(() => homeCall(async () => {
1239
+ // An invitation over a pairing joins by its group's gid (one tap); else a code, a link or a name.
1240
+ const r = await G2.join({ ...hfile(), code: b['code'] ?? hgid(b), ...(typeof b['with'] === 'string' && b['with'].trim() !== '' && { with: b['with'] }), name: carrier.selfName() ?? 'member', kind: 'human' });
1241
+ (data.gjoin ??= {})[r.group.gid] = { approve: r.approve, at: nowS() };
1242
+ saveData();
1243
+ carrier.wake?.({ now: true });
1244
+ return { group: homeOne(r.group.gid) ?? r.group, status: 'waiting', approve: r.approve, words: r.words };
1245
+ })),
1246
+ 'POST /api/groups/drop': (b) => serial(() => homeCall(async () => {
1247
+ const r = G2.drop({ ...hfile(), group: hgid(b) });
1248
+ delete data.gjoin?.[r.dropped]; delete data.gread[r.dropped]; delete data.notify[r.dropped];
1249
+ saveData();
1250
+ return r;
1251
+ })),
1252
+ 'POST /api/groups/sync': (b) => serial(() => homeCall(async () => {
1253
+ const r = await G2.sync({ ...hfile(), ...(b['group'] !== undefined && { group: hgid(b) }), take: true });
1254
+ return { groups: r.groups.map((g) => homeOne(g.gid) ?? g) };
1255
+ })),
1256
+ 'POST /api/groups/link': (b) => serial(() => homeCall(async () => {
1257
+ const ttl = b['ttl'] === undefined ? undefined : Number(b['ttl']), approve = b['approve'];
1258
+ if (approve !== undefined && approve !== 'auto' && approve !== 'admin') refuse(400, 'body', 'approve: auto or admin');
1259
+ const r = await G2.link({ ...hfile(), group: hgid(b), ...(ttl !== undefined && { ttl }), ...(approve !== undefined && { approve }) });
1260
+ // The long invite stays out: what a person sees and shares is the GRP code and its link.
1261
+ return { id: r.id, code: r.code, link: r.link ?? null, words: r.words, exp: r.exp, approve: r.approve, cap: r.cap, home: r.home, ...(r.park_error && { park_error: r.park_error }) };
1262
+ })),
1263
+ 'POST /api/groups/unlink': (b) => serial(() => homeCall(async () => homeOut(await G2.unlink({ ...hfile(), group: hgid(b), id: String(b['id'] ?? '') }), b['group']))),
1264
+ 'GET /api/groups/requests': (_, q) => homeCall(async () => {
1265
+ const g = q.get('group') ?? refuse(400, 'body', 'group: its gid');
1266
+ if (!isHome(g)) refuse(404, 'group_unknown', `no home group ${g} here`);
1267
+ const cs = new Map(carrier.contacts().contacts.filter((c) => !c.revoked).map((c) => [c.did, c]));
1268
+ return { requests: (G2.local(hfile())[g]?.requests ?? []).map((x) => ({ ...x, contact: cs.has(x.did), ...(cs.has(x.did) && { name: cs.get(x.did).name }) })) };
1269
+ }),
1270
+ // The event history (owner and admins: all; moderators: kicks, bans, deletes, pins; a member: 409 group_role), from this
1271
+ // device's file: names as the list shows them (a contact's name, You), a deleted message's text never (not kept).
1272
+ 'POST /api/groups/events': (b) => homeCall(async () => {
1273
+ const g = hgid(b), one = homeOne(g), me = hooks.me().original;
1274
+ const num = (k, lo, hi) => (b[k] === undefined || b[k] === null ? undefined : Number.isSafeInteger(b[k]) && b[k] >= lo && b[k] <= hi ? b[k] : refuse(400, 'body', `${k}: a whole number, ${lo} to ${hi}`));
1275
+ const r = G2.events({ ...hfile(), group: g, since: num('since', 0, Number.MAX_SAFE_INTEGER), limit: num('limit', 1, 500) });
1276
+ const names = new Map((one?.members ?? []).map((m) => [m.did, m.name])), who = (x) => (x ? { did: x.did, name: x.did === me ? 'You' : names.get(x.did) ?? x.name ?? data.gnames?.[x.did] ?? null, me: x.did === me } : null);
1277
+ return { group: one, role: r.role, full: r.full, more: r.more, events: r.events.map((e) => ({ ...e, by: who(e.by), ...(e.target && { target: who(e.target) }) })) };
1278
+ }, true),
1279
+ 'POST /api/groups/approve': (b) => serial(() => homeCall(async () => homeOut(await G2.approve({ ...hfile(), group: hgid(b), id: String(b['id'] ?? '') }), b['group']))),
1280
+ 'POST /api/groups/refuse': (b) => serial(() => homeCall(async () => ({ ...(await G2.refuse({ ...hfile(), group: hgid(b), id: String(b['id'] ?? '') })), group: homeOne(b['group']) }))),
1281
+ 'POST /api/groups/kick': (b) => serial(() => homeCall(async () => {
1282
+ const g = hgid(b), m = memberArg(b), who = homeOne(g)?.members.find((x) => x.did === m);
1283
+ if (who) { (data.gnames ??= {})[m] = who.name; saveData(); }
1284
+ return homeOut(await G2.kick({ ...hfile(), group: g, member: m, bar: b['bar'] === true }), g);
1285
+ })),
1286
+ 'POST /api/groups/unbar': (b) => serial(() => homeCall(async () => homeOut(await G2.unbar({ ...hfile(), group: hgid(b), member: memberArg(b) }), b['group']))),
1287
+ 'POST /api/groups/role': (b) => serial(() => homeCall(async () => {
1288
+ if (!['admin', 'moderator', 'member'].includes(b['role'])) refuse(400, 'body', 'role: admin, moderator or member');
1289
+ return homeOut(await G2.role({ ...hfile(), group: hgid(b), member: memberArg(b), role: b['role'] }), b['group']);
1290
+ })),
1291
+ 'POST /api/groups/set': (b) => serial(() => homeCall(async () => {
1292
+ if (!HOME_KEYS.includes(b['key'])) refuse(400, 'body', `key: one of ${HOME_KEYS.join(', ')}`);
1293
+ return homeOut(await G2.set({ ...hfile(), group: hgid(b), key: b['key'], value: b['value'] }), b['group']);
1294
+ })),
1295
+ 'POST /api/groups/rename': (b) => serial(() => homeCall(async () => homeOut(await G2.set({ ...hfile(), group: hgid(b), key: 'name', value: typeof b['name'] === 'string' ? b['name'].trim() : b['name'] }), b['group']))),
1296
+ 'POST /api/groups/brake': (b) => serial(() => homeCall(async () => homeOut(await G2.set({ ...hfile(), group: hgid(b), key: 'brake', value: b['brake'] }), b['group']))),
1297
+ 'POST /api/groups/handover': (b) => serial(() => homeCall(async () => homeOut(await G2.handover({ ...hfile(), group: hgid(b), member: memberArg(b) }), b['group']))),
1298
+ 'POST /api/groups/end': (b) => serial(() => homeCall(async () => homeOut(await G2.end({ ...hfile(), group: hgid(b) }), b['group']))),
1299
+ 'POST /api/groups/leave': (b) => serial(() => homeCall(async () => ({ ...homeOut(await G2.leave({ ...hfile(), group: hgid(b) }), b['group']), copies: [], told: true }))),
1300
+ 'POST /api/groups/history': (b) => serial(() => homeCall(async () => homeOut(await G2.historyAsk({ ...hfile(), group: hgid(b) }), b['group']))),
1301
+ 'POST /api/groups/send': (b) => serial(() => homeCall(async () => {
1302
+ const g = hgid(b), text = b['text'], re = b['re'];
1303
+ if (typeof text !== 'string' || text.trim() === '') refuse(400, 'body', 'text: the message');
1304
+ // @name in the text mentions that member, as in a group of contacts.
1305
+ const esc = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1306
+ const at = (homeOne(g)?.members ?? []).filter((m) => !m.me && new RegExp(`(^|\\s)@${esc(m.name)}(?=$|[\\s.,!?:;])`).test(text)).map((m) => m.did);
1307
+ const given = Array.isArray(b['mentions']) ? b['mentions'].filter((x) => typeof x === 'string') : [];
1308
+ const r = await G2.send({ ...hfile(), group: g, text, ...(typeof re === 'string' && re !== '' && { re }), mentions: [...new Set([...given, ...at])] });
1309
+ return { gid: g, mid: r.mid, seq: r.seq ?? null, copies: [], via_creator: [], unreached: [] };
1310
+ })),
1311
+ 'GET /api/groups/history': (_, q) => homeCall(async () => {
1312
+ const g = q.get('group'), one = homeOne(g) ?? refuse(404, 'group_unknown', `no home group ${g} here`), me = hooks.me().original;
1313
+ const msgs = one.status === 'joining' ? [] : G2.show({ ...hfile(), group: g }).messages, items = homeItems(msgs), last = items.at(-1);
1314
+ const m0 = data.gread[g], at0 = m0 ? items.findIndex((i) => i.mid === m0.mid) : -1;
1315
+ const unreadFrom = (!m0 ? items : at0 >= 0 ? items.slice(at0 + 1) : items.filter((i) => (i.received ?? 0) > m0.at)).find((i) => !i.mine)?.mid ?? null;
1316
+ if (last && data.gread[g]?.mid !== last.mid) { data.gread[g] = { mid: last.mid, at: last.received }; saveData(); }
1317
+ const names = new Map(one.members.map((m) => [m.did, m.name])), nameOf = (d) => (d === me ? 'You' : names.get(d) ?? 'A former member');
1318
+ // Step 7: reactions (each emoji: count, mine, who), the poll's view (tallies, my choices), a file's manifest, pins with a line each.
1319
+ const reactions = (r) => Object.entries(r ?? {}).map(([emoji, ds]) => ({ emoji, n: ds.length, mine: ds.includes(me), who: ds.map(nameOf) })).filter((x) => x.n);
1320
+ const pollOf = (p) => ({ question: p.question, options: p.options, multi: p.multi, closed: p.closed, tallies: p.options.map((_, i) => Object.values(p.votes).filter((c) => c.includes(i)).length),
1321
+ voters: Object.keys(p.votes).length, mine: p.votes[me] ?? [] });
1322
+ const byMid = new Map(msgs.map((m) => [m.mid, m]));
1323
+ return { group: { ...one, unread: 0 }, unread_from: unreadFrom,
1324
+ pins: [...one.pins].reverse().map((mid) => byMid.get(mid)).filter((m) => m && !m.deleted).map((m) => ({ mid: m.mid, name: nameOf(m.from), text: homeText(m).split('\n')[0].slice(0, 120), at: m.iat })),
1325
+ messages: msgs.slice(-200).map((m) => ({ mid: m.mid, seq: m.seq, re: m.re ?? null, from: m.from, name: names.get(m.from) ?? m.name, role: m.role, kind: m.kind,
1326
+ tier: null, mine: m.mine === true, operator: false, note: null, text: homeText(m), ...(m.deleted && { deleted: true, ...(m.deleted_by && { deleted_by: m.deleted_by }) }), ...(m.edited && { edited: true }),
1327
+ ...(m.poll && { poll: pollOf(m.poll) }), ...(m.file && !m.deleted && { file: { name: m.file.name, size: m.file.size, type: m.file.type, sha256: m.file.sha256, ...(m.text === undefined && { only: true }) } }),
1328
+ reactions: reactions(m.reactions), pinned: m.pinned === true,
1329
+ mentions: m.mentions ?? [], mentioned: (m.mentions ?? []).includes(me), via: null, photo: null, at: m.iat })) };
1330
+ }),
1331
+ };
1332
+ // ---- step 7 (design/groups-build.md; UI-API.md "Home groups: in the chat"): reactions, edit, delete, pins, polls, files up
1333
+ // to 8 MiB in the log, the group's picture. A file comes up in chunks (the ui server takes 256 KiB a request): POST
1334
+ // /api/groups/file {group, upload, name, type, size, offset, data} until offset + its bytes = size, then it goes.
1335
+ const midArg = (b, k = 'mid') => (typeof b[k] === 'string' && /^[0-9a-f]{16}$/.test(b[k]) ? b[k] : refuse(400, 'body', `${k}: a message's mid (16 hex)`));
1336
+ const FILE_LOG = 8 * 2 ** 20, UPLOAD_CHUNK = 128 * 1024, UPLOADS = new Map();
1337
+ const sweepUploads = () => { for (const [k, u] of UPLOADS) if (nowS() - u.at > 600) UPLOADS.delete(k); };
1338
+ Object.assign(homeRoutes, {
1339
+ 'POST /api/groups/react': (b) => serial(() => homeCall(async () => {
1340
+ const g = hgid(b);
1341
+ if (typeof b['emoji'] !== 'string' || b['emoji'] === '') refuse(400, 'body', 'emoji: one emoji');
1342
+ return homeOut(await G2.react({ ...hfile(), group: g, re: midArg(b), emoji: b['emoji'], on: b['on'] !== false }), g);
1343
+ })),
1344
+ 'POST /api/groups/edit': (b) => serial(() => homeCall(async () => {
1345
+ const g = hgid(b);
1346
+ if (typeof b['text'] !== 'string' || b['text'].trim() === '') refuse(400, 'body', 'text: the new text');
1347
+ return homeOut(await G2.edit({ ...hfile(), group: g, re: midArg(b), text: b['text'] }), g);
1348
+ })),
1349
+ 'POST /api/groups/delete': (b) => serial(() => homeCall(async () => homeOut(await G2.remove({ ...hfile(), group: hgid(b), re: midArg(b) }), b['group']))),
1350
+ 'POST /api/groups/pin': (b) => serial(() => homeCall(async () => homeOut(await G2.pin({ ...hfile(), group: hgid(b), re: midArg(b), on: b['on'] !== false }), b['group']))),
1351
+ 'POST /api/groups/poll': (b) => serial(() => homeCall(async () => {
1352
+ hgid(b);
1353
+ const options = Array.isArray(b['options']) ? b['options'].map((o) => (typeof o === 'string' ? o.trim() : o)).filter((o) => o !== '') : refuse(400, 'body', 'options: 2 to 10 answers');
1354
+ return homeOut(await G2.poll({ ...hfile(), group: hgid(b), question: typeof b['question'] === 'string' ? b['question'].trim() : b['question'], options, multi: b['multi'] === true }), b['group']);
1355
+ })),
1356
+ 'POST /api/groups/vote': (b) => serial(() => homeCall(async () => {
1357
+ hgid(b);
1358
+ const choices = Array.isArray(b['choices']) && b['choices'].every((c) => Number.isSafeInteger(c)) ? b['choices'] : refuse(400, 'body', 'choices: the answers\' numbers, from 0 ([] takes the vote back)');
1359
+ return homeOut(await G2.vote({ ...hfile(), group: hgid(b), re: midArg(b), choices }), b['group']);
1360
+ })),
1361
+ 'POST /api/groups/poll_end': (b) => serial(() => homeCall(async () => homeOut(await G2.pollEnd({ ...hfile(), group: hgid(b), re: midArg(b) }), b['group']))),
1362
+ 'POST /api/groups/file': (b) => homeCall(async () => {
1363
+ sweepUploads();
1364
+ const g = hgid(b), id = typeof b['upload'] === 'string' && /^[0-9a-f]{16,32}$/.test(b['upload']) ? b['upload'] : refuse(400, 'body', 'upload: 16 to 32 hex, the same for every chunk of one file');
1365
+ const size = b['size'], off = b['offset'];
1366
+ if (!Number.isSafeInteger(size) || size < 1) refuse(400, 'body', 'size: the file\'s bytes');
1367
+ if (size > FILE_LOG) refuse(400, 'group_file_size', `a file in a group is at most 8 MiB; this one is ${(size / 2 ** 20).toFixed(1)} MiB`);
1368
+ if (typeof b['data'] !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(b['data'])) refuse(400, 'body', 'data: base64 of the next chunk');
1369
+ const chunk = unb64(b['data']);
1370
+ if (chunk.length === 0 || chunk.length > UPLOAD_CHUNK) refuse(400, 'body', `data: a chunk of 1 to ${UPLOAD_CHUNK / 1024} KiB`);
1371
+ let u = UPLOADS.get(id);
1372
+ if (off === 0) {
1373
+ if (!u && UPLOADS.size >= 4) refuse(409, 'busy', 'four files are coming up already: wait for one');
1374
+ const name = typeof b['name'] === 'string' ? b['name'] : refuse(400, 'body', 'name: the file\'s name');
1375
+ u = { group: g, name, type: typeof b['type'] === 'string' && b['type'] !== '' ? b['type'].toLowerCase() : 'application/octet-stream', bytes: new Uint8Array(size), got: 0, at: nowS(),
1376
+ text: typeof b['text'] === 'string' && b['text'].trim() !== '' ? b['text'] : undefined, re: typeof b['re'] === 'string' && b['re'] !== '' ? b['re'] : undefined };
1377
+ UPLOADS.set(id, u);
1378
+ }
1379
+ if (!u || u.group !== g || off !== u.got || u.bytes.length !== size || u.got + chunk.length > size) { UPLOADS.delete(id); refuse(409, 'upload', 'not the next chunk of this upload: start again from offset 0'); }
1380
+ u.bytes.set(chunk, u.got); u.got += chunk.length; u.at = nowS();
1381
+ if (u.got < size) return { upload: id, got: u.got, size };
1382
+ UPLOADS.delete(id);
1383
+ const r = await serial(() => G2.sendFile({ ...hfile(), group: g, name: u.name, type: u.type, bytes: u.bytes, text: u.text, re: u.re }));
1384
+ return { upload: id, got: size, size, gid: g, mid: r.mid, seq: r.seq ?? null };
1385
+ }),
1386
+ 'GET /api/groups/file': (_, q) => homeCall(async () => {
1387
+ const g = q.get('group');
1388
+ if (!isHome(g)) refuse(404, 'group_unknown', `no home group ${g} here`);
1389
+ const f = G2.fileOf({ ...hfile(), group: g, mid: midArg({ mid: q.get('mid') }) });
1390
+ return { name: f.name, type: f.type, size: f.size, sha256: f.sha256, data: b64(f.bytes) };
1391
+ }),
1392
+ // The group's picture for everyone (an admin): a picture as POST /api/picture takes one, w and h its pixels; remove: none.
1393
+ 'POST /api/groups/avatar': (b) => serial(() => homeCall(async () => {
1394
+ const g = hgid(b);
1395
+ if (b['remove'] === true) return homeOut(await G2.avatar({ ...hfile(), group: g, bytes: null }), g);
1396
+ const bytes = pictureBytes(b['type'], b['data']), side = (k) => (Number.isSafeInteger(b[k]) && b[k] >= 1 && b[k] <= 1024 ? b[k] : refuse(400, 'body', `${k}: the picture's pixels, 1 to 1024`));
1397
+ return homeOut(await G2.avatar({ ...hfile(), group: g, type: b['type'], bytes, w: side('w'), h: side('h') }), g);
1398
+ })),
1399
+ });
1400
+ // Which side a shared route takes: create with no members, join by a code, and a group that is a home group go to group2.mjs.
1401
+ const homeAsked = (key, b, q) => {
1402
+ if (key === 'POST /api/groups/create') return true; // step 8: every new group is a home group
1403
+ if (key === 'POST /api/groups/join') return b['code'] !== undefined || isHome(b['group']);
1404
+ if (key === 'GET /api/groups/history' || key === 'GET /api/groups/file') return isHome(q.get('group'));
1405
+ return isHome(b['group']);
1406
+ };
1407
+
1004
1408
  // ---- writes
1005
1409
  const contactOf = (d) => {
1006
1410
  if (typeof d !== 'string') refuse(400, 'body', 'contact: a DID');
1007
1411
  return carrier.contacts().contacts.find((x) => !x.revoked && x.did === d && !hidden(x)) ?? refuse(404, 'not_contact', `${String(d)} is not a contact`);
1008
1412
  };
1413
+ // The agent's caps with the Session card (its session), else refused: it has not said it takes these.
1414
+ const hostSession = (c) => { const h = data.host[c.did]; if (!h?.session) refuse(409, 'host_none', 'This agent has not said it takes these (an older host?)'); return h; };
1009
1415
  const cleanName = (v, what) => {
1010
1416
  if (typeof v !== 'string' || v.trim() === '' || [...v.trim()].length > NAME_MAX || /[\u0000-\u001f\u007f-\u009f]/.test(v)) refuse(400, 'body', `${what}: 1 to ${NAME_MAX} characters, no controls`);
1011
1417
  return v.trim();
@@ -1029,7 +1435,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1029
1435
  const m = hooks.me();
1030
1436
  if (v.original === m.original && m.chain.includes(v.did)) return { kind: 'me', did: m.original, name: null, words_checked: true };
1031
1437
  const c = carrier.contacts().contacts.find((x) => !x.revoked && !hidden(x) && x.did === v.original && x.chain.includes(v.did));
1032
- return c ? { kind: 'contact', did: c.did, name: c.name, words_checked: c.pair !== null && data.checked[c.did] === c.pair } : { kind: 'unknown', did: v.original, name: null, words_checked: false };
1438
+ return c ? { kind: 'contact', did: c.did, name: c.name, words_checked: c.pair !== null && (data.checked[c.did] === c.pair || Boolean(c.kin)) } : { kind: 'unknown', did: v.original, name: null, words_checked: false };
1033
1439
  }
1034
1440
  const checked = (v) => (v.valid ? { ...v, words: didWords(v.original), by: signerOf(v) } : v);
1035
1441
  // A statement in a chat (the bubble's "Signed by … · check"): checked once per message, kept for the page's life.
@@ -1074,12 +1480,19 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1074
1480
  }
1075
1481
  if (one === null) {
1076
1482
  const gs = G && groupsFile && carrier.platform.files.read(groupsFile) !== null ? G.list({ carrier, file: groupsFile }).filter((g) => grp === null || g.gid === grp) : [];
1077
- if (grp !== null && !gs.length) refuse(404, 'group_unknown', `no group ${grp} here`);
1483
+ if (grp !== null && !gs.length && !isHome(grp)) refuse(404, 'group_unknown', `no group ${grp} here`);
1078
1484
  for (const g of gs) {
1079
1485
  let items = [];
1080
1486
  try { items = G.history({ carrier, file: groupsFile, group: g.gid }); } catch {}
1081
1487
  for (const i of items) if (!i.photo && !i.voice) hit({ chat: g.gid, kind: 'group', name: g.name, n: i.mid, dir: i.mine ? 'out' : 'in', at: i.received ?? i.iat }, textOf(i.content));
1082
1488
  }
1489
+ // Home groups' chats (the groups file's history).
1490
+ const hs = homeList().filter((g) => g.status !== 'joining' && (grp === null || g.gid === grp));
1491
+ for (const g of hs) {
1492
+ let msgs = [];
1493
+ try { msgs = G2.show({ carrier, file: groups2File, group: g.gid }).messages; } catch {}
1494
+ for (const m of msgs) if (typeof m.text === 'string' && !m.deleted) hit({ chat: g.gid, kind: 'group', name: g.name, n: m.mid, dir: m.mine ? 'out' : 'in', at: m.iat }, m.text);
1495
+ }
1083
1496
  }
1084
1497
  return { hits: hits.reverse().sort((a, b) => b.at - a.at).slice(0, lim) };
1085
1498
  }
@@ -1095,6 +1508,11 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1095
1508
  const of = q.get('of') ?? '';
1096
1509
  if (of !== 'me' && !isGroup(of)) contactOf(of);
1097
1510
  const key = picOf(of), bytes = key && data.pics[key] ? store.readPicture?.(picFile(key)) ?? null : null;
1511
+ // A home group's own picture (its admins', in the log: design/groups-build.md step 7) when none is set on this device.
1512
+ if (!bytes && G2 && groups2File && isHome(of)) {
1513
+ const a = G2.avatarOf({ carrier, file: groups2File, group: of });
1514
+ if (a) return { of, type: a.type, data: b64(a.bytes), rev: `a${a.sha256.slice(0, 16)}`, local: false };
1515
+ }
1098
1516
  if (!bytes) refuse(404, 'picture_none', 'no picture: the initial or the mark shows');
1099
1517
  return { of, type: data.pics[key].type, data: b64(bytes), rev: data.pics[key].rev, local: key.startsWith('l:') };
1100
1518
  },
@@ -1120,7 +1538,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1120
1538
  if (typeof b['statement'] !== 'string' || b['statement'].length > 4 * TEXT_MAX) refuse(400, 'body', 'statement: the signed text, as it was shared');
1121
1539
  return checked(checkStatement(b['statement'], nowS()));
1122
1540
  },
1123
- // Proof of age (Me → Proof of age): what this identity's own bundle shows of its age, checked (SPEC §9): the day its
1541
+ // How old this identity is (Me → How old this identity is): what this identity's own bundle shows of its age, checked (SPEC §9): the day its
1124
1542
  // genesis names (its own word) and each attestation a world signed, with when.
1125
1543
  'GET /api/attestations': () => {
1126
1544
  const bundle = carrier.identity().bundle, r = verify(bundle, nowS());
@@ -1182,7 +1600,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1182
1600
  changed();
1183
1601
  return { cancelled: true, ...(r.unparked !== undefined && { unparked: r.unparked }), ...(r.detail && { detail: r.detail }) };
1184
1602
  }),
1185
- // A public code's requests and settings (UI-API.md "Public invite").
1603
+ // A public code's requests and settings (UI-API.md "Public code").
1186
1604
  'POST /api/public/approve': (b) => serial(async () => {
1187
1605
  if (typeof b['id'] !== 'string') refuse(400, 'body', 'id: a request\'s id (pending.public.requests[].id)');
1188
1606
  const r = await carrier.approvePublic(b['id'], { started: startedBy(b) }).catch((e) => (e.check === 'challenge_unknown' ? refuse(404, 'request', e.message) : Promise.reject(e)));
@@ -1227,7 +1645,9 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1227
1645
  }),
1228
1646
  'POST /api/rename': (b) => serial(async () => {
1229
1647
  // A name another live contact holds is refused (409 name_taken): `send <name>` would refuse both.
1230
- return carrier.rename(contactOf(b['contact']).did, cleanName(b['name'], 'name'));
1648
+ const c = contactOf(b['contact']), r = await carrier.rename(c.did, cleanName(b['name'], 'name'));
1649
+ await hostName(c, r?.name ?? b['name']);
1650
+ return r;
1231
1651
  }),
1232
1652
  'POST /api/tier': (b) => serial(async () => {
1233
1653
  const c = contactOf(b['contact']), tier = b['tier'];
@@ -1253,6 +1673,45 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1253
1673
  saveData(); changed();
1254
1674
  return { did: c.did, host: h, status: r.status };
1255
1675
  }),
1676
+ // Ask again (the agent page waiting for its settings): HOST_SET_LABEL {ask: "caps"}, which a host answers with its caps
1677
+ // (sigelo-agent-host.ts; an older host notes "Not a setting" and sends them too). My own agents only; nothing kept.
1678
+ 'POST /api/host/ask': (b) => serial(async () => {
1679
+ const c = contactOf(b['contact']);
1680
+ if (!(c.ours === true || c.tier === 'own' || c.chain?.some((d) => workerDids.has(d)))) refuse(409, 'host_not_own', 'only your own agent is asked for its settings');
1681
+ const r = await carrier.send(c.did, { ask: 'caps' }, { label: HOST_SET_LABEL });
1682
+ saveData(); changed();
1683
+ return { did: c.did, status: r.status };
1684
+ }),
1685
+ // The Session card (the header's): a folder listing, a new session (or in another folder), the login; the agent answers on the
1686
+ // same label. Only to an agent whose caps carry the session.
1687
+ 'POST /api/host/dirs': (b) => serial(async () => {
1688
+ const c = contactOf(b['contact']), h = hostSession(c), path = b['path'] ?? '', into = b['into'] ?? '';
1689
+ if (!isStr(path, 4096) || !isStr(into, 255) || /[\\/]/.test(into)) refuse(400, 'body', 'path: a folder of its computer; into: one folder name');
1690
+ const id = hexOf(6), r = await carrier.send(c.did, { path, ...(into !== '' && { into }), id }, { label: HOST_DIRS_LABEL });
1691
+ h.dirs_ask = { id, path, into, at: nowS() };
1692
+ saveData(); changed();
1693
+ return { did: c.did, id, status: r.status };
1694
+ }),
1695
+ 'POST /api/host/session': (b) => serial(async () => {
1696
+ const c = contactOf(b['contact']), h = hostSession(c), d = b['do'];
1697
+ if (d !== 'new' && d !== 'folder') refuse(400, 'body', 'do: new or folder');
1698
+ if (d === 'folder' && !(isStr(b['path'], 4096) && b['path'] !== '')) refuse(400, 'body', 'path: a folder of its computer');
1699
+ const r = await carrier.send(c.did, d === 'folder' ? { do: d, path: b['path'] } : { do: d }, { label: HOST_SESSION_LABEL });
1700
+ delete h.session_ev;
1701
+ saveData(); changed();
1702
+ return { did: c.did, host: h, status: r.status };
1703
+ }),
1704
+ 'POST /api/host/login': (b) => serial(async () => {
1705
+ const c = contactOf(b['contact']), h = hostSession(c), d = b['do'];
1706
+ if (d !== 'start' && d !== 'code' && d !== 'cancel') refuse(400, 'body', 'do: start, code or cancel');
1707
+ if (h.session.login.here === false) refuse(409, 'host_off', 'It signs in on its own computer');
1708
+ const code = d === 'code' ? String(b['code'] ?? '').replace(/\s+/g, '') : '';
1709
+ if (d === 'code' && !HOST_LOGIN_CODE.test(code)) refuse(400, 'body', 'That is not the code the sign-in page shows: one piece with a # in it');
1710
+ const r = await carrier.send(c.did, d === 'code' ? { do: d, code } : { do: d }, { label: HOST_LOGIN_LABEL });
1711
+ if (d === 'start') { delete h.login_ev; h.session.login = { ...h.session.login, state: 'signing_in' }; }
1712
+ saveData(); changed();
1713
+ return { did: c.did, host: h, status: r.status };
1714
+ }),
1256
1715
  // A contact's kind, the human's choice (Chat settings → "This is"): person, agent, desk, or null (the page decides again).
1257
1716
  'POST /api/kind': (b) => serial(async () => {
1258
1717
  const c = contactOf(b['contact']), k = b['kind'];
@@ -1263,7 +1722,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1263
1722
  }),
1264
1723
  // The keeper's settings and payment requests (UI-API.md "Keeper"): `sigelo-agent ui` answers them where the
1265
1724
  // keeper runs. Here, with hooks.computer (a computer of this operator paired to this profile, scope all;
1266
- // design/agent-wallet-page.md §4), they go to that computer, and a limit is changed by a policy-change this
1725
+ // UI-API.md "Computers"), they go to that computer, and a limit is changed by a policy-change this
1267
1726
  // page signs with its own identity: the computer carries it to its keeper and cannot alter it. Without one:
1268
1727
  // elsewhere, and the writes are refused keeper_elsewhere.
1269
1728
  'GET /api/keeper': async () => {
@@ -1330,10 +1789,13 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1330
1789
  const q = all.filter((x) => x.n < r.n && x.kind === kind && typeof x.text === 'string' && quoteHash(x.text) === m[1]).at(-1);
1331
1790
  return { n: q?.n ?? null, dir: kind, text: q ? q.text.split('\n')[0].slice(0, 120) : null };
1332
1791
  };
1792
+ // The first message new to this look (unread as state counts it: theirs, past the read mark, a call only missed),
1793
+ // read before the mark moves: the page opens the chat there ("New messages"). null: nothing was unread.
1794
+ const read = data.read[d] ?? 0, unreadFrom = all.find((r) => r.kind === 'in' && r.n > read && (!r.call || r.call.state === 'missed'))?.n ?? null;
1333
1795
  // Read: the page has shown them; a seen receipt when one is due (the header's).
1334
- if ((data.read[d] ?? 0) < seq) { data.read[d] = seq; saveData(); }
1796
+ if (read < seq) { data.read[d] = seq; saveData(); }
1335
1797
  receipt(d);
1336
- return { seq, messages: msgs.map((r) => ({ n: r.n, dir: r.kind, at: r.at, iat: r.iat ?? null, text: textOf(r.text), label: r.label ?? '', status: statusOf(r, x.seen_upto), code: r.code ?? null, detail: r.detail ?? null, link: r.link ?? null,
1798
+ return { seq, unread_from: unreadFrom, messages: msgs.map((r) => ({ n: r.n, dir: r.kind, at: r.at, iat: r.iat ?? null, text: textOf(r.text), label: r.label ?? '', status: statusOf(r, x.seen_upto), code: r.code ?? null, detail: r.detail ?? null, link: r.link ?? null,
1337
1799
  ...(RE_LABEL.test(r.label ?? '') && { re: reOf(r) }),
1338
1800
  ...(r.label === STATEMENT_LABEL && { statement: statementOf(r) }), ...(r.photo && { photo: r.photo }), ...(r.voice && { voice: r.voice }), ...(r.file && { file: r.file }), ...(r.call && { call: r.call }),
1339
1801
  ...(r.approval && { approval: r.approval }), ...(r.question && { question: r.question }) })) };
@@ -1358,7 +1820,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1358
1820
  'POST /api/notify': (b) => serial(async () => {
1359
1821
  const chat = b['chat'], on = b['on'];
1360
1822
  if (typeof on !== 'boolean') refuse(400, 'body', 'on: true or false');
1361
- const isGroup = typeof chat === 'string' && G && groupsFile && G.list({ carrier, file: groupsFile }).some((g) => g.gid === chat);
1823
+ const isGroup = typeof chat === 'string' && ((G && groupsFile && G.list({ carrier, file: groupsFile }).some((g) => g.gid === chat)) || isHome(chat));
1362
1824
  const id = isGroup ? chat : contactOf(chat).did;
1363
1825
  if (on) delete data.notify[id]; else data.notify[id] = false;
1364
1826
  saveData(); changed();
@@ -1366,11 +1828,13 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1366
1828
  }),
1367
1829
  // Settings: the relay new codes name (above). relay: a host[:port], or "" / null for relay.sigelo.ai.
1368
1830
  'GET /api/settings': () => settingsAll(),
1369
- // Any of: relay, seen_receipts, notify, new_tier, new_presence (Settings → Chats); wallet, prices, currency (Settings → Wallet); each checked before any is kept.
1831
+ // Any of: relay, seen_receipts, new_tier, new_presence (Settings → Chats); alerts (Settings → Notifications; notify, an
1832
+ // older page's switch: true → all, false → none); wallet, prices, currency (Settings → Wallet); each checked before any is kept.
1370
1833
  'POST /api/settings': (b) => serial(async () => {
1371
- const v = b['relay'], flags = ['seen_receipts', 'notify', 'new_presence', 'wallet', 'prices', 'calls', 'relay_media'].filter((k) => b[k] !== undefined), t = b['new_tier'], cur = b['currency'];
1372
- if (v === undefined && flags.length === 0 && t === undefined && cur === undefined) refuse(400, 'body', 'relay: a host[:port], or "" for the default (or seen_receipts, notify, new_tier, new_presence, wallet, prices, currency, calls, relay_media)');
1834
+ const v = b['relay'], flags = ['seen_receipts', 'notify', 'new_presence', 'wallet', 'prices', 'relay_media'].filter((k) => b[k] !== undefined), t = b['new_tier'], cur = b['currency'], al = b['alerts'];
1835
+ if (v === undefined && flags.length === 0 && t === undefined && cur === undefined && al === undefined) refuse(400, 'body', 'relay: a host[:port], or "" for the default (or seen_receipts, alerts, new_tier, new_presence, wallet, prices, currency, relay_media)');
1373
1836
  for (const k of flags) if (typeof b[k] !== 'boolean') refuse(400, 'body', `${k}: true or false`);
1837
+ if (al !== undefined && !ALERTS.includes(al)) refuse(400, 'body', 'alerts: all, people or none');
1374
1838
  if (t !== undefined && !TIER_NEW.has(t)) refuse(400, 'body', 'new_tier: own, friend or quiet');
1375
1839
  if (cur !== undefined && cur !== null && !CURRENCIES.includes(cur)) refuse(400, 'body', `currency: one of ${CURRENCIES.join(', ')}`);
1376
1840
  if (v === undefined) {} else if (v === null || v === '' || v === DEFAULT_RELAY) delete data.settings.relay;
@@ -1380,9 +1844,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1380
1844
  }
1381
1845
  else refuse(400, 'body', `relay: a host name, as relay.example.org (a port after a colon if not the usual)`);
1382
1846
  if (b['seen_receipts'] !== undefined) data.settings.seen = b['seen_receipts'];
1383
- if (b['notify'] !== undefined) data.settings.notify = b['notify'];
1847
+ if (al !== undefined || b['notify'] !== undefined) { data.settings.alerts = al ?? (b['notify'] ? 'all' : 'none'); delete data.settings.notify; }
1384
1848
  if (b['new_presence'] !== undefined) data.settings.new_presence = b['new_presence'];
1385
- if (b['calls'] !== undefined) data.settings.calls = b['calls'];
1386
1849
  if (b['relay_media'] !== undefined) data.settings.relay_media = b['relay_media'];
1387
1850
  if (t !== undefined) data.settings.new_tier = t;
1388
1851
  if (b['wallet'] !== undefined) data.settings.wallet = b['wallet'];
@@ -1451,7 +1914,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1451
1914
  changed();
1452
1915
  return pub(e);
1453
1916
  }),
1454
- // "Try now" (design/profiles.md §6): the automatic tries paused for the day; the human's goes now.
1917
+ // "Try now": the automatic tries paused for the day; the human's goes now.
1455
1918
  'POST /api/pow/try': (b) => serial(async () => {
1456
1919
  const r = await carrier.tryNow({ confirmed: b['pow_confirmed'] === true });
1457
1920
  live.powCapped = null; live.powConfirm = null; keepOffline(); changed();
@@ -1522,6 +1985,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1522
1985
  if (same) refuse(409, 'name_taken', `${name} is worker ${same[0]} already: another name`);
1523
1986
  const c = contactOfWorker(w);
1524
1987
  if (c && c.name !== name) carrier.rename(c.did, name);
1988
+ if (c) await hostName(c, name);
1525
1989
  await K.update((x) => { if (x.workers[i]) x.workers[i].name = name; });
1526
1990
  changed();
1527
1991
  return { worker: i, name };
@@ -1594,8 +2058,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1594
2058
  stun: (c) => stunOf(carrier.relay, c?.relay),
1595
2059
  turn: () => (globalThis.process?.env?.SIGELO_TURN === 'off' ? null : carrier.turnServer?.() ?? null), // SIGELO_TURN=off: STUN alone (the transfer engine reads it too)
1596
2060
  policy: relayMedia,
1597
- can: { speaker: typeof CH.speaker === 'function', mic: typeof CH.mic === 'function', ring: typeof CH.alert === 'function' },
1598
- hooks: { speaker: CH.speaker, mic: CH.mic, micSettings: CH.micSettings },
2061
+ can: { speaker: typeof CH.speaker === 'function', mic: typeof CH.mic === 'function', ring: typeof CH.alert === 'function', route: typeof CH.route === 'function' },
2062
+ hooks: { speaker: CH.speaker, mic: CH.mic, micSettings: CH.micSettings, route: CH.route },
1599
2063
  allow: (c, on) => { if (on === null) delete data.calls[c.did]; else data.calls[c.did] = on; saveData(); changed(); },
1600
2064
  allowOf: (c) => canCall(c),
1601
2065
  });
@@ -1627,6 +2091,15 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
1627
2091
  };
1628
2092
  if (transfers) Object.assign(routes, transferRoutes({ X: transfers.lib, engine: transfers.engine, host: hooks.transfers, carrier, identity: hooks.transfers.identity, serial, contactOf, changed, record, groups: G && groupsFile ? { G, file: groupsFile, list: groupsList } : null }));
1629
2093
  if (G) Object.assign(routes, groupRoutes);
2094
+ // Home groups beside them: the list adds them; a shared route goes where homeAsked says.
2095
+ if (G2 && groups2File) {
2096
+ for (const [k, f] of Object.entries(homeRoutes)) { const g1 = routes[k]; routes[k] = g1 ? (b, q) => (homeAsked(k, b, q) ? f(b, q) : g1(b, q)) : f; }
2097
+ const g1List = routes['GET /api/groups'];
2098
+ routes['GET /api/groups'] = async (b, q) => {
2099
+ const r = g1List ? await g1List(b, q) : { tier: null, groups: [], notices: data.gnotices.slice() };
2100
+ return { ...r, groups: [...r.groups, ...homeList()], home: { relay: carrier.relay } };
2101
+ };
2102
+ }
1630
2103
  // One handler for every listener: the route's answer as [status, JSON value].
1631
2104
  async function dispatch(method, url, b) {
1632
2105
  const route = routes[`${method} ${url.pathname}`];
@@ -1689,7 +2162,7 @@ function transferRoutes({ X, engine, host, carrier, identity, serial, contactOf,
1689
2162
  'POST /api/transfers/send': (b) => serial(() => call(async () => {
1690
2163
  const vo = voiceOf(b), src = vo ? await host.rec.keep(recOf(b), vo.name) : sourceOf(b), d = directOf(b), via = viaOf(b), shot = shotOf(b);
1691
2164
  if (shot) { const p = { ...shot, sha256: '0'.repeat(64), size: 0, name: 'x' }; try { checkPhoto(p); } catch (e) { e.status = 400; throw e; } }
1692
- // A group (design §10.3): one transfer per member paired with; the preview (or a line naming the file) as one group message.
2165
+ // A group: one transfer per member paired with; the preview (or a line naming the file) as one group message.
1693
2166
  if (b['group'] !== undefined) {
1694
2167
  if (!groups) refuse(404, 'route', 'no groups here');
1695
2168
  const g = groups.list().find((x) => x.gid === b['group']) ?? refuse(404, 'group_unknown', `no group ${String(b['group'])} here`);
@@ -1724,8 +2197,8 @@ function transferRoutes({ X, engine, host, carrier, identity, serial, contactOf,
1724
2197
  }
1725
2198
  return strip(r);
1726
2199
  })),
1727
- // The phone's own: a file picked (the system's picker), a photo taken (the system's camera), a file that landed opened.
1728
- // images: the picker shows pictures only (the composer's Photo). multiple (2026-11-25): several at once → { docs: [...] },
2200
+ // From the phone itself: a file picked (the system's picker), a photo taken (the system's camera), a file that landed opened.
2201
+ // images: the picker shows pictures only (the composer's Photo). multiple: several at once → { docs: [...] },
1729
2202
  // each then sent as its own transfer (POST /api/transfers/send per doc, in order).
1730
2203
  ...(docs && { 'POST /api/transfers/pick': (b) => serial(async () => {
1731
2204
  const multiple = b?.['multiple'] === true, x = await host.pick({ images: b?.['images'] === true, ...(multiple && { multiple: true }) });
@@ -1788,7 +2261,12 @@ function transferRoutes({ X, engine, host, carrier, identity, serial, contactOf,
1788
2261
  'POST /api/transfers/cancel': (b) => serial(() => call(async () => strip(await X.cancel({ carrier, identity, id: idOf(b), engine })))),
1789
2262
  'POST /api/transfers/forget': (b) => serial(() => call(async () => strip(X.forget({ carrier, identity, id: idOf(b), engine })))),
1790
2263
  'POST /api/transfers/direct': (b) => serial(() => call(async () => {
1791
- if (typeof b['on'] !== 'boolean') refuse(400, 'body', 'on: true or false');
2264
+ // A contact's route (Settings → Privacy's choice, per contact): direct, relay, tor, or null (the default again).
2265
+ if (b['route'] !== undefined) {
2266
+ if (b['route'] !== null && !['direct', 'relay', 'tor'].includes(b['route'])) refuse(400, 'body', 'route: direct, relay, tor or null (the default)');
2267
+ return X.setRoute({ carrier, identity, contact: contactOf(b['contact']).did, route: b['route'] });
2268
+ }
2269
+ if (typeof b['on'] !== 'boolean') refuse(400, 'body', 'on: true or false (or route)');
1792
2270
  return X.setDirect({ carrier, identity, contact: contactOf(b['contact']).did, on: b['on'] });
1793
2271
  })),
1794
2272
  'GET /api/transfers/settings': () => settings(),
@@ -1798,6 +2276,7 @@ function transferRoutes({ X, engine, host, carrier, identity, serial, contactOf,
1798
2276
  if (b['prefer'] !== undefined) { if (b['prefer'] !== 'fast' && b['prefer'] !== 'private') refuse(400, 'body', 'prefer: fast or private'); patch.prefer = b['prefer']; }
1799
2277
  if (b['auto_mb'] !== undefined) { if (typeof b['auto_mb'] !== 'number' || !Number.isFinite(b['auto_mb']) || b['auto_mb'] < 0) refuse(400, 'body', 'auto_mb: a size in MB, 0: always ask'); patch.auto_mb = b['auto_mb']; }
1800
2278
  if (b['keep_location'] !== undefined) { if (typeof b['keep_location'] !== 'boolean') refuse(400, 'body', 'keep_location: true or false'); patch.keep_location = b['keep_location']; }
2279
+ if (b['route'] !== undefined) { if (b['route'] !== null && !['direct', 'relay', 'tor'].includes(b['route'])) refuse(400, 'body', 'route: direct, relay, tor or null'); patch.route = b['route']; }
1801
2280
  X.settings({ identity, patch });
1802
2281
  return settings();
1803
2282
  })),