sigelo-contact 0.1.14 → 0.1.21
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/README.md +13 -10
- package/call.mjs +831 -0
- package/carrier.mjs +1013 -112
- package/control.mjs +81 -22
- package/device.mjs +1 -1
- package/enrol.mjs +214 -35
- package/gen-carrier.mjs +4 -4
- package/gen-device.mjs +2 -2
- package/gen-envelope.mjs +3 -3
- package/gen-invite.mjs +3 -3
- package/gen-short.mjs +3 -3
- package/group.mjs +28 -9
- package/invite.mjs +63 -13
- package/kdf.mjs +1 -1
- package/link.mjs +1 -1
- package/package.json +34 -7
- package/page.mjs +1018 -81
- package/photo.mjs +37 -0
- package/platform-node.mjs +110 -13
- package/prekeys.mjs +10 -2
- package/public.mjs +93 -0
- package/relays.mjs +1 -1
- package/restore.mjs +3 -3
- package/rtc-web.mjs +109 -0
- package/short.mjs +19 -3
- package/store.mjs +126 -10
- package/test-carrier.mjs +121 -18
- package/test-device.mjs +1 -1
- package/test-enrol.mjs +123 -8
- package/test-envelope.mjs +16 -3
- package/test-file.mjs +5 -5
- package/test-group.mjs +48 -7
- package/test-invite.mjs +15 -2
- package/test-link.mjs +6 -6
- package/test-platform.mjs +5 -5
- package/test-presence.mjs +5 -5
- package/test-push.mjs +136 -0
- package/test-relay-lane.mjs +323 -0
- package/test-short.mjs +35 -12
- package/test-tier.mjs +6 -6
- package/test-transfer-web.mjs +313 -0
- package/test-transfer.mjs +51 -11
- package/test-voice.mjs +161 -0
- package/test-ws.mjs +5 -5
- package/transfer-engine.mjs +858 -0
- package/transfer-node.mjs +254 -641
- package/transfer-web.mjs +80 -0
- package/transfer.mjs +25 -6
- package/voice-web.mjs +113 -0
- package/voice.mjs +70 -0
- package/words-lock.mjs +25 -10
package/transfer-web.mjs
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Transfers in a page that holds its own identity (the phone app, design/transfer.md §10): the io of
|
|
3
|
+
// transfer-engine.mjs over the platform's files (the records, the chunk bitmaps and lists: small) and
|
|
4
|
+
// the shell's big-file bridge (the bytes: never in the page's storage, never a Blob held whole).
|
|
5
|
+
//
|
|
6
|
+
// const io = webIo({ files, big, base, profile }) files: the platform's (sync read/write/remove);
|
|
7
|
+
// big: platform.big (below); base: 'app/me.local'
|
|
8
|
+
// const X = webTransfers(io) the verbs with { carrier } as transfer-node.mjs's take them
|
|
9
|
+
//
|
|
10
|
+
// big (apps/web/platform-android.mjs, SigeloBridge "big-*"): every call names this profile.
|
|
11
|
+
// pick({images}) → { doc, name, size, mtime } | null the system's document picker (images: pictures only); the grant kept (a resume after a restart reads it)
|
|
12
|
+
// hash(doc) → { size, mtime, sha256, hashes } in the shell (each 1 MiB chunk and the whole), hashes: bytes
|
|
13
|
+
// stat(doc) → { size, mtime } read(doc, offset, length, { size, mtime }) → bytes (a range; file_changed when either moved)
|
|
14
|
+
// write(part, offset, bytes); flush(part); sha256(part) → hex; drop(part); free() → bytes
|
|
15
|
+
// land(part, name) → { uri, name } the partial moved into the phone's Downloads (MediaStore, pending until whole)
|
|
16
|
+
// part: the transfer id. Partials live in the app's private storage until they land.
|
|
17
|
+
import { CHUNK, chunkLength } from './transfer.mjs';
|
|
18
|
+
import { fail } from './kdf.mjs';
|
|
19
|
+
import * as E from './transfer-engine.mjs';
|
|
20
|
+
|
|
21
|
+
const enc = new TextEncoder(), dec = new TextDecoder();
|
|
22
|
+
|
|
23
|
+
export function webIo({ files, big, base = 'app/me.local', flushEach = 1 }) {
|
|
24
|
+
const file = `${base}.transfers.json`, dir = `${base}.files/.transfer/`;
|
|
25
|
+
let freeBytes = Infinity;
|
|
26
|
+
const refresh = () => { void big.free().then((n) => { if (Number.isFinite(n)) freeBytes = n; }, () => {}); };
|
|
27
|
+
refresh();
|
|
28
|
+
return {
|
|
29
|
+
flushEach,
|
|
30
|
+
lock: (fn) => fn(), // one owner per identity (platform.owner): this page alone writes it
|
|
31
|
+
read: () => { const b = files.read(file); return b === null ? null : dec.decode(b); },
|
|
32
|
+
write: (text) => files.write(file, enc.encode(text)),
|
|
33
|
+
have: {
|
|
34
|
+
read: (id) => files.read(`${dir}${id}.have`),
|
|
35
|
+
write: (id, bits) => { if (bits === null) files.remove(`${dir}${id}.have`); else files.write(`${dir}${id}.have`, Uint8Array.from(bits)); },
|
|
36
|
+
},
|
|
37
|
+
list: {
|
|
38
|
+
read: (id, side) => files.read(`${dir}${id}.${side}.list`),
|
|
39
|
+
write: (id, side, bytes) => files.write(`${dir}${id}.${side}.list`, Uint8Array.from(bytes)),
|
|
40
|
+
drop: (id, side) => files.remove(`${dir}${id}.${side}.list`),
|
|
41
|
+
},
|
|
42
|
+
part: {
|
|
43
|
+
async open(id) {
|
|
44
|
+
return { write: (b, pos) => big.write(id, pos, b), flush: () => big.flush(id), close: async () => { refresh(); } };
|
|
45
|
+
},
|
|
46
|
+
drop: (id) => { void big.drop(id).catch(() => {}); },
|
|
47
|
+
sha256: (id) => big.sha256(id),
|
|
48
|
+
},
|
|
49
|
+
free: () => { refresh(); return freeBytes; },
|
|
50
|
+
async land(r) { const x = await big.land(r.id, r.name); refresh(); return x.uri; },
|
|
51
|
+
async prepare({ doc }) {
|
|
52
|
+
if (typeof doc !== 'string' || doc === '') fail('usage', 'doc: a file picked on this phone');
|
|
53
|
+
const h = await big.hash(doc);
|
|
54
|
+
return { file: doc, name: h.name, size: h.size, mtimeMs: h.mtime, hashes: h.hashes, whole: h.sha256 };
|
|
55
|
+
},
|
|
56
|
+
async changed(r) { try { const s = await big.stat(r.file); return s.size !== r.size || s.mtime !== r.mtimeMs; } catch { return true; } },
|
|
57
|
+
async source(r) {
|
|
58
|
+
return {
|
|
59
|
+
read: (i) => big.read(r.file, i * CHUNK, chunkLength(r.size, i), { size: r.size, mtime: r.mtimeMs }),
|
|
60
|
+
close: async () => {},
|
|
61
|
+
};
|
|
62
|
+
},
|
|
63
|
+
tor: null, // no Tor on the phone (a later build: Orbot's SOCKS port)
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The verbs over io, taking what transfer-node.mjs's take (identity is ignored: the io names the files). */
|
|
68
|
+
export function webTransfers(io, { compared = () => false, rtc = null } = {}) {
|
|
69
|
+
const w = (f) => (o) => f({ ...o, io });
|
|
70
|
+
return {
|
|
71
|
+
io,
|
|
72
|
+
send: w(E.send), accept: w(E.accept), resume: w(E.resume), retry: w(E.retry), decline: w(E.decline), cancel: w(E.cancel), forget: w(E.forget),
|
|
73
|
+
list: w(E.list), setDirect: w(E.setDirect), setAuto: w(E.setAuto), settings: ({ patch, now } = {}) => E.settings({ io, patch, ...(now !== undefined && { now }) }),
|
|
74
|
+
prepare: w(E.prepare), sendTo: w(E.sendTo), fanOut: w(E.fanOut), contactOf: E.contactOf, trustOf: E.trustOf,
|
|
75
|
+
intake: ({ carrier }) => E.intake({ carrier, io, compared }),
|
|
76
|
+
torCaps: async () => ({ serve: false, connect: false }), torConfig: () => null,
|
|
77
|
+
loadRtc: async () => rtc,
|
|
78
|
+
Engine: E.Engine,
|
|
79
|
+
};
|
|
80
|
+
}
|
package/transfer.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
|
-
// Big files agent to agent (design/transfer.md,
|
|
2
|
+
// Big files agent to agent (design/transfer.md, apps/agent/TRANSFER.md): the pure part, no I/O.
|
|
3
3
|
// The relay carries only the introduction, four small messages labelled TRANSFER_LABEL inside the
|
|
4
4
|
// pairing's end-to-end envelopes; the bytes go over a direct WebRTC data channel (sigelo-transfer,
|
|
5
5
|
// werift) or a one-shot Tor onion stream, both driven by transfer-node.mjs. Here: the messages and
|
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
// answer sender → receiver {typ, id, attempt, sdp, tor}
|
|
13
13
|
// onion the side that serves {typ, id, attempt, onion (56 base32), port, auth (x25519 client key, base64, or null), token (64 hex)}
|
|
14
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.
|
|
15
17
|
// The receiver offers because it pulls. Offer and answer ride signed envelopes naming id and attempt,
|
|
16
18
|
// so the two identities authenticate the DTLS fingerprints and the onion address: the relay cannot sit
|
|
17
19
|
// in the middle. Data channel label: `sigelo-transfer/0 <id> <attempt>`; any other is closed.
|
|
@@ -38,7 +40,10 @@ export const OUTSTANDING = 8, HIGH = 4 * CHUNK, LOW = CHUNK, RETRIES = 1;
|
|
|
38
40
|
export const DAY = 86400, MANIFEST_TTL = 7 * DAY, GATHER_MS = 3000, ANSWER_WAIT = 600, ICE_MS = 30_000;
|
|
39
41
|
// Manifests waiting for a yes: so many per contact and in all; more get `end busy`.
|
|
40
42
|
export const WAIT_CONTACT = 8, WAIT_ALL = 64;
|
|
41
|
-
|
|
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'];
|
|
42
47
|
export const TYPS = ['manifest', 'offer', 'answer', 'onion', 'end'];
|
|
43
48
|
export const T = { LIST: 1, WANT: 2, DATA: 3, END: 4, TOKEN: 5 };
|
|
44
49
|
export const NAME_MAX_IN = 1024, SDP_MAX = 16384, ATTEMPT_MAX = 1000;
|
|
@@ -245,8 +250,8 @@ export class Serve {
|
|
|
245
250
|
* finish('chunk_hash'). hashes: the list from an earlier attempt (a resume), else it comes first.
|
|
246
251
|
*/
|
|
247
252
|
export class Pull {
|
|
248
|
-
constructor({ m, have, hashes = null, write, flush, channel, onEnd, onProgress = () => {}, onList = () => {}, h = sha256 }) {
|
|
249
|
-
Object.assign(this, { m, have, write, flush, ch: channel, onEnd, onProgress, onList, h });
|
|
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)) });
|
|
250
255
|
this.hashes = hashes ?? (m.chunks === 0 ? new Uint8Array(0) : null);
|
|
251
256
|
this.listGot = 0; this.listBuf = this.hashes ? null : new Uint8Array(m.chunks * 32);
|
|
252
257
|
this.out = new Map(); this.writingSet = new Set(); this.unflushed = []; this.again = []; this.next = 0;
|
|
@@ -300,7 +305,7 @@ export class Pull {
|
|
|
300
305
|
this.writingSet.delete(i);
|
|
301
306
|
this.unflushed.push(i);
|
|
302
307
|
this.onProgress(buf.length);
|
|
303
|
-
if (this.unflushed.length >=
|
|
308
|
+
if (this.unflushed.length >= this.flushEach || (this.out.size === 0 && this.writingSet.size === 0)) await this.#flush();
|
|
304
309
|
this.#ask();
|
|
305
310
|
}).catch((e) => { this.error = e; this.#end('cancelled'); });
|
|
306
311
|
}
|
|
@@ -359,6 +364,17 @@ export function pathOrder({ pro = false, prefer = 'fast', via = 'auto', direct =
|
|
|
359
364
|
const order = pro && prefer === 'private' ? ['tor', 'direct', 'turn'] : pro ? ['direct', 'turn', 'tor'] : ['direct', 'tor'];
|
|
360
365
|
return order.filter((p) => (p === 'direct' ? direct : p === 'tor' ? tor : turn && pro));
|
|
361
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. The lane is not the rule's (2026-11-25): direct off, the file comes over Tor or the relay lane.
|
|
372
|
+
*/
|
|
373
|
+
export function acceptRule({ size, trust, limitMb = null, defaultMb = AUTO_MB }) {
|
|
374
|
+
if (trust !== 'own' && trust !== 'compared') return 'ask';
|
|
375
|
+
const mb = limitMb ?? defaultMb;
|
|
376
|
+
return Number.isFinite(mb) && mb > 0 && size <= mb * 1e6 ? 'auto' : 'ask';
|
|
377
|
+
}
|
|
362
378
|
/** Who serves the onion: the sender if it can, else the receiver; null when no pair of the two works. */
|
|
363
379
|
export function torRoles(sender, receiver) {
|
|
364
380
|
if (sender?.serve && receiver?.connect) return 'sender';
|
|
@@ -366,6 +382,9 @@ export function torRoles(sender, receiver) {
|
|
|
366
382
|
return null;
|
|
367
383
|
}
|
|
368
384
|
/** The free refusal (design §5), for a contact's name. */
|
|
369
|
-
|
|
385
|
+
// relayed: a TURN server was offered and still no pair answered (UDP and TCP to the relay host blocked, say).
|
|
386
|
+
export const noPath = (name, relayed = false) => (relayed
|
|
387
|
+
? `No path to ${name} from these two networks, not even through the relay host, and no Tor. Up to 8 MiB: send-file. Tor on both sides carries larger files.`
|
|
388
|
+
: `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.`);
|
|
370
389
|
|
|
371
390
|
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,70 @@
|
|
|
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]"); a hosted agent's
|
|
11
|
+
// settings (sigelo-host-caps/0, meant for the app) marked as data with one line, its content kept.
|
|
12
|
+
import { fail } from './kdf.mjs';
|
|
13
|
+
|
|
14
|
+
export const VOICE_LABEL = 'sigelo-voice/0', VOICE_MAX_S = 300, WAVE_MAX = 64, VOICE_SIZE_MAX = 16 * 2 ** 20;
|
|
15
|
+
/** The recorder's container → the file's extension (MediaRecorder's type, its codecs dropped). */
|
|
16
|
+
export const VOICE_EXT = { 'audio/webm': 'webm', 'audio/ogg': 'ogg', 'audio/mp4': 'm4a' };
|
|
17
|
+
const KEYS = ['duration_s', 'name', 'sha256', 'size', 'type'];
|
|
18
|
+
const int = (x, lo, hi) => Number.isSafeInteger(x) && x >= lo && x <= hi;
|
|
19
|
+
const unb64 = (t) => Uint8Array.from(atob(t), (c) => c.charCodeAt(0));
|
|
20
|
+
|
|
21
|
+
/** 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. */
|
|
22
|
+
export function checkVoice(x) {
|
|
23
|
+
const bad = (why) => fail('voice', `not a ${VOICE_LABEL} message: ${why}`);
|
|
24
|
+
if (typeof x !== 'object' || x === null || Array.isArray(x)) bad(`{${KEYS.join(', ')}, waveform?}`);
|
|
25
|
+
const keys = Object.keys(x).filter((k) => k !== 'waveform').sort();
|
|
26
|
+
if (keys.join() !== KEYS.join()) bad(`{${KEYS.join(', ')}, waveform?}`);
|
|
27
|
+
if (!Object.hasOwn(VOICE_EXT, x.type)) bad(`type: ${Object.keys(VOICE_EXT).join(', ')}`);
|
|
28
|
+
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');
|
|
29
|
+
if (!int(x.size, 1, VOICE_SIZE_MAX)) bad(`size: bytes, 1 to ${VOICE_SIZE_MAX / 2 ** 20} MiB`);
|
|
30
|
+
if (typeof x.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(x.sha256)) bad('sha256: 64 lowercase hex digits');
|
|
31
|
+
if (!int(x.duration_s, 1, VOICE_MAX_S)) bad(`duration_s: whole seconds, 1 to ${VOICE_MAX_S}`);
|
|
32
|
+
if (Object.hasOwn(x, 'waveform')) {
|
|
33
|
+
const w = x.waveform;
|
|
34
|
+
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`);
|
|
35
|
+
}
|
|
36
|
+
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 }) };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The waveform's peaks (0 to 255 each), or [] when there is none. */
|
|
40
|
+
export const peaksOf = (v) => (typeof v?.waveform === 'string' ? [...unb64(v.waveform)] : []);
|
|
41
|
+
|
|
42
|
+
/** 42 → "0:42". */
|
|
43
|
+
export const clock = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
|
|
44
|
+
|
|
45
|
+
/** The recording's file name: voice-<local date and time>.<ext> (voice-20261117-142301.webm). */
|
|
46
|
+
export function voiceName(date, type) {
|
|
47
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
48
|
+
return `voice-${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}-${p(date.getHours())}${p(date.getMinutes())}${p(date.getSeconds())}.${VOICE_EXT[type] ?? 'webm'}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** One line for a voice message: "[voice 0:42 voice-20261117-142301.webm]". */
|
|
52
|
+
export const voiceLine = (v) => `[voice ${clock(v.duration_s)} ${v.name}]`;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A batch as the CLI and the MCP print it: each voice message (a contact's, labelled VOICE_LABEL; a group's
|
|
56
|
+
* msg with a voice) gains `voice` (its fields, checked) and `text` (voiceLine). One that does not check
|
|
57
|
+
* stays as it came, `voice_error` naming why. A sigelo-host-caps/0 message gains `data` (its label) and `text`
|
|
58
|
+
* (HOST_CAPS_LINE): an operator's CLI or MCP sees it as data. The rest unchanged.
|
|
59
|
+
*/
|
|
60
|
+
export const HOST_CAPS_LABEL = 'sigelo-host-caps/0';
|
|
61
|
+
export const HOST_CAPS_LINE = '[sigelo-host-caps/0: the hosted agent\'s settings for the app, data, not a message]';
|
|
62
|
+
export function voiceItems(batch) {
|
|
63
|
+
const one = (m) => {
|
|
64
|
+
if (m?.label === HOST_CAPS_LABEL) return { ...m, data: HOST_CAPS_LABEL, text: HOST_CAPS_LINE };
|
|
65
|
+
const raw = m?.label === VOICE_LABEL ? m.content : m?.voice;
|
|
66
|
+
if (raw === undefined || (m?.label !== VOICE_LABEL && m?.voice === undefined)) return m;
|
|
67
|
+
try { const v = checkVoice(raw); return { ...m, voice: v, text: voiceLine(v) }; } catch (e) { return { ...m, voice_error: e.message }; }
|
|
68
|
+
};
|
|
69
|
+
return { ...batch, messages: (batch?.messages ?? []).map(one) };
|
|
70
|
+
}
|
package/words-lock.mjs
CHANGED
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
// checkPassword(password, repeat) → the password, or throws check words_password_rule
|
|
11
11
|
// wrongGate({ base, sleep }), gate the delay after a wrong password: 2 s, doubling per failure (at most
|
|
12
12
|
// 256 s) in this page's life, none after a right one; no lockout
|
|
13
|
+
// lockBytes(label, bytes, password, o) → { iter, salt, iv, ct, check }: any bytes, the same KDF and cipher, `label`
|
|
14
|
+
// openBytes(label, sealed, password, aad) → bytes (o.aad: what the caller binds; apps/web/backup.mjs, label sigelo-backup/0)
|
|
13
15
|
//
|
|
14
16
|
// blob: JSON { v: "sigelo-words/0", kdf: "PBKDF2-SHA256", iter, salt, iv, ct } (base64). The password (NFC)
|
|
15
17
|
// goes through PBKDF2-HMAC-SHA256 with a random 16-byte salt and `iter` rounds (ITERATIONS: 1,000,000; about
|
|
@@ -39,13 +41,13 @@ export function checkPassword(password, repeat = password) {
|
|
|
39
41
|
if (p !== String(repeat ?? '')) refuse('words_password_rule', 'The two passwords are not the same.');
|
|
40
42
|
return p;
|
|
41
43
|
}
|
|
42
|
-
async function keys(password, salt, iter) {
|
|
44
|
+
async function keys(password, salt, iter, label = V) {
|
|
43
45
|
const s = subtle();
|
|
44
46
|
const pw = await s.importKey('raw', te.encode(String(password).normalize('NFC')), 'PBKDF2', false, ['deriveBits']);
|
|
45
47
|
const master = new Uint8Array(await s.deriveBits({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations: iter }, pw, 256));
|
|
46
48
|
try {
|
|
47
49
|
const h = await s.importKey('raw', master, 'HKDF', false, ['deriveKey', 'deriveBits']);
|
|
48
|
-
const hk = (info) => ({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: te.encode(`${
|
|
50
|
+
const hk = (info) => ({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: te.encode(`${label} ${info}`) });
|
|
49
51
|
const key = await s.deriveKey(hk('key'), h, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
50
52
|
const check = hex(new Uint8Array(await s.deriveBits(hk('check'), h, 256)));
|
|
51
53
|
return { key, check };
|
|
@@ -60,22 +62,35 @@ function parse(blob) {
|
|
|
60
62
|
}
|
|
61
63
|
export function wordsMeta(blob) { const { v, kdf, iter } = parse(blob); return { v, kdf, iter }; }
|
|
62
64
|
|
|
65
|
+
/**
|
|
66
|
+
* Bytes encrypted under the password, as the words are: PBKDF2 with a fresh 16-byte salt, HKDF info "<label> key" and
|
|
67
|
+
* "<label> check", AES-256-GCM over aad → { iter, salt, iv, ct (bytes), check (hex) }.
|
|
68
|
+
*/
|
|
69
|
+
export async function lockBytes(label, bytes, password, { iterations = ITERATIONS, aad: ad = new Uint8Array(0) } = {}) {
|
|
70
|
+
if (!Number.isSafeInteger(iterations) || iterations < MIN_ITERATIONS) refuse('words_kdf', `at least ${MIN_ITERATIONS} rounds`);
|
|
71
|
+
const salt = globalThis.crypto.getRandomValues(new Uint8Array(16)), iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
|
|
72
|
+
const { key, check } = await keys(password, salt, iterations, label);
|
|
73
|
+
const ct = new Uint8Array(await subtle().encrypt({ name: 'AES-GCM', iv, additionalData: ad }, key, bytes));
|
|
74
|
+
return { iter: iterations, salt, iv, ct, check };
|
|
75
|
+
}
|
|
76
|
+
/** lockBytes's bytes back → { plain, check }; a wrong password (or a changed aad): check words_password. */
|
|
77
|
+
export async function openBytes(label, { iter, salt, iv, ct }, password, ad = new Uint8Array(0)) {
|
|
78
|
+
if (!Number.isSafeInteger(iter) || iter < MIN_ITERATIONS) refuse('words_kdf', `at least ${MIN_ITERATIONS} rounds`);
|
|
79
|
+
const { key, check } = await keys(String(password ?? ''), salt, iter, label);
|
|
80
|
+
try { return { plain: new Uint8Array(await subtle().decrypt({ name: 'AES-GCM', iv, additionalData: ad }, key, ct)), check }; } catch { return refuse('words_password', 'Wrong password.'); }
|
|
81
|
+
}
|
|
82
|
+
|
|
63
83
|
/** The 25 words encrypted under the password → { blob (bytes), check (hex) }. */
|
|
64
84
|
export async function lockWords(words, password, { iterations = ITERATIONS } = {}) {
|
|
65
85
|
const line = te.encode(cleanWords(words)), p = checkPassword(password);
|
|
66
|
-
if (!Number.isSafeInteger(iterations) || iterations < MIN_ITERATIONS) refuse('words_kdf', `at least ${MIN_ITERATIONS} rounds`);
|
|
67
|
-
const salt = globalThis.crypto.getRandomValues(new Uint8Array(16)), iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
|
|
68
86
|
try {
|
|
69
|
-
const {
|
|
70
|
-
|
|
71
|
-
return { blob: te.encode(JSON.stringify({ v: V, kdf: KDF, iter: iterations, salt: b64(salt), iv: b64(iv), ct: b64(ct) })), check };
|
|
87
|
+
const { iter, salt, iv, ct, check } = await lockBytes(V, line, p, { iterations, aad: aad(iterations) });
|
|
88
|
+
return { blob: te.encode(JSON.stringify({ v: V, kdf: KDF, iter, salt: b64(salt), iv: b64(iv), ct: b64(ct) })), check };
|
|
72
89
|
} finally { line.fill(0); }
|
|
73
90
|
}
|
|
74
91
|
/** The words back → { words: [25], check }; a wrong password: check words_password. */
|
|
75
92
|
export async function openWords(blob, password) {
|
|
76
|
-
const o = parse(blob), {
|
|
77
|
-
let plain;
|
|
78
|
-
try { plain = new Uint8Array(await subtle().decrypt({ name: 'AES-GCM', iv: o.iv, additionalData: aad(o.iter) }, key, o.ct)); } catch { return refuse('words_password', 'Wrong password.'); }
|
|
93
|
+
const o = parse(blob), { plain, check } = await openBytes(V, o, password, aad(o.iter));
|
|
79
94
|
try { return { words: td.decode(plain).split(' '), check }; } finally { plain.fill(0); }
|
|
80
95
|
}
|
|
81
96
|
/** The check for a password, after the words opened under it (so a wrong one is refused here too). */
|