sigelo-contact 0.1.13 → 0.1.14
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/carrier.mjs +277 -35
- package/enrol.mjs +34 -17
- package/group.mjs +597 -0
- package/link.mjs +23 -15
- package/package.json +19 -4
- package/page.mjs +278 -19
- package/platform-node.mjs +15 -5
- package/short.mjs +12 -0
- package/store.mjs +21 -2
- package/test-carrier.mjs +18 -4
- package/test-enrol.mjs +36 -2
- package/test-group.mjs +383 -0
- package/test-link.mjs +5 -2
- package/test-presence.mjs +169 -0
- package/test-short.mjs +4 -1
- package/test-transfer.mjs +435 -0
- package/transfer-node.mjs +845 -0
- package/transfer.mjs +371 -0
- package/words-lock.mjs +100 -0
package/transfer.mjs
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Big files agent to agent (design/transfer.md, adapters/moadim/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
|
+
// The receiver offers because it pulls. Offer and answer ride signed envelopes naming id and attempt,
|
|
16
|
+
// so the two identities authenticate the DTLS fingerprints and the onion address: the relay cannot sit
|
|
17
|
+
// in the middle. Data channel label: `sigelo-transfer/0 <id> <attempt>`; any other is closed.
|
|
18
|
+
//
|
|
19
|
+
// The frames (binary, at most FRAME bytes each; on a Tor stream each behind a u32 BE length):
|
|
20
|
+
// LIST sender [1][u32 first index][32-byte chunk hashes…] checked whole against the manifest's list
|
|
21
|
+
// WANT receiver [2][u32 from][u16 n] at most OUTSTANDING chunks asked and not yet written
|
|
22
|
+
// DATA sender [3][u32 index][u32 offset][bytes] a chunk in frames of DATA_MAX (17 for 1 MiB)
|
|
23
|
+
// END either [4][u8 reason] done once the receiver read the file back
|
|
24
|
+
// TOKEN connector [5][32 bytes] the first frame on a Tor stream, else it is closed
|
|
25
|
+
// Back-pressure: the receiver asks again only after writing to disk; the sender stops above HIGH
|
|
26
|
+
// buffered and goes on below LOW. A chunk whose SHA-256 is not the list's is asked once more, then
|
|
27
|
+
// the transfer ends chunk_hash. Nothing is written before the receiver's operator said yes.
|
|
28
|
+
import { sha256 } from '@noble/hashes/sha2.js';
|
|
29
|
+
import { bytesToHex, concatBytes, hexToBytes, randomBytes } from '@noble/hashes/utils.js';
|
|
30
|
+
import { fail } from './kdf.mjs';
|
|
31
|
+
|
|
32
|
+
export const TRANSFER_LABEL = 'sigelo-transfer/0';
|
|
33
|
+
export const CHUNK = 1 << 20, MAX_SIZE = 16 * 2 ** 30, MAX_CHUNKS = MAX_SIZE / CHUNK;
|
|
34
|
+
export const FRAME = 65536, DATA_HEAD = 9, DATA_MAX = FRAME - DATA_HEAD, HASHES_PER_FRAME = Math.floor((FRAME - 5) / 32);
|
|
35
|
+
export const OUTSTANDING = 8, HIGH = 4 * CHUNK, LOW = CHUNK, RETRIES = 1;
|
|
36
|
+
// Timings (design §3): a manifest lives 7 days; candidates gathered 3 s; an offer waits 10 minutes
|
|
37
|
+
// for its answer, then ICE has 30 s.
|
|
38
|
+
export const DAY = 86400, MANIFEST_TTL = 7 * DAY, GATHER_MS = 3000, ANSWER_WAIT = 600, ICE_MS = 30_000;
|
|
39
|
+
// Manifests waiting for a yes: so many per contact and in all; more get `end busy`.
|
|
40
|
+
export const WAIT_CONTACT = 8, WAIT_ALL = 64;
|
|
41
|
+
export const REASONS = ['done', 'declined', 'cancelled', 'no_path', 'try_tor', 'chunk_hash', 'file_changed', 'busy'];
|
|
42
|
+
export const TYPS = ['manifest', 'offer', 'answer', 'onion', 'end'];
|
|
43
|
+
export const T = { LIST: 1, WANT: 2, DATA: 3, END: 4, TOKEN: 5 };
|
|
44
|
+
export const NAME_MAX_IN = 1024, SDP_MAX = 16384, ATTEMPT_MAX = 1000;
|
|
45
|
+
|
|
46
|
+
const ID = /^[0-9a-f]{32}$/, HEX64 = /^[0-9a-f]{64}$/, ONION = /^[a-z2-7]{56}$/, B64KEY = /^[A-Za-z0-9+/]{43}=$/;
|
|
47
|
+
const isObject = (x) => typeof x === 'object' && x !== null && !Array.isArray(x);
|
|
48
|
+
const int = (n, lo, hi) => Number.isSafeInteger(n) && n >= lo && n <= hi;
|
|
49
|
+
const hex = (b) => bytesToHex(b);
|
|
50
|
+
/** A transfer id: 16 random bytes as hex. */
|
|
51
|
+
export const newId = (rng = randomBytes) => hex(rng(16));
|
|
52
|
+
/** How many chunks a file of n bytes goes in. */
|
|
53
|
+
export const chunksOf = (n) => Math.ceil(n / CHUNK);
|
|
54
|
+
/** The length of chunk i of a file of size bytes. */
|
|
55
|
+
export const chunkLength = (size, i) => Math.min(CHUNK, size - i * CHUNK);
|
|
56
|
+
/** The manifest's list: SHA-256 over the chunk hashes, in order (hashes: 32 bytes each, concatenated). */
|
|
57
|
+
export const listOf = (hashes, h = sha256) => hex(h(hashes));
|
|
58
|
+
export const sha256Hex = (b) => hex(sha256(b));
|
|
59
|
+
|
|
60
|
+
// ---------------------------------------------------------------- the messages
|
|
61
|
+
|
|
62
|
+
/** A manifest for a file whose chunk hashes are known. → the message content. */
|
|
63
|
+
export function manifest({ id = newId(), name, size, sha256: whole, hashes, now, h = sha256 }) {
|
|
64
|
+
if (!int(size, 0, MAX_SIZE)) fail('transfer_too_large', `${size} bytes: at most ${MAX_SIZE} (16 GiB) a file`);
|
|
65
|
+
if (hashes.length !== chunksOf(size) * 32) throw new TypeError('hashes: 32 bytes per chunk');
|
|
66
|
+
return { typ: 'manifest', id, name, size, sha256: whole, chunk: CHUNK, chunks: chunksOf(size), list: listOf(hashes, h), exp: now + MANIFEST_TTL };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const SHAPES = {
|
|
70
|
+
manifest: ['name', 'size', 'sha256', 'chunk', 'chunks', 'list', 'exp'],
|
|
71
|
+
offer: ['attempt', 'sdp', 'tor'],
|
|
72
|
+
answer: ['attempt', 'sdp', 'tor'],
|
|
73
|
+
onion: ['attempt', 'onion', 'port', 'auth', 'token'],
|
|
74
|
+
end: ['reason'],
|
|
75
|
+
};
|
|
76
|
+
const MAY = { offer: ['via'], end: ['attempt'] };
|
|
77
|
+
/** A TRANSFER_LABEL message's content, checked for shape (transfer_message, transfer_too_large). → it. */
|
|
78
|
+
export function checkMessage(x) {
|
|
79
|
+
const bad = (why) => fail('transfer_message', `not a ${TRANSFER_LABEL} message: ${why}`);
|
|
80
|
+
if (!isObject(x) || !TYPS.includes(x.typ)) bad('typ');
|
|
81
|
+
if (typeof x.id !== 'string' || !ID.test(x.id)) bad('id: 32 lowercase hex digits');
|
|
82
|
+
const need = SHAPES[x.typ], may = MAY[x.typ] ?? [];
|
|
83
|
+
for (const k of need) if (!Object.hasOwn(x, k)) bad(`${x.typ} needs ${k}`);
|
|
84
|
+
for (const k of Object.keys(x)) if (k !== 'typ' && k !== 'id' && !need.includes(k) && !may.includes(k)) bad(`${x.typ} has no ${k}`);
|
|
85
|
+
if (Object.hasOwn(x, 'attempt') && !int(x.attempt, 1, ATTEMPT_MAX)) bad(`attempt: 1 to ${ATTEMPT_MAX}`);
|
|
86
|
+
switch (x.typ) {
|
|
87
|
+
case 'manifest':
|
|
88
|
+
if (typeof x.name !== 'string' || x.name.length === 0 || x.name.length > NAME_MAX_IN) bad(`name: 1 to ${NAME_MAX_IN} characters`);
|
|
89
|
+
if (!int(x.size, 0, Number.MAX_SAFE_INTEGER)) bad('size: whole bytes');
|
|
90
|
+
if (x.size > MAX_SIZE) fail('transfer_too_large', `the manifest says ${x.size} bytes, at most ${MAX_SIZE} (16 GiB) a file`);
|
|
91
|
+
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');
|
|
92
|
+
if (x.chunk !== CHUNK) bad(`chunk: ${CHUNK}`);
|
|
93
|
+
if (x.chunks !== chunksOf(x.size)) bad(`chunks: ${x.size} bytes go in ${chunksOf(x.size)}`);
|
|
94
|
+
if (!int(x.exp, 0, Number.MAX_SAFE_INTEGER)) bad('exp: unix seconds');
|
|
95
|
+
break;
|
|
96
|
+
case 'offer': case 'answer':
|
|
97
|
+
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`);
|
|
98
|
+
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');
|
|
99
|
+
if (Object.hasOwn(x, 'via') && x.via !== 'tor') bad('via: "tor"');
|
|
100
|
+
break;
|
|
101
|
+
case 'onion':
|
|
102
|
+
if (typeof x.onion !== 'string' || !ONION.test(x.onion)) bad('onion: 56 base32 characters, no .onion');
|
|
103
|
+
if (!int(x.port, 1, 65535)) bad('port: 1 to 65535');
|
|
104
|
+
if (x.auth !== null && (typeof x.auth !== 'string' || !B64KEY.test(x.auth))) bad('auth: null or a base64 x25519 key');
|
|
105
|
+
if (typeof x.token !== 'string' || !HEX64.test(x.token)) bad('token: 64 lowercase hex digits');
|
|
106
|
+
break;
|
|
107
|
+
case 'end':
|
|
108
|
+
if (!REASONS.includes(x.reason)) bad(`reason: ${REASONS.join(', ')}`);
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
return x;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The data channel's label for an attempt. */
|
|
115
|
+
export const channelLabel = (id, attempt) => `${TRANSFER_LABEL} ${id} ${attempt}`;
|
|
116
|
+
|
|
117
|
+
// ---------------------------------------------------------------- the frames
|
|
118
|
+
|
|
119
|
+
const u32 = (b, o) => ((b[o] << 24) >>> 0) + (b[o + 1] << 16) + (b[o + 2] << 8) + b[o + 3];
|
|
120
|
+
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; };
|
|
121
|
+
export const frames = {
|
|
122
|
+
list(first, hashes) { const f = new Uint8Array(5 + hashes.length); f[0] = T.LIST; put32(f, 1, first); f.set(hashes, 5); return f; },
|
|
123
|
+
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; },
|
|
124
|
+
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; },
|
|
125
|
+
end(reason) { const f = new Uint8Array(2); f[0] = T.END; f[1] = Math.max(0, REASONS.indexOf(reason)); return f; },
|
|
126
|
+
token(t) { const f = new Uint8Array(33); f[0] = T.TOKEN; f.set(t, 1); return f; },
|
|
127
|
+
};
|
|
128
|
+
/** A frame as received, checked for shape (transfer_frame). → { type, … }. */
|
|
129
|
+
export function readFrame(f) {
|
|
130
|
+
const bad = (why) => fail('transfer_frame', why);
|
|
131
|
+
if (!(f instanceof Uint8Array) || f.length < 2 || f.length > FRAME) bad('a frame is 2 to 65,536 bytes');
|
|
132
|
+
switch (f[0]) {
|
|
133
|
+
case T.LIST:
|
|
134
|
+
if (f.length < 5 + 32 || (f.length - 5) % 32 !== 0) bad('LIST: a first index and whole hashes');
|
|
135
|
+
return { type: T.LIST, first: u32(f, 1), hashes: f.subarray(5) };
|
|
136
|
+
case T.WANT:
|
|
137
|
+
if (f.length !== 7) bad('WANT: 7 bytes');
|
|
138
|
+
return { type: T.WANT, from: u32(f, 1), n: (f[5] << 8) + f[6] };
|
|
139
|
+
case T.DATA:
|
|
140
|
+
if (f.length <= DATA_HEAD) bad('DATA: a header and bytes');
|
|
141
|
+
return { type: T.DATA, index: u32(f, 1), offset: u32(f, 5), bytes: f.subarray(DATA_HEAD) };
|
|
142
|
+
case T.END:
|
|
143
|
+
if (f.length !== 2 || f[1] >= REASONS.length) bad('END: a reason');
|
|
144
|
+
return { type: T.END, reason: REASONS[f[1]] };
|
|
145
|
+
case T.TOKEN:
|
|
146
|
+
if (f.length !== 33) bad('TOKEN: 32 bytes');
|
|
147
|
+
return { type: T.TOKEN, token: f.subarray(1) };
|
|
148
|
+
default: return bad(`frame type ${f[0]}`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** Length-prefixed frames on a byte stream (Tor): push(bytes) → the whole frames received so far. */
|
|
152
|
+
export function deframer(max = FRAME) {
|
|
153
|
+
let buf = new Uint8Array(0);
|
|
154
|
+
return (bytes) => {
|
|
155
|
+
buf = buf.length ? concatBytes(buf, bytes) : bytes;
|
|
156
|
+
const out = [];
|
|
157
|
+
while (buf.length >= 4) {
|
|
158
|
+
const n = u32(buf, 0);
|
|
159
|
+
if (n < 2 || n > max) fail('transfer_frame', `a stream frame of ${n} bytes`);
|
|
160
|
+
if (buf.length < 4 + n) break;
|
|
161
|
+
out.push(buf.slice(4, 4 + n));
|
|
162
|
+
buf = buf.subarray(4 + n);
|
|
163
|
+
}
|
|
164
|
+
return out;
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/** A frame for a byte stream: its u32 BE length, then the frame. */
|
|
168
|
+
export const enframe = (f) => { const b = new Uint8Array(4 + f.length); put32(b, 0, f.length); b.set(f, 4); return b; };
|
|
169
|
+
|
|
170
|
+
// ---------------------------------------------------------------- the chunk bitmap (<id>.have)
|
|
171
|
+
|
|
172
|
+
export class Have {
|
|
173
|
+
constructor(chunks, bytes) {
|
|
174
|
+
this.chunks = chunks;
|
|
175
|
+
this.bits = bytes ? Uint8Array.from(bytes) : new Uint8Array(Math.ceil(chunks / 8));
|
|
176
|
+
if (this.bits.length !== Math.ceil(chunks / 8)) fail('transfer_have', `a bitmap of ${this.bits.length} bytes for ${chunks} chunks`);
|
|
177
|
+
}
|
|
178
|
+
has(i) { return (this.bits[i >> 3] & (1 << (i & 7))) !== 0; }
|
|
179
|
+
set(i) { this.bits[i >> 3] |= 1 << (i & 7); }
|
|
180
|
+
count() { let n = 0; for (let i = 0; i < this.chunks; i++) if (this.has(i)) n++; return n; }
|
|
181
|
+
done() { return this.count() === this.chunks; }
|
|
182
|
+
/** Bytes held, of a file of size bytes. */
|
|
183
|
+
bytes(size) { let n = 0; for (let i = 0; i < this.chunks; i++) if (this.has(i)) n += chunkLength(size, i); return n; }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ---------------------------------------------------------------- the two ends
|
|
187
|
+
//
|
|
188
|
+
// channel: { send(frame), buffered() → bytes not yet on the wire, close(), on(event, fn) } with the
|
|
189
|
+
// events 'frame' (a Uint8Array), 'low' (buffered fell below LOW) and 'close'. Both ends end once:
|
|
190
|
+
// onEnd(reason, { remote }) — remote: the other side said it.
|
|
191
|
+
|
|
192
|
+
/** The sender's end: the list first, then the chunks the receiver asks for, read in place (read(i) → bytes). */
|
|
193
|
+
export class Serve {
|
|
194
|
+
constructor({ m, hashes, read, channel, onEnd, onProgress = () => {} }) {
|
|
195
|
+
Object.assign(this, { m, hashes, read, ch: channel, onEnd, onProgress });
|
|
196
|
+
this.queue = []; this.busy = false; this.ended = false; this.sent = 0;
|
|
197
|
+
channel.on('frame', (f) => this.#frame(f));
|
|
198
|
+
channel.on('low', () => this.#pump());
|
|
199
|
+
channel.on('close', () => this.#end('cancelled', true, true));
|
|
200
|
+
}
|
|
201
|
+
start() {
|
|
202
|
+
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)));
|
|
203
|
+
}
|
|
204
|
+
#frame(f) {
|
|
205
|
+
if (this.ended) return;
|
|
206
|
+
let x;
|
|
207
|
+
try { x = readFrame(f); } catch { return this.#end('cancelled'); }
|
|
208
|
+
if (x.type === T.END) return this.#end(x.reason, true);
|
|
209
|
+
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');
|
|
210
|
+
for (let i = x.from; i < x.from + x.n; i++) this.queue.push(i);
|
|
211
|
+
void this.#pump();
|
|
212
|
+
}
|
|
213
|
+
async #pump() {
|
|
214
|
+
if (this.busy || this.ended) return;
|
|
215
|
+
this.busy = true;
|
|
216
|
+
try {
|
|
217
|
+
while (!this.ended && this.queue.length && this.ch.buffered() < HIGH) {
|
|
218
|
+
const i = this.queue.shift();
|
|
219
|
+
let bytes;
|
|
220
|
+
try { bytes = await this.read(i); } catch (e) { this.#end(e?.check === 'file_changed' ? 'file_changed' : 'cancelled'); return; }
|
|
221
|
+
if (this.ended) return;
|
|
222
|
+
for (let o = 0; o < bytes.length; o += DATA_MAX) if (!this.#send(frames.data(i, o, bytes.subarray(o, o + DATA_MAX)))) return;
|
|
223
|
+
this.sent += bytes.length;
|
|
224
|
+
this.onProgress(this.sent);
|
|
225
|
+
}
|
|
226
|
+
} finally { this.busy = false; }
|
|
227
|
+
}
|
|
228
|
+
// A channel that went away while sending: the end, as if it had closed.
|
|
229
|
+
#send(f) { try { this.ch.send(f); return true; } catch { this.#end('cancelled', true, true); return false; } }
|
|
230
|
+
/** Stop: the other side is told reason (unless it said it, or the channel went). */
|
|
231
|
+
#end(reason, remote = false, gone = false) {
|
|
232
|
+
if (this.ended) return;
|
|
233
|
+
this.ended = true;
|
|
234
|
+
if (!remote && !gone) { try { this.ch.send(frames.end(reason)); } catch {} }
|
|
235
|
+
this.onEnd(reason, { remote: remote && !gone, gone });
|
|
236
|
+
}
|
|
237
|
+
stop(reason = 'cancelled') { this.#end(reason); }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* The receiver's end: checks the list, asks for what `have` lacks, at most OUTSTANDING chunks asked
|
|
242
|
+
* and not yet written, checks each chunk's SHA-256 and writes it (write(i, bytes); flush() before the
|
|
243
|
+
* bits are set: a bit means checked and on disk). A bad chunk is asked once more, then chunk_hash.
|
|
244
|
+
* When every bit is set, onEnd('complete'): the caller reads the file back, then finish('done') or
|
|
245
|
+
* finish('chunk_hash'). hashes: the list from an earlier attempt (a resume), else it comes first.
|
|
246
|
+
*/
|
|
247
|
+
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 });
|
|
250
|
+
this.hashes = hashes ?? (m.chunks === 0 ? new Uint8Array(0) : null);
|
|
251
|
+
this.listGot = 0; this.listBuf = this.hashes ? null : new Uint8Array(m.chunks * 32);
|
|
252
|
+
this.out = new Map(); this.writingSet = new Set(); this.unflushed = []; this.again = []; this.next = 0;
|
|
253
|
+
this.tries = new Map(); this.ended = false; this.writing = Promise.resolve();
|
|
254
|
+
channel.on('frame', (f) => this.#frame(f));
|
|
255
|
+
channel.on('close', () => this.#end('cancelled', true, true));
|
|
256
|
+
}
|
|
257
|
+
start() {
|
|
258
|
+
if (this.m.chunks === 0 && listOf(new Uint8Array(0), this.h) !== this.m.list) return this.#end('chunk_hash');
|
|
259
|
+
if (this.hashes) this.#ask();
|
|
260
|
+
}
|
|
261
|
+
#frame(f) {
|
|
262
|
+
if (this.ended) return;
|
|
263
|
+
let x;
|
|
264
|
+
try { x = readFrame(f); } catch { return this.#end('cancelled'); }
|
|
265
|
+
if (x.type === T.END) return this.#end(x.reason, true);
|
|
266
|
+
if (x.type === T.LIST) return this.#list(x);
|
|
267
|
+
if (x.type !== T.DATA || !this.hashes) return this.#end('cancelled');
|
|
268
|
+
const p = this.out.get(x.index);
|
|
269
|
+
if (!p || x.offset !== p.got || p.got + x.bytes.length > p.len) return this.#end('cancelled');
|
|
270
|
+
p.buf.set(x.bytes, p.got);
|
|
271
|
+
p.got += x.bytes.length;
|
|
272
|
+
if (p.got === p.len) this.#chunk(x.index, p.buf);
|
|
273
|
+
}
|
|
274
|
+
#list(x) {
|
|
275
|
+
if (this.listBuf === null) return; // known already (a resume): the sender sends it again
|
|
276
|
+
const n = x.hashes.length / 32;
|
|
277
|
+
if (x.first !== this.listGot || x.first + n > this.m.chunks) return this.#end('cancelled');
|
|
278
|
+
this.listBuf.set(x.hashes, x.first * 32);
|
|
279
|
+
this.listGot += n;
|
|
280
|
+
if (this.listGot < this.m.chunks) return;
|
|
281
|
+
if (listOf(this.listBuf, this.h) !== this.m.list) return this.#end('chunk_hash');
|
|
282
|
+
this.hashes = this.listBuf; this.listBuf = null;
|
|
283
|
+
this.onList(this.hashes);
|
|
284
|
+
this.#ask();
|
|
285
|
+
}
|
|
286
|
+
#chunk(i, buf) {
|
|
287
|
+
this.out.delete(i);
|
|
288
|
+
if (!same(this.h(buf), this.hashes.subarray(i * 32, i * 32 + 32))) {
|
|
289
|
+
const t = (this.tries.get(i) ?? 0) + 1;
|
|
290
|
+
this.tries.set(i, t);
|
|
291
|
+
if (t > RETRIES) return this.#end('chunk_hash');
|
|
292
|
+
this.again.push(i);
|
|
293
|
+
return this.#ask();
|
|
294
|
+
}
|
|
295
|
+
// Written in order of arrival; its slot is free once it is on disk (the back-pressure).
|
|
296
|
+
this.writingSet.add(i);
|
|
297
|
+
this.writing = this.writing.then(async () => {
|
|
298
|
+
if (this.ended) return;
|
|
299
|
+
await this.write(i, buf);
|
|
300
|
+
this.writingSet.delete(i);
|
|
301
|
+
this.unflushed.push(i);
|
|
302
|
+
this.onProgress(buf.length);
|
|
303
|
+
if (this.unflushed.length >= OUTSTANDING || (this.out.size === 0 && this.writingSet.size === 0)) await this.#flush();
|
|
304
|
+
this.#ask();
|
|
305
|
+
}).catch((e) => { this.error = e; this.#end('cancelled'); });
|
|
306
|
+
}
|
|
307
|
+
async #flush() {
|
|
308
|
+
if (!this.unflushed.length) return;
|
|
309
|
+
const now = this.unflushed.splice(0);
|
|
310
|
+
await this.flush();
|
|
311
|
+
for (const i of now) this.have.set(i);
|
|
312
|
+
}
|
|
313
|
+
#ask() {
|
|
314
|
+
if (this.ended || !this.hashes) return;
|
|
315
|
+
const wanted = [], busy = () => this.out.size + this.writingSet.size + wanted.length;
|
|
316
|
+
while (this.again.length && busy() < OUTSTANDING) wanted.push(this.again.shift());
|
|
317
|
+
while (this.next < this.m.chunks && busy() < OUTSTANDING) {
|
|
318
|
+
const i = this.next++;
|
|
319
|
+
if (!this.have.has(i)) wanted.push(i);
|
|
320
|
+
}
|
|
321
|
+
// Runs of consecutive chunks, one WANT each.
|
|
322
|
+
wanted.sort((a, b) => a - b);
|
|
323
|
+
for (let k = 0; k < wanted.length;) {
|
|
324
|
+
let n = 1;
|
|
325
|
+
while (k + n < wanted.length && wanted[k + n] === wanted[k] + n) n++;
|
|
326
|
+
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) }); }
|
|
327
|
+
try { this.ch.send(frames.want(wanted[k], n)); } catch { return this.#end('cancelled', true, true); }
|
|
328
|
+
k += n;
|
|
329
|
+
}
|
|
330
|
+
if (busy() === 0 && this.next >= this.m.chunks && this.again.length === 0) {
|
|
331
|
+
this.writing = this.writing.then(() => this.#flush()).then(() => {
|
|
332
|
+
if (!this.ended && this.have.done()) { this.ended = true; this.onEnd('complete', { remote: false }); }
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
#end(reason, remote = false, gone = false) {
|
|
337
|
+
if (this.ended) return;
|
|
338
|
+
this.ended = true;
|
|
339
|
+
if (!remote && !gone) { try { this.ch.send(frames.end(reason)); } catch {} }
|
|
340
|
+
// What was checked and written is kept (a resume asks only for the rest).
|
|
341
|
+
void this.writing.then(() => this.#flush()).catch(() => {}).finally(() => this.onEnd(reason, { remote: remote && !gone, gone }));
|
|
342
|
+
}
|
|
343
|
+
/** After 'complete': the file read back; done or chunk_hash goes to the sender. */
|
|
344
|
+
finish(reason) { try { this.ch.send(frames.end(reason)); } catch {} }
|
|
345
|
+
stop(reason = 'cancelled') { this.#end(reason); }
|
|
346
|
+
}
|
|
347
|
+
const same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
|
|
348
|
+
|
|
349
|
+
// ---------------------------------------------------------------- the paths
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* The order the paths are tried in (design §2, §9): free, direct then Tor; Pro by its setting, fast
|
|
353
|
+
* (direct, TURN, Tor) or private (Tor, direct, TURN). via tor: Tor only (the address stays hidden).
|
|
354
|
+
* TURN is T4: until it exists it is left out. direct: allowed with this contact and possible here;
|
|
355
|
+
* tor: both sides can (one serves, the other connects). → ['direct', 'tor'], …
|
|
356
|
+
*/
|
|
357
|
+
export function pathOrder({ pro = false, prefer = 'fast', via = 'auto', direct = true, tor = false, turn = false }) {
|
|
358
|
+
if (via === 'tor') return tor ? ['tor'] : [];
|
|
359
|
+
const order = pro && prefer === 'private' ? ['tor', 'direct', 'turn'] : pro ? ['direct', 'turn', 'tor'] : ['direct', 'tor'];
|
|
360
|
+
return order.filter((p) => (p === 'direct' ? direct : p === 'tor' ? tor : turn && pro));
|
|
361
|
+
}
|
|
362
|
+
/** Who serves the onion: the sender if it can, else the receiver; null when no pair of the two works. */
|
|
363
|
+
export function torRoles(sender, receiver) {
|
|
364
|
+
if (sender?.serve && receiver?.connect) return 'sender';
|
|
365
|
+
if (receiver?.serve && sender?.connect) return 'receiver';
|
|
366
|
+
return null;
|
|
367
|
+
}
|
|
368
|
+
/** The free refusal (design §5), for a contact's name. */
|
|
369
|
+
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.`;
|
|
370
|
+
|
|
371
|
+
export { hexToBytes, bytesToHex };
|
package/words-lock.mjs
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// The words password (design/apps-seed.md §8): the 25 words kept on a phone, encrypted under a key made from
|
|
3
|
+
// a password the human chose, so Me → Security can show them again (Monerujo-style, but optional). WebCrypto
|
|
4
|
+
// only, no import: it runs as it is in the Android app's WebView, in the GTK app's WebKit and in Node.
|
|
5
|
+
//
|
|
6
|
+
// lockWords(words, password, { iterations }) → { blob, check } blob: the bytes to seal in the keystore
|
|
7
|
+
// openWords(blob, password) → { words, check } a wrong password throws check words_password
|
|
8
|
+
// proofOf(blob, password) → check, the same refusal: what a shell compares (GTK)
|
|
9
|
+
// wordsMeta(blob) → { v, kdf, iter } (no secret)
|
|
10
|
+
// checkPassword(password, repeat) → the password, or throws check words_password_rule
|
|
11
|
+
// wrongGate({ base, sleep }), gate the delay after a wrong password: 2 s, doubling per failure (at most
|
|
12
|
+
// 256 s) in this page's life, none after a right one; no lockout
|
|
13
|
+
//
|
|
14
|
+
// blob: JSON { v: "sigelo-words/0", kdf: "PBKDF2-SHA256", iter, salt, iv, ct } (base64). The password (NFC)
|
|
15
|
+
// goes through PBKDF2-HMAC-SHA256 with a random 16-byte salt and `iter` rounds (ITERATIONS: 1,000,000; about
|
|
16
|
+
// 0.45 s in WebKit on a 2018 phone), 32 bytes out; HKDF-SHA256 of those makes the AES-256-GCM key (info
|
|
17
|
+
// "sigelo-words/0 key") and the check (info "sigelo-words/0 check", 32 bytes, hex). The AAD names the version
|
|
18
|
+
// and the KDF with its rounds. The check is never stored in the blob: a shell that keeps it beside the blob
|
|
19
|
+
// (the GTK app's keyring item) knows the password was typed without seeing the words.
|
|
20
|
+
export const V = 'sigelo-words/0', KDF = 'PBKDF2-SHA256', ITERATIONS = 1_000_000, MIN_ITERATIONS = 1_000, PASSWORD_MIN = 8, WORD_COUNT = 25;
|
|
21
|
+
const te = new TextEncoder(), td = new TextDecoder();
|
|
22
|
+
const refuse = (check, message) => { throw Object.assign(new Error(message), { check }); };
|
|
23
|
+
const b64 = (b) => { let s = ''; for (const x of b) s += String.fromCharCode(x); return btoa(s); };
|
|
24
|
+
const unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
|
|
25
|
+
const hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
|
|
26
|
+
const subtle = () => globalThis.crypto?.subtle ?? refuse('words_crypto', 'this page has no WebCrypto');
|
|
27
|
+
const aad = (iter) => te.encode(`${V} ${KDF} ${iter}`);
|
|
28
|
+
|
|
29
|
+
/** The words as one line: lowercase, one space between, exactly 25 (they are checked by the restore before this). */
|
|
30
|
+
function cleanWords(words) {
|
|
31
|
+
const w = (Array.isArray(words) ? words.join(' ') : String(words ?? '')).trim().toLowerCase().split(/\s+/);
|
|
32
|
+
if (w.length !== WORD_COUNT || w.some((x) => !/^[a-z]+$/.test(x))) refuse('words', `${WORD_COUNT} words`);
|
|
33
|
+
return w.join(' ');
|
|
34
|
+
}
|
|
35
|
+
/** A password as set: at least 8 characters, the repeat the same. → the password. */
|
|
36
|
+
export function checkPassword(password, repeat = password) {
|
|
37
|
+
const p = String(password ?? '');
|
|
38
|
+
if ([...p].length < PASSWORD_MIN) refuse('words_password_rule', `A password of at least ${PASSWORD_MIN} characters.`);
|
|
39
|
+
if (p !== String(repeat ?? '')) refuse('words_password_rule', 'The two passwords are not the same.');
|
|
40
|
+
return p;
|
|
41
|
+
}
|
|
42
|
+
async function keys(password, salt, iter) {
|
|
43
|
+
const s = subtle();
|
|
44
|
+
const pw = await s.importKey('raw', te.encode(String(password).normalize('NFC')), 'PBKDF2', false, ['deriveBits']);
|
|
45
|
+
const master = new Uint8Array(await s.deriveBits({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations: iter }, pw, 256));
|
|
46
|
+
try {
|
|
47
|
+
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(`${V} ${info}`) });
|
|
49
|
+
const key = await s.deriveKey(hk('key'), h, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
50
|
+
const check = hex(new Uint8Array(await s.deriveBits(hk('check'), h, 256)));
|
|
51
|
+
return { key, check };
|
|
52
|
+
} finally { master.fill(0); }
|
|
53
|
+
}
|
|
54
|
+
/** The blob's fields, checked: { v, kdf, iter, salt, iv, ct } (bytes for the last three). */
|
|
55
|
+
function parse(blob) {
|
|
56
|
+
let o;
|
|
57
|
+
try { o = JSON.parse(td.decode(blob)); } catch { refuse('words_blob', 'the kept words are damaged'); }
|
|
58
|
+
if (o?.v !== V || o.kdf !== KDF || !Number.isSafeInteger(o.iter) || o.iter < MIN_ITERATIONS) refuse('words_blob', 'the kept words are of an unknown kind');
|
|
59
|
+
try { return { ...o, salt: unb64(o.salt), iv: unb64(o.iv), ct: unb64(o.ct) }; } catch { return refuse('words_blob', 'the kept words are damaged'); }
|
|
60
|
+
}
|
|
61
|
+
export function wordsMeta(blob) { const { v, kdf, iter } = parse(blob); return { v, kdf, iter }; }
|
|
62
|
+
|
|
63
|
+
/** The 25 words encrypted under the password → { blob (bytes), check (hex) }. */
|
|
64
|
+
export async function lockWords(words, password, { iterations = ITERATIONS } = {}) {
|
|
65
|
+
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
|
+
try {
|
|
69
|
+
const { key, check } = await keys(p, salt, iterations);
|
|
70
|
+
const ct = new Uint8Array(await subtle().encrypt({ name: 'AES-GCM', iv, additionalData: aad(iterations) }, key, line));
|
|
71
|
+
return { blob: te.encode(JSON.stringify({ v: V, kdf: KDF, iter: iterations, salt: b64(salt), iv: b64(iv), ct: b64(ct) })), check };
|
|
72
|
+
} finally { line.fill(0); }
|
|
73
|
+
}
|
|
74
|
+
/** The words back → { words: [25], check }; a wrong password: check words_password. */
|
|
75
|
+
export async function openWords(blob, password) {
|
|
76
|
+
const o = parse(blob), { key, check } = await keys(String(password ?? ''), o.salt, o.iter);
|
|
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.'); }
|
|
79
|
+
try { return { words: td.decode(plain).split(' '), check }; } finally { plain.fill(0); }
|
|
80
|
+
}
|
|
81
|
+
/** The check for a password, after the words opened under it (so a wrong one is refused here too). */
|
|
82
|
+
export async function proofOf(blob, password) { return (await openWords(blob, password)).check; }
|
|
83
|
+
|
|
84
|
+
/** A wrong password costs 2 s, then 4, 8, … up to 256 s (in this gate's life: the page's); a right one resets it. Never a lockout. */
|
|
85
|
+
export function wrongGate({ base = 2000, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
|
|
86
|
+
let fails = 0, last = Promise.resolve();
|
|
87
|
+
const attempt = async (fn) => {
|
|
88
|
+
try { const r = await fn(); fails = 0; return r; } catch (e) {
|
|
89
|
+
if (e?.check === 'words_password') { fails++; await sleep(base * 2 ** Math.min(fails - 1, 7)); }
|
|
90
|
+
throw e;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
return {
|
|
94
|
+
get fails() { return fails; },
|
|
95
|
+
/** One attempt at a time: a second tap waits for the first's delay, so taps in parallel do not skip it. */
|
|
96
|
+
run(fn) { const r = last.then(() => attempt(fn)); last = r.catch(() => {}); return r; },
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** The page's one gate: every place that asks the password counts in it. */
|
|
100
|
+
export const gate = wrongGate();
|