sigelo-contact 0.1.21 → 0.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/GROUPS-REFERENCE.md +165 -0
- package/GROUPS.md +53 -0
- package/LICENSE +235 -21
- package/README.md +4 -5
- package/call.mjs +89 -28
- package/carrier.mjs +230 -51
- package/control.mjs +2 -2
- package/create.mjs +2 -2
- package/device.mjs +2 -2
- package/enrol.mjs +2 -2
- package/envelope.mjs +6 -6
- package/file.mjs +2 -2
- package/fixtures/carrier-v0.json +1 -1
- package/fixtures/envelope-v0.json +1 -1
- package/fixtures/group-v2.json +2999 -0
- package/gen-carrier.mjs +2 -2
- package/gen-device.mjs +1 -1
- package/gen-envelope.mjs +2 -2
- package/gen-group2.mjs +291 -0
- package/gen-invite.mjs +2 -2
- package/gen-short.mjs +1 -1
- package/group.mjs +116 -17
- package/group2.mjs +1534 -0
- package/home-wire.mjs +812 -0
- package/invite.mjs +3 -3
- package/kdf.mjs +2 -2
- package/kin.mjs +62 -0
- package/link.mjs +6 -6
- package/package.json +25 -8
- package/page.mjs +507 -57
- package/photo.mjs +2 -2
- package/platform-node.mjs +6 -6
- package/prekeys.mjs +3 -3
- package/public.mjs +2 -2
- package/qr-decode.mjs +1 -1
- package/qr.mjs +2 -2
- package/relays.mjs +2 -2
- package/restore.mjs +2 -2
- package/rtc-web.mjs +3 -3
- package/short.mjs +2 -2
- package/store.mjs +22 -9
- package/test-carrier.mjs +32 -11
- package/test-device.mjs +3 -3
- package/test-enrol.mjs +9 -4
- package/test-envelope.mjs +2 -2
- package/test-file.mjs +2 -2
- package/test-group-move.mjs +225 -0
- package/test-group.mjs +1 -1
- package/test-group2.mjs +202 -0
- package/test-home.mjs +225 -0
- package/test-invite.mjs +1 -1
- package/test-link.mjs +3 -3
- package/test-platform.mjs +2 -2
- package/test-presence.mjs +2 -2
- package/test-push.mjs +5 -5
- package/test-relay-lane.mjs +3 -3
- package/test-short.mjs +1 -1
- package/test-tier.mjs +8 -2
- package/test-transfer-web.mjs +7 -7
- package/test-transfer.mjs +6 -6
- package/test-voice.mjs +2 -2
- package/test-ws.mjs +1 -1
- package/transfer-engine.mjs +6 -6
- package/transfer-node.mjs +5 -5
- package/transfer-web.mjs +3 -3
- package/transfer.mjs +8 -8
- package/voice-web.mjs +2 -2
- package/voice.mjs +7 -3
- package/words-lock.mjs +2 -2
package/group2.mjs
ADDED
|
@@ -0,0 +1,1534 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
// Home groups, the member's side: contract sigelo-group/2 (GROUPS.md, design/groups-build.md §2, §4).
|
|
3
|
+
// The wire is home-wire.mjs (pure); the home relay's side is relay/home.mjs; the session at a home
|
|
4
|
+
// relay is carrier.mjs home(). Here: the group state machine (the roster in seq order, roles,
|
|
5
|
+
// renewals, the history policy, links and doors, the join and its answer) and the verbs.
|
|
6
|
+
//
|
|
7
|
+
// create({ carrier, file, name, home, kind, selfName, brake, members }) → { group, invited? } a group at home (default: this
|
|
8
|
+
// agent's relay); members: contacts invited at once (add)
|
|
9
|
+
// link({ …, group, ttl, cap, approve }) → { code: GRP-…, link, invite, words, exp, id } a door, a link body, a parked GRP code
|
|
10
|
+
// unlink({ …, group, id })
|
|
11
|
+
// join({ carrier, file, code, with, home, name, kind }) → { group, status: 'waiting' } a GRP code, its link, a long invite, or a
|
|
12
|
+
// supergroup's name@relay (private: with = a code or link an admin gave)
|
|
13
|
+
// name({ …, group, name, public, listed }) → { address, link, exp, members } the owner binds its slot's name (a signed card)
|
|
14
|
+
// card({ carrier, address }) → the checked card; listed({ carrier, relay, after }) → [{ name, about, address }] supergroups
|
|
15
|
+
// sync({ carrier, file, group? }) → { items, groups } every live group at its home: the answer, the log, door
|
|
16
|
+
// requests (approve auto at once), renewal duty; items: new messages, taken
|
|
17
|
+
// requests / approve / refuse({ …, group, id }) door requests and history asks waiting for an admin
|
|
18
|
+
// send / react / edit / remove (delete) / pin / poll / vote / pollEnd / kick / unbar / role / set / leave / renew /
|
|
19
|
+
// historyAsk / end → { group, mid, seq }
|
|
20
|
+
// list({ carrier, file }), show({ carrier, file, group }), unread({ file, pick }), homes({ carrier, file }) → [relay]
|
|
21
|
+
// events({ carrier, file, group, since, limit }) → { events } the event history (owner, admins: all; moderators: kicks,
|
|
22
|
+
// deletes, pins; else group_role): eventsOf(G, me) over the file, no relay
|
|
23
|
+
// moderate({ carrier, file, group, on, rules, kicks, deletes }) the operator's rules for its model (local), the owner's caps (settings.mod)
|
|
24
|
+
// add({ carrier, file, group, members, moved_from?, local }) → { gid, code, copies } invites contacts over their pairings (§1.6):
|
|
25
|
+
// the group's direct link (30 days, an admin approves), its invite as the last line of a
|
|
26
|
+
// text an older app shows; the inviter's app lets those it invited in at once (expect)
|
|
27
|
+
// invited({ carrier, file, invite, from, text }) → filed as status invited (group.mjs handle, on an invite over a pairing);
|
|
28
|
+
// join({ code: its gid }) joins by it, drop() declines it
|
|
29
|
+
// model: true, a model asks (MCP, every call): kick / remove never an admin's or a moderator's; role / set / link / unlink /
|
|
30
|
+
// handover / end / name / avatar / moderate refused (group_person: people administer). A moderator's or agent admin's kicks
|
|
31
|
+
// and deletes are capped and counted per UTC day on every path, model or not (modGate, settings.mod)
|
|
32
|
+
//
|
|
33
|
+
// The file (sigelo-groups/2, 0600, beside the identity: x.json → x.groups2.json, under its lock):
|
|
34
|
+
// { v, groups: { gid: G }, unread: [items] }, G = { gid, name, home, topic, owner, status (invited | joining | member |
|
|
35
|
+
// left | removed | closed), invite and invited (an invite over a pairing, not used yet), moved_from (the sigelo-group/1 gid it
|
|
36
|
+
// replaces), direct (the link of invites over pairings) and expect ({ original: { link, until } }: invited, let in at once), seq (the last log row handled), epoch (the one this member writes under),
|
|
37
|
+
// epochs: { e: { E?, W, HK } }, V? (admins), L, gkey (its X-Wing seed), mine: { n, ck }, chains: { e: { hint:
|
|
38
|
+
// { n, ck, skipped } } }, keys: { seq: mk } (a welcome's), roster: { original: { current, name, kind, role,
|
|
39
|
+
// gkey, chain, since, L? } }, settings, barred, links, requests, asks, history, pins, seen, sent, run,
|
|
40
|
+
// roster_keys (the message keys of roster rows, for the next welcome), dropped: { check: n }, acts (kicks,
|
|
41
|
+
// deletes and pins, by whom), events (the event history: each roster body, renewal, edit, delete and pin applied, a
|
|
42
|
+
// refusal of this admin's, newest EVENTS_MAX; no text), moderate (the operator's: { on, rules }), mod_day (this member's count here a UTC day) }; mod (its count across groups)
|
|
43
|
+
// Keys are base64url. Message keys are deleted once used (§2.2), except roster rows' (a welcome hands them on).
|
|
44
|
+
import { ed25519 } from '@noble/curves/ed25519.js';
|
|
45
|
+
import { sha256 } from '@noble/hashes/sha2.js';
|
|
46
|
+
import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
47
|
+
import { canonicalize, did as didOf, verify, verifySig } from 'sigelo';
|
|
48
|
+
import * as W from './home-wire.mjs';
|
|
49
|
+
import { MsgError, checkNow, fail, signAs, step } from './kdf.mjs';
|
|
50
|
+
import { didWords, makeShort, relayTag } from './short.mjs';
|
|
51
|
+
import { GROUP_SEND } from './carrier.mjs';
|
|
52
|
+
import { platform as nodePlatform } from './platform-node.mjs';
|
|
53
|
+
|
|
54
|
+
export const FILE_V = 'sigelo-groups/2', LABEL = W.GROUP2_V, NOT_OPERATOR = 'not your operator';
|
|
55
|
+
export const groups2Path = (identityFile) => identityFile.replace(/\.json$/, '') + '.groups2.json';
|
|
56
|
+
const HISTORY_MAX = 500, UNREAD_MAX = 1000, SEEN_MAX = 4096, ROSTER_KEYS_MAX = 2000, JUMP_MAX = 4096, ACTS_MAX = 100, EVENTS_MAX = 500;
|
|
57
|
+
// Door requests kept for an admin: a flood through a link (its cap a day, 16 links) never grows the file past this; the oldest go.
|
|
58
|
+
export const REQUESTS_MAX = 200;
|
|
59
|
+
// Bodies that change the roster, settings or links: their message keys go to a joiner (welcome keys).
|
|
60
|
+
const ROSTER_TYPS = new Set(['create', 'add', 'leave', 'kick', 'unbar', 'role', 'kind', 'profile', 'handover', 'settings', 'link', 'unlink', 'moved', 'end']);
|
|
61
|
+
// Bodies sent under the admin credential when this member holds the vault.
|
|
62
|
+
const ADMIN_TYPS = new Set(['create', 'add', 'welcome', 'epoch', 'link', 'unlink', 'vault', 'history', 'settings', 'role', 'kick', 'unbar', 'kind', 'handover', 'moved', 'end']);
|
|
63
|
+
const OPERATOR_CTX = 'sigelo-relay/operator';
|
|
64
|
+
// How long a catch-up waits with nothing arriving, and for its own entry to come back (ms).
|
|
65
|
+
const QUIET_MS = 1500, ECHO_MS = 15000;
|
|
66
|
+
|
|
67
|
+
const b64 = W.b64u, unb = (s) => W.unb64u(s) ?? fail('group_file', 'a key in the groups file is not base64url');
|
|
68
|
+
const u32 = (n) => { const b = new Uint8Array(4); new DataView(b.buffer).setUint32(0, n); return b; };
|
|
69
|
+
const hashOf = (bytes) => W.hex(sha256(bytes)).slice(0, 32);
|
|
70
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
71
|
+
const isAdmin = (role) => role === 'owner' || role === 'admin';
|
|
72
|
+
const DAY = 86400;
|
|
73
|
+
|
|
74
|
+
// ---------------------------------------------------------------- the file
|
|
75
|
+
const textOf = (b) => new TextDecoder().decode(b);
|
|
76
|
+
const platformOf = (carrier) => carrier?.platform ?? nodePlatform;
|
|
77
|
+
function readFile(file, platform) {
|
|
78
|
+
return platform.transact(file, () => {
|
|
79
|
+
const raw = platform.files.read(file);
|
|
80
|
+
if (raw === null) return { v: FILE_V, groups: {}, unread: [] };
|
|
81
|
+
let s;
|
|
82
|
+
try { s = JSON.parse(textOf(raw)); } catch (e) { fail('group_file', `${file} does not parse (${e.message})`); }
|
|
83
|
+
if (s?.v !== FILE_V || typeof s.groups !== 'object' || !Array.isArray(s.unread)) fail('group_file', `${file} is not a ${FILE_V} file`);
|
|
84
|
+
return s;
|
|
85
|
+
}, 'sigelo');
|
|
86
|
+
}
|
|
87
|
+
function writeFile(file, s, platform) {
|
|
88
|
+
platform.transact(file, () => platform.files.write(file, new TextEncoder().encode(JSON.stringify(s, null, 1))), 'sigelo');
|
|
89
|
+
}
|
|
90
|
+
/** The groups file's state, and save() to write it (after every step that matters: a crash loses little). */
|
|
91
|
+
function open(o) {
|
|
92
|
+
const platform = platformOf(o.carrier), s = readFile(o.file, platform);
|
|
93
|
+
return { s, save: () => writeFile(o.file, s, platform) };
|
|
94
|
+
}
|
|
95
|
+
function pick(s, group, live = true) {
|
|
96
|
+
if (typeof group !== 'string' || group === '') fail('group_unknown', 'name a home group, by name or gid');
|
|
97
|
+
if (s.groups[group]) return s.groups[group];
|
|
98
|
+
const named = Object.values(s.groups).filter((g) => g.name === group.trim() && (!live || ['member', 'joining', 'invited'].includes(g.status)));
|
|
99
|
+
if (named.length > 1) fail('group_name', `${named.length} home groups are called ${JSON.stringify(group)}: use the gid`);
|
|
100
|
+
return named[0] ?? fail('group_unknown', `no home group ${JSON.stringify(group)} here (sigelo-agent group list)`);
|
|
101
|
+
}
|
|
102
|
+
/** Is `group` one of this file's home groups? (the CLI routes a verb to sigelo-group/1 otherwise) */
|
|
103
|
+
export function has({ carrier, file, group }) {
|
|
104
|
+
try { pick(readFile(file, platformOf(carrier)), group, false); return true; } catch { return false; }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ---------------------------------------------------------------- this agent
|
|
108
|
+
function meOf(carrier, now) {
|
|
109
|
+
const id = carrier.identity(), { bundle } = id;
|
|
110
|
+
const r = verify({ ...bundle, bindings: [] }, now), operators = new Set();
|
|
111
|
+
for (const [iss, bodies] of Object.entries(r.attestations ?? {})) if (!r.chain.includes(iss) && bodies.some((b) => b.ctx === OPERATOR_CTX)) operators.add(iss);
|
|
112
|
+
const genesis = [bundle.genesis, ...bundle.rotations.map((x) => x.next_genesis)].at(-1);
|
|
113
|
+
return { original: r.chain[0], current: r.did, operators, own: { genesis: bundle.genesis, rotations: bundle.rotations }, genesis, sign: (body) => signAs(id, body) };
|
|
114
|
+
}
|
|
115
|
+
const nowOf = (carrier) => checkNow(carrier.clock());
|
|
116
|
+
|
|
117
|
+
// ---------------------------------------------------------------- keys of a group
|
|
118
|
+
const writeKey = (seed) => ({ seed, pub: ed25519.getPublicKey(seed) });
|
|
119
|
+
function installEpoch(G, e, E) {
|
|
120
|
+
const k = W.epochKeys(E, G.gid);
|
|
121
|
+
G.epochs[e] = { E: b64(E), W: b64(k.W.seed), HK: b64(k.HK) };
|
|
122
|
+
}
|
|
123
|
+
const hintOf = (G, e, did) => W.hex(W.senderHint(unb(G.epochs[e].HK), did));
|
|
124
|
+
/** A sender's chain record in epoch e by its hint: kept, else from E (every member of the roster and the owner). */
|
|
125
|
+
function chainRec(G, e, hint) {
|
|
126
|
+
const c = (G.chains[e] ??= {});
|
|
127
|
+
if (c[hint]) return c[hint];
|
|
128
|
+
const ek = G.epochs[e];
|
|
129
|
+
if (!ek?.E) return null;
|
|
130
|
+
for (const did of new Set([...Object.keys(G.roster), G.owner])) {
|
|
131
|
+
if (did && hintOf(G, e, did) === hint) return (c[hint] = { n: 0, ck: b64(W.chainStart(unb(ek.E), G.gid, did)), skipped: {} });
|
|
132
|
+
}
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
/** The message key at counter n of a chain record (64 skipped keys kept, kdf.mjs step), or null: before this member's start. */
|
|
136
|
+
function takeKey(rec, n) {
|
|
137
|
+
if (n < rec.n) { const k = rec.skipped[n]; if (k === undefined) return null; delete rec.skipped[n]; return unb(k); }
|
|
138
|
+
if (n - rec.n > JUMP_MAX) fail('group_order', `a counter ${n - rec.n} ahead of the last one read`);
|
|
139
|
+
let ck = unb(rec.ck);
|
|
140
|
+
for (let i = rec.n; i < n; i++) { const r = step(ck); rec.skipped[i] = b64(r.mk); ck = r.next; }
|
|
141
|
+
const ks = Object.keys(rec.skipped);
|
|
142
|
+
if (ks.length > W.WINDOW) for (const k of ks.map(Number).sort((a, b) => a - b).slice(0, ks.length - W.WINDOW)) delete rec.skipped[k];
|
|
143
|
+
const r = step(ck);
|
|
144
|
+
rec.ck = b64(r.next); rec.n = n + 1;
|
|
145
|
+
return r.mk;
|
|
146
|
+
}
|
|
147
|
+
function nextMine(G) {
|
|
148
|
+
const ck = unb(G.mine.ck), n = G.mine.n, r = step(ck);
|
|
149
|
+
G.mine = { n: n + 1, ck: b64(r.next) };
|
|
150
|
+
return { n, mk: r.mk };
|
|
151
|
+
}
|
|
152
|
+
const gkeyPair = (G) => W.boxKey(unb(G.gkey));
|
|
153
|
+
const roleOf = (G, did) => G.roster[did]?.role ?? null;
|
|
154
|
+
function byCurrent(G, did) {
|
|
155
|
+
for (const [o, m] of Object.entries(G.roster)) if (m.current === did || o === did) return o;
|
|
156
|
+
return did === G.owner ? did : null;
|
|
157
|
+
}
|
|
158
|
+
function count(G, check) { G.dropped[check] = (G.dropped[check] ?? 0) + 1; }
|
|
159
|
+
// What only a relay hiding or renumbering rows explains (step 11, design/groups-build.md §8): at, a row whose sender says it had
|
|
160
|
+
// read this seq or a later one (an honest sender's at is below the seq the relay gives its row); own, this member's entry the
|
|
161
|
+
// relay took (PUBACK) and never sent back though a later open read the log to its end. Counted, shown (summary suspect).
|
|
162
|
+
function suspect(G, what) { (G.suspect ??= {})[what] = (G.suspect[what] ?? 0) + 1; }
|
|
163
|
+
function fresh(fields) {
|
|
164
|
+
return { status: 'joining', seq: 0, epoch: 0, epochs: {}, chains: {}, keys: {}, roster: {}, settings: { ...W.DEFAULTS }, barred: [], links: {}, requests: {}, asks: {},
|
|
165
|
+
history: [], pins: [], seen: {}, sent: {}, run: 0, roster_keys: [], dropped: {}, renew_due: false, ...fields };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ---------------------------------------------------------------- reading the log
|
|
169
|
+
/** One delivered row (lane, seq, bytes) into G. ctx: { me, now, auto: [] }. MsgError: dropped and counted by name. */
|
|
170
|
+
function readRow(G, ctx, row) {
|
|
171
|
+
if (row.seq <= G.seq) return;
|
|
172
|
+
try {
|
|
173
|
+
if (row.lane === 1) readDoor(G, ctx, row);
|
|
174
|
+
else readEntry(G, ctx, row);
|
|
175
|
+
} catch (e) {
|
|
176
|
+
if (!(e instanceof MsgError)) throw e;
|
|
177
|
+
count(G, e.check);
|
|
178
|
+
} finally { G.seq = Math.max(G.seq, row.seq); }
|
|
179
|
+
}
|
|
180
|
+
function readEntry(G, ctx, { seq, bytes }) {
|
|
181
|
+
const head = W.parseEntry(bytes), h = hashOf(bytes);
|
|
182
|
+
// Its own entry, back from the relay: applied now, with the key it was sealed under.
|
|
183
|
+
const own = G.sent[h];
|
|
184
|
+
if (own) {
|
|
185
|
+
delete G.sent[h];
|
|
186
|
+
const content = W.openEntry(bytes, G.topic, unb(own.mk));
|
|
187
|
+
own.seq = seq;
|
|
188
|
+
ctx.echo?.set(content.body.mid, { seq, mk: own.mk });
|
|
189
|
+
return apply(G, ctx, seq, head, { original: ctx.me.original, current: ctx.me.current }, content, unb(own.mk));
|
|
190
|
+
}
|
|
191
|
+
let mk = G.keys[seq] ? unb(G.keys[seq]) : null, hint = null;
|
|
192
|
+
if (mk) delete G.keys[seq];
|
|
193
|
+
else {
|
|
194
|
+
const ek = G.epochs[head.epoch];
|
|
195
|
+
if (!ek) return count(G, 'group_history'); // an epoch this member holds no key for: before it joined, or after it left
|
|
196
|
+
const hd = W.openHeader(bytes, G.topic, unb(ek.HK));
|
|
197
|
+
hint = W.hex(hd.hint);
|
|
198
|
+
const rec = chainRec(G, head.epoch, hint) ?? fail('group_member', 'a sender this member does not know (its hint)');
|
|
199
|
+
mk = takeKey(rec, hd.n);
|
|
200
|
+
if (mk === null) return count(G, 'group_history'); // before this member's start in the epoch
|
|
201
|
+
}
|
|
202
|
+
const content = W.openEntry(bytes, G.topic, mk), b = content.body;
|
|
203
|
+
if (b.typ === 'welcome' && b.to === ctx.me.original && G.welcomed === seq) { G.seen[b.mid] = b.iat; return; } // opened before the rest (sync)
|
|
204
|
+
let who;
|
|
205
|
+
if (b.typ === 'create') {
|
|
206
|
+
if (Object.keys(G.roster).length > 0) fail('group_order', 'a second create');
|
|
207
|
+
who = W.verifyCreate(content, content.chain ?? fail('group_sig', 'a create carries its creator\'s chain'), ctx.now);
|
|
208
|
+
if (b.gid !== G.gid) fail('group_message', 'a create for another group');
|
|
209
|
+
} else {
|
|
210
|
+
let o = byCurrent(G, b.from);
|
|
211
|
+
if (o === null && content.chain) { const c = W.chainKey(content.chain, ctx.now); if (G.roster[c.original]) o = c.original; }
|
|
212
|
+
if (o === null || !G.roster[o]) fail('group_member', `${b.from} is not a member`);
|
|
213
|
+
who = W.verifyContent(content, content.chain ?? G.roster[o].chain, ctx.now);
|
|
214
|
+
if (who.original !== o) fail('group_sig', 'a chain that is not the member\'s');
|
|
215
|
+
if (content.chain) G.roster[o].chain = content.chain;
|
|
216
|
+
G.roster[o].current = who.current;
|
|
217
|
+
if (hint !== null && hintOf(G, head.epoch, o) !== hint) fail('group_sig', 'sent under another member\'s chain');
|
|
218
|
+
}
|
|
219
|
+
return apply(G, ctx, seq, head, who, content, mk);
|
|
220
|
+
}
|
|
221
|
+
// A row's checks and effect. who: {original, current}, its signature checked (or this agent's own).
|
|
222
|
+
function apply(G, ctx, seq, head, who, content, mk) {
|
|
223
|
+
const b = content.body, me = ctx.me, now = ctx.now;
|
|
224
|
+
if (b.gid !== G.gid) fail('group_message', 'a body for another group');
|
|
225
|
+
if (G.seen[b.mid] !== undefined) fail('group_message', 'a mid seen already');
|
|
226
|
+
W.checkFresh(b, now);
|
|
227
|
+
if (b.typ !== 'create' && b.at >= seq) suspect(G, 'at');
|
|
228
|
+
const role = b.typ === 'create' ? null : roleOf(G, who.original);
|
|
229
|
+
const named = b.member ?? b.to;
|
|
230
|
+
const target = typeof named === 'string' && G.roster[named] ? { did: named, role: G.roster[named].role, kind: G.roster[named].kind } : null;
|
|
231
|
+
const item = typeof b.re === 'string' ? G.history.find((x) => x.mid === b.re) : undefined;
|
|
232
|
+
W.authorize(b, { role, self: who.original, target, author: item?.from ?? null, channel: G.settings.channel, agents: G.settings.agents, slot: head.slot });
|
|
233
|
+
const sender = G.roster[who.original];
|
|
234
|
+
// The picture's blob (keep slot 9) too: a joiner reads it with the roster (step 7).
|
|
235
|
+
if (ROSTER_TYPS.has(b.typ) || (b.typ === 'blob' && head.slot === W.KEEP_AVATAR)) { G.roster_keys.push({ seq, key: b64(mk) }); if (G.roster_keys.length > ROSTER_KEYS_MAX) G.roster_keys.splice(0, G.roster_keys.length - ROSTER_KEYS_MAX); }
|
|
236
|
+
const mine = who.original === me.original;
|
|
237
|
+
const pre = EVENT_TYPS.has(b.typ) ? eventPre(G, b, who, item) : null;
|
|
238
|
+
switch (b.typ) {
|
|
239
|
+
case 'create':
|
|
240
|
+
if (b.home !== G.home) fail('group_message', `a create for home ${b.home}, not ${G.home}`);
|
|
241
|
+
G.owner = who.original; G.name = b.name; G.settings = { ...b.settings };
|
|
242
|
+
G.roster[who.original] = { current: who.current, name: 'owner', kind: 'human', role: 'owner', gkey: null, chain: content.chain, since: seq };
|
|
243
|
+
break;
|
|
244
|
+
case 'profile':
|
|
245
|
+
if (b.name !== undefined) sender.name = b.name;
|
|
246
|
+
if (b.gkey !== undefined) sender.gkey = b.gkey;
|
|
247
|
+
break;
|
|
248
|
+
case 'add': {
|
|
249
|
+
const adminChain = (G.roster[who.original] ?? {}).chain;
|
|
250
|
+
if (!mine) W.verifyAdd(content, adminChain, now);
|
|
251
|
+
const d = b.member.did;
|
|
252
|
+
if (G.barred.includes(d)) fail('group_member', 'an add of a barred member');
|
|
253
|
+
if (G.roster[d]) fail('group_member', 'an add of a member');
|
|
254
|
+
const j = b.request.body;
|
|
255
|
+
G.roster[d] = { current: b.member.current, name: b.member.name, kind: b.member.kind, role: 'member', gkey: j.gkey, chain: j.chain, since: seq };
|
|
256
|
+
const e = head.epoch, c = (G.chains[e] ??= {}), hint = G.epochs[e] ? hintOf(G, e, d) : null;
|
|
257
|
+
if (d === me.original) { G.status = 'member'; G.joined = seq; }
|
|
258
|
+
else if (hint !== null && !c[hint]) c[hint] = { n: 0, ck: b64(G.epochs[e].E ? W.chainStart(unb(G.epochs[e].E), G.gid, d) : W.openChainStart(unb(G.epochs[e].HK), G.gid, d, b.ck)), skipped: {} };
|
|
259
|
+
if (G.V) G.roster[d].L = b64(W.openForAdmins(unb(G.V), G.gid, d, b.vault));
|
|
260
|
+
for (const [id, r] of Object.entries(G.requests)) if (r.original === d) delete G.requests[id];
|
|
261
|
+
if (G.expect) delete G.expect[d];
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
case 'leave': {
|
|
265
|
+
const was = roleOf(G, who.original);
|
|
266
|
+
delete G.roster[who.original];
|
|
267
|
+
if (mine) G.status = 'left';
|
|
268
|
+
else if (isAdmin(roleOf(G, me.original))) { G.renew_due = true; if (isAdmin(was)) G.renew_full = true; }
|
|
269
|
+
break;
|
|
270
|
+
}
|
|
271
|
+
case 'kick':
|
|
272
|
+
act(G, seq, who, b, { member: b.member, name: G.roster[b.member]?.name ?? null, bar: b.bar, ...(b.reason && { reason: b.reason }) });
|
|
273
|
+
// An admin out (kicked, left, made member or moderator) knew V and every member's L: the next renewal is a full one.
|
|
274
|
+
if (isAdmin(G.roster[b.member]?.role) && isAdmin(roleOf(G, me.original))) G.renew_full = true;
|
|
275
|
+
delete G.roster[b.member];
|
|
276
|
+
if (b.bar && !G.barred.includes(b.member)) G.barred.push(b.member);
|
|
277
|
+
if (b.member === me.original) G.status = 'removed';
|
|
278
|
+
else if (isAdmin(roleOf(G, me.original))) { G.renew_due = true; forgetLater(G, b.member); }
|
|
279
|
+
break;
|
|
280
|
+
case 'unbar': G.barred = G.barred.filter((d) => d !== b.member); break;
|
|
281
|
+
case 'role':
|
|
282
|
+
if (isAdmin(G.roster[b.member].role) && !isAdmin(b.role) && isAdmin(roleOf(G, me.original)) && b.member !== me.original) { G.renew_due = true; G.renew_full = true; }
|
|
283
|
+
G.roster[b.member].role = b.role;
|
|
284
|
+
if (b.member === me.original && !isAdmin(b.role)) forgetAdmin(G);
|
|
285
|
+
break;
|
|
286
|
+
case 'kind': G.roster[b.member].kind = b.kind; break;
|
|
287
|
+
case 'vault':
|
|
288
|
+
if (b.to === me.original) {
|
|
289
|
+
const box = W.openBox(b, gkeyPair(G).secretKey);
|
|
290
|
+
G.V = box.V;
|
|
291
|
+
for (const [d, k] of Object.entries(box.L)) if (G.roster[d]) G.roster[d].L = k;
|
|
292
|
+
takeDoors(G, box.D ?? []);
|
|
293
|
+
}
|
|
294
|
+
break;
|
|
295
|
+
case 'settings': Object.assign(G.settings, b.settings); if (b.settings.name) G.name = b.settings.name; break;
|
|
296
|
+
case 'link':
|
|
297
|
+
G.links[b.id] = { door: b.door, door_key: b.door_key, exp: b.exp, cap: b.cap, approve: b.approve, ...(G.links[b.id]?.code && { code: G.links[b.id].code, code_hash: G.links[b.id].code_hash }),
|
|
298
|
+
...(G.V ? { seed: b64(W.openDoorSeed(unb(G.V), G.gid, b.id, b.box)) } : { box: b.box }) };
|
|
299
|
+
break;
|
|
300
|
+
case 'unlink': delete G.links[b.id]; break;
|
|
301
|
+
case 'epoch': letters(G, ctx, b); break;
|
|
302
|
+
case 'handover':
|
|
303
|
+
G.roster[G.owner].role = 'admin';
|
|
304
|
+
G.roster[b.to].role = 'owner';
|
|
305
|
+
G.owner = b.to;
|
|
306
|
+
if (b.to === me.original) G.handover_due = { op: { body: b, sig: content.sig }, chain: G.roster[who.original].chain };
|
|
307
|
+
break;
|
|
308
|
+
case 'moved': case 'end': G.status = 'closed'; G.closed = b.typ; break;
|
|
309
|
+
case 'welcome': break; // to another joiner; this member's own was opened first (sync)
|
|
310
|
+
case 'history_ask': if (!mine && isAdmin(roleOf(G, me.original))) G.asks[String(seq)] = { seq, from: who.original, name: sender.name, at: now }; break;
|
|
311
|
+
case 'history':
|
|
312
|
+
if (b.to === me.original) {
|
|
313
|
+
const box = W.openBox(b, gkeyPair(G).secretKey);
|
|
314
|
+
for (const x of box.secrets) if (!G.epochs[x.epoch]?.E) installEpoch(G, x.epoch, unb(x.E));
|
|
315
|
+
G.reread = true;
|
|
316
|
+
}
|
|
317
|
+
break;
|
|
318
|
+
case 'msg': case 'poll': {
|
|
319
|
+
const agent = sender.kind === 'agent';
|
|
320
|
+
if (agent && G.settings.brake !== 'off' && G.run >= G.settings.brake && !mine) fail('group_quiet', `${G.run} agent messages in a row, the group's brake`);
|
|
321
|
+
G.run = agent ? G.run + 1 : 0;
|
|
322
|
+
const it = { mid: b.mid, seq, typ: b.typ, from: who.original, current: who.current, name: sender.name, kind: sender.kind, role: sender.role, iat: b.iat,
|
|
323
|
+
...(b.text !== undefined && { text: b.text }), ...(b.re !== undefined && { re: b.re }), ...(b.mentions && { mentions: b.mentions }), ...(b.file && { file: b.file }),
|
|
324
|
+
...(b.typ === 'poll' && { poll: { question: b.question, options: b.options, multi: b.multi, votes: {}, closed: false } }), reactions: {} };
|
|
325
|
+
G.history.push(it);
|
|
326
|
+
if (G.history.length > HISTORY_MAX) G.history.splice(0, G.history.length - HISTORY_MAX);
|
|
327
|
+
if (!mine) ctx.items.push(itemOf(G, it, me));
|
|
328
|
+
break;
|
|
329
|
+
}
|
|
330
|
+
// The inbox (§4.4): an edit updates the item still waiting, else comes again marked edited; a deleted one
|
|
331
|
+
// waiting is taken back; a reaction to this member's own message is a count; a poll's end carries its tallies.
|
|
332
|
+
case 'edit':
|
|
333
|
+
if (item) {
|
|
334
|
+
item.text = b.text; item.edited = true;
|
|
335
|
+
if (!mine && item.typ === 'msg') { const p = pending(G, ctx, item.mid, 'msg'); if (p) p.l[p.i] = { ...p.l[p.i], content: b.text, edited: true }; else ctx.items.push(itemOf(G, item, me)); }
|
|
336
|
+
}
|
|
337
|
+
break;
|
|
338
|
+
case 'delete':
|
|
339
|
+
if (item) {
|
|
340
|
+
if (item.file) ctx.blobs?.drop(G, item.file.parts ?? []);
|
|
341
|
+
delete item.text; delete item.poll; delete item.file; item.deleted = true;
|
|
342
|
+
if (item.from !== who.original) { item.deleted_by = sender.name; act(G, seq, who, b, { re: b.re, author: item.from }); }
|
|
343
|
+
const p = pending(G, ctx, item.mid, item.typ);
|
|
344
|
+
if (p) p.l.splice(p.i, 1);
|
|
345
|
+
}
|
|
346
|
+
break;
|
|
347
|
+
case 'react':
|
|
348
|
+
if (item) {
|
|
349
|
+
const l = (item.reactions[b.emoji] ??= []).filter((d) => d !== who.original); if (b.on) l.push(who.original); if (l.length) item.reactions[b.emoji] = l; else delete item.reactions[b.emoji];
|
|
350
|
+
if (item.from === me.original && !mine) {
|
|
351
|
+
const it = { label: LABEL, group: { gid: G.gid, name: G.name }, typ: 'reactions', mid: item.mid, re: item.mid, reactions: Object.fromEntries(Object.entries(item.reactions).map(([e, x]) => [e, x.length])), home: G.home, iat: b.iat, received: me.now ?? b.iat };
|
|
352
|
+
const p = pending(G, ctx, item.mid, 'reactions');
|
|
353
|
+
if (p) p.l[p.i] = it; else ctx.items.push(it);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
break;
|
|
357
|
+
case 'pin': G.pins = G.pins.filter((m) => m !== b.re); if (b.on) G.pins.push(b.re); act(G, seq, who, b, { re: b.re, on: b.on }); break;
|
|
358
|
+
case 'vote': if (item?.poll && !item.poll.closed) { W.checkVote(b, item.poll); if (b.choices.length) item.poll.votes[who.original] = b.choices; else delete item.poll.votes[who.original]; } break;
|
|
359
|
+
case 'poll_end': if (item?.poll) { item.poll.closed = true; if (!mine) ctx.items.push({ ...itemOf(G, item, me), typ: 'poll_end' }); } break;
|
|
360
|
+
case 'blob': ctx.blobs?.put(G, seq, who.original, b, head.slot); break; // a file's part, the avatar (step 7: blobStore)
|
|
361
|
+
default: break; // state: not used by this client yet
|
|
362
|
+
}
|
|
363
|
+
if (pre) logEvent(G, seq, b, pre);
|
|
364
|
+
G.seen[b.mid] = b.iat;
|
|
365
|
+
const ks = Object.keys(G.seen);
|
|
366
|
+
if (ks.length > SEEN_MAX) for (const k of ks.slice(0, ks.length - SEEN_MAX)) delete G.seen[k];
|
|
367
|
+
}
|
|
368
|
+
// An epoch body (one part: this client writes renewals of one): this member's letter opens the next
|
|
369
|
+
// epoch; none means it was removed. Then every holder steps its letter keys (§2.3).
|
|
370
|
+
function letters(G, ctx, b) {
|
|
371
|
+
const next = b.next, me = ctx.me;
|
|
372
|
+
let fresh = null;
|
|
373
|
+
if (!G.epochs[next]?.E) {
|
|
374
|
+
const r = W.openLetter(b.letters, unb(G.L), G.gid, next, gkeyPair(G).secretKey);
|
|
375
|
+
if (r === null) { if (G.status === 'member') G.status = 'removed'; return; }
|
|
376
|
+
installEpoch(G, next, r.E);
|
|
377
|
+
if (r.V) G.V = b64(r.V);
|
|
378
|
+
fresh = r.L ?? null;
|
|
379
|
+
}
|
|
380
|
+
if (b.part !== b.parts) return;
|
|
381
|
+
const kem = b.letters.some((x) => x.kem !== undefined);
|
|
382
|
+
if (kem) {
|
|
383
|
+
// A full renewal (an admin out): fresh letter keys and a fresh V. Its maker knows them all (G.fresh); another admin
|
|
384
|
+
// gets them in the vault body that follows; nobody steps the old ones, which the admin who left knew.
|
|
385
|
+
const f = G.fresh?.next === next ? G.fresh : null;
|
|
386
|
+
G.L = f ? f.L[me.original] : b64(fresh ?? W.nextLetterKey(unb(G.L), G.gid));
|
|
387
|
+
if (f) G.V = f.V;
|
|
388
|
+
for (const [d, m] of Object.entries(G.roster)) { if (f?.L[d]) m.L = f.L[d]; else delete m.L; }
|
|
389
|
+
delete G.fresh;
|
|
390
|
+
} else {
|
|
391
|
+
G.L = b64(fresh ?? W.nextLetterKey(unb(G.L), G.gid));
|
|
392
|
+
for (const m of Object.values(G.roster)) if (m.L) m.L = b64(W.nextLetterKey(unb(m.L), G.gid));
|
|
393
|
+
}
|
|
394
|
+
G.epoch = next;
|
|
395
|
+
G.mine = { n: 0, ck: b64(W.chainStart(unb(G.epochs[next].E), G.gid, me.original)) };
|
|
396
|
+
G.chains[next] = {};
|
|
397
|
+
// Read in seq order, this renewal comes after the leave or kick that made one due here: another admin did it (a symmetric
|
|
398
|
+
// one does not stand for a full one).
|
|
399
|
+
if (kem || !G.renew_full) { G.renew_due = false; G.renew_full = false; }
|
|
400
|
+
}
|
|
401
|
+
// The door seeds an admin made after a link gets with its vault (§4.15): D's, each checked against the link's door key, then
|
|
402
|
+
// any link whose own box (kept while this member held no V) the vault's V opens (V not renewed since the link).
|
|
403
|
+
function takeDoors(G, D) {
|
|
404
|
+
for (const { id, seed } of D) {
|
|
405
|
+
const l = G.links[id];
|
|
406
|
+
if (!l || l.seed) continue; // unlinked meanwhile, or held already
|
|
407
|
+
if (b64(W.boxKey(unb(seed)).publicKey) !== l.door_key) { count(G, 'group_key'); continue; }
|
|
408
|
+
l.seed = seed; delete l.box;
|
|
409
|
+
}
|
|
410
|
+
for (const [id, l] of Object.entries(G.links)) {
|
|
411
|
+
if (l.seed || !l.box) continue;
|
|
412
|
+
try { l.seed = b64(W.openDoorSeed(unb(G.V), G.gid, id, l.box)); delete l.box; } catch (e) { if (!(e instanceof MsgError)) throw e; }
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
/** The vault's D: the seeds of the live links this admin holds, or nothing (an older app refuses a vault with D: none, none sent). */
|
|
416
|
+
function doorsOf(G, now) {
|
|
417
|
+
const D = Object.entries(G.links).filter(([, l]) => l.seed && l.exp > now).map(([id, l]) => ({ id, seed: l.seed }));
|
|
418
|
+
return D.length ? { D } : {};
|
|
419
|
+
}
|
|
420
|
+
// Made member or moderator: what only an admin holds goes (V, the door seeds, the requests). The relay stops the door rows
|
|
421
|
+
// at the next renewal (a new V, so a new admin key); a door seed does not renew: unlink a link to end it (§4.15).
|
|
422
|
+
function forgetAdmin(G) {
|
|
423
|
+
delete G.V; delete G.fresh;
|
|
424
|
+
for (const l of Object.values(G.links)) delete l.seed;
|
|
425
|
+
G.requests = {}; G.asks = {}; G.renew_due = false; G.renew_full = false;
|
|
426
|
+
}
|
|
427
|
+
// A door request (lane 1, admins): the joiner's signed join, kept as a request; approved at once on an auto link.
|
|
428
|
+
function readDoor(G, ctx, { seq, bytes }) {
|
|
429
|
+
if (bytes.length < 10) fail('group_entry', 'a door request shorter than its head');
|
|
430
|
+
const id = W.hex(bytes.subarray(2, 10)), l = G.links[id];
|
|
431
|
+
if (!l?.seed) fail('group_key', 'a door request for a link this admin holds no key of');
|
|
432
|
+
const { content } = W.openDoor(bytes, { doorSecret: W.boxKey(unb(l.seed)).secretKey, gid: G.gid, door: l.door });
|
|
433
|
+
const who = W.verifyJoin(content, ctx.now), j = content.body;
|
|
434
|
+
W.checkFresh(j, ctx.now);
|
|
435
|
+
if (l.exp <= ctx.now) fail('group_stale', 'a request through a link that ended');
|
|
436
|
+
if (G.roster[who.original]) return;
|
|
437
|
+
if (G.barred.includes(who.original)) fail('group_member', 'a request from a barred identity');
|
|
438
|
+
if (!G.settings.agents && j.kind === 'agent') fail('group_role', 'a request from an agent: agents are not allowed here');
|
|
439
|
+
// The relay could store a request again as a new row (a joiner who left, let in again through an auto link): its mid is seen.
|
|
440
|
+
if (G.seen[j.mid] !== undefined) fail('group_message', 'a door request seen already (stored again by the relay)');
|
|
441
|
+
G.seen[j.mid] = j.iat;
|
|
442
|
+
// One request a joiner (its newest), at most REQUESTS_MAX: a flood through a link does not grow this file without end.
|
|
443
|
+
for (const [k, r] of Object.entries(G.requests)) if (r.original === who.original) delete G.requests[k];
|
|
444
|
+
const ks = Object.keys(G.requests).sort((a, b) => Number(a) - Number(b));
|
|
445
|
+
for (const k of ks.slice(0, Math.max(0, ks.length - REQUESTS_MAX + 1))) { delete G.requests[k]; count(G, 'group_requests'); }
|
|
446
|
+
G.requests[String(seq)] = { seq, link: id, join: content, original: who.original, current: who.current, name: j.name, kind: j.kind, at: ctx.now };
|
|
447
|
+
// Invited over its pairing by this admin (add): let in at once, through the link it was given, as an auto link's.
|
|
448
|
+
const e = G.expect?.[who.original];
|
|
449
|
+
if (l.approve === 'auto' || (e && e.link === id && e.until > ctx.now)) ctx.auto.push(String(seq));
|
|
450
|
+
}
|
|
451
|
+
/** A kick, a delete of another's message, a pin: kept with who did it (shown "by <name>"). */
|
|
452
|
+
function act(G, seq, who, b, extra) {
|
|
453
|
+
const m = G.roster[who.original];
|
|
454
|
+
(G.acts ??= []).push({ typ: b.typ, seq, by: who.original, by_name: m?.name ?? null, by_kind: m?.kind ?? null, iat: b.iat, ...extra });
|
|
455
|
+
if (G.acts.length > ACTS_MAX) G.acts.splice(0, G.acts.length - ACTS_MAX);
|
|
456
|
+
}
|
|
457
|
+
// The event history (admins; design/groups-build.md "Built: event history"): each roster body, renewal, edit, delete and pin
|
|
458
|
+
// this member applied, kept as one line in G.events (newest EVENTS_MAX), never its text: what eventsOf reads. Recorded after
|
|
459
|
+
// the body took effect, so a body refused by a check leaves none; the names are those of that moment.
|
|
460
|
+
const EVENT_TYPS = new Set([...ROSTER_TYPS, 'epoch', 'edit', 'delete', 'pin']);
|
|
461
|
+
function eventPre(G, b, who, item) {
|
|
462
|
+
const named = b.member?.did ?? b.member ?? b.to, t = typeof named === 'string' ? G.roster[named] : undefined;
|
|
463
|
+
return { by: who.original, by_name: b.typ === 'create' ? 'owner' : G.roster[who.original]?.name ?? null, by_role: G.roster[who.original]?.role ?? null,
|
|
464
|
+
by_since: G.roster[who.original]?.since ?? null, target: typeof named === 'string' ? named : null, target_name: t?.name ?? null, target_role: t?.role ?? null, target_kind: t?.kind ?? null, group_name: G.name,
|
|
465
|
+
author: item?.from ?? null, author_name: item ? (G.roster[item.from]?.name ?? item.name ?? null) : null, sent: item?.iat ?? null };
|
|
466
|
+
}
|
|
467
|
+
const settingView = (k, v) => (k === 'avatar' ? (v ? 'set' : 'removed') : v);
|
|
468
|
+
function eventOf(G, seq, b, p) {
|
|
469
|
+
const t = p.target ? { target: p.target, target_name: p.target_name } : {};
|
|
470
|
+
// The owner's first entries (its name and kind right after the create) and a joiner's that say what its add said: no event.
|
|
471
|
+
const setup = p.by_since !== null && seq - p.by_since <= 2;
|
|
472
|
+
switch (b.typ) {
|
|
473
|
+
case 'create': return { kind: 'created', detail: { name: b.name } };
|
|
474
|
+
case 'add': { const link = b.request.body.link; return { kind: 'joined', target: b.member.did, target_name: b.member.name, detail: { kind: b.member.kind, link, approve: G.links[link]?.approve ?? null } }; }
|
|
475
|
+
case 'leave': return { kind: 'left', detail: { role: p.by_role } };
|
|
476
|
+
case 'kick': return { kind: b.bar ? 'banned' : 'kicked', ...t, detail: { role: p.target_role, ...(b.reason && { reason: b.reason }) } };
|
|
477
|
+
case 'unbar': return { kind: 'unbanned', target: b.member, target_name: [...(G.events ?? [])].reverse().find((e) => e.target === b.member && e.target_name)?.target_name ?? null, detail: {} };
|
|
478
|
+
case 'role': return { kind: 'role', ...t, detail: { from: p.target_role, to: b.role } };
|
|
479
|
+
case 'kind': return b.kind === p.target_kind || (setup && p.target === p.by) ? null : { kind: 'kind', ...t, detail: { from: p.target_kind, to: b.kind } };
|
|
480
|
+
case 'profile': return b.name === undefined || b.name === p.by_name || setup ? null : { kind: 'name', detail: { from: p.by_name, to: b.name } };
|
|
481
|
+
case 'handover': return { kind: 'handover', ...t, detail: {} };
|
|
482
|
+
case 'settings': {
|
|
483
|
+
const changed = Object.fromEntries(Object.entries(b.settings).map(([k, v]) => [k, settingView(k, v)]));
|
|
484
|
+
return b.settings.name !== undefined ? { kind: 'renamed', detail: { from: p.group_name, to: b.settings.name, changed } } : { kind: 'settings', detail: { changed } };
|
|
485
|
+
}
|
|
486
|
+
case 'link': return { kind: 'link', detail: { id: b.id, exp: b.exp, approve: b.approve, cap: b.cap } };
|
|
487
|
+
case 'unlink': return { kind: 'unlink', detail: { id: b.id } };
|
|
488
|
+
case 'moved': return { kind: 'moved', detail: { home: b.home } };
|
|
489
|
+
case 'end': return { kind: 'ended', detail: {} };
|
|
490
|
+
case 'epoch': return b.part === b.parts ? { kind: 'renewal', detail: { epoch: b.next, full: b.letters.some((x) => x.kem !== undefined), letters: b.letters.length } } : null;
|
|
491
|
+
case 'edit': return { kind: 'edited', ...(p.author && { target: p.author, target_name: p.author_name }), detail: { re: b.re, count: (G.events ?? []).filter((e) => e.kind === 'edited' && e.detail.re === b.re).length + 1 } };
|
|
492
|
+
case 'delete': return { kind: 'deleted', ...(p.author && { target: p.author, target_name: p.author_name }), detail: { re: b.re, own: p.author === p.by, sent: p.sent } };
|
|
493
|
+
case 'pin': return { kind: b.on ? 'pinned' : 'unpinned', ...(p.author && { target: p.author, target_name: p.author_name }), detail: { re: b.re } };
|
|
494
|
+
default: return null;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
function logEvent(G, seq, b, p) {
|
|
498
|
+
const e = eventOf(G, seq, b, p);
|
|
499
|
+
if (!e) return;
|
|
500
|
+
(G.events ??= []).push({ seq, at: b.iat, by: p.by, by_name: p.by_name, ...e });
|
|
501
|
+
if (G.events.length > EVENTS_MAX) G.events.splice(0, G.events.length - EVENTS_MAX);
|
|
502
|
+
}
|
|
503
|
+
/** An item of this group still waiting for the inbox: this round's, or an earlier sync's not taken yet. */
|
|
504
|
+
function pending(G, ctx, mid, typ) {
|
|
505
|
+
for (const l of [ctx.items, ctx.unread ?? []]) { const i = l.findIndex((x) => x.group?.gid === G.gid && x.mid === mid && x.typ === typ); if (i >= 0) return { l, i }; }
|
|
506
|
+
return null;
|
|
507
|
+
}
|
|
508
|
+
const pollView = (p) => ({ question: p.question, options: p.options, multi: p.multi, tallies: p.options.map((_, i) => Object.values(p.votes).filter((c) => c.includes(i)).length), closed: p.closed });
|
|
509
|
+
/** An inbox item of a message or poll (§4.4): group, sender, role (owner/admin/moderator/member), kind (human/agent), home, "not your operator". */
|
|
510
|
+
function itemOf(G, it, me) {
|
|
511
|
+
const operator = me.operators.has(it.from);
|
|
512
|
+
return { label: LABEL, group: { gid: G.gid, name: G.name }, mid: it.mid, seq: it.seq, typ: it.typ, ...(it.re && { re: it.re }), from: it.from, current_did: it.current, name: it.name, role: it.role, kind: it.kind,
|
|
513
|
+
operator, ...(!operator && { note: NOT_OPERATOR }), content: it.typ === 'poll' ? it.poll.question : it.text, ...(it.edited && { edited: true }), ...(it.poll && { poll: pollView(it.poll) }),
|
|
514
|
+
...(it.mentions && { mentions: it.mentions }), mentioned: Boolean(it.mentions?.includes(me.original)), ...(isMod(roleOf(G, me.original)) && { moderate: true }), home: G.home, iat: it.iat, received: me.now ?? it.iat };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// A kicked member's account, for the home relay to take off the group's wake list (an admin's `forget`, relay/home.mjs).
|
|
518
|
+
function forgetLater(G, original) { if (!(G.forget_due ??= []).includes(original)) G.forget_due.push(original); }
|
|
519
|
+
|
|
520
|
+
// ---------------------------------------------------------------- a session at the home relay
|
|
521
|
+
/** The open proof: Ed25519 by the epoch's write key over "sigelo-home/0 open\n" ‖ topic ‖ epoch ‖ account (64 hex) ‖ UTC day (relay/home.mjs openInput). */
|
|
522
|
+
export const openInput = (topic, epoch, account, day) => concatBytes(utf8ToBytes(`${W.HOME_V} open\n${topic}`), u32(epoch), utf8ToBytes(account), u32(day));
|
|
523
|
+
/** What an admin's control request is signed over: "sigelo-home/0 control\n" ‖ JCS(the request without sig, v included). */
|
|
524
|
+
export const controlInput = (req) => utf8ToBytes(`${W.HOME_V} control\n${canonicalize({ v: W.HOME_V, ...req })}`);
|
|
525
|
+
|
|
526
|
+
class Session {
|
|
527
|
+
constructor(o, h, s, save, G) {
|
|
528
|
+
this.o = o; this.h = h; this.s = s; this.save = save; this.G = G;
|
|
529
|
+
this.ctx = { me: null, now: 0, auto: [], items: [], echo: new Map(), unread: s.unread, blobs: blobStore(o) };
|
|
530
|
+
this.opened = 0; // the epoch the log is open under (0: not open)
|
|
531
|
+
}
|
|
532
|
+
refresh() { const now = nowOf(this.o.carrier); this.ctx.now = now; this.ctx.me = { ...meOf(this.o.carrier, now), now }; return this.ctx; }
|
|
533
|
+
get admin() { return Boolean(this.G.V) && isAdmin(roleOf(this.G, this.ctx.me.original)); }
|
|
534
|
+
writeOf(admin) {
|
|
535
|
+
const G = this.G;
|
|
536
|
+
return admin ? W.adminKey(unb(G.V), G.gid, G.epoch) : writeKey(unb(G.epochs[G.epoch].W));
|
|
537
|
+
}
|
|
538
|
+
async open() {
|
|
539
|
+
const G = this.G, h = this.h, admin = this.admin, k = this.writeOf(admin), day = Math.floor(this.ctx.now / DAY);
|
|
540
|
+
const proof = b64(ed25519.sign(openInput(G.topic, G.epoch, h.account, day), k.seed));
|
|
541
|
+
for (let i = h.notes.length - 1; i >= 0; i--) if (h.notes[i].topic === G.topic) h.notes.splice(i, 1);
|
|
542
|
+
const t0 = Date.now();
|
|
543
|
+
const a = await h.control({ typ: 'open', topic: G.topic, epoch: G.epoch, since: G.seq, as: admin ? 'admin' : 'member', proof });
|
|
544
|
+
this.opened = G.epoch; this.last = a.last;
|
|
545
|
+
// The members the home holds now (the owner's tier, or the slot's): approve lets nobody in past it (relay/home.mjs open).
|
|
546
|
+
if (Number.isSafeInteger(a.cap)) G.cap = a.cap;
|
|
547
|
+
const reached = await this.catchUp(a.last);
|
|
548
|
+
// Read to the log's end: an entry of this member's the relay took before this open and never sent back is one it hides.
|
|
549
|
+
if (reached && !this.hold) {
|
|
550
|
+
for (const [k, x] of Object.entries(G.sent)) if (x.acked !== undefined && x.acked < t0) { delete G.sent[k]; suspect(G, 'own'); }
|
|
551
|
+
this.save();
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
// Rows until the open's last seq came (a member sees no door row: then QUIET_MS without one), or its end. → whether the last came.
|
|
555
|
+
async catchUp(last = 0) {
|
|
556
|
+
const G = this.G, h = this.h, t0 = Date.now();
|
|
557
|
+
let reached = false;
|
|
558
|
+
for (;;) {
|
|
559
|
+
const top = h.rows.filter((r) => r.topic === G.topic).reduce((m, r) => Math.max(m, r.seq), G.seq);
|
|
560
|
+
const ended = h.notes.some((n) => n.topic === G.topic);
|
|
561
|
+
if (top >= last) { reached = true; break; }
|
|
562
|
+
if (ended || !h.up) break;
|
|
563
|
+
if (Date.now() - Math.max(h.at, t0) > QUIET_MS) break;
|
|
564
|
+
await sleep(25);
|
|
565
|
+
}
|
|
566
|
+
if (!this.hold) this.pump();
|
|
567
|
+
return reached;
|
|
568
|
+
}
|
|
569
|
+
// Handle what arrived: the rows in seq order; then the relay's word (the next epoch, the end).
|
|
570
|
+
pump() {
|
|
571
|
+
const G = this.G, h = this.h, ctx = this.refresh();
|
|
572
|
+
const rows = [];
|
|
573
|
+
for (let i = h.rows.length - 1; i >= 0; i--) if (h.rows[i].topic === G.topic) rows.push(...h.rows.splice(i, 1));
|
|
574
|
+
rows.sort((a, b) => a.seq - b.seq);
|
|
575
|
+
for (const r of rows) readRow(G, ctx, r);
|
|
576
|
+
// The relay's word that the open ended: the next epoch (this member holds its key, or was removed), the log closed.
|
|
577
|
+
for (const n of h.notes.filter((x) => x.topic === G.topic)) {
|
|
578
|
+
h.notes.splice(h.notes.indexOf(n), 1);
|
|
579
|
+
if (n.typ === 'epoch' && this.opened === n.epoch - 1) { this.opened = 0; if (!G.epochs[n.epoch] && G.status === 'member') G.status = 'removed'; }
|
|
580
|
+
if (n.typ === 'closed' || n.typ === 'dropped') { this.opened = 0; G.status = 'closed'; }
|
|
581
|
+
}
|
|
582
|
+
this.save();
|
|
583
|
+
}
|
|
584
|
+
// Open (again) when the log is not open under this member's epoch: after a renewal switched it.
|
|
585
|
+
async ensure(strict = true) {
|
|
586
|
+
for (let i = 0; i < 4 && this.G.status === 'member' && this.opened !== this.G.epoch; i++) await this.open();
|
|
587
|
+
if (strict && this.G.status === 'invited') fail('group_pending', `home group ${this.G.name}: an invitation; join it first (group join ${this.G.gid})`);
|
|
588
|
+
if (strict && this.G.status !== 'member') fail(this.G.status === 'removed' ? 'group_member' : 'group_closed', `home group ${this.G.name}: ${this.G.status === 'removed' ? 'you were removed' : this.G.status}`);
|
|
589
|
+
}
|
|
590
|
+
/** One entry: sign, seal under this member's chain, publish, then wait for it to come back (its seq). → { mid, seq, mk }. */
|
|
591
|
+
async post(typ, fields, { authorize = true, slot = 0 } = {}) {
|
|
592
|
+
const G = this.G, ctx = this.refresh(), me = ctx.me;
|
|
593
|
+
if (typ !== 'create') await this.ensure();
|
|
594
|
+
const body = { v: W.GROUP2_V, typ, gid: G.gid, mid: W.newMid(), iat: ctx.now, from: me.current, epoch: G.epoch, at: G.seq, ...fields };
|
|
595
|
+
W.checkBody(body);
|
|
596
|
+
if (authorize && typ !== 'create') {
|
|
597
|
+
const named = body.member ?? body.to, t = typeof named === 'string' && G.roster[named] ? { did: named, role: G.roster[named].role, kind: G.roster[named].kind } : null;
|
|
598
|
+
const item = typeof body.re === 'string' ? G.history.find((x) => x.mid === body.re) : undefined;
|
|
599
|
+
W.authorize(body, { role: roleOf(G, me.original), self: me.original, target: t, author: item?.from ?? null, channel: G.settings.channel, agents: G.settings.agents, slot });
|
|
600
|
+
if ((typ === 'msg' || typ === 'poll') && G.roster[me.original]?.kind === 'agent' && G.settings.brake !== 'off' && G.run >= G.settings.brake) fail('group_quiet', `${G.run} agent messages in a row, the group's brake (${G.settings.brake}): a human writes first`);
|
|
601
|
+
}
|
|
602
|
+
const rotated = typ === 'create' || (G.roster[me.original] && G.roster[me.original].current !== me.current);
|
|
603
|
+
const content = W.signBody(me, body, rotated ? me.own : undefined);
|
|
604
|
+
// A kept entry (slot), and an admin's post in channel mode (the relay holds a member credential's entry there to 4 KiB): the admin credential.
|
|
605
|
+
const admin = Boolean(G.V) && (ADMIN_TYPS.has(typ) || slot > 0 || (G.settings.channel === true && ['msg', 'poll', 'blob'].includes(typ))), ek = G.epochs[G.epoch], HK = unb(ek.HK);
|
|
606
|
+
const { n, mk } = nextMine(G);
|
|
607
|
+
const bytes = W.sealEntry({ topic: G.topic, epoch: G.epoch, flags: (admin ? W.FLAG.admin : 0) | (slot ? W.FLAG.keep : 0) | (typ === 'epoch' ? W.FLAG.letters : 0), slot, write: this.writeOf(admin), HK, hint: W.senderHint(HK, me.original), n, mk, content });
|
|
608
|
+
const h = hashOf(bytes);
|
|
609
|
+
G.sent[h] = { mk: b64(mk) };
|
|
610
|
+
this.save();
|
|
611
|
+
// The group's rate (relay/home.mjs ENTRY_RATE): the same bytes again a second later, a few times.
|
|
612
|
+
let r = await this.h.publish(G.topic, bytes);
|
|
613
|
+
for (let i = 0; r?.code === 'rate' && i < 5; i++) { await sleep(1100); r = await this.h.publish(G.topic, bytes); }
|
|
614
|
+
if (r) { delete G.sent[h]; this.save(); throw new MsgError(r.code, `${r.detail}`); }
|
|
615
|
+
if (G.sent[h]) { G.sent[h].acked = Date.now(); this.save(); }
|
|
616
|
+
const end = Date.now() + ECHO_MS;
|
|
617
|
+
while (!ctx.echo.has(body.mid) && Date.now() < end && this.h.up) { this.pump(); if (!ctx.echo.has(body.mid)) await sleep(25); }
|
|
618
|
+
const e = ctx.echo.get(body.mid);
|
|
619
|
+
return { mid: body.mid, seq: e?.seq ?? null, mk: e?.mk ?? b64(mk) };
|
|
620
|
+
}
|
|
621
|
+
async control(req, signed = true) {
|
|
622
|
+
const G = this.G;
|
|
623
|
+
const r = signed ? { ...req, sig: b64(ed25519.sign(controlInput(req), W.adminKey(unb(G.V), G.gid, G.epoch).seed)) } : req;
|
|
624
|
+
return this.h.control(r);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
// ---- duties of an admin
|
|
628
|
+
async renew() {
|
|
629
|
+
const G = this.G, me = this.refresh().me;
|
|
630
|
+
if (!this.admin) fail('group_role', 'a renewal needs an admin holding the vault');
|
|
631
|
+
await this.ensure();
|
|
632
|
+
const full = G.renew_full === true;
|
|
633
|
+
const e = G.epoch, next = e + 1, E2 = randomBytes(32), k = W.epochKeys(E2, G.gid), V2 = full ? randomBytes(32) : unb(G.V), AW2 = W.adminKey(V2, G.gid, next);
|
|
634
|
+
const members = Object.keys(G.roster);
|
|
635
|
+
// A member whose letter key this admin does not hold yet (after another admin's full renewal, before its vault body)
|
|
636
|
+
// would get no letter, so be cut off: the renewal waits for that vault.
|
|
637
|
+
const missing = members.filter((d) => d !== me.original && !G.roster[d].L);
|
|
638
|
+
if (missing.length) { G.renew_due = true; this.save(); return { renewed: false, detail: `${missing.length} members' letter keys have not come yet (another admin's renewal): later` }; }
|
|
639
|
+
// Too soon after the last switch, or another admin's pending: renewed at this admin's next sync.
|
|
640
|
+
try { await this.control({ typ: 'epoch', topic: G.topic, epoch: next, write: b64(k.W.pub), admin: b64(AW2.pub), parts: 1, members: members.length, channel: G.settings.channel }); } catch (e) {
|
|
641
|
+
if (e.check !== 'home_epoch') throw e;
|
|
642
|
+
G.renew_due = true; this.save();
|
|
643
|
+
return { renewed: false, detail: e.message };
|
|
644
|
+
}
|
|
645
|
+
const list = [], freshL = {};
|
|
646
|
+
for (const d of members) {
|
|
647
|
+
const L = d === me.original ? G.L : G.roster[d].L, admin = isAdmin(G.roster[d].role), gkey = d === me.original ? b64(gkeyPair(G).publicKey) : G.roster[d].gkey;
|
|
648
|
+
if (!L) continue;
|
|
649
|
+
// Full: a KEM letter to the member's box key with a fresh L; the old L opens nothing (the admin out knew it).
|
|
650
|
+
if (full && gkey) { const L2 = randomBytes(32); freshL[d] = b64(L2); list.push(W.kemLetter(unb(L), unb(gkey), G.gid, next, concatBytes(L2, E2, ...(admin ? [V2] : [])))); }
|
|
651
|
+
else { list.push(W.letter(unb(L), G.gid, next, admin ? concatBytes(E2, V2) : E2)); freshL[d] = b64(W.nextLetterKey(unb(L), G.gid)); }
|
|
652
|
+
}
|
|
653
|
+
installEpoch(G, next, E2);
|
|
654
|
+
if (full) G.fresh = { next, V: b64(V2), L: freshL };
|
|
655
|
+
G.renew_due = false;
|
|
656
|
+
this.save();
|
|
657
|
+
let r;
|
|
658
|
+
try { r = await this.post('epoch', { next, part: 1, parts: 1, letters: list }); } catch (x) { delete G.fresh; G.renew_due = true; this.save(); throw x; }
|
|
659
|
+
await this.ensure();
|
|
660
|
+
if (full) {
|
|
661
|
+
G.renew_full = false;
|
|
662
|
+
// The other admins: the new V and every member's new letter key (they had V2 in their letter, not the others' L).
|
|
663
|
+
const L = Object.fromEntries(Object.entries(G.roster).filter(([, x]) => x.L).map(([o, x]) => [o, x.L]));
|
|
664
|
+
L[me.original] = G.L;
|
|
665
|
+
for (const [d, m] of Object.entries(G.roster)) {
|
|
666
|
+
if (d === me.original || !isAdmin(m.role) || !m.gkey) continue;
|
|
667
|
+
const box = W.sealBox('vault', unb(m.gkey), G.gid, G.epoch, { V: G.V, L, ...doorsOf(G, this.ctx.now) });
|
|
668
|
+
await this.post('vault', { to: d, kem: box.kem, box: box.box });
|
|
669
|
+
}
|
|
670
|
+
this.save();
|
|
671
|
+
}
|
|
672
|
+
return { renewed: true, epoch: next, ...(full && { full: true }), ...r };
|
|
673
|
+
}
|
|
674
|
+
async approve(id) {
|
|
675
|
+
const G = this.G, req = G.requests[id] ?? fail('group_request', `no request ${id} waiting (group requests)`);
|
|
676
|
+
const me = this.refresh().me, j = req.join.body, d = req.original;
|
|
677
|
+
if (!this.admin) fail('group_role', 'approving needs an admin');
|
|
678
|
+
if (G.roster[d]) { delete G.requests[id]; return { added: false }; }
|
|
679
|
+
await this.ensure();
|
|
680
|
+
// Past the members the home holds, the joiner could never open, and a renewal naming them all would be refused: it waits.
|
|
681
|
+
if (Number.isSafeInteger(G.cap) && Object.keys(G.roster).length >= G.cap) fail('home_cap', `${G.name} has ${G.cap} members, the most its home ${G.home} holds for its owner: the request waits until one leaves`);
|
|
682
|
+
const e = G.epoch, ek = G.epochs[e];
|
|
683
|
+
if (!ek.E) fail('group_key', 'this admin holds no epoch secret yet: it comes with the next renewal');
|
|
684
|
+
const L = randomBytes(32), ck0 = W.chainStart(unb(ek.E), G.gid, d);
|
|
685
|
+
const add = await this.post('add', { member: { did: d, current: req.current, name: j.name, kind: j.kind }, request: req.join, vault: W.sealForAdmins(unb(G.V), G.gid, d, L), ck: W.sealChainStart(unb(ek.HK), G.gid, d, ck0) });
|
|
686
|
+
if (add.seq === null) fail('connect', 'the add did not come back from the home relay: run sync, then approve again');
|
|
687
|
+
// Every member's chain at this moment, this admin's own at the counter the welcome takes.
|
|
688
|
+
const chains = [];
|
|
689
|
+
for (const o of Object.keys(G.roster)) {
|
|
690
|
+
const hint = hintOf(G, e, o);
|
|
691
|
+
const rec = o === me.original ? G.mine : chainRec(G, e, hint);
|
|
692
|
+
if (rec) chains.push({ hint, n: rec.n, ck: rec.ck });
|
|
693
|
+
}
|
|
694
|
+
const keys = G.roster_keys.filter((x) => x.seq <= add.seq);
|
|
695
|
+
const secrets = G.settings.history === 'always' ? Object.entries(G.epochs).filter(([, x]) => x.E).map(([n, x]) => ({ epoch: Number(n), E: x.E })) : [];
|
|
696
|
+
const box = W.sealBox('welcome', unb(j.gkey), G.gid, e, { L: b64(L), chains, keys, secrets });
|
|
697
|
+
const w = await this.post('welcome', { to: d, kem: box.kem, box: box.box });
|
|
698
|
+
if (w.seq === null) fail('connect', 'the welcome did not come back from the home relay');
|
|
699
|
+
const start = Math.min(w.seq, ...keys.map((x) => x.seq));
|
|
700
|
+
const body = { v: W.GROUP2_V, typ: 'answer', gid: G.gid, mid: W.newMid(), iat: this.ctx.now, from: me.current, epoch: e, at: G.seq, to: d, link: req.link, write: ek.W, hk: ek.HK, start, welcome: w.seq, mk: w.mk };
|
|
701
|
+
const bytes = W.sealAnswer({ gkey: unb(j.gkey), gid: G.gid, link: req.link, reply: j.reply, content: W.signBody(me, body, me.own) });
|
|
702
|
+
const r = await this.h.publish(j.reply, bytes);
|
|
703
|
+
if (r) fail(r.code, `the answer to ${j.name}: ${r.detail}`);
|
|
704
|
+
delete G.requests[id];
|
|
705
|
+
this.save();
|
|
706
|
+
return { added: true, member: { did: d, name: j.name, kind: j.kind }, seq: add.seq };
|
|
707
|
+
}
|
|
708
|
+
async history(id) {
|
|
709
|
+
const G = this.G, a = G.asks[id] ?? fail('group_request', `no history ask ${id} waiting`), m = G.roster[a.from];
|
|
710
|
+
if (!m?.gkey) { delete G.asks[id]; fail('group_member', 'the asker left, or has no box key'); }
|
|
711
|
+
const secrets = Object.entries(G.epochs).filter(([, x]) => x.E).map(([n, x]) => ({ epoch: Number(n), E: x.E }));
|
|
712
|
+
const box = W.sealBox('history', unb(m.gkey), G.gid, G.epoch, { secrets });
|
|
713
|
+
const r = await this.post('history', { to: a.from, kem: box.kem, box: box.box });
|
|
714
|
+
delete G.asks[id];
|
|
715
|
+
this.save();
|
|
716
|
+
return r;
|
|
717
|
+
}
|
|
718
|
+
// What an admin's app does unasked: approve auto links' requests, renew after a leave or kick, take a handover.
|
|
719
|
+
async duties() {
|
|
720
|
+
const G = this.G;
|
|
721
|
+
if (G.status !== 'member') return;
|
|
722
|
+
if (G.handover_due) { await this.h.control({ typ: 'handover', topic: G.topic, ...G.handover_due }); G.handover_due = null; this.save(); }
|
|
723
|
+
if (!this.admin) return;
|
|
724
|
+
for (const id of this.ctx.auto.splice(0)) if (G.requests[id]) { try { await this.approve(id); } catch (e) { if (!(e instanceof MsgError)) throw e; count(G, e.check); } }
|
|
725
|
+
if (G.renew_due) await this.renew();
|
|
726
|
+
await this.forgets();
|
|
727
|
+
}
|
|
728
|
+
// The kicked accounts off the home relay's wake list (no wake for them any more), signed by the current AW.
|
|
729
|
+
async forgets() {
|
|
730
|
+
const G = this.G;
|
|
731
|
+
for (const d of [...(G.forget_due ?? [])]) {
|
|
732
|
+
try { await this.control({ typ: 'forget', topic: G.topic, account: W.hex(sha256(utf8ToBytes(d))) }); } catch (e) { if (!(e instanceof MsgError) || e.check === 'connect') throw e; }
|
|
733
|
+
G.forget_due = G.forget_due.filter((x) => x !== d);
|
|
734
|
+
this.save();
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// The joiner's answer, from its reply topic: the admin's signed answer sealed to its gkey.
|
|
740
|
+
function takeAnswer(G, ctx) {
|
|
741
|
+
if (!G.answer_raw || G.answer) return;
|
|
742
|
+
try {
|
|
743
|
+
const { content } = W.openAnswer(unb(G.answer_raw), { gkeySecret: gkeyPair(G).secretKey, gid: G.gid, reply: G.joining.reply });
|
|
744
|
+
const who = W.verifyContent(content, content.chain, ctx.now), a = content.body;
|
|
745
|
+
if (a.to !== ctx.me.original || a.link !== G.joining.link) fail('group_message', 'an answer for another joiner or link');
|
|
746
|
+
G.answer = { by: who.original, chain: content.chain, epoch: a.epoch, start: a.start, welcome: a.welcome, mk: a.mk };
|
|
747
|
+
G.epoch = a.epoch; G.epochs[a.epoch] = { W: a.write, HK: a.hk };
|
|
748
|
+
G.seq = a.start - 1;
|
|
749
|
+
} catch (e) { if (!(e instanceof MsgError)) throw e; count(G, e.check); delete G.answer_raw; }
|
|
750
|
+
}
|
|
751
|
+
// The joiner's welcome, opened before the rows around it: its letter key, every member's chain, the
|
|
752
|
+
// roster rows' keys, and per the history policy the epoch secrets.
|
|
753
|
+
function takeWelcome(S) {
|
|
754
|
+
const G = S.G, h = S.h, ctx = S.refresh();
|
|
755
|
+
if (G.welcomed || !G.answer) return true;
|
|
756
|
+
const row = h.rows.find((r) => r.topic === G.topic && r.seq === G.answer.welcome);
|
|
757
|
+
if (!row) return false;
|
|
758
|
+
const content = W.openEntry(row.bytes, G.topic, unb(G.answer.mk)), b = content.body;
|
|
759
|
+
W.verifyContent(content, G.answer.chain, ctx.now);
|
|
760
|
+
if (b.typ !== 'welcome' || b.to !== ctx.me.original) fail('group_message', 'the answer\'s welcome is not this joiner\'s');
|
|
761
|
+
const box = W.openBox(b, gkeyPair(G).secretKey);
|
|
762
|
+
G.L = box.L;
|
|
763
|
+
for (const x of box.secrets) installEpoch(G, x.epoch, unb(x.E));
|
|
764
|
+
const e = G.answer.epoch, c = (G.chains[e] ??= {});
|
|
765
|
+
const mine = hintOf(G, e, ctx.me.original);
|
|
766
|
+
for (const x of box.chains) {
|
|
767
|
+
if (x.hint === mine) G.mine = { n: x.n, ck: x.ck };
|
|
768
|
+
else if (!G.epochs[e].E) c[x.hint] = { n: x.n, ck: x.ck, skipped: {} };
|
|
769
|
+
}
|
|
770
|
+
if (!G.mine && G.epochs[e].E) G.mine = { n: 0, ck: b64(W.chainStart(unb(G.epochs[e].E), G.gid, ctx.me.original)) };
|
|
771
|
+
if (!G.mine) fail('group_key', 'the welcome holds no chain of this joiner');
|
|
772
|
+
for (const k of box.keys) G.keys[k.seq] = k.key;
|
|
773
|
+
G.welcomed = row.seq;
|
|
774
|
+
return true;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** Run fn(session) for each named group (all live ones by default), one connection per home relay. */
|
|
778
|
+
async function run(o, gids, fn, { quietOnly = false } = {}) {
|
|
779
|
+
const { s, save } = open(o);
|
|
780
|
+
const byHome = new Map();
|
|
781
|
+
for (const gid of gids(s)) { const G = s.groups[gid]; if (!byHome.has(G.home)) byHome.set(G.home, []); byHome.get(G.home).push(G); }
|
|
782
|
+
const out = [], items = [];
|
|
783
|
+
// A verb refused after the catch-up (group_limit, group_role at the post) keeps the items it read: they are in the file's
|
|
784
|
+
// seq already, so they go to unread whatever fn does (else a refused kick lost the messages read before it).
|
|
785
|
+
try {
|
|
786
|
+
for (const [home, list] of byHome) {
|
|
787
|
+
const inbox = list.filter((G) => G.status === 'joining').map((G) => G.joining.reply);
|
|
788
|
+
await o.carrier.home(home, async (h) => {
|
|
789
|
+
for (const G of list) {
|
|
790
|
+
const S = new Session(o, h, s, save, G);
|
|
791
|
+
S.refresh();
|
|
792
|
+
if (G.status === 'joining') {
|
|
793
|
+
if (!G.answer_raw) await waitFor(() => G.answer_raw, QUIET_MS, h);
|
|
794
|
+
takeAnswer(G, S.ctx);
|
|
795
|
+
save();
|
|
796
|
+
if (!G.answer) { out.push(await fn(S)); continue; }
|
|
797
|
+
S.hold = true;
|
|
798
|
+
await S.open();
|
|
799
|
+
for (let i = 0; i < 100 && !takeWelcome(S); i++) await sleep(50);
|
|
800
|
+
S.hold = false;
|
|
801
|
+
if (!G.welcomed) fail('group_key', `home group ${G.name}: the welcome (row ${G.answer.welcome}) did not come`);
|
|
802
|
+
S.pump();
|
|
803
|
+
} else if (G.status === 'member') await S.ensure(false);
|
|
804
|
+
if (G.status === 'member' && !quietOnly) await S.duties();
|
|
805
|
+
try { out.push(await fn(S)); } finally { items.push(...S.ctx.items); save(); }
|
|
806
|
+
}
|
|
807
|
+
}, { inbox, onInbox: (t, bytes) => { const G = list.find((x) => x.joining?.reply === t); if (G && !G.answer_raw) { G.answer_raw = b64(bytes); save(); } } });
|
|
808
|
+
}
|
|
809
|
+
} finally {
|
|
810
|
+
if (items.length) { s.unread.push(...items); if (s.unread.length > UNREAD_MAX) s.unread.splice(0, s.unread.length - UNREAD_MAX); save(); }
|
|
811
|
+
}
|
|
812
|
+
return out;
|
|
813
|
+
}
|
|
814
|
+
async function waitFor(cond, ms, h) { const end = Date.now() + ms; while (!cond() && Date.now() < end && h.up) await sleep(25); }
|
|
815
|
+
const one = (o, group, fn, opts) => run(o, (s) => [pick(s, group).gid], fn, opts).then((r) => r[0]);
|
|
816
|
+
|
|
817
|
+
// ---------------------------------------------------------------- who may do what (agents moderate, people administer)
|
|
818
|
+
// Agents moderate, people administer. A moderator or admin kicks (bans too), deletes another's message, pins, unpins,
|
|
819
|
+
// unbars, approves and refuses by itself, no operator confirmation; W.authorize holds which role may sign which body.
|
|
820
|
+
// Capped: a moderator (human or agent) and an admin that is an agent. Their kicks (bans counted with them) and deletes
|
|
821
|
+
// of others' messages are counted here, in this member's file, on every path (MCP, the CLI, the app, a watcher): at most
|
|
822
|
+
// the group's caps (settings.mod, the owner's: `group moderate <g> --kicks n --deletes n`; default and most 20 and 200)
|
|
823
|
+
// a UTC day in a group, and 20 and 200 across this identity's groups. The owner and human admins are not capped.
|
|
824
|
+
// Self-enforced only: no other member can check the count (members read from different starts, history never, and would
|
|
825
|
+
// part); every act is still a signed body shown "by <name>" (acts). Approvals, refusals, pins and unbars are not counted.
|
|
826
|
+
// A model (MCP: model true) also never touches an admin's or a moderator's member or message (group_role), and never does
|
|
827
|
+
// a person's act (personGate): role, set, link, unlink, handover, end, name, the picture, moderate (and group.mjs move). Those stay a
|
|
828
|
+
// person's: the app and the CLI pass no model (the CLI is the operator's shell: an agent given that shell can run them).
|
|
829
|
+
export const MOD_KICKS = W.MOD_KICKS, MOD_DELETES = W.MOD_DELETES;
|
|
830
|
+
const roleName = (r) => (r === 'moderator' || r === 'member' ? `a ${r}` : `an ${r}`);
|
|
831
|
+
const isMod = (role) => role === 'owner' || role === 'admin' || role === 'moderator';
|
|
832
|
+
const capsOf = (G) => G.settings?.mod ?? { kicks: MOD_KICKS, deletes: MOD_DELETES };
|
|
833
|
+
/** A moderator, or an admin that is an agent: its kicks and deletes are capped. The owner and human admins are not. */
|
|
834
|
+
const isCapped = (G, did) => { const r = roleOf(G, did); return r === 'moderator' || (r === 'admin' && G.roster[did]?.kind === 'agent'); };
|
|
835
|
+
function counts(x, day) { return x?.day === day ? x : { day, kick: 0, delete: 0 }; }
|
|
836
|
+
/** A person's act (people administer): refused when a model asks (MCP passes model: true on every call, either transport). */
|
|
837
|
+
export function personGate(model, what) {
|
|
838
|
+
if (model !== false && model !== undefined) fail('group_person', `${what} is a person's act, never a model's: ask your operator to do it (the app, or sigelo-agent group in a terminal)`);
|
|
839
|
+
}
|
|
840
|
+
// A moderation act: a model never touches an admin's or a moderator's; a capped member within its caps. → counted (true)
|
|
841
|
+
// when capped: the caller counts it (modCount) before the act goes, so a crash after the post never gives one more.
|
|
842
|
+
function modGate(G, s, now, me, what, { model = false, targetRole } = {}) {
|
|
843
|
+
if (model && targetRole !== undefined && targetRole !== 'member') fail('group_role', `a ${what} by an agent never touches ${roleName(targetRole)}: tell your operator`);
|
|
844
|
+
if ((what !== 'kick' && what !== 'delete') || !isCapped(G, me)) return false;
|
|
845
|
+
const day = Math.floor(now / DAY), mine = counts(s.mod, day)[what], here = counts(G.mod_day, day)[what];
|
|
846
|
+
const cap = what === 'kick' ? MOD_KICKS : MOD_DELETES, set = capsOf(G)[what === 'kick' ? 'kicks' : 'deletes'];
|
|
847
|
+
if (mine >= cap) fail('group_limit', `${cap} ${what}s today across your groups, the most a moderator or agent admin makes in a UTC day: none until 00:00 UTC`);
|
|
848
|
+
if (here >= set) fail('group_limit', `${set} ${what}s today in ${G.name}, the cap its owner set for moderators and agent admins, a UTC day: none until 00:00 UTC`);
|
|
849
|
+
return true;
|
|
850
|
+
}
|
|
851
|
+
function modCount(G, s, now, what) {
|
|
852
|
+
const day = Math.floor(now / DAY);
|
|
853
|
+
s.mod = counts(s.mod, day); s.mod[what]++;
|
|
854
|
+
G.mod_day = counts(G.mod_day, day); G.mod_day[what]++;
|
|
855
|
+
}
|
|
856
|
+
// What this member may do here (list, show): on (it moderates: moderator, admin, owner), capped, the caps and what is left
|
|
857
|
+
// today; rules: its operator's own text for its model (local, `group moderate <g> on --rules`), never the group's.
|
|
858
|
+
const modLeft = (G, s, me, now) => {
|
|
859
|
+
const rules = G.moderate?.on ? { rules: G.moderate.rules, from: 'your operator' } : {};
|
|
860
|
+
if (!me || !isMod(roleOf(G, me))) return { on: false, ...rules };
|
|
861
|
+
if (!isCapped(G, me)) return { on: true, capped: false, ...rules };
|
|
862
|
+
const c = capsOf(G), day = Math.floor(now / DAY), a = counts(s?.mod, day), g = counts(G.mod_day, day);
|
|
863
|
+
return { on: true, capped: true, kicks: c.kicks, deletes: c.deletes, kicks_left: Math.max(0, Math.min(MOD_KICKS - a.kick, c.kicks - g.kick)),
|
|
864
|
+
deletes_left: Math.max(0, Math.min(MOD_DELETES - a.delete, c.deletes - g.delete)), ...rules };
|
|
865
|
+
};
|
|
866
|
+
/**
|
|
867
|
+
* group moderate: the operator's rules for its own model (local: on with rules, or off; read as its operator's text), and
|
|
868
|
+
* the owner's caps for the group (kicks, deletes a UTC day: a settings body, so every member's software counts by them).
|
|
869
|
+
* A person's act (model: refused).
|
|
870
|
+
*/
|
|
871
|
+
export async function moderate({ carrier, file, group, on, rules, kicks, deletes, model = false }) {
|
|
872
|
+
personGate(model, 'group moderate (rules and caps)');
|
|
873
|
+
if (on !== undefined && typeof on !== 'boolean') fail('group_settings', 'moderate: on or off');
|
|
874
|
+
if (on && (typeof rules !== 'string' || rules.trim() === '' || rules.length > 4000)) fail('group_settings', 'moderate on needs your rules, 1 to 4,000 characters (--rules)');
|
|
875
|
+
if (on === false && rules !== undefined) fail('group_settings', 'moderate off takes no rules');
|
|
876
|
+
for (const [k, v, max] of [['kicks', kicks, MOD_KICKS], ['deletes', deletes, MOD_DELETES]]) if (v !== undefined && (!Number.isSafeInteger(v) || v < 0 || v > max)) fail('group_settings', `--${k}: 0 to ${max} a UTC day`);
|
|
877
|
+
if (on === undefined && kicks === undefined && deletes === undefined) fail('group_settings', 'moderate: on --rules …, off, or the caps (--kicks, --deletes)');
|
|
878
|
+
if (kicks !== undefined || deletes !== undefined) {
|
|
879
|
+
await one({ carrier, file }, group, async (S) => {
|
|
880
|
+
if (roleOf(S.G, S.refresh().me.original) !== 'owner') fail('group_role', `only the owner of ${S.G.name} sets its caps for moderators and agent admins`);
|
|
881
|
+
const c = capsOf(S.G);
|
|
882
|
+
return S.post('settings', { settings: { mod: { kicks: kicks ?? c.kicks, deletes: deletes ?? c.deletes } } });
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
const { s, save } = open({ carrier, file }), G = pick(s, group), now = nowOf(carrier);
|
|
886
|
+
if (on !== undefined) { G.moderate = on ? { on, rules: rules.trim(), at: now } : { on: false }; save(); }
|
|
887
|
+
return { gid: G.gid, name: G.name, caps: capsOf(G), moderate: modLeft(G, s, meOf(carrier, now).original, now) };
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// ---------------------------------------------------------------- the verbs
|
|
891
|
+
/** A home group at `home` (default: this agent's relay), this agent its owner; members: contacts invited over their pairings (add). */
|
|
892
|
+
export async function create({ carrier, file, name, home = carrier.relay, kind = 'agent', selfName = 'owner', brake, moved_from, members, local = false }) {
|
|
893
|
+
const now = nowOf(carrier), me = meOf(carrier, now), settings = { ...W.DEFAULTS, name, ...(brake !== undefined && { brake }) };
|
|
894
|
+
// Contacts to invite (add), checked before anything is made.
|
|
895
|
+
const picked = members === undefined || members.length === 0 ? [] : contactsFor(carrier, members);
|
|
896
|
+
W.checkBody({ v: W.GROUP2_V, typ: 'create', gid: '0'.repeat(32), mid: '0'.repeat(16), iat: now, from: me.current, epoch: 1, at: 0, name, nonce: '0'.repeat(32), home, settings });
|
|
897
|
+
if (moved_from !== undefined && (typeof moved_from !== 'string' || !/^[0-9a-f]{32}$/.test(moved_from))) fail('group_message', 'moved_from: a sigelo-group/1 gid');
|
|
898
|
+
const nonce = W.newNonce(), gid = W.gidOf(me.original, nonce), E = randomBytes(32), V = randomBytes(32), gseed = randomBytes(32);
|
|
899
|
+
const { s, save } = open({ carrier, file });
|
|
900
|
+
const G = fresh({ gid, name, home, topic: W.topicOf(gid), owner: me.original, status: 'member', epoch: 1, V: b64(V), L: b64(randomBytes(32)), gkey: b64(gseed), ...(moved_from && { moved_from }) });
|
|
901
|
+
installEpoch(G, 1, E);
|
|
902
|
+
G.mine = { n: 0, ck: b64(W.chainStart(E, gid, me.original)) };
|
|
903
|
+
s.groups[gid] = G;
|
|
904
|
+
save();
|
|
905
|
+
await carrier.home(home, async (h) => {
|
|
906
|
+
const S = new Session({ carrier, file }, h, s, save, G);
|
|
907
|
+
S.refresh();
|
|
908
|
+
const k = W.epochKeys(E, gid);
|
|
909
|
+
try { await h.control({ typ: 'create', topic: G.topic, write: b64(k.W.pub), admin: b64(W.adminKey(V, gid, 1).pub), members: 1, channel: false }); } catch (e) { delete s.groups[gid]; save(); throw e; }
|
|
910
|
+
await S.open();
|
|
911
|
+
await S.post('create', { name, nonce, home, settings });
|
|
912
|
+
await S.post('profile', { name: selfName, gkey: b64(W.boxKey(gseed).publicKey) });
|
|
913
|
+
await S.post('kind', { member: me.original, kind });
|
|
914
|
+
});
|
|
915
|
+
if (picked.length === 0) return { group: summary(G, me) };
|
|
916
|
+
const invited = await add({ carrier, file, group: gid, members: picked.map((c) => c.did), local });
|
|
917
|
+
return { group: summary(G, me), invited };
|
|
918
|
+
}
|
|
919
|
+
/** An invite link: a door at the home relay, a link body, the signed invite, its GRP code parked there. */
|
|
920
|
+
export async function link({ carrier, file, group, ttl = W.LINK_TTL, cap = W.LINK_CAP, approve, model = false }) {
|
|
921
|
+
personGate(model, 'an invite link');
|
|
922
|
+
return one({ carrier, file }, group, (S) => makeLink(S, { ttl, cap, approve }));
|
|
923
|
+
}
|
|
924
|
+
// park false: no GRP code (a supergroup's card carries the long invite; its name is the address).
|
|
925
|
+
async function makeLink(S, { ttl, cap, approve, park = true }) {
|
|
926
|
+
const G = S.G, me = S.refresh().me, now = S.ctx.now, carrier = S.o.carrier;
|
|
927
|
+
if (!S.admin) fail('group_role', 'a link needs an admin');
|
|
928
|
+
if (!Number.isSafeInteger(ttl) || ttl < W.LINK_MIN || ttl > W.LINK_MAX) fail('group_link', 'ttl: 1 hour to 366 days');
|
|
929
|
+
approve ??= G.settings.join === 'open' ? 'auto' : 'admin';
|
|
930
|
+
const id = W.newLinkId(), door = W.newDoor(), seed = randomBytes(32), dk = W.boxKey(seed), exp = now + ttl;
|
|
931
|
+
await S.control({ typ: 'door', topic: G.topic, door, exp, cap });
|
|
932
|
+
G.links[id] = { door, door_key: b64(dk.publicKey), exp, cap, approve, seed: b64(seed) };
|
|
933
|
+
S.save();
|
|
934
|
+
await S.post('link', { id, door, door_key: b64(dk.publicKey), exp, cap, approve, box: W.sealDoorSeed(unb(G.V), G.gid, id, seed) });
|
|
935
|
+
const body = { v: W.GROUP2_V, typ: 'invite', gid: G.gid, name: G.name, owner: G.owner, home: G.home, door, door_key: b64(dk.publicKey), link: id, by: me.current, iat: now, exp, approve };
|
|
936
|
+
const inv = W.checkInvite({ body, sig: me.sign(body), genesis: me.genesis }, now), long = W.inviteLong(inv);
|
|
937
|
+
if (!park) return { id, code: null, invite: long, words: didWords(G.owner), exp, approve, cap, home: G.home };
|
|
938
|
+
const norm = makeShort(undefined, G.home === carrier.shortRelay ? null : relayTag(G.home)), code = W.formatGroupCode(norm), code_hash = W.groupCodeHash(code);
|
|
939
|
+
let parked = true, why;
|
|
940
|
+
try { await S.h.park({ code_hash, invite: long, exp }); } catch (e) { parked = false; why = e.message; }
|
|
941
|
+
G.links[id] = { ...G.links[id], ...(parked && { code, code_hash }) };
|
|
942
|
+
S.save();
|
|
943
|
+
return { id, ...(parked ? { code, link: W.groupLink(norm) } : { code: null, park_error: why }), invite: long, words: didWords(G.owner), exp, approve, cap, home: G.home };
|
|
944
|
+
}
|
|
945
|
+
export async function unlink({ carrier, file, group, id, model = false }) {
|
|
946
|
+
personGate(model, 'removing an invite link');
|
|
947
|
+
return one({ carrier, file }, group, (S) => dropLink(S, id));
|
|
948
|
+
}
|
|
949
|
+
async function dropLink(S, id) {
|
|
950
|
+
const G = S.G, l = G.links[id] ?? fail('group_link', `no link ${id} in ${G.name}`);
|
|
951
|
+
if (!S.admin) fail('group_role', 'unlinking needs an admin');
|
|
952
|
+
try { await S.control({ typ: 'undoor', topic: G.topic, door: l.door }); } catch (e) { if (e.check !== 'home_door') throw e; }
|
|
953
|
+
if (l.code_hash) await S.h.unpark(l.code_hash).catch(() => false);
|
|
954
|
+
return S.post('unlink', { id });
|
|
955
|
+
}
|
|
956
|
+
// A GRP code (home: its relay when the code names none), its link, or a long invite → the checked invite.
|
|
957
|
+
async function inviteFrom(carrier, text, home, now) {
|
|
958
|
+
const frag = text.includes('#') ? text.slice(text.indexOf('#') + 1) : text;
|
|
959
|
+
if (!W.isGroupCode(frag)) return W.parseInviteLong(frag, now);
|
|
960
|
+
const norm = W.normaliseGroupCode(frag);
|
|
961
|
+
const at = (await carrier.relayForShort(norm, home === undefined ? {} : { relay: home })).relay;
|
|
962
|
+
const long = await carrier.fetchGroupCode(at, W.groupCodeHash(frag)) ?? fail('group_code', `no group code ${W.formatGroupCode(norm)} at ${at}: it ended, was unlinked, or lives at another home relay (--home)`);
|
|
963
|
+
const inv = W.parseInviteLong(long, now);
|
|
964
|
+
if (inv.body.home !== at) fail('group_code', `the invite parked at ${at} names home ${inv.body.home}`);
|
|
965
|
+
return inv;
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* Join by a GRP code, its link, a long invite, or a supergroup's name (name@relay, or its sigelo.io/join# link).
|
|
969
|
+
* By name: the card is fetched and checked offline (checkCard); a public one joins by its invite; a private one
|
|
970
|
+
* needs `with`, a code or link an admin gave, for the same group. → waiting for an admin.
|
|
971
|
+
*/
|
|
972
|
+
export async function join({ carrier, file, code, with: given, home, name, kind = 'agent', operator }) {
|
|
973
|
+
const now = nowOf(carrier), me = meOf(carrier, now), text = String(code ?? '').trim();
|
|
974
|
+
let inv, card = null;
|
|
975
|
+
const addr = parseAddress(text), asked = invitedOf(readFile(file, platformOf(carrier)), text);
|
|
976
|
+
// An invitation over a pairing (add): its invite, kept in the file.
|
|
977
|
+
if (asked) inv = W.parseInviteLong(asked.invite, now);
|
|
978
|
+
else if (addr) {
|
|
979
|
+
card = await cardOf(carrier, addr, now, operator);
|
|
980
|
+
if (card.public) inv = W.parseInviteLong(card.invite, now);
|
|
981
|
+
else if (given === undefined || String(given).trim() === '') fail('group_private', `${addr.name}@${addr.relay} is a private supergroup: ask an admin for a link or code, then join with it (--code)`);
|
|
982
|
+
else inv = await inviteFrom(carrier, String(given).trim(), card.relay, now);
|
|
983
|
+
if (inv.body.gid !== card.gid || inv.body.home !== card.relay || inv.body.owner !== card.owner) fail('group_code', `that ${card.public ? 'card\'s invite' : 'code'} is for another group than ${addr.name}@${addr.relay}`);
|
|
984
|
+
} else inv = await inviteFrom(carrier, text, home, now);
|
|
985
|
+
const b = inv.body;
|
|
986
|
+
const { s, save } = open({ carrier, file });
|
|
987
|
+
const was = s.groups[b.gid];
|
|
988
|
+
if (was && ['member', 'joining'].includes(was.status)) fail('group_member', `already ${was.status === 'member' ? 'a member of' : 'joining'} ${was.name}`);
|
|
989
|
+
const gseed = randomBytes(32), reply = W.newReply();
|
|
990
|
+
const G = fresh({ gid: b.gid, name: b.name, home: b.home, topic: W.topicOf(b.gid), owner: b.owner, gkey: b64(gseed), joining: { reply, link: b.link, door: b.door, by: b.by, at: now },
|
|
991
|
+
...(b.moved_from && { moved_from: b.moved_from }), ...(was?.invited && { invited: was.invited }) });
|
|
992
|
+
s.groups[b.gid] = G;
|
|
993
|
+
save();
|
|
994
|
+
const body = { v: W.GROUP2_V, typ: 'join', gid: b.gid, mid: W.newMid(), iat: now, from: me.current, epoch: 0, at: 0, name: name ?? 'member', kind, gkey: b64(W.boxKey(gseed).publicKey), chain: me.own, link: b.link, reply };
|
|
995
|
+
const bytes = W.sealDoor({ doorKey: unb(b.door_key), gid: b.gid, door: b.door, content: W.signBody(me, body) });
|
|
996
|
+
try {
|
|
997
|
+
await carrier.home(b.home, async (h) => {
|
|
998
|
+
await h.claim([reply]);
|
|
999
|
+
// A door request shares the group's rate (relay/home.mjs rated): in a busy group (a file's 32 parts) it is tried
|
|
1000
|
+
// again a second later, a few times, as a post is (step 7: a join right after a file failed with rate).
|
|
1001
|
+
let r = await h.publish(b.door, bytes);
|
|
1002
|
+
for (let i = 0; r?.code === 'rate' && i < 5; i++) { await sleep(1100); r = await h.publish(b.door, bytes); }
|
|
1003
|
+
if (r) fail(r.code, r.detail);
|
|
1004
|
+
}, { inbox: [reply] });
|
|
1005
|
+
} catch (e) { if (was?.status === 'invited') s.groups[b.gid] = was; else delete s.groups[b.gid]; save(); throw e; }
|
|
1006
|
+
return { group: summary(G, me), status: 'waiting', approve: b.approve, owner: b.owner, words: didWords(b.owner), ...(card && { supergroup: `${card.name}@${card.relay}` }) };
|
|
1007
|
+
}
|
|
1008
|
+
/** Every live group (or one) at its home: the answer, the log, the duties. → { items (new messages, taken now), groups }. */
|
|
1009
|
+
export async function sync({ carrier, file, group, take = true }) {
|
|
1010
|
+
const o = { carrier, file };
|
|
1011
|
+
const res = await run(o, (s) => (group ? [pick(s, group).gid] : Object.values(s.groups).filter((G) => ['member', 'joining'].includes(G.status)).map((G) => G.gid)), async (S) => summary(S.G, S.ctx.me, S.s));
|
|
1012
|
+
const { s, save } = open(o);
|
|
1013
|
+
const items = take ? s.unread.splice(0) : [...s.unread];
|
|
1014
|
+
if (take) save();
|
|
1015
|
+
return { items, groups: res };
|
|
1016
|
+
}
|
|
1017
|
+
const verb = (typ, fieldsOf) => async ({ carrier, file, group, ...a }) => one({ carrier, file }, group, async (S) => S.post(typ, fieldsOf(S, a)));
|
|
1018
|
+
const memberOf = (S, who) => {
|
|
1019
|
+
const G = S.G;
|
|
1020
|
+
if (G.roster[who] || G.barred.includes(who)) return who;
|
|
1021
|
+
const hit = Object.entries(G.roster).filter(([o, m]) => m.name === who || m.current === who || o === who);
|
|
1022
|
+
if (hit.length > 1) fail('group_member', `${hit.length} members are called ${JSON.stringify(who)}: use the DID`);
|
|
1023
|
+
return hit[0]?.[0] ?? fail('group_member', `${JSON.stringify(who)} is not a member of ${G.name}`);
|
|
1024
|
+
};
|
|
1025
|
+
export const send = verb('msg', (S, { text, re, mentions = [] }) => ({ text, ...(re && { re }), ...(mentions.length && { mentions: mentions.map((m) => memberOf(S, m)) }) }));
|
|
1026
|
+
export const react = verb('react', (S, { re, emoji, on = true }) => ({ re, emoji, on }));
|
|
1027
|
+
export const edit = verb('edit', (S, { re, text }) => ({ re, text }));
|
|
1028
|
+
/** Delete a message: one's own, or (a moderator, an admin) another's: a capped member's counted (modGate), a model's never an admin's or moderator's. */
|
|
1029
|
+
export async function remove({ carrier, file, group, re, model = false }) {
|
|
1030
|
+
return one({ carrier, file }, group, async (S) => {
|
|
1031
|
+
const G = S.G, it = G.history.find((x) => x.mid === re), other = it?.from !== S.ctx.me.original;
|
|
1032
|
+
if (model && !it) fail('group_message', `no message ${re} in ${G.name} (group show)`);
|
|
1033
|
+
// Another's (or one not held here: counted too). Counted before it goes: a crash after the post never gives one more.
|
|
1034
|
+
if (other && modGate(G, S.s, S.ctx.now, S.ctx.me.original, 'delete', { model, targetRole: it ? (G.roster[it.from]?.role ?? 'member') : undefined })) { modCount(G, S.s, S.ctx.now, 'delete'); S.save(); }
|
|
1035
|
+
return S.post('delete', { re });
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
export async function pin({ carrier, file, group, re, on = true }) {
|
|
1039
|
+
return one({ carrier, file }, group, async (S) => S.post('pin', { re, on }));
|
|
1040
|
+
}
|
|
1041
|
+
export const poll = verb('poll', (S, { question, options, multi = false }) => ({ question, options, multi }));
|
|
1042
|
+
export const vote = verb('vote', (S, { re, choices }) => {
|
|
1043
|
+
const it = S.G.history.find((x) => x.mid === re && x.poll) ?? fail('group_message', `no poll ${re} in ${S.G.name}`);
|
|
1044
|
+
const c = [...new Set(choices)].sort((a, b) => a - b);
|
|
1045
|
+
W.checkVote({ choices: c }, it.poll);
|
|
1046
|
+
return { re, choices: c };
|
|
1047
|
+
});
|
|
1048
|
+
export const pollEnd = verb('poll_end', (S, { re }) => ({ re }));
|
|
1049
|
+
export async function unbar({ carrier, file, group, member }) {
|
|
1050
|
+
return one({ carrier, file }, group, async (S) => S.post('unbar', { member: memberOf(S, member) }));
|
|
1051
|
+
}
|
|
1052
|
+
export const historyAsk = verb('history_ask', () => ({}));
|
|
1053
|
+
/** Out of the group: a kick (bar: a ban, counted as a kick), then (an admin) a renewal at once, and the relay forgets the account. */
|
|
1054
|
+
export async function kick({ carrier, file, group, member, bar = false, reason, model = false }) {
|
|
1055
|
+
return one({ carrier, file }, group, async (S) => {
|
|
1056
|
+
const d = memberOf(S, member);
|
|
1057
|
+
if (modGate(S.G, S.s, S.ctx.now, S.refresh().me.original, 'kick', { model, targetRole: S.G.roster[d]?.role ?? 'member' })) { modCount(S.G, S.s, S.ctx.now, 'kick'); S.save(); }
|
|
1058
|
+
const r = await S.post('kick', { member: d, bar, ...(reason && { reason }) });
|
|
1059
|
+
if (S.admin) {
|
|
1060
|
+
forgetLater(S.G, d);
|
|
1061
|
+
await S.renew();
|
|
1062
|
+
try { await S.forgets(); } catch {}
|
|
1063
|
+
}
|
|
1064
|
+
return r;
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
/** A role: admin (the owner; its own agents too, ruling 15), moderator or member. A new admin gets the vault, then a renewal gives it E. */
|
|
1068
|
+
export async function role({ carrier, file, group, member, role: r, model = false }) {
|
|
1069
|
+
personGate(model, 'a role');
|
|
1070
|
+
return one({ carrier, file }, group, async (S) => {
|
|
1071
|
+
const G = S.G, d = memberOf(S, member), m = G.roster[d];
|
|
1072
|
+
const out = await S.post('role', { member: d, role: r, agent: m.kind === 'agent' });
|
|
1073
|
+
if (r === 'admin' && S.admin) {
|
|
1074
|
+
if (!m.gkey) fail('group_key', `${m.name} has no box key in the roster`);
|
|
1075
|
+
const L = Object.fromEntries(Object.entries(G.roster).filter(([, x]) => x.L).map(([o, x]) => [o, x.L]));
|
|
1076
|
+
L[S.ctx.me.original] = G.L;
|
|
1077
|
+
const box = W.sealBox('vault', unb(m.gkey), G.gid, G.epoch, { V: G.V, L, ...doorsOf(G, S.ctx.now) });
|
|
1078
|
+
await S.post('vault', { to: d, kem: box.kem, box: box.box });
|
|
1079
|
+
// The epoch secrets this owner holds: a new admin serves history (always, request) as any admin does.
|
|
1080
|
+
const secrets = Object.entries(G.epochs).filter(([, x]) => x.E).map(([n, x]) => ({ epoch: Number(n), E: x.E }));
|
|
1081
|
+
const hb = W.sealBox('history', unb(m.gkey), G.gid, G.epoch, { secrets });
|
|
1082
|
+
await S.post('history', { to: d, kem: hb.kem, box: hb.box });
|
|
1083
|
+
await S.renew();
|
|
1084
|
+
} else if (S.admin && G.renew_full) await S.renew(); // an admin made member or moderator: a full renewal (it knew V)
|
|
1085
|
+
return out;
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
const SETTERS = {
|
|
1089
|
+
name: (v) => v, about: (v) => v,
|
|
1090
|
+
channel: (v) => onOff(v), agents: (v) => onOff(v),
|
|
1091
|
+
join: (v) => v, history: (v) => v,
|
|
1092
|
+
brake: (v) => (v === 'off' ? 'off' : Number(v)),
|
|
1093
|
+
};
|
|
1094
|
+
function onOff(v) { if (v === 'on' || v === true) return true; if (v === 'off' || v === false) return false; fail('group_settings', 'on or off'); }
|
|
1095
|
+
export async function set({ carrier, file, group, key, value, model = false }) {
|
|
1096
|
+
personGate(model, 'a setting');
|
|
1097
|
+
if (!Object.hasOwn(SETTERS, key)) fail('group_settings', `a setting is one of ${Object.keys(SETTERS).join(', ')} (the picture: avatar)`);
|
|
1098
|
+
return one({ carrier, file }, group, async (S) => {
|
|
1099
|
+
const r = await S.post('settings', { settings: { [key]: SETTERS[key](value) } });
|
|
1100
|
+
// The relay reads channel mode from a renewal's request only (relay/home.mjs): one now, so it holds members to 4 KiB at once.
|
|
1101
|
+
if (key === 'channel' && S.admin) { try { await S.renew(); } catch {} }
|
|
1102
|
+
return r;
|
|
1103
|
+
});
|
|
1104
|
+
}
|
|
1105
|
+
export async function leave({ carrier, file, group }) {
|
|
1106
|
+
const { s } = open({ carrier, file }), G0 = pick(s, group);
|
|
1107
|
+
if (G0.status === 'invited') return { ...drop({ carrier, file, group: G0.gid }), declined: true };
|
|
1108
|
+
return one({ carrier, file }, group, async (S) => {
|
|
1109
|
+
const r = await S.post('leave', {});
|
|
1110
|
+
try { await S.h.control({ typ: 'close', topic: S.G.topic, forget: true }); } catch {}
|
|
1111
|
+
return r;
|
|
1112
|
+
});
|
|
1113
|
+
}
|
|
1114
|
+
export async function handover({ carrier, file, group, member, model = false }) { personGate(model, 'a handover'); return one({ carrier, file }, group, (S) => S.post('handover', { to: memberOf(S, member) })); }
|
|
1115
|
+
export async function end({ carrier, file, group, model = false }) {
|
|
1116
|
+
personGate(model, 'ending the group');
|
|
1117
|
+
return one({ carrier, file }, group, async (S) => {
|
|
1118
|
+
const r = await S.post('end', {});
|
|
1119
|
+
await S.h.control({ typ: 'end', topic: S.G.topic, seq: r.seq ?? fail('connect', 'the end did not come back') });
|
|
1120
|
+
return r;
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
export const renew = ({ carrier, file, group }) => one({ carrier, file }, group, (S) => S.renew());
|
|
1124
|
+
/** Door requests and history asks waiting for an admin (after a sync). */
|
|
1125
|
+
export async function requests({ carrier, file, group }) {
|
|
1126
|
+
return one({ carrier, file }, group, async (S) => listRequests(S.G));
|
|
1127
|
+
}
|
|
1128
|
+
const listRequests = (G) => [...Object.entries(G.requests).map(([id, r]) => ({ id, kind: 'join', name: r.name, did: r.original, agent: r.kind === 'agent', words: didWords(r.original), link: r.link, at: r.at })),
|
|
1129
|
+
...Object.entries(G.asks).map(([id, a]) => ({ id, kind: 'history', name: a.name, did: a.from, at: a.at }))];
|
|
1130
|
+
export async function approve({ carrier, file, group, id }) {
|
|
1131
|
+
return one({ carrier, file }, group, (S) => (S.G.asks[id] ? S.history(id) : S.approve(id)));
|
|
1132
|
+
}
|
|
1133
|
+
export async function refuse({ carrier, file, group, id }) {
|
|
1134
|
+
const { s, save } = open({ carrier, file });
|
|
1135
|
+
const G = pick(s, group);
|
|
1136
|
+
if (!G.requests[id] && !G.asks[id]) fail('group_request', `no request ${id} waiting`);
|
|
1137
|
+
// No body says a refusal (the joiner waits until it cancels): this admin's own, kept as a local event.
|
|
1138
|
+
const r = G.requests[id] ?? G.asks[id], now = nowOf(carrier), me = meOf(carrier, now).original;
|
|
1139
|
+
(G.events ??= []).push({ seq: G.seq, at: now, by: me, by_name: G.roster[me]?.name ?? null, kind: 'refused', target: r.original ?? r.from, target_name: r.name ?? null,
|
|
1140
|
+
detail: { ask: G.requests[id] ? 'join' : 'history', ...(r.link && { link: r.link }), local: true } });
|
|
1141
|
+
if (G.events.length > EVENTS_MAX) G.events.splice(0, G.events.length - EVENTS_MAX);
|
|
1142
|
+
delete G.requests[id]; delete G.asks[id];
|
|
1143
|
+
save();
|
|
1144
|
+
return { refused: id };
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
// ---------------------------------------------------------------- invites over a pairing (design/groups-build.md §1.6, §5)
|
|
1148
|
+
// An admin invites a contact directly: the group's direct link (DIRECT_TTL, an admin approves, renewed when it has less than
|
|
1149
|
+
// DIRECT_RENEW left), its invite signed again for each call (moved_from: the sigelo-group/1 group it replaces), sent over the
|
|
1150
|
+
// pair with the label sigelo-group/2 as a text whose last line is the long invite: an older app, which has no branch for the
|
|
1151
|
+
// label, shows the text (the update line, the GRP link to use once updated). The contact's app checks it (group.mjs handle:
|
|
1152
|
+
// signed by its sender, not expired) and joins by G1's rule: own at once, friend after its operator says yes, quiet never.
|
|
1153
|
+
// The inviter's app lets in those it invited (expect) through that link at once, as an auto link's requests.
|
|
1154
|
+
export const DIRECT_TTL = 30 * DAY, DIRECT_RENEW = 7 * DAY, INVITE_LINE = `${W.GROUP2_V} invite `;
|
|
1155
|
+
/** The pairing's message: the text an older app shows, then the long invite on its own last line. */
|
|
1156
|
+
export const pairContent = (text, long) => `${text}\n\n${INVITE_LINE}${long}`;
|
|
1157
|
+
/** An invite over a pairing → { invite (checked: shape, signature, expiry), text }. */
|
|
1158
|
+
export function parsePairInvite(content, now) {
|
|
1159
|
+
const no = (why) => fail('group_message', `not a ${W.GROUP2_V} invite over a pairing: ${why}`);
|
|
1160
|
+
if (typeof content !== 'string' || content.length > 16384) no('a text of at most 16 KiB');
|
|
1161
|
+
const i = content.lastIndexOf(`\n${INVITE_LINE}`);
|
|
1162
|
+
if (i < 0) no(`no "${INVITE_LINE.trim()}" line`);
|
|
1163
|
+
return { invite: W.parseInviteLong(content.slice(i + 1 + INVITE_LINE.length), now), text: content.slice(0, i).trim() };
|
|
1164
|
+
}
|
|
1165
|
+
// Live contacts (names or DIDs), each once; else not_contact.
|
|
1166
|
+
function contactsFor(carrier, members) {
|
|
1167
|
+
if (!Array.isArray(members) || members.length === 0) fail('group_members', 'name a contact to invite');
|
|
1168
|
+
const live = carrier.contacts().contacts.filter((c) => !c.revoked && c.pair !== null && c.pair !== undefined);
|
|
1169
|
+
const each = (w) => {
|
|
1170
|
+
if (typeof w !== 'string' || w === '') fail('not_contact', 'name a contact, by name or DID');
|
|
1171
|
+
const byDid = w.startsWith('did:') ? live.find((c) => c.did === w || c.chain?.includes(w)) : null;
|
|
1172
|
+
if (byDid) return byDid;
|
|
1173
|
+
const named = live.filter((c) => c.name === w);
|
|
1174
|
+
if (named.length > 1) fail('name', `${named.length} contacts are called ${JSON.stringify(w)}: use the DID`);
|
|
1175
|
+
return named[0] ?? fail('not_contact', `${JSON.stringify(w)} is not a contact`);
|
|
1176
|
+
};
|
|
1177
|
+
return [...new Map(members.map(each).map((c) => [c.did, c])).values()];
|
|
1178
|
+
}
|
|
1179
|
+
/** Invite contacts to a home group over their pairings (an admin). local: queued for a watcher. → { gid, name, code, exp, copies }. */
|
|
1180
|
+
export async function add({ carrier, file, group, members, moved_from, text, local = false }) {
|
|
1181
|
+
const picked = contactsFor(carrier, members);
|
|
1182
|
+
const made = await one({ carrier, file }, group, async (S) => {
|
|
1183
|
+
const G = S.G, me = S.refresh().me, now = S.ctx.now;
|
|
1184
|
+
if (!S.admin) fail('group_role', 'inviting needs an admin');
|
|
1185
|
+
for (const c of picked) {
|
|
1186
|
+
if (G.roster[c.did]) fail('group_member', `${c.name} is in ${G.name} already`);
|
|
1187
|
+
if (G.barred.includes(c.did)) fail('group_member', `${c.name} is banned from ${G.name}: unbar first`);
|
|
1188
|
+
}
|
|
1189
|
+
let l = G.direct ? G.links[G.direct] : null;
|
|
1190
|
+
if (!l || l.exp - now < DIRECT_RENEW) { G.direct = (await makeLink(S, { ttl: DIRECT_TTL, cap: W.LINK_CAP_MAX, approve: 'admin' })).id; l = G.links[G.direct]; }
|
|
1191
|
+
G.expect ??= {};
|
|
1192
|
+
for (const c of picked) G.expect[c.did] = { link: G.direct, until: l.exp };
|
|
1193
|
+
S.save();
|
|
1194
|
+
const body = { v: W.GROUP2_V, typ: 'invite', gid: G.gid, name: G.name, owner: G.owner, home: G.home, door: l.door, door_key: l.door_key, link: G.direct, by: me.current, iat: now, exp: l.exp, approve: l.approve,
|
|
1195
|
+
...(moved_from !== undefined && { moved_from }) };
|
|
1196
|
+
const inv = W.checkInvite({ body, sig: me.sign(body), genesis: me.genesis }, now);
|
|
1197
|
+
return { gid: G.gid, name: G.name, long: W.inviteLong(inv), code: l.code ?? null, exp: l.exp };
|
|
1198
|
+
});
|
|
1199
|
+
const link = made.code ? W.LINK_BASE + made.code : null;
|
|
1200
|
+
const say = text ?? (moved_from !== undefined ? `${made.name} moved to a home group. Update sigelo to keep reading it${link ? `, then join with ${link}` : ''}.`
|
|
1201
|
+
: `You are invited to ${made.name}, a sigelo group. Update sigelo to join${link ? `, then open ${link}` : ''}.`);
|
|
1202
|
+
const copies = [];
|
|
1203
|
+
for (const c of picked) {
|
|
1204
|
+
try { await carrier.send(c.did, pairContent(say, made.long), { label: LABEL, internal: GROUP_SEND, local: true }); copies.push({ to: c.did, name: c.name, status: 'queued' }); } catch (e) {
|
|
1205
|
+
if (!(e instanceof MsgError)) throw e;
|
|
1206
|
+
copies.push({ to: c.did, name: c.name, status: 'refused', check: e.check, detail: e.message });
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
let offline;
|
|
1210
|
+
if (!local && copies.some((x) => x.status === 'queued')) {
|
|
1211
|
+
try { await carrier.sync(); } catch (e) { offline = e.message; }
|
|
1212
|
+
const q = new Map(carrier.contacts().contacts.map((c) => [c.did, c.queued]));
|
|
1213
|
+
for (const x of copies) if (x.status === 'queued' && q.get(x.to) === 0) x.status = 'sent';
|
|
1214
|
+
}
|
|
1215
|
+
return { gid: made.gid, name: made.name, code: made.code, exp: made.exp, copies, ...(offline !== undefined && { offline }) };
|
|
1216
|
+
}
|
|
1217
|
+
/** An invite over a pairing, checked (group.mjs handle): filed as status invited, unless this member is in or joining. from: the contact { did, name }. */
|
|
1218
|
+
export function invited({ carrier, file, invite, from, text = '' }) {
|
|
1219
|
+
const now = nowOf(carrier), b = W.checkInvite(invite, now).body;
|
|
1220
|
+
const { s, save } = open({ carrier, file }), was = s.groups[b.gid];
|
|
1221
|
+
if (was && ['member', 'joining'].includes(was.status)) return { gid: b.gid, name: b.name, status: was.status };
|
|
1222
|
+
s.groups[b.gid] = fresh({ gid: b.gid, name: b.name, home: b.home, topic: W.topicOf(b.gid), owner: b.owner, status: 'invited', invite: W.inviteLong(invite),
|
|
1223
|
+
invited: { by: from.did, name: from.name, at: now, exp: b.exp, ...(text && { text: text.slice(0, 500) }) }, ...(b.moved_from && { moved_from: b.moved_from }) });
|
|
1224
|
+
save();
|
|
1225
|
+
return { gid: b.gid, name: b.name, status: 'invited' };
|
|
1226
|
+
}
|
|
1227
|
+
// An invitation of the file by gid or name, or null.
|
|
1228
|
+
function invitedOf(s, text) {
|
|
1229
|
+
if (s.groups[text]?.status === 'invited') return s.groups[text];
|
|
1230
|
+
const named = Object.values(s.groups).filter((g) => g.status === 'invited' && g.name === text);
|
|
1231
|
+
return named.length === 1 ? named[0] : null;
|
|
1232
|
+
}
|
|
1233
|
+
/** The home group this owner made by moving a sigelo-group/1 group (group.mjs move), or null: a move is taken up again, never made twice. */
|
|
1234
|
+
export function movedHome({ carrier, file, gid, owner }) {
|
|
1235
|
+
let s;
|
|
1236
|
+
try { s = readFile(file, platformOf(carrier)); } catch { return null; }
|
|
1237
|
+
const G = Object.values(s.groups).find((x) => x.moved_from === gid && x.status === 'member' && x.owner === owner && x.roster?.[owner]?.role === 'owner');
|
|
1238
|
+
return G ? { gid: G.gid, name: G.name, home: G.home } : null;
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// ---------------------------------------------------------------- supergroups (design/groups-build.md §3.7)
|
|
1242
|
+
// A supergroup is a home group with a permanent name at its home relay, public or private. The relay's
|
|
1243
|
+
// operator sells the slot (a SPEC §5 attestation, ctx SLOT_CTX: relay/home.mjs `slot issue`, then `slot`);
|
|
1244
|
+
// the owner binds the name with a signed card (name); anyone reads the card (GET /group/<name>) and checks it
|
|
1245
|
+
// here, offline: the slot by the operator (the relay registry's DID for that host, when it names one), the
|
|
1246
|
+
// owner's chain, the card's signature. A public card carries a live link's invite; a private one the name,
|
|
1247
|
+
// about and owner only, so a joiner also needs a code or link an admin gave.
|
|
1248
|
+
export const SLOT_CTX = 'sigelo-relay/group-name', NAME_RE = /^[a-z0-9-]{3,32}$/;
|
|
1249
|
+
const CARD_KEYS = 'about,avatar,gid,home,iat,invite,name,owner,public,typ,v';
|
|
1250
|
+
const isObj = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
1251
|
+
/** "community@relay.sigelo.ai", or https://sigelo.io/join#community@relay.sigelo.ai → { name, relay }; null when it is not one. */
|
|
1252
|
+
export function parseAddress(text) {
|
|
1253
|
+
const t = String(text ?? '').trim(), frag = t.includes('#') ? t.slice(t.indexOf('#') + 1) : t;
|
|
1254
|
+
const m = /^([A-Za-z0-9-]{3,32})@([A-Za-z0-9.-]{1,253}(?::\d{1,5})?)$/.exec(frag);
|
|
1255
|
+
return m ? { name: m[1].toLowerCase(), relay: m[2].toLowerCase() } : null;
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* GET /group/<name>'s answer checked offline (pure): { name, relay, gid, owner, words, public, about, avatar,
|
|
1259
|
+
* invite, approve, operator, operator_words, pinned, slot: { exp, members } }. operator: the operator's
|
|
1260
|
+
* original DID the relay registry names for `relay` (pinned), or null (the card's own, not pinned).
|
|
1261
|
+
* Refused: group_card (any check), group_slot (no running slot by the operator).
|
|
1262
|
+
*/
|
|
1263
|
+
export function checkCard(ans, { name, relay, now, operator = null }) {
|
|
1264
|
+
const at = `${name}@${relay}`, bad = (why) => fail('group_card', `${at}: ${why}`);
|
|
1265
|
+
if (!isObj(ans) || !isObj(ans.card) || !isObj(ans.card.body) || typeof ans.card.sig !== 'string' || !isObj(ans.slot) || !isObj(ans.slot.body) || !isObj(ans.chain) || !isObj(ans.issuer)) bad('not a name card {card, slot, chain, issuer}');
|
|
1266
|
+
const opRots = ans.issuer_rotations ?? [];
|
|
1267
|
+
if (!Array.isArray(opRots)) bad('issuer_rotations is not a list');
|
|
1268
|
+
let op;
|
|
1269
|
+
try { op = verify({ v: 'sigelo/0', typ: 'bundle', genesis: ans.issuer, rotations: opRots, bindings: [], attestations: [], issuers: [] }, now); } catch (e) { bad(`the operator's chain does not verify (${e.message})`); }
|
|
1270
|
+
if (operator && op.chain[0] !== operator) bad(`its slot is by ${op.chain[0]}, not ${relay}'s operator ${operator} (the relay registry)`);
|
|
1271
|
+
const signer = [ans.issuer, ...opRots.map((r) => r?.next_genesis)].find((g) => { try { return didOf(g) === ans.slot.body.iss; } catch { return false; } });
|
|
1272
|
+
if (!signer || !op.chain.includes(ans.slot.body.iss)) bad('its slot is not signed by the relay\'s operator');
|
|
1273
|
+
let v;
|
|
1274
|
+
try { v = verify({ v: 'sigelo/0', typ: 'bundle', genesis: ans.chain.genesis, rotations: ans.chain.rotations ?? [], bindings: [], attestations: [ans.slot], issuers: [signer] }, now); } catch (e) { bad(`the owner's chain does not verify (${e.message})`); }
|
|
1275
|
+
const slot = (v.attestations[ans.slot.body.iss] ?? []).find((a) => a.ctx === SLOT_CTX);
|
|
1276
|
+
if (!slot) fail('group_slot', `${at}: no running slot by the relay's operator (it ended, or it is not one)`);
|
|
1277
|
+
const c = slot.claims ?? {};
|
|
1278
|
+
if (c.relay !== relay || c.name !== name || slot.sub !== v.chain[0]) bad(`the slot is for ${c.name}@${c.relay}, owner ${slot.sub}`);
|
|
1279
|
+
const b = ans.card.body;
|
|
1280
|
+
if (Object.keys(b).sort().join() !== CARD_KEYS || b.v !== W.GROUP2_V || b.typ !== 'card' || b.name !== name || b.home !== relay || b.owner !== v.chain[0]
|
|
1281
|
+
|| typeof b.gid !== 'string' || !/^[0-9a-f]{32}$/.test(b.gid) || typeof b.public !== 'boolean' || b.public !== (b.invite !== null) || (!b.public && b.avatar !== null)
|
|
1282
|
+
|| typeof b.about !== 'string' || b.about.length > 500 || !Number.isSafeInteger(b.iat)) bad('the card is not {v, typ: card, name, home, gid, owner (the slot\'s), public, about, avatar, invite, iat}; a private one has no invite and no avatar');
|
|
1283
|
+
const key = [ans.chain.genesis, ...(ans.chain.rotations ?? []).map((r) => r.next_genesis)].find((g) => didOf(g) === v.did)?.key;
|
|
1284
|
+
if (!key || !verifySig(key, b, ans.card.sig)) bad('the card is not signed by its owner\'s current key');
|
|
1285
|
+
let approve = null, linkExp = null;
|
|
1286
|
+
if (b.public) {
|
|
1287
|
+
const inv = W.parseInviteLong(b.invite, now);
|
|
1288
|
+
if (inv.body.gid !== b.gid || inv.body.home !== relay || inv.body.owner !== b.owner) bad('its invite is for another group');
|
|
1289
|
+
approve = inv.body.approve; linkExp = inv.body.exp;
|
|
1290
|
+
}
|
|
1291
|
+
return { name, relay, gid: b.gid, owner: b.owner, words: didWords(b.owner), public: b.public, about: b.about, avatar: b.avatar, invite: b.invite, approve, link_exp: linkExp,
|
|
1292
|
+
operator: op.chain[0], operator_words: didWords(op.chain[0]), pinned: Boolean(operator), slot: { exp: slot.exp, members: c.members } };
|
|
1293
|
+
}
|
|
1294
|
+
// The operator the signed relay registry names for a host (relays.mjs: the did of its host statement), or null.
|
|
1295
|
+
async function registryOperator(carrier, relay) {
|
|
1296
|
+
try { return (await carrier.registryRelays()).find((e) => e.host === relay)?.did ?? null; } catch { return null; }
|
|
1297
|
+
}
|
|
1298
|
+
async function cardOf(carrier, { name, relay }, now, operator) {
|
|
1299
|
+
const ans = await carrier.fetchGroupCard(relay, name) ?? fail('group_name', `no supergroup ${name} at ${relay} (or its slot ended)`);
|
|
1300
|
+
return checkCard(ans, { name, relay, now, operator: operator ?? await registryOperator(carrier, relay) });
|
|
1301
|
+
}
|
|
1302
|
+
/** A supergroup's card by its address (name@relay), checked offline; invite left out (join takes it). The join screen's preview. */
|
|
1303
|
+
export async function card({ carrier, address, operator }) {
|
|
1304
|
+
const addr = parseAddress(address) ?? fail('group_name', 'a supergroup\'s address: name@relay (3 to 32 of a-z, 0-9 and -)');
|
|
1305
|
+
const { invite, ...c } = await cardOf(carrier, addr, nowOf(carrier), operator);
|
|
1306
|
+
return { ...c, address: `${c.name}@${c.relay}`, link: `https://sigelo.io/join#${c.name}@${c.relay}` };
|
|
1307
|
+
}
|
|
1308
|
+
/** The listed public supergroups of a relay (GET /groups): [{ name, about, address }], a page of 100 by name after `after`. A page of the relay, never a verify path. */
|
|
1309
|
+
export async function listed({ carrier, relay, after = '' }) {
|
|
1310
|
+
return (await carrier.fetchGroupList(relay, after)).map((g) => ({ ...g, address: `${g.name}@${relay}` }));
|
|
1311
|
+
}
|
|
1312
|
+
/**
|
|
1313
|
+
* The owner names its group with the slot its home relay's operator sold it: a card signed by the owner, then the
|
|
1314
|
+
* `name` request. public (default): the card carries a new link's invite (ttl, cap, approve: a link's; default 366
|
|
1315
|
+
* days, 500 a day, the group's join setting), and listed puts it on GET /groups; private: no invite, no avatar, never
|
|
1316
|
+
* listed. Again with the same name: a new card (about, avatar, link); the old card's link is ended.
|
|
1317
|
+
*/
|
|
1318
|
+
export async function name({ carrier, file, group, name: nm, public: pub = true, listed: list = false, ttl = W.LINK_MAX, cap = W.LINK_CAP_MAX, approve, model = false }) {
|
|
1319
|
+
personGate(model, 'naming a supergroup');
|
|
1320
|
+
if (typeof nm !== 'string' || !NAME_RE.test(nm)) fail('group_name', 'a supergroup name: 3 to 32 of a-z, 0-9 and -');
|
|
1321
|
+
if (typeof pub !== 'boolean' || typeof list !== 'boolean') fail('group_name', 'public and listed: true or false');
|
|
1322
|
+
return one({ carrier, file }, group, async (S) => {
|
|
1323
|
+
const G = S.G, me = S.refresh().me;
|
|
1324
|
+
if (roleOf(G, me.original) !== 'owner') fail('group_role', 'only the group\'s owner names it (with the slot its relay sold the owner)');
|
|
1325
|
+
const was = G.super, l = pub ? await makeLink(S, { ttl, cap, approve, park: false }) : null;
|
|
1326
|
+
const body = { v: W.GROUP2_V, typ: 'card', name: nm, home: G.home, gid: G.gid, owner: me.original, public: pub, about: G.settings.about ?? '', avatar: pub ? G.settings.avatar ?? null : null, invite: l ? l.invite : null, iat: S.refresh().now };
|
|
1327
|
+
let a;
|
|
1328
|
+
try { a = await S.h.control({ typ: 'name', topic: G.topic, card: { body, sig: me.sign(body) }, chain: me.own, listed: pub && list }); } catch (e) { if (l) await dropLink(S, l.id).catch(() => {}); throw e; }
|
|
1329
|
+
G.super = { name: nm, public: pub, listed: pub && list, exp: a.exp, members: a.members, ...(l && { link: l.id }) };
|
|
1330
|
+
S.save();
|
|
1331
|
+
if (was?.link && was.link !== l?.id && G.links[was.link]) await dropLink(S, was.link).catch(() => {});
|
|
1332
|
+
return { name: nm, relay: G.home, address: `${nm}@${G.home}`, link: `https://sigelo.io/join#${nm}@${G.home}`, public: pub, listed: pub && list, exp: a.exp, members: a.members, words: didWords(me.original), ...(l && { approve: l.approve, link_exp: l.exp }) };
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
// ---------------------------------------------------------------- views
|
|
1337
|
+
function summary(G, me, s) {
|
|
1338
|
+
const myRole = me ? roleOf(G, me.original) : null;
|
|
1339
|
+
return { gid: G.gid, name: G.name, v: 2, home: G.home, status: G.status, role: myRole, epoch: G.epoch, seq: G.seq, settings: G.settings, moderate: modLeft(G, s, me?.original, me?.now ?? 0),
|
|
1340
|
+
members: Object.entries(G.roster).map(([did, m]) => ({ did, name: m.name, kind: m.kind, role: m.role, me: me?.original === did })),
|
|
1341
|
+
links: Object.entries(G.links).filter(([, l]) => l.exp > (me?.now ?? 0)).map(([id, l]) => ({ id, exp: l.exp, approve: l.approve, ...(l.code && { code: l.code }) })),
|
|
1342
|
+
requests: Object.keys(G.requests).length + Object.keys(G.asks).length, pins: G.pins, dropped: G.dropped, ...(G.suspect && { suspect: G.suspect }), ...(G.super && { supergroup: { ...G.super, address: `${G.super.name}@${G.home}` } }),
|
|
1343
|
+
...(G.invited && { invited: G.invited }), ...(G.moved_from && { moved_from: G.moved_from }) };
|
|
1344
|
+
}
|
|
1345
|
+
export function list({ carrier, file }) {
|
|
1346
|
+
const { s } = open({ carrier, file }), now = nowOf(carrier), me = { ...meOf(carrier, now), now };
|
|
1347
|
+
return Object.values(s.groups).map((G) => summary(G, me, s));
|
|
1348
|
+
}
|
|
1349
|
+
/** The chat as this member holds it: messages and polls, edits, deletions, reactions, votes, pins; acts: kicks, deletes, pins, by whom. */
|
|
1350
|
+
export function show({ carrier, file, group }) {
|
|
1351
|
+
const { s } = open({ carrier, file }), G = pick(s, group, false), now = nowOf(carrier), me = { ...meOf(carrier, now), now };
|
|
1352
|
+
return { group: summary(G, me, s), messages: G.history.map((x) => ({ ...x, mine: x.from === me.original, pinned: G.pins.includes(x.mid) })), acts: G.acts ?? [] };
|
|
1353
|
+
}
|
|
1354
|
+
// What a moderator sees of the event history (agents moderate, people administer: design/groups-build.md §4.13): what it may
|
|
1355
|
+
// act on. The owner and admins see every kind.
|
|
1356
|
+
export const MOD_EVENTS = new Set(['kicked', 'banned', 'deleted', 'pinned', 'unpinned']);
|
|
1357
|
+
export const EVENTS_LIMIT = 100;
|
|
1358
|
+
/**
|
|
1359
|
+
* The event history of one group as this member holds it (pure: the group's record G and this member's original DID).
|
|
1360
|
+
* From G.events (recorded as each body was applied, since this build) and, for rows read before it, G.acts (kicks, deletes
|
|
1361
|
+
* of others' messages, pins). → { gid, name, role, full, events: [{ seq, at, kind, by: {did, name}, target?: {did, name},
|
|
1362
|
+
* detail }], more }, newest first (seq, then at); since: unix seconds, events at or after it; limit 1-500 (default 100).
|
|
1363
|
+
* Owner and admins: every kind (full); a moderator: kicks, bans, deletes, pins; anyone else: group_role.
|
|
1364
|
+
* A deleted message's text: never kept (a delete takes it out of the file); detail.text only for the owner or an admin and
|
|
1365
|
+
* only when the file still holds it.
|
|
1366
|
+
*/
|
|
1367
|
+
export function eventsOf(G, me, { since, limit = EVENTS_LIMIT } = {}) {
|
|
1368
|
+
// A group that ended stays readable to those who ran it; one left or removed from does not.
|
|
1369
|
+
const role = G.status === 'member' || G.status === 'closed' ? roleOf(G, me) : null;
|
|
1370
|
+
if (!isMod(role)) fail('group_role', `the event history of ${G.name} is for its owner, admins and moderators`);
|
|
1371
|
+
if (since !== undefined && (!Number.isSafeInteger(since) || since < 0)) fail('group_events', 'since: unix seconds');
|
|
1372
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > EVENTS_MAX) fail('group_events', `limit: 1 to ${EVENTS_MAX}`);
|
|
1373
|
+
const full = isAdmin(role), recs = [...(G.events ?? [])], seqs = new Set(recs.map((e) => e.seq));
|
|
1374
|
+
// Rows read before the event history was built: their acts (kick, a delete of another's message, pin) only.
|
|
1375
|
+
for (const a of G.acts ?? []) {
|
|
1376
|
+
if (seqs.has(a.seq)) continue;
|
|
1377
|
+
const kind = a.typ === 'kick' ? (a.bar ? 'banned' : 'kicked') : a.typ === 'delete' ? 'deleted' : a.on ? 'pinned' : 'unpinned';
|
|
1378
|
+
const target = a.typ === 'kick' ? { target: a.member, target_name: a.name } : a.author ? { target: a.author, target_name: null } : {};
|
|
1379
|
+
recs.push({ seq: a.seq, at: a.iat, by: a.by, by_name: a.by_name, kind, ...target, detail: a.typ === 'kick' ? { ...(a.reason && { reason: a.reason }) } : { re: a.re, ...(a.typ === 'delete' && { own: false }) } });
|
|
1380
|
+
}
|
|
1381
|
+
const nameOf = (did, n) => G.roster[did]?.name ?? n ?? null;
|
|
1382
|
+
const list = recs.map((e, i) => ({ e, i })).filter(({ e }) => (full || MOD_EVENTS.has(e.kind)) && (since === undefined || e.at >= since))
|
|
1383
|
+
.sort((x, y) => y.e.seq - x.e.seq || y.e.at - x.e.at || y.i - x.i).map(({ e }) => {
|
|
1384
|
+
const it = full && e.kind === 'deleted' ? G.history.find((x) => x.mid === e.detail.re) : undefined;
|
|
1385
|
+
return { seq: e.seq, at: e.at, kind: e.kind, by: { did: e.by, name: nameOf(e.by, e.by_name) }, ...(e.target && { target: { did: e.target, name: nameOf(e.target, e.target_name) } }),
|
|
1386
|
+
detail: { ...e.detail, ...(it?.text !== undefined && { text: it.text }) } };
|
|
1387
|
+
});
|
|
1388
|
+
return { gid: G.gid, name: G.name, role, full, events: list.slice(0, limit), more: Math.max(0, list.length - limit) };
|
|
1389
|
+
}
|
|
1390
|
+
/** The event history of a group from this member's file (no relay): eventsOf. */
|
|
1391
|
+
export function events({ carrier, file, group, since, limit }) {
|
|
1392
|
+
const { s } = open({ carrier, file }), G = pick(s, group, false), now = nowOf(carrier);
|
|
1393
|
+
return eventsOf(G, meOf(carrier, now).original, { since, ...(limit !== undefined && { limit }) });
|
|
1394
|
+
}
|
|
1395
|
+
/** The items waiting for the inbox; pick(item) true: taken. */
|
|
1396
|
+
export function unread({ carrier, file, pick: p = () => true }) {
|
|
1397
|
+
const { s, save } = open({ carrier, file });
|
|
1398
|
+
const took = s.unread.filter((x) => p(x));
|
|
1399
|
+
if (took.length) { s.unread = s.unread.filter((x) => !took.includes(x)); save(); }
|
|
1400
|
+
return took;
|
|
1401
|
+
}
|
|
1402
|
+
/** The home relays of the live home groups (carrier.mjs setHomes: a started carrier stays there and registers push). */
|
|
1403
|
+
export function homes({ carrier, file }) {
|
|
1404
|
+
try { return [...new Set(Object.values(readFile(file, platformOf(carrier)).groups).filter((G) => ['member', 'joining'].includes(G.status)).map((G) => G.home))]; } catch { return []; }
|
|
1405
|
+
}
|
|
1406
|
+
/** Live home groups in the file (inbox syncs them). */
|
|
1407
|
+
export function live({ carrier, file }) {
|
|
1408
|
+
try { return Object.values(readFile(file, platformOf(carrier)).groups).filter((G) => ['member', 'joining'].includes(G.status)).length; } catch { return 0; }
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
// ---------------------------------------------------------------- the app's screens (design/groups-build.md step 6)
|
|
1412
|
+
/** Beside list(), per gid, what the app's screens read: the owner, how a closed group ended (end, moved), the barred, the
|
|
1413
|
+
* requests waiting, a join waiting (its time), the last seq handled. The file only, no relay. */
|
|
1414
|
+
export function local({ carrier, file }) {
|
|
1415
|
+
let s;
|
|
1416
|
+
try { s = readFile(file, platformOf(carrier)); } catch { return {}; }
|
|
1417
|
+
return Object.fromEntries(Object.values(s.groups).map((G) => [G.gid, { name: G.name, status: G.status, owner: G.owner ?? null, closed: G.closed ?? null, barred: [...(G.barred ?? [])],
|
|
1418
|
+
requests: listRequests(G), joining: G.joining ? { at: G.joining.at } : null, seq: G.seq, invited: G.invited ?? null, moved_from: G.moved_from ?? null }]));
|
|
1419
|
+
}
|
|
1420
|
+
/** A home group out of this file: a join still waiting (the app's Cancel), or one that ended for this member (left, removed,
|
|
1421
|
+
* closed: Delete chat). A member leaves first. */
|
|
1422
|
+
export function drop({ carrier, file, group }) {
|
|
1423
|
+
const { s, save } = open({ carrier, file }), G = pick(s, group, false);
|
|
1424
|
+
if (G.status === 'member') fail('group_member', `still a member of ${G.name}: leave it first`);
|
|
1425
|
+
blobStore({ carrier, file }).drop(G, Object.keys(G.blobs ?? {})); // its files and picture (step 7)
|
|
1426
|
+
delete s.groups[G.gid];
|
|
1427
|
+
save();
|
|
1428
|
+
return { dropped: G.gid, was: G.status };
|
|
1429
|
+
}
|
|
1430
|
+
/** A GRP code, its link or a long invite read but not used (the app's join screen): the group's name, home, owner, approve, exp. */
|
|
1431
|
+
export async function peek({ carrier, code, home }) {
|
|
1432
|
+
const now = nowOf(carrier), text = String(code ?? '').trim(), frag = text.includes('#') ? text.slice(text.indexOf('#') + 1) : text;
|
|
1433
|
+
let inv;
|
|
1434
|
+
if (W.isGroupCode(frag)) {
|
|
1435
|
+
const norm = W.normaliseGroupCode(frag), at = (await carrier.relayForShort(norm, home === undefined ? {} : { relay: home })).relay;
|
|
1436
|
+
const long = await carrier.fetchGroupCode(at, W.groupCodeHash(frag)) ?? fail('group_code', `no group code ${W.formatGroupCode(norm)} at ${at}: it ended or was unlinked`);
|
|
1437
|
+
inv = W.parseInviteLong(long, now);
|
|
1438
|
+
if (inv.body.home !== at) fail('group_code', `the invite parked at ${at} names home ${inv.body.home}`);
|
|
1439
|
+
} else inv = W.parseInviteLong(frag, now);
|
|
1440
|
+
const b = inv.body;
|
|
1441
|
+
return { gid: b.gid, name: b.name, home: b.home, owner: b.owner, words: didWords(b.owner), approve: b.approve, exp: b.exp };
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
// ---------------------------------------------------------------- files and the picture in the log (design/groups-build.md step 7)
|
|
1445
|
+
// A file up to 8 MiB goes as blob entries (256 KiB each), then the msg naming their mids (§1.4); the group's picture is one
|
|
1446
|
+
// blob in keep slot 9 under the admin credential, then a settings body naming it. Each part read is kept beside the groups
|
|
1447
|
+
// file (x.groups2.blobs/<gid>.<mid>, its bytes; G.blobs: {mid: {sha256, type, part, parts, from, seq, n, avatar?}}): its
|
|
1448
|
+
// message key is gone once used (§2.2), so the log cannot be read again. At most FILE_KEEP a group: the oldest parts go
|
|
1449
|
+
// first, never the picture in use; a deleted message's parts go at once; a dropped group's all.
|
|
1450
|
+
export const FILE_KEEP = 64 * 2 ** 20;
|
|
1451
|
+
const blobDir = (file) => file.replace(/\.json$/, '') + '.blobs';
|
|
1452
|
+
function blobStore(o) {
|
|
1453
|
+
const platform = platformOf(o.carrier), dir = blobDir(o.file), at = (gid, mid) => `${dir}/${gid}.${mid}`;
|
|
1454
|
+
const S = {
|
|
1455
|
+
put(G, seq, from, b, slot) {
|
|
1456
|
+
const bytes = W.unb64u(b.data);
|
|
1457
|
+
if (!bytes) return;
|
|
1458
|
+
platform.files.folder?.(dir);
|
|
1459
|
+
platform.files.write(at(G.gid, b.mid), bytes);
|
|
1460
|
+
const avatar = slot === W.KEEP_AVATAR;
|
|
1461
|
+
// A new picture: the parts of pictures neither in use nor this one go.
|
|
1462
|
+
if (avatar) S.drop(G, Object.entries(G.blobs ?? {}).filter(([, x]) => x.avatar && x.sha256 !== b.sha256 && x.sha256 !== G.settings.avatar?.sha256).map(([m]) => m));
|
|
1463
|
+
(G.blobs ??= {})[b.mid] = { sha256: b.sha256, type: b.type, part: b.part, parts: b.parts, from, seq, n: bytes.length, ...(avatar && { avatar: true }) };
|
|
1464
|
+
S.trim(G);
|
|
1465
|
+
},
|
|
1466
|
+
drop(G, mids) { for (const m of mids) if (G.blobs?.[m]) { platform.files.remove(at(G.gid, m)); delete G.blobs[m]; } },
|
|
1467
|
+
trim(G) {
|
|
1468
|
+
const pic = G.settings.avatar?.sha256, oldest = G.history.length >= HISTORY_MAX ? G.history[0].seq : 0;
|
|
1469
|
+
const live = ([, x]) => x.avatar && x.sha256 === pic;
|
|
1470
|
+
S.drop(G, Object.entries(G.blobs).filter((e) => !live(e) && e[1].seq < oldest).map(([m]) => m)); // past the history kept
|
|
1471
|
+
let total = Object.values(G.blobs).reduce((a, x) => a + x.n, 0);
|
|
1472
|
+
for (const e of Object.entries(G.blobs).sort((a, b) => a[1].seq - b[1].seq)) { if (total <= FILE_KEEP) break; if (live(e)) continue; total -= e[1].n; S.drop(G, [e[0]]); }
|
|
1473
|
+
},
|
|
1474
|
+
read: (G, mid) => platform.files.read(at(G.gid, mid)),
|
|
1475
|
+
};
|
|
1476
|
+
return S;
|
|
1477
|
+
}
|
|
1478
|
+
/** A file into the log (≤ 8 MiB: FILE_IN_LOG): its parts as blob entries, then the msg with its manifest {name, size, sha256, type, parts}. */
|
|
1479
|
+
export async function sendFile({ carrier, file, group, name, type = 'application/octet-stream', bytes, text, re }) {
|
|
1480
|
+
if (!(bytes instanceof Uint8Array) || bytes.length === 0) fail('group_file', 'a file of at least one byte');
|
|
1481
|
+
if (bytes.length > W.FILE_IN_LOG) fail('group_file_size', `${name} is ${bytes.length} bytes: a file in a group is at most 8 MiB (${W.FILE_IN_LOG} bytes)`);
|
|
1482
|
+
const sha = W.hex(sha256(bytes)), parts = Math.ceil(bytes.length / W.BLOB_PART);
|
|
1483
|
+
return one({ carrier, file }, group, async (S) => {
|
|
1484
|
+
const G = S.G, me = S.refresh().me;
|
|
1485
|
+
// The msg it will be, checked before any part goes (its name, type, text, the role in channel mode).
|
|
1486
|
+
const draft = { name, size: bytes.length, sha256: sha, type, parts: Array.from({ length: parts }, () => W.newMid()) };
|
|
1487
|
+
const body = { v: W.GROUP2_V, typ: 'msg', gid: G.gid, mid: W.newMid(), iat: S.ctx.now, from: me.current, epoch: G.epoch || 1, at: G.seq, file: draft, ...(text && { text }), ...(re && { re }) };
|
|
1488
|
+
W.checkBody(body);
|
|
1489
|
+
W.authorize(body, { role: roleOf(G, me.original), self: me.original, channel: G.settings.channel, agents: G.settings.agents });
|
|
1490
|
+
const mids = [];
|
|
1491
|
+
for (let i = 0; i < parts; i++) mids.push((await S.post('blob', { sha256: sha, type, part: i + 1, parts, data: b64(bytes.subarray(i * W.BLOB_PART, (i + 1) * W.BLOB_PART)) })).mid);
|
|
1492
|
+
return S.post('msg', { file: { ...draft, parts: mids }, ...(text && { text }), ...(re && { re }) });
|
|
1493
|
+
});
|
|
1494
|
+
}
|
|
1495
|
+
/** A file of a message, from the parts this member kept: → { name, type, size, sha256, bytes }; group_file_gone when a part is not here. */
|
|
1496
|
+
export function fileOf({ carrier, file, group, mid }) {
|
|
1497
|
+
const { s } = open({ carrier, file }), G = pick(s, group, false), st = blobStore({ carrier, file });
|
|
1498
|
+
const it = G.history.find((x) => x.mid === mid) ?? fail('group_message', `no message ${mid} in ${G.name}`);
|
|
1499
|
+
const f = it.file ?? fail('group_message', `message ${mid} carries no file`);
|
|
1500
|
+
if (!Array.isArray(f.parts)) fail('group_file_gone', `${f.name} was sent direct (not in the log)`);
|
|
1501
|
+
const out = new Uint8Array(f.size);
|
|
1502
|
+
let off = 0;
|
|
1503
|
+
for (const [i, m] of f.parts.entries()) {
|
|
1504
|
+
const x = G.blobs?.[m], b = x && x.from === it.from && x.sha256 === f.sha256 && x.part === i + 1 && x.parts === f.parts.length ? st.read(G, m) : null;
|
|
1505
|
+
if (!b || off + b.length > f.size) fail('group_file_gone', `${f.name} is not on this device (sent before you joined, or let go to keep space)`);
|
|
1506
|
+
out.set(b, off); off += b.length;
|
|
1507
|
+
}
|
|
1508
|
+
if (off !== f.size || W.hex(sha256(out)) !== f.sha256) fail('group_file_gone', `${f.name}: the parts kept here do not make the file`);
|
|
1509
|
+
return { name: f.name, type: f.type, size: f.size, sha256: f.sha256, bytes: out };
|
|
1510
|
+
}
|
|
1511
|
+
/** The group's picture for everyone (an admin): one blob in keep slot 9, then settings {avatar: {sha256, type, w, h}}; bytes null removes it. */
|
|
1512
|
+
export async function avatar({ carrier, file, group, type, bytes, w, h, model = false }) {
|
|
1513
|
+
personGate(model, 'the group\'s picture');
|
|
1514
|
+
return one({ carrier, file }, group, async (S) => {
|
|
1515
|
+
if (!S.admin) fail('group_role', 'the group\'s picture needs an admin');
|
|
1516
|
+
if (bytes === null) return S.post('settings', { settings: { avatar: null } });
|
|
1517
|
+
if (!(bytes instanceof Uint8Array) || bytes.length === 0 || bytes.length > W.BLOB_PART) fail('group_file_size', `a group picture is 1 byte to ${W.BLOB_PART / 1024} KiB`);
|
|
1518
|
+
const a = { sha256: W.hex(sha256(bytes)), type, w, h };
|
|
1519
|
+
W.checkBody({ v: W.GROUP2_V, typ: 'settings', gid: S.G.gid, mid: W.newMid(), iat: S.refresh().now, from: S.ctx.me.current, epoch: S.G.epoch, at: S.G.seq, settings: { avatar: a } });
|
|
1520
|
+
await S.post('blob', { sha256: a.sha256, type, part: 1, parts: 1, data: b64(bytes) }, { slot: W.KEEP_AVATAR });
|
|
1521
|
+
return S.post('settings', { settings: { avatar: a } });
|
|
1522
|
+
});
|
|
1523
|
+
}
|
|
1524
|
+
/** The group's picture as kept here: → { type, sha256, bytes } or null (none set, or its blob not here). */
|
|
1525
|
+
export function avatarOf({ carrier, file, group }) {
|
|
1526
|
+
let s;
|
|
1527
|
+
try { s = readFile(file, platformOf(carrier)); } catch { return null; }
|
|
1528
|
+
const G = s.groups[group], a = G?.settings?.avatar;
|
|
1529
|
+
if (!a) return null;
|
|
1530
|
+
const m = Object.entries(G.blobs ?? {}).find(([, x]) => x.avatar && x.sha256 === a.sha256)?.[0];
|
|
1531
|
+
const bytes = m ? blobStore({ carrier, file }).read(G, m) : null;
|
|
1532
|
+
// A picture is shown as one: an admin's type that is not a common image is not handed on (a page never renders it as a document).
|
|
1533
|
+
return bytes && W.hex(sha256(bytes)) === a.sha256 ? { type: /^image\/(png|jpeg|gif|webp)$/.test(a.type) ? a.type : 'application/octet-stream', sha256: a.sha256, bytes } : null;
|
|
1534
|
+
}
|