sigelo-contact 0.1.13 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +13 -10
  2. package/call.mjs +727 -0
  3. package/carrier.mjs +1204 -137
  4. package/control.mjs +81 -22
  5. package/device.mjs +1 -1
  6. package/enrol.mjs +239 -43
  7. package/gen-carrier.mjs +4 -4
  8. package/gen-device.mjs +2 -2
  9. package/gen-envelope.mjs +3 -3
  10. package/gen-invite.mjs +3 -3
  11. package/gen-short.mjs +3 -3
  12. package/group.mjs +616 -0
  13. package/invite.mjs +63 -13
  14. package/kdf.mjs +1 -1
  15. package/link.mjs +24 -16
  16. package/package.json +49 -7
  17. package/page.mjs +1172 -70
  18. package/photo.mjs +37 -0
  19. package/platform-node.mjs +125 -18
  20. package/prekeys.mjs +10 -2
  21. package/public.mjs +93 -0
  22. package/relays.mjs +1 -1
  23. package/restore.mjs +3 -3
  24. package/rtc-web.mjs +95 -0
  25. package/short.mjs +31 -3
  26. package/store.mjs +147 -12
  27. package/test-carrier.mjs +138 -21
  28. package/test-device.mjs +1 -1
  29. package/test-enrol.mjs +157 -8
  30. package/test-envelope.mjs +16 -3
  31. package/test-file.mjs +5 -5
  32. package/test-group.mjs +413 -0
  33. package/test-invite.mjs +15 -2
  34. package/test-link.mjs +11 -8
  35. package/test-platform.mjs +5 -5
  36. package/test-presence.mjs +169 -0
  37. package/test-push.mjs +136 -0
  38. package/test-relay-lane.mjs +248 -0
  39. package/test-short.mjs +38 -12
  40. package/test-tier.mjs +6 -6
  41. package/test-transfer-web.mjs +246 -0
  42. package/test-transfer.mjs +463 -0
  43. package/test-voice.mjs +158 -0
  44. package/test-ws.mjs +5 -5
  45. package/transfer-engine.mjs +800 -0
  46. package/transfer-node.mjs +449 -0
  47. package/transfer-web.mjs +80 -0
  48. package/transfer.mjs +388 -0
  49. package/voice-web.mjs +113 -0
  50. package/voice.mjs +65 -0
  51. package/words-lock.mjs +115 -0
package/transfer.mjs ADDED
@@ -0,0 +1,388 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Big files agent to agent (design/transfer.md, apps/agent/TRANSFER.md): the pure part, no I/O.
3
+ // The relay carries only the introduction, four small messages labelled TRANSFER_LABEL inside the
4
+ // pairing's end-to-end envelopes; the bytes go over a direct WebRTC data channel (sigelo-transfer,
5
+ // werift) or a one-shot Tor onion stream, both driven by transfer-node.mjs. Here: the messages and
6
+ // their checks, the frames on the channel, the chunk bitmap, the two ends of the chunk protocol
7
+ // over an abstract channel, and the order the paths are tried in.
8
+ //
9
+ // The messages (content of a TRANSFER_LABEL message; id: 32 hex digits, one per file offered):
10
+ // manifest sender → receiver {typ, id, name, size, sha256 (the file), chunk, chunks, list (SHA-256 of the chunk hashes), exp}
11
+ // offer receiver → sender {typ, id, attempt, sdp (null: no direct path from this side), tor: {serve, connect}, via?: "tor"}
12
+ // answer sender → receiver {typ, id, attempt, sdp, tor}
13
+ // onion the side that serves {typ, id, attempt, onion (56 base32), port, auth (x25519 client key, base64, or null), token (64 hex)}
14
+ // end either side {typ, id, reason, attempt?} reason one of REASONS
15
+ // End `relay` (0.1.19): the sender sends the file over sigelo-file/0 instead (file.mjs, at most 8 MiB); the receiver's
16
+ // record stops there (relayed), its partial dropped.
17
+ // The receiver offers because it pulls. Offer and answer ride signed envelopes naming id and attempt,
18
+ // so the two identities authenticate the DTLS fingerprints and the onion address: the relay cannot sit
19
+ // in the middle. Data channel label: `sigelo-transfer/0 <id> <attempt>`; any other is closed.
20
+ //
21
+ // The frames (binary, at most FRAME bytes each; on a Tor stream each behind a u32 BE length):
22
+ // LIST sender [1][u32 first index][32-byte chunk hashes…] checked whole against the manifest's list
23
+ // WANT receiver [2][u32 from][u16 n] at most OUTSTANDING chunks asked and not yet written
24
+ // DATA sender [3][u32 index][u32 offset][bytes] a chunk in frames of DATA_MAX (17 for 1 MiB)
25
+ // END either [4][u8 reason] done once the receiver read the file back
26
+ // TOKEN connector [5][32 bytes] the first frame on a Tor stream, else it is closed
27
+ // Back-pressure: the receiver asks again only after writing to disk; the sender stops above HIGH
28
+ // buffered and goes on below LOW. A chunk whose SHA-256 is not the list's is asked once more, then
29
+ // the transfer ends chunk_hash. Nothing is written before the receiver's operator said yes.
30
+ import { sha256 } from '@noble/hashes/sha2.js';
31
+ import { bytesToHex, concatBytes, hexToBytes, randomBytes } from '@noble/hashes/utils.js';
32
+ import { fail } from './kdf.mjs';
33
+
34
+ export const TRANSFER_LABEL = 'sigelo-transfer/0';
35
+ export const CHUNK = 1 << 20, MAX_SIZE = 16 * 2 ** 30, MAX_CHUNKS = MAX_SIZE / CHUNK;
36
+ export const FRAME = 65536, DATA_HEAD = 9, DATA_MAX = FRAME - DATA_HEAD, HASHES_PER_FRAME = Math.floor((FRAME - 5) / 32);
37
+ export const OUTSTANDING = 8, HIGH = 4 * CHUNK, LOW = CHUNK, RETRIES = 1;
38
+ // Timings (design §3): a manifest lives 7 days; candidates gathered 3 s; an offer waits 10 minutes
39
+ // for its answer, then ICE has 30 s.
40
+ export const DAY = 86400, MANIFEST_TTL = 7 * DAY, GATHER_MS = 3000, ANSWER_WAIT = 600, ICE_MS = 30_000;
41
+ // Manifests waiting for a yes: so many per contact and in all; more get `end busy`.
42
+ export const WAIT_CONTACT = 8, WAIT_ALL = 64;
43
+ // The accept rule's default (design §10.2, decided 2026-11-13): files up to 25 MB land without a question
44
+ // from own agents and contacts and from friends whose words were compared.
45
+ export const AUTO_MB = 25;
46
+ export const REASONS = ['done', 'declined', 'cancelled', 'no_path', 'try_tor', 'chunk_hash', 'file_changed', 'busy', 'relay'];
47
+ export const TYPS = ['manifest', 'offer', 'answer', 'onion', 'end'];
48
+ export const T = { LIST: 1, WANT: 2, DATA: 3, END: 4, TOKEN: 5 };
49
+ export const NAME_MAX_IN = 1024, SDP_MAX = 16384, ATTEMPT_MAX = 1000;
50
+
51
+ const ID = /^[0-9a-f]{32}$/, HEX64 = /^[0-9a-f]{64}$/, ONION = /^[a-z2-7]{56}$/, B64KEY = /^[A-Za-z0-9+/]{43}=$/;
52
+ const isObject = (x) => typeof x === 'object' && x !== null && !Array.isArray(x);
53
+ const int = (n, lo, hi) => Number.isSafeInteger(n) && n >= lo && n <= hi;
54
+ const hex = (b) => bytesToHex(b);
55
+ /** A transfer id: 16 random bytes as hex. */
56
+ export const newId = (rng = randomBytes) => hex(rng(16));
57
+ /** How many chunks a file of n bytes goes in. */
58
+ export const chunksOf = (n) => Math.ceil(n / CHUNK);
59
+ /** The length of chunk i of a file of size bytes. */
60
+ export const chunkLength = (size, i) => Math.min(CHUNK, size - i * CHUNK);
61
+ /** The manifest's list: SHA-256 over the chunk hashes, in order (hashes: 32 bytes each, concatenated). */
62
+ export const listOf = (hashes, h = sha256) => hex(h(hashes));
63
+ export const sha256Hex = (b) => hex(sha256(b));
64
+
65
+ // ---------------------------------------------------------------- the messages
66
+
67
+ /** A manifest for a file whose chunk hashes are known. → the message content. */
68
+ export function manifest({ id = newId(), name, size, sha256: whole, hashes, now, h = sha256 }) {
69
+ if (!int(size, 0, MAX_SIZE)) fail('transfer_too_large', `${size} bytes: at most ${MAX_SIZE} (16 GiB) a file`);
70
+ if (hashes.length !== chunksOf(size) * 32) throw new TypeError('hashes: 32 bytes per chunk');
71
+ return { typ: 'manifest', id, name, size, sha256: whole, chunk: CHUNK, chunks: chunksOf(size), list: listOf(hashes, h), exp: now + MANIFEST_TTL };
72
+ }
73
+
74
+ const SHAPES = {
75
+ manifest: ['name', 'size', 'sha256', 'chunk', 'chunks', 'list', 'exp'],
76
+ offer: ['attempt', 'sdp', 'tor'],
77
+ answer: ['attempt', 'sdp', 'tor'],
78
+ onion: ['attempt', 'onion', 'port', 'auth', 'token'],
79
+ end: ['reason'],
80
+ };
81
+ const MAY = { offer: ['via'], end: ['attempt'] };
82
+ /** A TRANSFER_LABEL message's content, checked for shape (transfer_message, transfer_too_large). → it. */
83
+ export function checkMessage(x) {
84
+ const bad = (why) => fail('transfer_message', `not a ${TRANSFER_LABEL} message: ${why}`);
85
+ if (!isObject(x) || !TYPS.includes(x.typ)) bad('typ');
86
+ if (typeof x.id !== 'string' || !ID.test(x.id)) bad('id: 32 lowercase hex digits');
87
+ const need = SHAPES[x.typ], may = MAY[x.typ] ?? [];
88
+ for (const k of need) if (!Object.hasOwn(x, k)) bad(`${x.typ} needs ${k}`);
89
+ for (const k of Object.keys(x)) if (k !== 'typ' && k !== 'id' && !need.includes(k) && !may.includes(k)) bad(`${x.typ} has no ${k}`);
90
+ if (Object.hasOwn(x, 'attempt') && !int(x.attempt, 1, ATTEMPT_MAX)) bad(`attempt: 1 to ${ATTEMPT_MAX}`);
91
+ switch (x.typ) {
92
+ case 'manifest':
93
+ if (typeof x.name !== 'string' || x.name.length === 0 || x.name.length > NAME_MAX_IN) bad(`name: 1 to ${NAME_MAX_IN} characters`);
94
+ if (!int(x.size, 0, Number.MAX_SAFE_INTEGER)) bad('size: whole bytes');
95
+ if (x.size > MAX_SIZE) fail('transfer_too_large', `the manifest says ${x.size} bytes, at most ${MAX_SIZE} (16 GiB) a file`);
96
+ if (typeof x.sha256 !== 'string' || !HEX64.test(x.sha256) || typeof x.list !== 'string' || !HEX64.test(x.list)) bad('sha256 and list: 64 lowercase hex digits');
97
+ if (x.chunk !== CHUNK) bad(`chunk: ${CHUNK}`);
98
+ if (x.chunks !== chunksOf(x.size)) bad(`chunks: ${x.size} bytes go in ${chunksOf(x.size)}`);
99
+ if (!int(x.exp, 0, Number.MAX_SAFE_INTEGER)) bad('exp: unix seconds');
100
+ break;
101
+ case 'offer': case 'answer':
102
+ if (x.sdp !== null && (typeof x.sdp !== 'string' || x.sdp.length === 0 || x.sdp.length > SDP_MAX)) bad(`sdp: null or 1 to ${SDP_MAX} characters`);
103
+ if (!isObject(x.tor) || Object.keys(x.tor).length !== 2 || typeof x.tor.serve !== 'boolean' || typeof x.tor.connect !== 'boolean') bad('tor: {serve, connect}, both true or false');
104
+ if (Object.hasOwn(x, 'via') && x.via !== 'tor') bad('via: "tor"');
105
+ break;
106
+ case 'onion':
107
+ if (typeof x.onion !== 'string' || !ONION.test(x.onion)) bad('onion: 56 base32 characters, no .onion');
108
+ if (!int(x.port, 1, 65535)) bad('port: 1 to 65535');
109
+ if (x.auth !== null && (typeof x.auth !== 'string' || !B64KEY.test(x.auth))) bad('auth: null or a base64 x25519 key');
110
+ if (typeof x.token !== 'string' || !HEX64.test(x.token)) bad('token: 64 lowercase hex digits');
111
+ break;
112
+ case 'end':
113
+ if (!REASONS.includes(x.reason)) bad(`reason: ${REASONS.join(', ')}`);
114
+ break;
115
+ }
116
+ return x;
117
+ }
118
+
119
+ /** The data channel's label for an attempt. */
120
+ export const channelLabel = (id, attempt) => `${TRANSFER_LABEL} ${id} ${attempt}`;
121
+
122
+ // ---------------------------------------------------------------- the frames
123
+
124
+ const u32 = (b, o) => ((b[o] << 24) >>> 0) + (b[o + 1] << 16) + (b[o + 2] << 8) + b[o + 3];
125
+ const put32 = (b, o, n) => { b[o] = n >>> 24; b[o + 1] = (n >>> 16) & 255; b[o + 2] = (n >>> 8) & 255; b[o + 3] = n & 255; };
126
+ export const frames = {
127
+ list(first, hashes) { const f = new Uint8Array(5 + hashes.length); f[0] = T.LIST; put32(f, 1, first); f.set(hashes, 5); return f; },
128
+ want(from, n) { const f = new Uint8Array(7); f[0] = T.WANT; put32(f, 1, from); f[5] = n >>> 8; f[6] = n & 255; return f; },
129
+ data(index, offset, bytes) { const f = new Uint8Array(DATA_HEAD + bytes.length); f[0] = T.DATA; put32(f, 1, index); put32(f, 5, offset); f.set(bytes, DATA_HEAD); return f; },
130
+ end(reason) { const f = new Uint8Array(2); f[0] = T.END; f[1] = Math.max(0, REASONS.indexOf(reason)); return f; },
131
+ token(t) { const f = new Uint8Array(33); f[0] = T.TOKEN; f.set(t, 1); return f; },
132
+ };
133
+ /** A frame as received, checked for shape (transfer_frame). → { type, … }. */
134
+ export function readFrame(f) {
135
+ const bad = (why) => fail('transfer_frame', why);
136
+ if (!(f instanceof Uint8Array) || f.length < 2 || f.length > FRAME) bad('a frame is 2 to 65,536 bytes');
137
+ switch (f[0]) {
138
+ case T.LIST:
139
+ if (f.length < 5 + 32 || (f.length - 5) % 32 !== 0) bad('LIST: a first index and whole hashes');
140
+ return { type: T.LIST, first: u32(f, 1), hashes: f.subarray(5) };
141
+ case T.WANT:
142
+ if (f.length !== 7) bad('WANT: 7 bytes');
143
+ return { type: T.WANT, from: u32(f, 1), n: (f[5] << 8) + f[6] };
144
+ case T.DATA:
145
+ if (f.length <= DATA_HEAD) bad('DATA: a header and bytes');
146
+ return { type: T.DATA, index: u32(f, 1), offset: u32(f, 5), bytes: f.subarray(DATA_HEAD) };
147
+ case T.END:
148
+ if (f.length !== 2 || f[1] >= REASONS.length) bad('END: a reason');
149
+ return { type: T.END, reason: REASONS[f[1]] };
150
+ case T.TOKEN:
151
+ if (f.length !== 33) bad('TOKEN: 32 bytes');
152
+ return { type: T.TOKEN, token: f.subarray(1) };
153
+ default: return bad(`frame type ${f[0]}`);
154
+ }
155
+ }
156
+ /** Length-prefixed frames on a byte stream (Tor): push(bytes) → the whole frames received so far. */
157
+ export function deframer(max = FRAME) {
158
+ let buf = new Uint8Array(0);
159
+ return (bytes) => {
160
+ buf = buf.length ? concatBytes(buf, bytes) : bytes;
161
+ const out = [];
162
+ while (buf.length >= 4) {
163
+ const n = u32(buf, 0);
164
+ if (n < 2 || n > max) fail('transfer_frame', `a stream frame of ${n} bytes`);
165
+ if (buf.length < 4 + n) break;
166
+ out.push(buf.slice(4, 4 + n));
167
+ buf = buf.subarray(4 + n);
168
+ }
169
+ return out;
170
+ };
171
+ }
172
+ /** A frame for a byte stream: its u32 BE length, then the frame. */
173
+ export const enframe = (f) => { const b = new Uint8Array(4 + f.length); put32(b, 0, f.length); b.set(f, 4); return b; };
174
+
175
+ // ---------------------------------------------------------------- the chunk bitmap (<id>.have)
176
+
177
+ export class Have {
178
+ constructor(chunks, bytes) {
179
+ this.chunks = chunks;
180
+ this.bits = bytes ? Uint8Array.from(bytes) : new Uint8Array(Math.ceil(chunks / 8));
181
+ if (this.bits.length !== Math.ceil(chunks / 8)) fail('transfer_have', `a bitmap of ${this.bits.length} bytes for ${chunks} chunks`);
182
+ }
183
+ has(i) { return (this.bits[i >> 3] & (1 << (i & 7))) !== 0; }
184
+ set(i) { this.bits[i >> 3] |= 1 << (i & 7); }
185
+ count() { let n = 0; for (let i = 0; i < this.chunks; i++) if (this.has(i)) n++; return n; }
186
+ done() { return this.count() === this.chunks; }
187
+ /** Bytes held, of a file of size bytes. */
188
+ bytes(size) { let n = 0; for (let i = 0; i < this.chunks; i++) if (this.has(i)) n += chunkLength(size, i); return n; }
189
+ }
190
+
191
+ // ---------------------------------------------------------------- the two ends
192
+ //
193
+ // channel: { send(frame), buffered() → bytes not yet on the wire, close(), on(event, fn) } with the
194
+ // events 'frame' (a Uint8Array), 'low' (buffered fell below LOW) and 'close'. Both ends end once:
195
+ // onEnd(reason, { remote }) — remote: the other side said it.
196
+
197
+ /** The sender's end: the list first, then the chunks the receiver asks for, read in place (read(i) → bytes). */
198
+ export class Serve {
199
+ constructor({ m, hashes, read, channel, onEnd, onProgress = () => {} }) {
200
+ Object.assign(this, { m, hashes, read, ch: channel, onEnd, onProgress });
201
+ this.queue = []; this.busy = false; this.ended = false; this.sent = 0;
202
+ channel.on('frame', (f) => this.#frame(f));
203
+ channel.on('low', () => this.#pump());
204
+ channel.on('close', () => this.#end('cancelled', true, true));
205
+ }
206
+ start() {
207
+ for (let i = 0; i < this.m.chunks; i += HASHES_PER_FRAME) this.#send(frames.list(i, this.hashes.subarray(i * 32, Math.min(this.m.chunks, i + HASHES_PER_FRAME) * 32)));
208
+ }
209
+ #frame(f) {
210
+ if (this.ended) return;
211
+ let x;
212
+ try { x = readFrame(f); } catch { return this.#end('cancelled'); }
213
+ if (x.type === T.END) return this.#end(x.reason, true);
214
+ if (x.type !== T.WANT || x.n < 1 || x.n > OUTSTANDING || x.from + x.n > this.m.chunks || this.queue.length + x.n > 4 * OUTSTANDING) return this.#end('cancelled');
215
+ for (let i = x.from; i < x.from + x.n; i++) this.queue.push(i);
216
+ void this.#pump();
217
+ }
218
+ async #pump() {
219
+ if (this.busy || this.ended) return;
220
+ this.busy = true;
221
+ try {
222
+ while (!this.ended && this.queue.length && this.ch.buffered() < HIGH) {
223
+ const i = this.queue.shift();
224
+ let bytes;
225
+ try { bytes = await this.read(i); } catch (e) { this.#end(e?.check === 'file_changed' ? 'file_changed' : 'cancelled'); return; }
226
+ if (this.ended) return;
227
+ for (let o = 0; o < bytes.length; o += DATA_MAX) if (!this.#send(frames.data(i, o, bytes.subarray(o, o + DATA_MAX)))) return;
228
+ this.sent += bytes.length;
229
+ this.onProgress(this.sent);
230
+ }
231
+ } finally { this.busy = false; }
232
+ }
233
+ // A channel that went away while sending: the end, as if it had closed.
234
+ #send(f) { try { this.ch.send(f); return true; } catch { this.#end('cancelled', true, true); return false; } }
235
+ /** Stop: the other side is told reason (unless it said it, or the channel went). */
236
+ #end(reason, remote = false, gone = false) {
237
+ if (this.ended) return;
238
+ this.ended = true;
239
+ if (!remote && !gone) { try { this.ch.send(frames.end(reason)); } catch {} }
240
+ this.onEnd(reason, { remote: remote && !gone, gone });
241
+ }
242
+ stop(reason = 'cancelled') { this.#end(reason); }
243
+ }
244
+
245
+ /**
246
+ * The receiver's end: checks the list, asks for what `have` lacks, at most OUTSTANDING chunks asked
247
+ * and not yet written, checks each chunk's SHA-256 and writes it (write(i, bytes); flush() before the
248
+ * bits are set: a bit means checked and on disk). A bad chunk is asked once more, then chunk_hash.
249
+ * When every bit is set, onEnd('complete'): the caller reads the file back, then finish('done') or
250
+ * finish('chunk_hash'). hashes: the list from an earlier attempt (a resume), else it comes first.
251
+ */
252
+ export class Pull {
253
+ constructor({ m, have, hashes = null, write, flush, channel, onEnd, onProgress = () => {}, onList = () => {}, h = sha256, flushEach = OUTSTANDING }) {
254
+ Object.assign(this, { m, have, write, flush, ch: channel, onEnd, onProgress, onList, h, flushEach: Math.max(1, Math.min(OUTSTANDING, flushEach)) });
255
+ this.hashes = hashes ?? (m.chunks === 0 ? new Uint8Array(0) : null);
256
+ this.listGot = 0; this.listBuf = this.hashes ? null : new Uint8Array(m.chunks * 32);
257
+ this.out = new Map(); this.writingSet = new Set(); this.unflushed = []; this.again = []; this.next = 0;
258
+ this.tries = new Map(); this.ended = false; this.writing = Promise.resolve();
259
+ channel.on('frame', (f) => this.#frame(f));
260
+ channel.on('close', () => this.#end('cancelled', true, true));
261
+ }
262
+ start() {
263
+ if (this.m.chunks === 0 && listOf(new Uint8Array(0), this.h) !== this.m.list) return this.#end('chunk_hash');
264
+ if (this.hashes) this.#ask();
265
+ }
266
+ #frame(f) {
267
+ if (this.ended) return;
268
+ let x;
269
+ try { x = readFrame(f); } catch { return this.#end('cancelled'); }
270
+ if (x.type === T.END) return this.#end(x.reason, true);
271
+ if (x.type === T.LIST) return this.#list(x);
272
+ if (x.type !== T.DATA || !this.hashes) return this.#end('cancelled');
273
+ const p = this.out.get(x.index);
274
+ if (!p || x.offset !== p.got || p.got + x.bytes.length > p.len) return this.#end('cancelled');
275
+ p.buf.set(x.bytes, p.got);
276
+ p.got += x.bytes.length;
277
+ if (p.got === p.len) this.#chunk(x.index, p.buf);
278
+ }
279
+ #list(x) {
280
+ if (this.listBuf === null) return; // known already (a resume): the sender sends it again
281
+ const n = x.hashes.length / 32;
282
+ if (x.first !== this.listGot || x.first + n > this.m.chunks) return this.#end('cancelled');
283
+ this.listBuf.set(x.hashes, x.first * 32);
284
+ this.listGot += n;
285
+ if (this.listGot < this.m.chunks) return;
286
+ if (listOf(this.listBuf, this.h) !== this.m.list) return this.#end('chunk_hash');
287
+ this.hashes = this.listBuf; this.listBuf = null;
288
+ this.onList(this.hashes);
289
+ this.#ask();
290
+ }
291
+ #chunk(i, buf) {
292
+ this.out.delete(i);
293
+ if (!same(this.h(buf), this.hashes.subarray(i * 32, i * 32 + 32))) {
294
+ const t = (this.tries.get(i) ?? 0) + 1;
295
+ this.tries.set(i, t);
296
+ if (t > RETRIES) return this.#end('chunk_hash');
297
+ this.again.push(i);
298
+ return this.#ask();
299
+ }
300
+ // Written in order of arrival; its slot is free once it is on disk (the back-pressure).
301
+ this.writingSet.add(i);
302
+ this.writing = this.writing.then(async () => {
303
+ if (this.ended) return;
304
+ await this.write(i, buf);
305
+ this.writingSet.delete(i);
306
+ this.unflushed.push(i);
307
+ this.onProgress(buf.length);
308
+ if (this.unflushed.length >= this.flushEach || (this.out.size === 0 && this.writingSet.size === 0)) await this.#flush();
309
+ this.#ask();
310
+ }).catch((e) => { this.error = e; this.#end('cancelled'); });
311
+ }
312
+ async #flush() {
313
+ if (!this.unflushed.length) return;
314
+ const now = this.unflushed.splice(0);
315
+ await this.flush();
316
+ for (const i of now) this.have.set(i);
317
+ }
318
+ #ask() {
319
+ if (this.ended || !this.hashes) return;
320
+ const wanted = [], busy = () => this.out.size + this.writingSet.size + wanted.length;
321
+ while (this.again.length && busy() < OUTSTANDING) wanted.push(this.again.shift());
322
+ while (this.next < this.m.chunks && busy() < OUTSTANDING) {
323
+ const i = this.next++;
324
+ if (!this.have.has(i)) wanted.push(i);
325
+ }
326
+ // Runs of consecutive chunks, one WANT each.
327
+ wanted.sort((a, b) => a - b);
328
+ for (let k = 0; k < wanted.length;) {
329
+ let n = 1;
330
+ while (k + n < wanted.length && wanted[k + n] === wanted[k] + n) n++;
331
+ for (let j = 0; j < n; j++) { const len = chunkLength(this.m.size, wanted[k + j]); this.out.set(wanted[k + j], { len, got: 0, buf: new Uint8Array(len) }); }
332
+ try { this.ch.send(frames.want(wanted[k], n)); } catch { return this.#end('cancelled', true, true); }
333
+ k += n;
334
+ }
335
+ if (busy() === 0 && this.next >= this.m.chunks && this.again.length === 0) {
336
+ this.writing = this.writing.then(() => this.#flush()).then(() => {
337
+ if (!this.ended && this.have.done()) { this.ended = true; this.onEnd('complete', { remote: false }); }
338
+ });
339
+ }
340
+ }
341
+ #end(reason, remote = false, gone = false) {
342
+ if (this.ended) return;
343
+ this.ended = true;
344
+ if (!remote && !gone) { try { this.ch.send(frames.end(reason)); } catch {} }
345
+ // What was checked and written is kept (a resume asks only for the rest).
346
+ void this.writing.then(() => this.#flush()).catch(() => {}).finally(() => this.onEnd(reason, { remote: remote && !gone, gone }));
347
+ }
348
+ /** After 'complete': the file read back; done or chunk_hash goes to the sender. */
349
+ finish(reason) { try { this.ch.send(frames.end(reason)); } catch {} }
350
+ stop(reason = 'cancelled') { this.#end(reason); }
351
+ }
352
+ const same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
353
+
354
+ // ---------------------------------------------------------------- the paths
355
+
356
+ /**
357
+ * The order the paths are tried in (design §2, §9): free, direct then Tor; Pro by its setting, fast
358
+ * (direct, TURN, Tor) or private (Tor, direct, TURN). via tor: Tor only (the address stays hidden).
359
+ * TURN is T4: until it exists it is left out. direct: allowed with this contact and possible here;
360
+ * tor: both sides can (one serves, the other connects). → ['direct', 'tor'], …
361
+ */
362
+ export function pathOrder({ pro = false, prefer = 'fast', via = 'auto', direct = true, tor = false, turn = false }) {
363
+ if (via === 'tor') return tor ? ['tor'] : [];
364
+ const order = pro && prefer === 'private' ? ['tor', 'direct', 'turn'] : pro ? ['direct', 'turn', 'tor'] : ['direct', 'tor'];
365
+ return order.filter((p) => (p === 'direct' ? direct : p === 'tor' ? tor : turn && pro));
366
+ }
367
+ /**
368
+ * The accept rule (design §10.2): → 'auto' (lands without a question) or 'ask'. trust: 'own' (own agents and
369
+ * contacts), 'compared' (a friend whose four words were compared) or 'other' (not compared, a public-code
370
+ * joiner, quiet: always asked); limitMb: the contact's own size (0: always ask), null for defaultMb; MB are
371
+ * 10^6 bytes; direct: may this contact see the addresses already (else the human is asked first).
372
+ */
373
+ export function acceptRule({ size, trust, limitMb = null, defaultMb = AUTO_MB, direct = true }) {
374
+ if (trust !== 'own' && trust !== 'compared') return 'ask';
375
+ const mb = limitMb ?? defaultMb;
376
+ if (!(Number.isFinite(mb) && mb > 0) || !(size <= mb * 1e6)) return 'ask';
377
+ return direct === true ? 'auto' : 'ask';
378
+ }
379
+ /** Who serves the onion: the sender if it can, else the receiver; null when no pair of the two works. */
380
+ export function torRoles(sender, receiver) {
381
+ if (sender?.serve && receiver?.connect) return 'sender';
382
+ if (receiver?.serve && sender?.connect) return 'receiver';
383
+ return null;
384
+ }
385
+ /** The free refusal (design §5), for a contact's name. */
386
+ export const noPath = (name) => `No direct path to ${name} from these two networks, and no Tor. Up to 8 MiB: send-file. Tor on both sides, or Pro, carries larger files.`;
387
+
388
+ export { hexToBytes, bytesToHex };
package/voice-web.mjs ADDED
@@ -0,0 +1,113 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Recording a voice message in the page (design/transfer.md "Voice"): the browser's MediaRecorder over
3
+ // getUserMedia({audio: true}); the same code in the Android WebView, WebKitGTK and a browser tab. Loaded by
4
+ // ui.js at the first Voice (`/voice-web.mjs`: the `ui` server, the app's import map). No dependency.
5
+ //
6
+ // canRecord(env) a microphone API here (getUserMedia and MediaRecorder)
7
+ // const r = await record({ env, max, onTick }) starts at once; refused mic_permission | no_mic | no_recorder
8
+ // r.elapsed() → s r.stop() → { bytes, type, name, duration_s, waveform? } r.cancel(): nothing kept
9
+ // onTick({ elapsed, level, done }) every 200 ms; at max (300 s) it stops by itself (done: true; r.done: the stop's promise)
10
+ // Format: audio/webm;codecs=opus where the recorder has it (Chromium: the Android WebView, a Chrome tab), else
11
+ // audio/mp4 (AAC: WebKit, Safari), else audio/ogg;codecs=opus (Firefox); the file's kind read from its first
12
+ // bytes, whatever the recorder said. 32 kbit/s: five minutes are about 1.2 MB.
13
+ import { VOICE_EXT, VOICE_MAX_S, WAVE_MAX, voiceName } from './voice.mjs';
14
+ import { fail } from './kdf.mjs';
15
+
16
+ export const TYPES = ['audio/webm;codecs=opus', 'audio/mp4', 'audio/ogg;codecs=opus'];
17
+ const TICK_MS = 200, BITRATE = 32000;
18
+
19
+ /** The first of TYPES this recorder makes, or null (its own default then). */
20
+ export function recorderType(Rec) {
21
+ for (const t of TYPES) { try { if (Rec?.isTypeSupported?.(t)) return t; } catch {} }
22
+ return null;
23
+ }
24
+
25
+ export const canRecord = (env = globalThis) => typeof env?.navigator?.mediaDevices?.getUserMedia === 'function' && typeof env?.MediaRecorder === 'function';
26
+
27
+ /** The container by its first bytes: 'audio/webm' (EBML), 'audio/ogg' (OggS), 'audio/mp4' (ftyp), or null. */
28
+ export function sniff(b) {
29
+ if (b.length > 4 && b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3) return 'audio/webm';
30
+ if (b.length > 4 && b[0] === 0x4f && b[1] === 0x67 && b[2] === 0x67 && b[3] === 0x53) return 'audio/ogg';
31
+ if (b.length > 8 && b[4] === 0x66 && b[5] === 0x74 && b[6] === 0x79 && b[7] === 0x70) return 'audio/mp4';
32
+ return null;
33
+ }
34
+
35
+ /** Levels (0 to 255, one per tick) as at most n peaks: the loudest of each stretch. */
36
+ export function downsample(levels, n = WAVE_MAX) {
37
+ if (levels.length <= n) return Uint8Array.from(levels, (x) => Math.max(0, Math.min(255, Math.round(x))));
38
+ const out = new Uint8Array(n);
39
+ for (let i = 0; i < n; i++) {
40
+ const a = Math.floor((i * levels.length) / n), z = Math.max(a + 1, Math.floor(((i + 1) * levels.length) / n));
41
+ out[i] = Math.max(0, Math.min(255, Math.round(Math.max(...levels.slice(a, z)))));
42
+ }
43
+ return out;
44
+ }
45
+
46
+ const b64 = (bytes) => { let t = ''; for (const x of bytes) t += String.fromCharCode(x); return btoa(t); };
47
+
48
+ /** Starts recording now. → the handle (above); the microphone is let go at stop or cancel. */
49
+ export async function record({ env = globalThis, max = VOICE_MAX_S, onTick = () => {}, now = () => Date.now() } = {}) {
50
+ if (!canRecord(env)) fail('no_recorder', 'this page cannot record sound');
51
+ let stream;
52
+ try { stream = await env.navigator.mediaDevices.getUserMedia({ audio: true }); } catch (e) {
53
+ if (e?.name === 'NotAllowedError' || e?.name === 'SecurityError') fail('mic_permission', 'the microphone is not allowed here');
54
+ fail('no_mic', `no microphone here${e?.message ? ` (${e.message})` : ''}`);
55
+ }
56
+ const type = recorderType(env.MediaRecorder);
57
+ let rec;
58
+ try { rec = new env.MediaRecorder(stream, { ...(type && { mimeType: type }), audioBitsPerSecond: BITRATE }); } catch (e) {
59
+ for (const t of stream.getTracks?.() ?? []) t.stop();
60
+ fail('no_recorder', `this page cannot record sound (${e?.message ?? e})`);
61
+ }
62
+ // The level: an analyser where the page has Web Audio (a meter while recording, the waveform after); else none.
63
+ let ctx = null, an = null, buf = null;
64
+ try {
65
+ const AC = env.AudioContext ?? env.webkitAudioContext;
66
+ if (AC) { ctx = new AC(); an = ctx.createAnalyser(); an.fftSize = 512; buf = new Uint8Array(an.fftSize); ctx.createMediaStreamSource(stream).connect(an); }
67
+ } catch { ctx = null; an = null; }
68
+ const level = () => {
69
+ if (!an) return 0;
70
+ an.getByteTimeDomainData(buf);
71
+ let p = 0;
72
+ for (const v of buf) p = Math.max(p, Math.abs(v - 128));
73
+ return Math.min(255, p * 2);
74
+ };
75
+ const chunks = [], levels = [], t0 = now();
76
+ let ended = null, cancelled = false, timer = null;
77
+ const elapsed = () => Math.min(max, (now() - t0) / 1000);
78
+ const release = () => {
79
+ if (timer !== null) { clearInterval(timer); timer = null; }
80
+ for (const t of stream.getTracks?.() ?? []) t.stop();
81
+ try { void ctx?.close?.(); } catch {}
82
+ };
83
+ rec.ondataavailable = (e) => { if (e?.data?.size) chunks.push(e.data); };
84
+ const finished = new Promise((ok) => { rec.onstop = () => ok(); });
85
+ const finish = () => {
86
+ if (ended) return ended;
87
+ const secs = elapsed();
88
+ ended = (async () => {
89
+ if (rec.state !== 'inactive') rec.stop();
90
+ await finished;
91
+ release();
92
+ if (cancelled) return null;
93
+ const blob = new env.Blob(chunks, { type: rec.mimeType || type || '' });
94
+ const bytes = new Uint8Array(await blob.arrayBuffer());
95
+ if (!bytes.length) fail('voice', 'nothing was recorded');
96
+ const said = String(rec.mimeType || type || '').split(';')[0].trim();
97
+ const kind = sniff(bytes) ?? (Object.hasOwn(VOICE_EXT, said) ? said : null) ?? fail('voice', `this recorder makes ${said || 'an unknown kind'}, not webm, ogg or mp4`);
98
+ const peaks = downsample(levels);
99
+ return { bytes, type: kind, name: voiceName(new Date(t0), kind), duration_s: Math.max(1, Math.min(max, Math.round(secs))), ...(peaks.length && levels.some((x) => x > 0) && { waveform: b64(peaks) }) };
100
+ })();
101
+ return ended;
102
+ };
103
+ const handle = { type: type ?? '', elapsed, stop: finish, done: null, cancel: () => { cancelled = true; void finish().catch(() => {}); } };
104
+ rec.start(1000);
105
+ timer = setInterval(() => {
106
+ const l = level();
107
+ levels.push(l);
108
+ const s = elapsed();
109
+ if (s >= max && !ended) handle.done = finish();
110
+ try { onTick({ elapsed: s, level: l, done: handle.done !== null }); } catch {}
111
+ }, TICK_MS);
112
+ return handle;
113
+ }
package/voice.mjs ADDED
@@ -0,0 +1,65 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // A voice message (design/transfer.md "Voice"): what a chat shows at once while the recording comes by a
3
+ // transfer, as a photo's preview does (photo.mjs). One contact message labelled VOICE_LABEL (inside the
4
+ // pairing's end-to-end envelope, as any message), or the `voice` of a group's msg (group.mjs); either way
5
+ // { name, size (bytes of the file), type ('audio/webm' | 'audio/ogg' | 'audio/mp4'), sha256 (64 hex: the
6
+ // file's, the manifest's), duration_s (1 to 300, whole seconds: no floats), waveform? (base64 of 1 to 64
7
+ // bytes, each a peak 0 to 255, oldest first) }
8
+ // No audio inline: the file is the transfer whose manifest has that sha256, from the same sender.
9
+ // voiceItems(batch): what `sigelo-agent inbox` and sigelo_inbox print, a voice message with its checked
10
+ // fields (`voice`) and one line (`text`: "[voice 0:42 voice-20261117-142301.webm]").
11
+ import { fail } from './kdf.mjs';
12
+
13
+ export const VOICE_LABEL = 'sigelo-voice/0', VOICE_MAX_S = 300, WAVE_MAX = 64, VOICE_SIZE_MAX = 16 * 2 ** 20;
14
+ /** The recorder's container → the file's extension (MediaRecorder's type, its codecs dropped). */
15
+ export const VOICE_EXT = { 'audio/webm': 'webm', 'audio/ogg': 'ogg', 'audio/mp4': 'm4a' };
16
+ const KEYS = ['duration_s', 'name', 'sha256', 'size', 'type'];
17
+ const int = (x, lo, hi) => Number.isSafeInteger(x) && x >= lo && x <= hi;
18
+ const unb64 = (t) => Uint8Array.from(atob(t), (c) => c.charCodeAt(0));
19
+
20
+ /** A voice message's fields as they come (a contact's message, a group's msg, the page's send): them, checked, or throws check voice. */
21
+ export function checkVoice(x) {
22
+ const bad = (why) => fail('voice', `not a ${VOICE_LABEL} message: ${why}`);
23
+ if (typeof x !== 'object' || x === null || Array.isArray(x)) bad(`{${KEYS.join(', ')}, waveform?}`);
24
+ const keys = Object.keys(x).filter((k) => k !== 'waveform').sort();
25
+ if (keys.join() !== KEYS.join()) bad(`{${KEYS.join(', ')}, waveform?}`);
26
+ if (!Object.hasOwn(VOICE_EXT, x.type)) bad(`type: ${Object.keys(VOICE_EXT).join(', ')}`);
27
+ if (typeof x.name !== 'string' || x.name.length === 0 || x.name.length > 255 || /[\\/\u0000-\u001f]/.test(x.name)) bad('name: 1 to 255 characters, no slash');
28
+ if (!int(x.size, 1, VOICE_SIZE_MAX)) bad(`size: bytes, 1 to ${VOICE_SIZE_MAX / 2 ** 20} MiB`);
29
+ if (typeof x.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(x.sha256)) bad('sha256: 64 lowercase hex digits');
30
+ if (!int(x.duration_s, 1, VOICE_MAX_S)) bad(`duration_s: whole seconds, 1 to ${VOICE_MAX_S}`);
31
+ if (Object.hasOwn(x, 'waveform')) {
32
+ const w = x.waveform;
33
+ if (typeof w !== 'string' || w.length === 0 || w.length > Math.ceil(WAVE_MAX / 3) * 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(w) || w.length % 4 !== 0 || unb64(w).length > WAVE_MAX) bad(`waveform: base64 of 1 to ${WAVE_MAX} bytes`);
34
+ }
35
+ return { name: x.name, size: x.size, type: x.type, sha256: x.sha256, duration_s: x.duration_s, ...(Object.hasOwn(x, 'waveform') && { waveform: x.waveform }) };
36
+ }
37
+
38
+ /** The waveform's peaks (0 to 255 each), or [] when there is none. */
39
+ export const peaksOf = (v) => (typeof v?.waveform === 'string' ? [...unb64(v.waveform)] : []);
40
+
41
+ /** 42 → "0:42". */
42
+ export const clock = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
43
+
44
+ /** The recording's file name: voice-<local date and time>.<ext> (voice-20261117-142301.webm). */
45
+ export function voiceName(date, type) {
46
+ const p = (n) => String(n).padStart(2, '0');
47
+ return `voice-${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}-${p(date.getHours())}${p(date.getMinutes())}${p(date.getSeconds())}.${VOICE_EXT[type] ?? 'webm'}`;
48
+ }
49
+
50
+ /** One line for a voice message: "[voice 0:42 voice-20261117-142301.webm]". */
51
+ export const voiceLine = (v) => `[voice ${clock(v.duration_s)} ${v.name}]`;
52
+
53
+ /**
54
+ * A batch as the CLI and the MCP print it: each voice message (a contact's, labelled VOICE_LABEL; a group's
55
+ * msg with a voice) gains `voice` (its fields, checked) and `text` (voiceLine). One that does not check
56
+ * stays as it came, `voice_error` naming why. The rest unchanged.
57
+ */
58
+ export function voiceItems(batch) {
59
+ const one = (m) => {
60
+ const raw = m?.label === VOICE_LABEL ? m.content : m?.voice;
61
+ if (raw === undefined || (m?.label !== VOICE_LABEL && m?.voice === undefined)) return m;
62
+ try { const v = checkVoice(raw); return { ...m, voice: v, text: voiceLine(v) }; } catch (e) { return { ...m, voice_error: e.message }; }
63
+ };
64
+ return { ...batch, messages: (batch?.messages ?? []).map(one) };
65
+ }