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/photo.mjs
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// A photo's inline preview (design/transfer.md §10.4): what a chat shows at once while the full file
|
|
3
|
+
// comes by a transfer. Not sigelo-picture/0, which sets a contact's own picture. One contact message
|
|
4
|
+
// labelled PHOTO_LABEL (inside the pairing's end-to-end envelope, as any message), or the `photo` of a
|
|
5
|
+
// group's msg (group.mjs); either way the content is
|
|
6
|
+
// { type: 'image/jpeg' | 'image/webp', data: base64 of at most 64 KB, w, h (1 to 4096 pixels),
|
|
7
|
+
// sha256 (64 hex: the full file's, the manifest's), size (bytes of the full file), name }
|
|
8
|
+
// The full file is the transfer whose manifest has that sha256, from the same sender.
|
|
9
|
+
import { fail } from './kdf.mjs';
|
|
10
|
+
|
|
11
|
+
export const PHOTO_LABEL = 'sigelo-photo/0', PHOTO_MAX = 64 * 1024, PHOTO_SIDE = 4096, PHOTO_TYPES = new Set(['image/jpeg', 'image/webp']);
|
|
12
|
+
const KEYS = ['data', 'h', 'name', 'sha256', 'size', 'type', 'w'];
|
|
13
|
+
const unb64 = (t) => Uint8Array.from(atob(t), (c) => c.charCodeAt(0));
|
|
14
|
+
const int = (x, lo, hi) => Number.isSafeInteger(x) && x >= lo && x <= hi;
|
|
15
|
+
|
|
16
|
+
/** The image's kind by its first bytes: 'image/jpeg', 'image/webp', or null. */
|
|
17
|
+
export function imageType(b) {
|
|
18
|
+
if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return 'image/jpeg';
|
|
19
|
+
if (b.length > 12 && String.fromCharCode(...b.subarray(0, 4)) === 'RIFF' && String.fromCharCode(...b.subarray(8, 12)) === 'WEBP') return 'image/webp';
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A preview as it comes (a contact's message, a group's msg, the page's send): it, checked, or throws check photo. */
|
|
24
|
+
export function checkPhoto(x) {
|
|
25
|
+
const bad = (why) => fail('photo', `not a ${PHOTO_LABEL} preview: ${why}`);
|
|
26
|
+
if (typeof x !== 'object' || x === null || Array.isArray(x) || Object.keys(x).sort().join() !== KEYS.join()) bad(`{${KEYS.join(', ')}}`);
|
|
27
|
+
if (!PHOTO_TYPES.has(x.type)) bad('type: image/jpeg or image/webp');
|
|
28
|
+
if (typeof x.data !== 'string' || x.data.length === 0 || x.data.length > Math.ceil(PHOTO_MAX / 3) * 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(x.data)) bad(`data: base64 of at most ${PHOTO_MAX / 1024} KB`);
|
|
29
|
+
const b = unb64(x.data);
|
|
30
|
+
if (b.length > PHOTO_MAX) bad(`at most ${PHOTO_MAX / 1024} KB`);
|
|
31
|
+
if (imageType(b) !== x.type) bad(`not a ${x.type === 'image/jpeg' ? 'JPEG' : 'WebP'} image`);
|
|
32
|
+
if (!int(x.w, 1, PHOTO_SIDE) || !int(x.h, 1, PHOTO_SIDE)) bad(`w and h: 1 to ${PHOTO_SIDE} pixels`);
|
|
33
|
+
if (typeof x.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(x.sha256)) bad('sha256: 64 lowercase hex digits');
|
|
34
|
+
if (!int(x.size, 0, 16 * 2 ** 30)) bad('size: bytes, at most 16 GiB');
|
|
35
|
+
if (typeof x.name !== 'string' || x.name.length === 0 || x.name.length > 255) bad('name: 1 to 255 characters');
|
|
36
|
+
return { type: x.type, data: x.data, w: x.w, h: x.h, sha256: x.sha256, size: x.size, name: x.name };
|
|
37
|
+
}
|
package/platform-node.mjs
CHANGED
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
// fetch: async (url, { method, body, signal }) → { status, type, headers.get, body }, // fetch, or a tunnel
|
|
15
15
|
// mqtt: (url, opts) → an MQTT.js client (mqtts:// or wss://; HTTPS_PROXY for wss)
|
|
16
16
|
// transports: ['mqtts', 'wss'],
|
|
17
|
-
// pow: async (prefix, bits, { deadline, signal }) → the counter
|
|
17
|
+
// pow: async ({ prefix, salt, m, t, p }, bits, { deadline, signal, onProgress }) → the counter
|
|
18
|
+
// as a string, or null past deadline (the relay's Argon2id search: carrier.mjs solvePow)
|
|
18
19
|
// env: optionsFromEnv(process.env) and proxy (HTTPS_PROXY), read when asked
|
|
19
20
|
// openPath(path, own) → { bytes, name }: a file named by path, for sendFile (its checks)
|
|
20
21
|
// }
|
|
@@ -25,12 +26,14 @@
|
|
|
25
26
|
// and its parents created 0700, and each of `private` set 0700. files.add: bytes saved under the
|
|
26
27
|
// first of names not taken (a hard link of one temporary copy, else an exclusive write), never
|
|
27
28
|
// over a file; → the name, or null when all are taken. files.remove: a file or a folder, absent or not.
|
|
28
|
-
import {
|
|
29
|
+
import { randomBytes } from 'node:crypto';
|
|
29
30
|
import { request as httpRequest } from 'node:http';
|
|
30
31
|
import { Agent as HttpsAgent, request as httpsRequest } from 'node:https';
|
|
31
32
|
import { connect as tlsConnect } from 'node:tls';
|
|
32
33
|
import { chmodSync, closeSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs';
|
|
33
34
|
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
35
|
+
import { createRequire } from 'node:module';
|
|
36
|
+
import { Worker } from 'node:worker_threads';
|
|
34
37
|
import { connect } from 'mqtt';
|
|
35
38
|
import { MsgError, fail } from './kdf.mjs';
|
|
36
39
|
import { MAX_FILE } from './file.mjs';
|
|
@@ -81,13 +84,31 @@ export const path = { join, dirname, resolve };
|
|
|
81
84
|
|
|
82
85
|
// One lock file per name: every change is load, change, save inside it, so a CLI verb and a
|
|
83
86
|
// long-running carrier on the same identity cannot undo each other. As
|
|
84
|
-
//
|
|
87
|
+
// apps/agent/sigelo-agent-monero.ts withLock. who: the processes named in the refusal.
|
|
88
|
+
// The lock holds its process's pid: a lock whose process is gone (a CLI killed holding it, the agent-setup feedback
|
|
89
|
+
// point 9: every verb then waited and failed until a human deleted the file) is removed, with one line.
|
|
90
|
+
// Read twice before removal, so a lock taken over in between is never removed; an empty one (being
|
|
91
|
+
// written, or an older client's) waits as before.
|
|
85
92
|
const LOCK_TRIES = 200, LOCK_MS = 25;
|
|
93
|
+
const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
94
|
+
export function staleLock(lock, say = (l) => console.error(l)) {
|
|
95
|
+
const held = () => { try { return readFileSync(lock, 'utf8').trim(); } catch { return null; } };
|
|
96
|
+
const t = held();
|
|
97
|
+
if (!t || !/^\d+$/.test(t) || Number(t) === process.pid || pidAlive(Number(t)) || held() !== t) return false;
|
|
98
|
+
rmSync(lock, { force: true });
|
|
99
|
+
say(`sigelo: removed the stale lock ${lock} (its process ${t} is gone)`);
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
export function takeLockFile(lock) {
|
|
103
|
+
const fd = openSync(lock, 'wx', 0o600);
|
|
104
|
+
try { writeSync(fd, `${process.pid}\n`); } finally { closeSync(fd); }
|
|
105
|
+
}
|
|
86
106
|
export function transact(name, fn, who = 'sigelo-contact') {
|
|
87
107
|
const lock = `${name}.lock`, idle = new Int32Array(new SharedArrayBuffer(4));
|
|
88
108
|
for (let i = 0; ; i++) {
|
|
89
|
-
try {
|
|
109
|
+
try { takeLockFile(lock); break; } catch (e) {
|
|
90
110
|
if (e.code !== 'EEXIST') throw e;
|
|
111
|
+
if (staleLock(lock)) continue;
|
|
91
112
|
if (i === LOCK_TRIES) fail('lock', `${lock} is still held after ${(LOCK_TRIES * LOCK_MS) / 1000} s: another ${who} process holds it, or one was killed holding it; delete the file to continue`);
|
|
92
113
|
Atomics.wait(idle, 0, 0, LOCK_MS);
|
|
93
114
|
}
|
|
@@ -97,7 +118,7 @@ export function transact(name, fn, who = 'sigelo-contact') {
|
|
|
97
118
|
|
|
98
119
|
// ---------------------------------------------------------------- one owner per identity
|
|
99
120
|
|
|
100
|
-
// The pid lock beside an identity file, as
|
|
121
|
+
// The pid lock beside an identity file, as apps/agent/sigelo-agent-ui.ts takeLock writes it:
|
|
101
122
|
// "<pid>" for a page (kind ui), "<pid> watch" for a watcher. A lock whose process is gone is taken over.
|
|
102
123
|
const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
103
124
|
function holder(f) {
|
|
@@ -201,16 +222,92 @@ function mqtt(url, opts) {
|
|
|
201
222
|
|
|
202
223
|
const zeroBits = (d) => { let n = 0; for (const x of d) { if (x !== 0) return n + Math.clz32(x) - 24; n += 8; } return n; };
|
|
203
224
|
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
225
|
+
// The search's threads: hash-wasm's Argon2id (WebAssembly, as the app's Worker runs it). Each takes
|
|
226
|
+
// one search at a time, { job, bits } → a message { tried } after each evaluation and { found }
|
|
227
|
+
// once, or { stopped } after a { stop } (read between evaluations); an idle one is kept IDLE_MS for
|
|
228
|
+
// the next search (starting one costs ~0.1 s on a phone), then ends.
|
|
229
|
+
const HASH_WASM = createRequire(import.meta.url).resolve('hash-wasm');
|
|
230
|
+
const POW_THREAD = `const { parentPort, workerData } = require('node:worker_threads');
|
|
231
|
+
const { argon2id } = require(workerData);
|
|
232
|
+
const zero = ${zeroBits.toString()};
|
|
233
|
+
let stop = false;
|
|
234
|
+
const tick = () => new Promise((r) => setImmediate(r));
|
|
235
|
+
parentPort.on('message', async (msg) => {
|
|
236
|
+
if (msg.stop) { stop = true; return; }
|
|
237
|
+
stop = false;
|
|
238
|
+
const { prefix, salt, m, t, p, bits } = msg;
|
|
239
|
+
try {
|
|
240
|
+
for (let i = 0; ; i++) {
|
|
241
|
+
const out = await argon2id({ password: prefix + i, salt, parallelism: p, iterations: t, memorySize: m, hashLength: 32, outputType: 'binary' });
|
|
242
|
+
if (zero(out) >= bits) return parentPort.postMessage({ found: String(i) });
|
|
243
|
+
await tick();
|
|
244
|
+
if (stop) return parentPort.postMessage({ stopped: true });
|
|
245
|
+
parentPort.postMessage({ tried: i + 1 });
|
|
212
246
|
}
|
|
247
|
+
} catch (e) { parentPort.postMessage({ error: String(e && e.message || e) }); }
|
|
248
|
+
});`;
|
|
249
|
+
const POW_IDLE_MS = 30000, idleThreads = [];
|
|
250
|
+
function powThread() {
|
|
251
|
+
const w = idleThreads.pop();
|
|
252
|
+
if (w) { clearTimeout(w.idle); w.ref(); return w; }
|
|
253
|
+
return new Worker(POW_THREAD, { eval: true, workerData: HASH_WASM });
|
|
254
|
+
}
|
|
255
|
+
function powIdle(w) {
|
|
256
|
+
w.removeAllListeners('message');
|
|
257
|
+
w.unref();
|
|
258
|
+
w.idle = setTimeout(() => { const i = idleThreads.indexOf(w); if (i >= 0) idleThreads.splice(i, 1); void w.terminate(); }, POW_IDLE_MS);
|
|
259
|
+
w.idle.unref();
|
|
260
|
+
idleThreads.push(w);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** The first c (0, 1, 2, …) with Argon2id(password = prefix ‖ c, salt, m KiB, t passes, p lanes,
|
|
264
|
+
* 32 bytes) starting with `bits` zero bits (carrier.mjs solvePow), or null once Date.now() passes
|
|
265
|
+
* deadline (or signal aborts). In a worker thread: one evaluation at 64 MiB is ~0.5 s of a core
|
|
266
|
+
* on a phone-class CPU, which this thread never waits through, so the process's connections,
|
|
267
|
+
* keepalives and other identities carry on. onProgress(tried) after each evaluation. */
|
|
268
|
+
export function pow(job, bits, { deadline = Infinity, signal, onProgress } = {}) {
|
|
269
|
+
const { prefix, salt, m, t, p } = job ?? {};
|
|
270
|
+
if (typeof prefix !== 'string' || !(salt instanceof Uint8Array) || ![m, t, p].every(Number.isInteger) || !Number.isInteger(bits) || bits < 0 || bits > 64) {
|
|
271
|
+
return Promise.reject(new TypeError('pow: want ({ prefix, salt, m, t, p }, bits 0 to 64)'));
|
|
213
272
|
}
|
|
273
|
+
return new Promise((resolve, reject) => {
|
|
274
|
+
if (Date.now() > deadline || signal?.aborted) return resolve(null);
|
|
275
|
+
const w = powThread();
|
|
276
|
+
let timer = null, done = false;
|
|
277
|
+
// ok: the thread is free again (found, or stopped), else it is ended.
|
|
278
|
+
const end = (f, v, free) => {
|
|
279
|
+
if (done) return;
|
|
280
|
+
done = true;
|
|
281
|
+
if (timer !== null) clearTimeout(timer);
|
|
282
|
+
signal?.removeEventListener?.('abort', aborted);
|
|
283
|
+
w.off('error', failed); w.off('exit', exited);
|
|
284
|
+
if (free) powIdle(w); else { w.removeAllListeners('message'); void w.terminate(); }
|
|
285
|
+
f(v);
|
|
286
|
+
};
|
|
287
|
+
// Past the deadline or aborted: answered null now; the thread stops after its evaluation.
|
|
288
|
+
const aborted = () => {
|
|
289
|
+
if (done) return;
|
|
290
|
+
done = true;
|
|
291
|
+
if (timer !== null) clearTimeout(timer);
|
|
292
|
+
signal?.removeEventListener?.('abort', aborted);
|
|
293
|
+
w.removeAllListeners('message');
|
|
294
|
+
w.on('message', (d) => { if (d?.stopped || typeof d?.found === 'string' || d?.error) { w.off('error', failed); w.off('exit', exited); if (d?.error) void w.terminate(); else powIdle(w); } });
|
|
295
|
+
w.postMessage({ stop: true });
|
|
296
|
+
resolve(null);
|
|
297
|
+
};
|
|
298
|
+
const failed = (e) => { if (!done) end(reject, new Error(`proof of work: ${e.message}`), false); };
|
|
299
|
+
const exited = () => { const i = idleThreads.indexOf(w); if (i >= 0) idleThreads.splice(i, 1); if (!done) end(reject, new Error('proof of work: the worker stopped'), false); };
|
|
300
|
+
signal?.addEventListener?.('abort', aborted, { once: true });
|
|
301
|
+
if (deadline !== Infinity) timer = setTimeout(aborted, Math.max(0, deadline - Date.now()));
|
|
302
|
+
w.on('message', (d) => {
|
|
303
|
+
if (typeof d?.found === 'string') end(resolve, d.found, true);
|
|
304
|
+
else if (typeof d?.tried === 'number') onProgress?.(d.tried);
|
|
305
|
+
else end(reject, new Error(`proof of work: ${d?.error ?? 'the worker failed'}`), false);
|
|
306
|
+
});
|
|
307
|
+
w.on('error', failed);
|
|
308
|
+
w.on('exit', exited);
|
|
309
|
+
w.postMessage({ prefix, salt, m, t, p, bits });
|
|
310
|
+
});
|
|
214
311
|
}
|
|
215
312
|
|
|
216
313
|
// ---------------------------------------------------------------- sendFile's path
|
package/prekeys.mjs
CHANGED
|
@@ -26,6 +26,14 @@ import { MSG_V, checkNow, fail, hex, signAs } from './kdf.mjs';
|
|
|
26
26
|
|
|
27
27
|
export const ONE_TIME = 20, REPLENISH_BELOW = 5, LAST_RESORT_DAYS = 30, TTL = 31 * 86400, SKEW = 300;
|
|
28
28
|
export const REPLACE_DAYS = 7, REISSUE = 3600, RETIRED_MAX = 8 * ONE_TIME, USED_MAX = 1024;
|
|
29
|
+
// SIGELO_PREKEY_DAYS (1 to 7, default REPLACE_DAYS) shortens the replacement period on this holder
|
|
30
|
+
// only: nothing on the wire says it, a contact just gets bundles more often. Read at each use.
|
|
31
|
+
export function replaceDays(env = globalThis.process?.env) {
|
|
32
|
+
const v = env?.SIGELO_PREKEY_DAYS;
|
|
33
|
+
if (v === undefined || v === '') return REPLACE_DAYS;
|
|
34
|
+
if (!/^[1-7]$/.test(v)) fail('prekey_days', `SIGELO_PREKEY_DAYS is ${JSON.stringify(v)}: a whole number of days, 1 to 7`);
|
|
35
|
+
return Number(v);
|
|
36
|
+
}
|
|
29
37
|
const PK = 1216; // X-Wing public key bytes
|
|
30
38
|
const BODY = ['v', 'typ', 'did', 'pair', 'iat', 'exp', 'keys', 'last_resort'];
|
|
31
39
|
|
|
@@ -69,7 +77,7 @@ export class Prekeys {
|
|
|
69
77
|
due(now, me) {
|
|
70
78
|
checkNow(now);
|
|
71
79
|
return me.current_did !== this.did || !this.lastResort.length || now - this.lastResort[0].iat >= LAST_RESORT_DAYS * 86400
|
|
72
|
-
|| (this.oneTime.size > 0 && now - this.replaced >=
|
|
80
|
+
|| (this.oneTime.size > 0 && now - this.replaced >= replaceDays() * 86400)
|
|
73
81
|
|| (this.oneTime.size < REPLENISH_BELOW && now - this.issued >= REISSUE);
|
|
74
82
|
}
|
|
75
83
|
|
|
@@ -132,7 +140,7 @@ export class Prekeys {
|
|
|
132
140
|
this.did = me.current_did;
|
|
133
141
|
// All at once, not each key at its own age: replaced one by one, keys issued at different
|
|
134
142
|
// times would each bring a reissue of their own, every week from then on.
|
|
135
|
-
if (this.oneTime.size > 0 && now - this.replaced >=
|
|
143
|
+
if (this.oneTime.size > 0 && now - this.replaced >= replaceDays() * 86400) this.retireOneTime(now);
|
|
136
144
|
this.expire(now);
|
|
137
145
|
if (this.oneTime.size === 0) this.replaced = now;
|
|
138
146
|
this.issued = now;
|
package/public.mjs
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Public codes, contract sigelo-public/0 (design/public-invite.md): one code a business or an agent
|
|
3
|
+
// service posts for months, each use of it a pairing request. No network here; the carrier parks,
|
|
4
|
+
// fetches, answers and approves (carrier.mjs invitePublic, accept, approvePublic). Runner:
|
|
5
|
+
// test-public.mjs; the relay side: relay/park.mjs.
|
|
6
|
+
//
|
|
7
|
+
// The long code is invite.mjs's version 2 (sgl2…, makeInvite version 2, parsePublicCode), up to
|
|
8
|
+
// PUBLIC_TTL_MAX. Its short form is PUB-7Q4K-M2XD: "PUB" and a short code's 8 characters (a relay
|
|
9
|
+
// tag after them off the public relay), parked under SHA-256("sigelo-public/0" ‖ the 8 or 12), so a
|
|
10
|
+
// public hash is never a one-time code's (short.mjs codeHash). An older client refuses PUB- at its U.
|
|
11
|
+
//
|
|
12
|
+
// Every joiner holds the code's secret. From it (HKDF-SHA256, no salt): the answer topic, an
|
|
13
|
+
// ordinary mailbox m/<32 hex> the inviter claims (an i/ topic dies at its first answer), and the
|
|
14
|
+
// answer key. From it and the answer's id (invite.mjs answerId), per joiner: the reply topic i/<32
|
|
15
|
+
// hex> and its key; the joiner claims that topic before its answer goes, and no other joiner sees the
|
|
16
|
+
// answer (only the inviter reads the mailbox), so none can claim it first. The answer carries iat
|
|
17
|
+
// (invite.mjs buildAnswer); the inviter takes it up to REQUEST_TTL old and keeps the answer ids it
|
|
18
|
+
// has seen SEEN_KEEP: a replay is dropped. The pairing key is pairKey(secret, KEM, …) as ever, but
|
|
19
|
+
// the secret is public: K rests on the hybrid KEM alone.
|
|
20
|
+
//
|
|
21
|
+
// The four words published beside the code are the inviter's didWords(original DID): known before
|
|
22
|
+
// pairing, one value for every joiner, kept across rotations. A joiner given them checks the paired
|
|
23
|
+
// contact's; the inviter compares nothing with strangers, so its joiners stay unchecked (THREAT-MODEL §2.19).
|
|
24
|
+
import { hkdf } from '@noble/hashes/hkdf.js';
|
|
25
|
+
import { sha256 } from '@noble/hashes/sha2.js';
|
|
26
|
+
import { bytesToHex, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
|
27
|
+
import { fail } from './kdf.mjs';
|
|
28
|
+
import { didWords, formatShort, normaliseShort } from './short.mjs';
|
|
29
|
+
import { PUBLIC_TTL_MAX, REQUEST_TTL } from './invite.mjs';
|
|
30
|
+
|
|
31
|
+
export { PUBLIC_TTL_MAX, REQUEST_TTL };
|
|
32
|
+
export const PUBLIC_V = 'sigelo-public/0', PUB_PREFIX = 'PUB';
|
|
33
|
+
// Answers a UTC day by default and at most (the relay's cap: relay/park.mjs); 3 codes per account there.
|
|
34
|
+
export const PUBLIC_CAP = 50, PUBLIC_CAP_MAX = 500, PUBLIC_PER_ACCOUNT = 3;
|
|
35
|
+
// Answer ids seen, kept this long: past REQUEST_TTL an answer is refused by its iat anyway.
|
|
36
|
+
export const SEEN_KEEP = 8 * 86400;
|
|
37
|
+
// The link a business prints: the fragment never leaves the browser.
|
|
38
|
+
export const LINK_BASE = 'https://sigelo.io/join#';
|
|
39
|
+
export const LABELS = {
|
|
40
|
+
answer_topic: 'sigelo-public/0 answer topic', // 16 bytes → "m/" + hex: joiners write, the inviter reads
|
|
41
|
+
key: 'sigelo-public/0 key', // 32 bytes: the answers' key
|
|
42
|
+
reply_topic: 'sigelo-public/0 reply topic\n', // ‖ answer id, 16 bytes → "i/" + hex: the inviter writes, one joiner reads
|
|
43
|
+
reply_key: 'sigelo-public/0 reply key\n', // ‖ answer id, 32 bytes: that reply's key
|
|
44
|
+
};
|
|
45
|
+
const SEPARATORS = /[\s\-‐-―−]+/g;
|
|
46
|
+
const d = (secret, info, n) => hkdf(sha256, secret, undefined, utf8ToBytes(info), n);
|
|
47
|
+
const checkSecret = (s) => { if (!(s instanceof Uint8Array) || s.length !== 32) fail('secret', 'must be 32 bytes'); };
|
|
48
|
+
|
|
49
|
+
/** The code's answer topic and key. */
|
|
50
|
+
export function publicKeys(secret) {
|
|
51
|
+
checkSecret(secret);
|
|
52
|
+
return { answer_topic: 'm/' + bytesToHex(d(secret, LABELS.answer_topic, 16)), key: d(secret, LABELS.key, 32) };
|
|
53
|
+
}
|
|
54
|
+
/** One joiner's reply topic and key, from the code's secret and its answer's id. */
|
|
55
|
+
export function joinerKeys(secret, answerId) {
|
|
56
|
+
checkSecret(secret);
|
|
57
|
+
if (typeof answerId !== 'string' || answerId === '') fail('answer_id', 'an answer id (invite.mjs answerId)');
|
|
58
|
+
return { reply_topic: 'i/' + bytesToHex(d(secret, LABELS.reply_topic + answerId, 16)), key: d(secret, LABELS.reply_key + answerId, 32) };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Whether text reads as a PUB code (PUB, then 8 or 12 characters, dashes and spaces ignored). */
|
|
62
|
+
export const isPub = (text) => typeof text === 'string' && text.length <= 64 && /^PUB/i.test(text.replace(SEPARATORS, '')) && text.replace(SEPARATORS, '').length > 3 + 7;
|
|
63
|
+
/** The canonical 8 or 12 characters after PUB, or throws short_code. */
|
|
64
|
+
export function normalisePub(text) {
|
|
65
|
+
if (!isPub(text)) fail('short_code', 'not a public code (like PUB-7Q4K-M2XD)');
|
|
66
|
+
return normaliseShort(text.replace(SEPARATORS, '').slice(PUB_PREFIX.length));
|
|
67
|
+
}
|
|
68
|
+
/** "7Q4KM2XD" → "PUB-7Q4K-M2XD". */
|
|
69
|
+
export const formatPub = (norm) => `${PUB_PREFIX}-${formatShort(norm)}`;
|
|
70
|
+
/** The key the relay holds a public code under: hex SHA-256("sigelo-public/0" ‖ the normalised 8 or 12). */
|
|
71
|
+
export const publicHash = (text) => bytesToHex(sha256(concatBytes(utf8ToBytes(PUBLIC_V), utf8ToBytes(normalisePub(text)))));
|
|
72
|
+
|
|
73
|
+
/** The four words published beside the code: the inviter's didWords(original DID). */
|
|
74
|
+
export const publicWords = (originalDid) => didWords(originalDid);
|
|
75
|
+
/** Four words as typed ("Alpha-beta gamma, delta") → "alpha beta gamma delta", or throws words. */
|
|
76
|
+
export function normaliseWords(text) {
|
|
77
|
+
const w = typeof text === 'string' ? text.toLowerCase().split(/[\s,.;:\-]+/).filter(Boolean) : [];
|
|
78
|
+
if (w.length !== 4 || !w.every((x) => /^[a-z]{3,8}$/.test(x))) fail('words', 'four words, as printed beside the code');
|
|
79
|
+
return w.join(' ');
|
|
80
|
+
}
|
|
81
|
+
/** The link: https://sigelo.io/join#PUB-7Q4K-M2XD.word-word-word-word. */
|
|
82
|
+
export const publicLink = (pub, words) => `${LINK_BASE}${pub}.${words.split(' ').join('-')}`;
|
|
83
|
+
/** A link back → { code, words } (words null when the link carries none), or null when text is no such link. */
|
|
84
|
+
export function readLink(text) {
|
|
85
|
+
if (typeof text !== 'string' || !text.startsWith(LINK_BASE)) return null;
|
|
86
|
+
const [code, w] = text.slice(LINK_BASE.length).split('.');
|
|
87
|
+
return { code: decodeURIComponent(code), words: w ? normaliseWords(decodeURIComponent(w).replace(/-/g, ' ')) : null };
|
|
88
|
+
}
|
|
89
|
+
/** A cap as given: 1 to PUBLIC_CAP_MAX, or throws cap. */
|
|
90
|
+
export function checkCap(cap) {
|
|
91
|
+
if (!Number.isSafeInteger(cap) || cap < 1 || cap > PUBLIC_CAP_MAX) fail('cap', `new chats a day: 1 to ${PUBLIC_CAP_MAX}, not ${JSON.stringify(cap)}`);
|
|
92
|
+
return cap;
|
|
93
|
+
}
|
package/relays.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
|
-
// Which relay a 12-character short code was made on
|
|
2
|
+
// Which relay a 12-character short code was made on: its relay tag
|
|
3
3
|
// (short.mjs relayTag) resolved to a host. No network here but loadRegistry's one fetch, which the
|
|
4
4
|
// carrier passes in; nothing in pairing by long code or in verification calls this file.
|
|
5
5
|
//
|
package/restore.mjs
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// the Monero list (by position, never echoed), then the checksum
|
|
10
10
|
// parseRestore(text, now) → {} | { restore_height } | { restore_date } the height-or-date field
|
|
11
11
|
// restoreFromWords(text, o) → { identity, keeper, device, list, notes, did, worker }
|
|
12
|
-
// identity me.local.json: operatorIdentity(S, 0) (contact/enrol.mjs), `derived` marked
|
|
12
|
+
// identity me.local.json: operatorIdentity(S, 0) (apps/contact/enrol.mjs), `derived` marked
|
|
13
13
|
// keeper me.local.keeper.json: sigelo-keeper-hot/0, keeper j (1), root_hex = K_j, the seed's
|
|
14
14
|
// recovery commitment, `created` (the UTC day), the wallet metadata `net` and
|
|
15
15
|
// `restore_height` | `restore_date`, workers {0: this device}, me {n, did, original}
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
// seat "elsewhere": null (the seat's list is on the other device)
|
|
20
20
|
// notes me.local.seat.json: { v, here: {name, did, worker}, imported: 1 } or, elsewhere,
|
|
21
21
|
// { v, here, elsewhere: true, entry } (the list entry `takeSeat` signs later)
|
|
22
|
-
// restoreFromRoot(S, o) the same from the 32-byte root (a new identity, contact/create.mjs); S stays the caller's
|
|
22
|
+
// restoreFromRoot(S, o) the same from the 32-byte root (a new identity, apps/contact/create.mjs); S stays the caller's
|
|
23
23
|
// takeSeat(notes, identity, now) → { list, notes } standby → seat: the list naming this device
|
|
24
24
|
// (epoch 1: the other device's list is not known here, so this is
|
|
25
25
|
// `seat take --force` semantics; the caller warns first)
|
|
@@ -105,7 +105,7 @@ export function restoreFromWords(text, o = {}) {
|
|
|
105
105
|
|
|
106
106
|
/**
|
|
107
107
|
* The same files from the root S itself (32 bytes, canonical), for a new identity made on the device
|
|
108
|
-
* (contact/create.mjs): S is the caller's to zero. o as restoreFromWords.
|
|
108
|
+
* (apps/contact/create.mjs): S is the caller's to zero. o as restoreFromWords.
|
|
109
109
|
*/
|
|
110
110
|
export function restoreFromRoot(S, o = {}) {
|
|
111
111
|
checkOptions(o);
|
package/rtc-web.mjs
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// The direct path of a transfer in a page (design/transfer.md §10.1): the WebView's own RTCPeerConnection
|
|
3
|
+
// behind the interface of apps/transfer/rtc.mjs (werift, Node), so transfer-engine.mjs drives both alike
|
|
4
|
+
// and a phone talks to a Node agent or another phone over the same `sigelo-transfer/0` channel.
|
|
5
|
+
//
|
|
6
|
+
// const p = await peer({ stun, turn, gatherMs, RTC, policy }) RTC: the constructor (default globalThis.RTCPeerConnection);
|
|
7
|
+
// turn: { urls, username, credential } (carrier.turnServer) or null;
|
|
8
|
+
// policy "relay" ("Always relay my media"): iceTransportPolicy relay, no
|
|
9
|
+
// STUN, relayed candidates only in what leaves (call.mjs relayOnly); refused
|
|
10
|
+
// relay_only without turn
|
|
11
|
+
// await p.relayed() → the selected pair has a relayed candidate (true), none (false), not known (null): call.mjs relayedOf
|
|
12
|
+
// await p.offer(label) → sdp; await p.answer(sdp, label) → sdp; await p.accept(sdp)
|
|
13
|
+
// await p.open(ms) → the channel (transfer.mjs's: send, buffered, close, on) once it is open, or throws ice_timeout
|
|
14
|
+
// p.close()
|
|
15
|
+
//
|
|
16
|
+
// Candidates gathered at once and sent whole (not trickled), gatherMs at most. A `.local` candidate in the
|
|
17
|
+
// remote description is dropped (resolving it would put a multicast DNS socket on the LAN); the WebView
|
|
18
|
+
// itself hides its LAN addresses behind such names, so two devices on one network meet at the public
|
|
19
|
+
// address. The send buffer: the engine pauses above 4 MiB (transfer.mjs HIGH) and goes on below 1 MiB
|
|
20
|
+
// (bufferedamountlow); a browser closes a channel whose buffer passes 16 MiB, so neither is raised.
|
|
21
|
+
import { LOW } from './transfer.mjs';
|
|
22
|
+
import { RELAY_ONLY, relayOnly, relayedOf } from './call.mjs';
|
|
23
|
+
|
|
24
|
+
const fail = (check, why) => { throw Object.assign(new Error(`${check}: ${why}`), { check }); };
|
|
25
|
+
/** STUN ['host:port', …] and TURN ({ urls, username, credential } from the relay, or null) → RTCIceServer[]. The policy stays
|
|
26
|
+
* "all": a direct pair is preferred, the relayed candidate is used only when none answers. */
|
|
27
|
+
/** Browser and WebView DTLS checks the handshake signatures: TURN allowed here (apps/transfer/rtc.mjs: only with dtls-verify.mjs's checks in place). */
|
|
28
|
+
export const TURN_OK = true;
|
|
29
|
+
export const iceServers = (stun, turn = null) => [...(stun.length ? [{ urls: stun.map((s) => `stun:${s}`) }] : []),
|
|
30
|
+
...(turn ? [{ urls: [...turn.urls], username: turn.username, credential: turn.credential }] : [])];
|
|
31
|
+
export const noMdns = (sdp) => sdp.split(/\r?\n/).filter((l) => !/^a=candidate:.* [0-9a-f-]+\.local /i.test(l)).join('\r\n');
|
|
32
|
+
|
|
33
|
+
/** An RTCDataChannel as transfer.mjs's channel. */
|
|
34
|
+
export function channelOf(dc, pc) {
|
|
35
|
+
const on = { frame: [], low: [], close: [] };
|
|
36
|
+
let closed = false;
|
|
37
|
+
const shut = () => { if (closed) return; closed = true; for (const f of on.close) { try { f(); } catch {} } };
|
|
38
|
+
dc.binaryType = 'arraybuffer';
|
|
39
|
+
dc.bufferedAmountLowThreshold = LOW;
|
|
40
|
+
dc.addEventListener('message', (m) => { if (typeof m.data === 'string') return; const u = new Uint8Array(m.data); for (const f of on.frame) f(u); });
|
|
41
|
+
dc.addEventListener('bufferedamountlow', () => { for (const f of on.low) f(); });
|
|
42
|
+
dc.addEventListener('close', shut);
|
|
43
|
+
pc.addEventListener('connectionstatechange', () => { if (['failed', 'closed', 'disconnected'].includes(pc.connectionState)) shut(); });
|
|
44
|
+
return {
|
|
45
|
+
send(f) { if (closed || dc.readyState !== 'open') throw new Error('closed'); dc.send(f); },
|
|
46
|
+
buffered: () => dc.bufferedAmount,
|
|
47
|
+
close() { try { dc.close(); } catch {} shut(); },
|
|
48
|
+
on(e, fn) { on[e].push(fn); },
|
|
49
|
+
get closed() { return closed; },
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function peer({ stun = [], turn = null, gatherMs = 3000, RTC = globalThis.RTCPeerConnection, policy = 'all' } = {}) {
|
|
54
|
+
if (typeof RTC !== 'function') fail('no_rtc', 'this page has no RTCPeerConnection');
|
|
55
|
+
const relay = policy === 'relay';
|
|
56
|
+
if (relay && !turn) throw Object.assign(new Error(RELAY_ONLY), { check: 'relay_only' });
|
|
57
|
+
const pc = new RTC({ iceServers: iceServers(relay ? [] : stun, turn), ...(relay && { iceTransportPolicy: 'relay' }) });
|
|
58
|
+
let dc = null, want = null, gotDc;
|
|
59
|
+
const dcP = new Promise((r) => { gotDc = r; });
|
|
60
|
+
pc.addEventListener('datachannel', (ev) => {
|
|
61
|
+
const ch = ev.channel;
|
|
62
|
+
// Only the channel this attempt named; any other is closed (design §3 "Binding").
|
|
63
|
+
if (want === null || ch.label !== want || dc) { try { ch.close(); } catch {} return; }
|
|
64
|
+
dc = ch; gotDc(ch);
|
|
65
|
+
});
|
|
66
|
+
const gathered = async () => {
|
|
67
|
+
if (pc.iceGatheringState !== 'complete') {
|
|
68
|
+
await new Promise((r) => {
|
|
69
|
+
const t = setTimeout(r, gatherMs);
|
|
70
|
+
pc.addEventListener('icegatheringstatechange', () => { if (pc.iceGatheringState === 'complete') { clearTimeout(t); r(); } });
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
return relay ? relayOnly(pc.localDescription.sdp) : pc.localDescription.sdp;
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
pc,
|
|
77
|
+
async offer(label) {
|
|
78
|
+
want = label;
|
|
79
|
+
dc = pc.createDataChannel(label, { ordered: true });
|
|
80
|
+
gotDc(dc);
|
|
81
|
+
await pc.setLocalDescription(await pc.createOffer());
|
|
82
|
+
return gathered();
|
|
83
|
+
},
|
|
84
|
+
async answer(sdp, label) {
|
|
85
|
+
want = label;
|
|
86
|
+
await pc.setRemoteDescription({ type: 'offer', sdp: noMdns(sdp) });
|
|
87
|
+
await pc.setLocalDescription(await pc.createAnswer());
|
|
88
|
+
return gathered();
|
|
89
|
+
},
|
|
90
|
+
async accept(sdp) { await pc.setRemoteDescription({ type: 'answer', sdp: noMdns(sdp) }); },
|
|
91
|
+
/** The channel, open, within ms; else ice_timeout (no pair of candidates answered). */
|
|
92
|
+
async open(ms) {
|
|
93
|
+
let timer;
|
|
94
|
+
const timeout = new Promise((_, no) => { timer = setTimeout(() => no(Object.assign(new Error(`ice_timeout: no direct path within ${ms / 1000} s`), { check: 'ice_timeout' })), ms); });
|
|
95
|
+
try {
|
|
96
|
+
const ch = await Promise.race([dcP, timeout]);
|
|
97
|
+
if (ch.readyState !== 'open') {
|
|
98
|
+
await Promise.race([new Promise((r, no) => {
|
|
99
|
+
ch.addEventListener('open', () => r());
|
|
100
|
+
ch.addEventListener('close', () => no(Object.assign(new Error('ice_timeout: the channel closed'), { check: 'ice_timeout' })));
|
|
101
|
+
}), timeout]);
|
|
102
|
+
}
|
|
103
|
+
return channelOf(ch, pc);
|
|
104
|
+
} finally { clearTimeout(timer); }
|
|
105
|
+
},
|
|
106
|
+
async relayed() { try { return relayedOf(await pc.getStats()); } catch { return null; } },
|
|
107
|
+
close() { try { pc.close(); } catch {} },
|
|
108
|
+
};
|
|
109
|
+
}
|
package/short.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
|
-
// Short invite codes and the four words of a pairing, contract sigelo-park/0
|
|
2
|
+
// Short invite codes and the four words of a pairing, contract sigelo-park/0.
|
|
3
3
|
// No network here; the carrier parks and fetches (carrier.mjs invite, accept). Fixture and runner:
|
|
4
4
|
// fixtures/short-code-v0.json, gen-short.mjs, test-short.mjs.
|
|
5
5
|
//
|
|
@@ -36,8 +36,10 @@ import { fail, unhex } from './kdf.mjs';
|
|
|
36
36
|
|
|
37
37
|
export const PARK_V = 'sigelo-park/0', FINGERPRINT_LABEL = 'sigelo-fingerprint/0';
|
|
38
38
|
export const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
39
|
-
// Seconds a parked code lives at the relay; it goes at its first fetch before that.
|
|
40
|
-
|
|
39
|
+
// Seconds a parked code lives at the relay by default; it goes at its first fetch before that. The
|
|
40
|
+
// inviter may choose SHORT_TTL_MIN to SHORT_TTL_MAX (invite --ttl: a slow agent fetches late); the
|
|
41
|
+
// relay keeps it at most its PARK_TTL (relay/park.mjs: 3600; an older relay's, 600).
|
|
42
|
+
export const SHORT_TTL = 600, SHORT_TTL_MIN = 60, SHORT_TTL_MAX = 3600, SHORT_LENGTH = 8;
|
|
41
43
|
// A relay tag: 4 characters (20 bits) after the 8, on a code made on a relay that is not the public one.
|
|
42
44
|
export const TAG_LABEL = 'sigelo-relay-tag/0', TAG_LENGTH = 4, TAGGED_LENGTH = SHORT_LENGTH + TAG_LENGTH;
|
|
43
45
|
const FOLD = { I: '1', L: '1', O: '0' };
|
|
@@ -122,6 +124,20 @@ export function makeShort(rng = randomBytes, tag = null) {
|
|
|
122
124
|
/** The key the relay parks under: hex SHA-256("sigelo-park/0" ‖ the normalised code). */
|
|
123
125
|
export const codeHash = (text) => bytesToHex(sha256(concatBytes(utf8ToBytes(PARK_V), utf8ToBytes(normaliseShort(text)))));
|
|
124
126
|
|
|
127
|
+
// Enrolment codes (enrol.mjs issue): a short code like any other, shown with the prefix ENROL-
|
|
128
|
+
// (ENROL-K7F3-Q9ZP), so an agent given one knows it by its shape and never takes it for a pairing code
|
|
129
|
+
// (the agent-setup feedback, points 5 and 7: models fed enrolment codes to accept and lost them). The prefix is
|
|
130
|
+
// shown and read, never hashed or sent: the relay parks and fetches the 8 (or 12) characters as before.
|
|
131
|
+
// ENROL_TTL_MAX: an enrolment code may live a day (relay/park.mjs ENROL_TTL), an invite's short code an hour.
|
|
132
|
+
export const ENROL_PREFIX = 'ENROL', ENROL_TTL_MAX = 86400;
|
|
133
|
+
const ENROL_RE = /^\s*ENROL[\s\-\u2010-\u2015\u2212]*/i;
|
|
134
|
+
/** Whether `text` is an enrolment code by its shape: ENROL, then a short code. */
|
|
135
|
+
export const isEnrolCode = (text) => typeof text === 'string' && text.length <= MAX_INPUT + 8 && ENROL_RE.test(text) && isShort(text.replace(ENROL_RE, ''));
|
|
136
|
+
/** The short code inside an enrolment code (ENROL- taken off); any other text as it is. */
|
|
137
|
+
export const stripEnrol = (text) => (isEnrolCode(text) ? text.replace(ENROL_RE, '') : text);
|
|
138
|
+
/** "K7F3Q9ZP" → "ENROL-K7F3-Q9ZP", how an enrolment code is shown. */
|
|
139
|
+
export const formatEnrol = (norm) => `${ENROL_PREFIX}-${formatShort(norm)}`;
|
|
140
|
+
|
|
125
141
|
// Gift codes (sigelo-gift/0): Pro months for an operator, sold or handed out by the vendor
|
|
126
142
|
// (the issuer makes them offline; relay/gifts.mjs redeems them, POST /gift). The
|
|
127
143
|
// same 8 characters, alphabet and folding as a short code, shown with a prefix of their own,
|